diff options
author | Andrew John Hughes <gnu_andrew@member.fsf.org> | 2006-07-09 22:21:37 +0000 |
---|---|---|
committer | Andrew John Hughes <gnu_andrew@member.fsf.org> | 2006-07-09 22:21:37 +0000 |
commit | 0a54298efa8253b9aa8680075e7d34e3688057ef (patch) | |
tree | 4b3d17942838ad751b3eecfed5c9b1b80f9a86f4 | |
parent | 5dcdd6c62db92f3c76da56417a0a029a27d06ec3 (diff) | |
download | classpath-0a54298efa8253b9aa8680075e7d34e3688057ef.tar.gz |
2006-07-09 Andrew John Hughes <gnu_andrew@member.fsf.org>
* Merge of HEAD --> generics-branch for
2006/07/02 to 2006/07/09.
142 files changed, 8429 insertions, 3283 deletions
diff --git a/.classpath b/.classpath index f4ba74e8d..8d50115d8 100644 --- a/.classpath +++ b/.classpath @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> - <classpathentry excluding=".externalToolBuilders/|.settings/|ChangeLog*|Makefile*|autom4te.cache/|compat/|config*|doc/|examples/|external/|external/relaxngDatatype/|include/|install/|jessie-tests/|lib/|m4/|native/|resource/|scripts/|test/|testsuite/|tools/|vm/reference/" kind="src" path=""/> + <classpathentry excluding=".externalToolBuilders/|.settings/|ChangeLog*|Makefile*|autom4te.cache/|compat/|config*|doc/|examples/|external/|external/relaxngDatatype/|include/|install/|lib/|m4/|native/|resource/|scripts/|test/|testsuite/|tools/|vm/reference/|gnu/java/awt/peer/x/" kind="src" path=""/> <classpathentry excluding=".cvsignore|Makefile|Makefile.am|Makefile.in|README.txt" kind="src" path="external/relaxngDatatype"/> <classpathentry kind="src" path="external/jsr166"/> <classpathentry excluding=".cvsignore|Makefile|Makefile.am|Makefile.in|README" kind="src" path="tools"/> @@ -1,9 +1,665 @@ +2006-07-09 David Gilbert <david.gilbert@object-refinery.com> + + * javax/swing/Timer.java + (setDelay): Throw IllegalArgumentException for negative delay, + (setInitialDelay): Likewise, + * javax/swing/ToolTipManager.java + (setInitialDelay): Document IllegalArgumentException, + (setDismissDelay): Likewise, + (setReshowDelay): Likewise. + +2006-07-09 Andrew John Hughes <gnu_andrew@member.fsf.org> + + * java/lang/management/MemoryUsage.java: + (from(javax.management.openmbean.CompositeData)): + Implemented. + * java/lang/management/ThreadInfo.java: + Changed to use open types throughout for the state. + (ThreadInfo(long,String,String,long,long,String, + long,String,long,long,boolean,StackTraceElement[])): + New constructor. + (checkAttribute(javax.management.openmbean.CompositeType, + String, javax.management.openmbean.OpenType)): New method. + (from(javax.management.openmbean.CompositeData)): + Implemented. + (getLockName()): Fixed to use new variable. + (getLockOwnerId()): Likewise. + (getLockOwnerName()): Likewise. + (getThreadId()): Likewise. + (getThreadName()): Likewise. + (getThreadState()): Likewise. + (toString()): Refactored to use new variables. + * javax/management/openmbean/ArrayType.java: + New file. + * javax/management/openmbean/CompositeType.java: + Variables should be transient, not volatile. + * javax/management/openmbean/OpenDataException.java: + (serialVersionUID): Added. + * javax/management/openmbean/SimpleType.java: + New file. + * javax/management/openmbean/TabularType.java + Variables should be transient, not volatile. + +2006-07-09 Tom Tromey <tromey@redhat.com> + + * tools/.cvsignore: Updated for new tools. + +2006-07-09 Andrew John Hughes <gnu_andrew@member.fsf.org> + + * javax/management/openmbean/CompositeData.java, + * javax/management/openmbean/CompositeType.java, + * javax/management/openmbean/OpenDataException.java, + * javax/management/openmbean/OpenType.java, + * javax/management/openmbean/TabularData.java, + * javax/management/openmbean/TabularType.java, + * javax/management/openmbean/package.html: + New files. + +2006-07-09 Mark Wielaard <mark@klomp.org> + + * gnu/javax/print/ipp/IppRequest.java: Remove double assignment. + * gnu/java/rmi/server/UnicastServerRef.java: Likewise. + * gnu/java/rmi/server/ActivatableServerRef.java: Likewise. + +2006-07-08 Anthony Green <green@redhat.com> + + * gnu/javax/sound/sampled/WAV/WAVReader.java, + resource/META-INF/services/javax.sound.sampled.spi.AudioFileReader: + New files. + +2006-07-09 Mario Torre <neugens@limasoftware.net> + + * native/jni/gconf-peer/GConfNativePeer.c: + Fixed indentation to be more compliant to the GNU coding + guidelines. + (Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1unset): + Added explicit test for errors in the GConf backend. + (Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1get_1string): + Added explicit test for errors in the GConf backend. + Fixed Segmentation Fault when non valid key names are given as input. + (Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1set_1string): + likewise. + (Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1dir_1exists): + Added explicit test for errors in the GConf backend. + * gnu/java/util/prefs/gconf/GConfNativePeer.java: + Added javadoc comments for all native methods. + (nodeExist): removed test to check for valid absolute path name + for nodes. + (startWatchingNode): likewise. + (stopWatchingNode): likewise. + (setString): likewise, plus fixed javadoc comments. + (unset): likekwise. + (getKey): likewise. + (getKeys): likewise, also fixed javadoc comments. + (getChildrenNodes): likewise. + * gnu/java/util/prefs/GConfBasedPreferences.java: + changed DEFAULT_USER_ROOT to /apps/classpath. + (constructor): Test to check for a valid absolute path for nodes + is now in the contructor for that node, instead of being on + each method of the backend. + (getGConfKey): removed empty new line. + +2006-07-08 Mark Wielaard <mark@klomp.org> + + * .classpath: Add gnu/java/awt/peer/x/ to excludes. + +2006-07-08 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * javax/swing/text/FlowView.java (FlowStrategy.layoutRow): + Handle the forced break in the same way as exceeding the + available row space. + * javax/swing/text/html/HRuleView.java: Rewritten. + * javax/swing/text/html/HTMLDocument.java + (HTMLReader.addSpecialElement):Reserve two characters for + the special elements. + * examples/gnu/classpath/examples/swing/HtmlDemo.java + (text): Extended the HTML example to parse. + +2006-07-07 David Gilbert <david.gilbert@object-refinery.com> + + * javax/swing/AbstractButton.java + (setHorizontalAlignment): Check for illegal argument, + (setVerticalAlignment): Likewise. + +2006-07-07 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * javax/swing/text/html/TableView.java + (getStyleSheet): New method. (RowView.getStyleSheet): + New method. + +2006-07-07 David Gilbert <david.gilbert@object-refinery.com> + + * javax/swing/AbstractButton.java + (setRolloverIcon): Call setRolloverEnabled(true), + (setRolloverSelectedIcon): Likewise. + +2006-07-07 David Gilbert <david.gilbert@object-refinery.com> + + * javax/swing/border/TitledBorder.java + (setTitlePosition): Added message to exception, + (setTitleJustification): Likewise. + +2006-07-07 David Gilbert <david.gilbert@object-refinery.com> + + * javax/swing/plaf/metal/MetalLookAndFeel.java + (createDefaultTheme): Corrected API docs, + (initComponentDefaults): Added entry for 'TitledBorder.border', + (getCurrentTheme): Initialise theme if it is null. + +2006-07-07 Roman Kennke <kennke@aicas.com> + + * java/awt/Component.java + (isValid): Return false when component has no peer, + don't query the showing state. + +2006-07-07 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * javax/swing/text/FlowView.java (FlowStrategy.layoutRow): + Advance the offset also in the case of the enforced break. + +2006-07-07 David Gilbert <david.gilbert@object-refinery.com> + + * javax/swing/plaf/basic/BasicArrowButton.java + (MAXIMUM_SIZE): Removed field, + (MINIMUM_SIZE): Likewise, + (PREFERRED_SIZE): Likewise, + (getMaximumSize): Return new instance every time, + (getMinimumSize): Likewise, + (getPreferredSize): Likewise. + +2006-07-07 Roman Kennke <kennke@aicas.com> + + * java/awt/LightweightDispatcher.java + (findTarget): Avoid array copying in + Container.getComponents(). + +2006-07-07 Roman Kennke <kennke@aicas.com> + + * javax/swing/JComponent.java + (paintChildrenWithOverlap): Avoid array copying in + Container.getComponents(). + (paintChildrenOptimized): Avoid array copying in + Container.getComponents(). + (fireAncestorEvent): Avoid array copying in + Container.getComponents(). + (findOverlapFreeParent): Avoid array copying in + Container.getComponents(). + +2006-07-07 Matt Wringe <mwringe@redhat.com> + + * javax/crypto/spec/PBEKeySpec.java: Updated copyright year. + (passwordValid): New field. + (setPassword): New method. + (setSalt): Likewise. + (setIterationCount): Likewise. + (setKeyLength): Likewise. + (PBEKeySpec(char[])): Use new setter methods. + (PBEKeySpec(char[], byte[], int)): Likewise. + (PBEKeySpec(char[], byte[], int, int)): Likewise. + (clearPassword): Set passwordValid to false. + (getPassword): Check that clearPassword() was not called earlier. + Return a clone of the password. + (getSalt): Return a clone of the salt if it was not null. + +2006-07-07 Roman Kennke <kennke@aicas.com> + + * java/awt/Component.java + (isValid): Always return false when component is + not showing. + (setFont): Always set font, even when setting + the same or equal font again. + +2006-07-07 David Gilbert <david.gilbert@object-refinery.com> + + * javax/swing/plaf/metal/MetalIconFactory.java + (CheckBoxMenuItemIcon): Implement UIResource, + (FileChooserDetailViewIcon): Likewise, + (FileChooserHomeFolderIcon): Likewise, + (FileChooserListViewIcon): Likewise, + (FileChooserNewFolderIcon): Likewise, + (FileChooserUpFolderIcon): Removed redundant 'implements', + (RadioButtonMenuItemIcon): Implement UIResource, + (HorizontalSliderThumbIcon): Likewise, + (InternalFrameCloseIcon): Likewise, + (InternalFrameDefaultMenuIcon): Likewise, + (InternalFrameAltMaximizeIcon): Likewise, + (InternalFrameMaximizeIcon): Likewise, + (InternalFrameMinimizeIcon): Likewise, + (VerticalSliderThumbIcon): Likewise, + (TreeHardDriveIcon): Likewise, + (TreeFloppyDriveIcon): Likewise, + (TreeComputerIcon): Likewise, + (horizontalSliderThumbIcon): New field, + (verticalSliderThumbIcon): New field, + (getHorizontalSliderThumbIcon): Cache icon, + (getVerticalSliderThumbIcon): Likewise. + +2006-07-06 Mark Wielaard <mark@klomp.org> + + * lib/Makefile.am (CLEANFILES): Add Makefile.deps. + (DISTCLEANFILES): Add standard.omit. + (clean-local): Remove Makefile.deps, only remove dirs. + +2006-07-06 Roman Kennke <kennke@aicas.com> + + * java/awt/Component.java + (setFont): Only invalidate when component is valid. + * java/awt/Container.java + (setLayout): Only invalidate when component is valid. + +2006-07-06 Lillian Angel <langel@redhat.com> + + * gnu/java/awt/dnd/GtkMouseDragGestureRecognizer.java: + New class not fully implemented. + * gnu/java/awt/dnd/peer/gtk/GtkDragSourceContextPeer.java: + New class not fully implemented. + * gnu/java/awt/dnd/peer/gtk/GtkDropTargetPeer.java: + New class not fully implemented. + * gnu/java/awt/dnd/peer/gtk/GtkDropTargetContextPeer.java: + New class not fully implemented. + * nu/java/awt/peer/gtk/GtkToolkit.java: + Fixed Imports. + (createDragSourceContextPeer): Implemented. + (createDragGestureRecognizer): New function to override + java.awt.Toolkit.createDragGestureRecognizer. + * java/awt/dnd/DragSource.java + (NoDragGestureRecognizer): Removed inner class. + (createDragGestureRecognizer): Re-Implemented to + call Toolkit's createDragGestureRecognizer. + (createDefaultDragGestureRecognizer): Re-Implemented to + call Toolkit's createDragGestureRecognizer. + * java/awt/dnd/DropTarget.java + (addNotify): Added check to determine type of peer and call + addDropTarget. + (removeNotify): Added call to removeDropTarget. + +2006-07-06 Tom Tromey <tromey@redhat.com> + + * gnu/java/util/prefs/EventDispatcher.java (dispatch): Notify + 'queue'. + (run): Wait on queue, not 'this'. + +2006-07-06 Lillian Angel <langel@redhat.com> + + * java/awt/dnd/DragSource.java + (startDrag): Implemented. Added comments describing + what the function should do. Removed FIXME. + +2006-07-06 Tania Bento <tbento@redhat.com> + + * gnu/java/awt/Canvas.java + Added new private variable 'next_canvas_number'. + (generateName): Added. + (getUniqueLong): Added. + +2006-07-06 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * gnu/javax/swing/text/html/CharacterAttributeTranslator.java + (getColor): Made public. + * javax/swing/text/html/StyleSheet.java (stringToColor): + Use CharacterAttributeTranslator.getColor(String) + +2006-07-06 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * javax/swing/text/html/HTMLEditorKit.java: + (HTMLFactory.createElement): Update reference to the html table view. + * javax/swing/text/html/HTMLTableView.java: Removed (renamed). + * javax/swing/text/html/TableView.java: New file. + +2006-07-06 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * javax/swing/text/html/HTMLEditorKit.java: + (HTMLFactory.createElement): Uncomment + code for BRView and HRuleView. + * javax/swing/text/html/BRView.java, + javax/swing/text/html/HRuleView.java: New files. + 2006-07-05 Andrew John Hughes <gnu_andrew@member.fsf.org> * java/lang/Thread.java: (getAllStackTraces(Map<Thread,StackTraceElement[]>)): Added generic type signature. +2006-07-05 Andrew John Hughes <gnu_andrew@member.fsf.org> + + * NEWS: Updated. + * doc/vmintegration.texinfo: Likewise. + * examples/gnu/classpath/examples/management/TestGarbageCollector.java, + * examples/gnu/classpath/examples/management/TestMemoryManager.java, + * gnu/java/lang/management/GarbageCollectorMXBeanImpl.java, + * gnu/java/lang/management/MemoryManagerMXBeanImpl.java, + * java/lang/management/GarbageCollectorMXBean.java: + New files. + * java/lang/management/ManagementFactory.java: + (getGarbageCollectorMXBeans()): Implemented. + (getMemoryManagerMXBeans()): Likewise. + * vm/reference/gnu/java/lang/management/VMGarbageCollectorMXBeanImpl.java, + * vm/reference/gnu/java/lang/management/VMMemoryManagerMXBeanImpl.java: + New files. + * vm/reference/java/lang/management/VMManagementFactory.java: + (getMemoryManagerNames()): Added. + (getGarbageCollectorNames()): Added. + +2006-07-05 Thomas Fitzsimmons <fitzsim@redhat.com> + + * native/plugin/Makefile.am (nativeexeclib_LTLIBRARIES): Rename + from lib_LTLIBRARIES. + (install-plugin): Depend on nativeexeclib_LTLIBRARIES. + +2006-07-05 Lillian Angel <langel@redhat.com> + + * java/awt/dnd/DragGestureEvent.java: + Added new fields. + (DragGestureEvent): Initialized new fields, added to check and + added documentation. + (getSourceAsDragGestureRecognizer): Added documentation and + changed to use getSource. + (getComponent): Added documentation and fixed to return the proper + value. + (getDragSource): Likewise. + (getDragOrigin): Added documentation. + (iterator): Implemented and added documentation. + (toArray): Likewise. + (toArray): Likewise. + (getDragAction): Likewise. + (getTriggerEvent): Likewise. + (startDrag): Likewise. + * java/awt/dnd/DragGestureRecognizer.java + (resetRecognizer): Added FIXME. + * java/awt/dnd/DragSource.java: + Added new field. + (DragSource): Set ds to be null if headless. + (getDefaultDragSource): Added documentation and implemented. + (isDragImageSupported): Marked as unimplemented. + (startDrag): Likewise. + (createDragSourceContext): Implemented. + (NoDragGestureRecognizer): Formatted inner class. + * java/awt/dnd/DropTarget.java + (stop): Marked as unimplemented. + (actionPerformed): Likewise. + (addDropTargetListener): Added code to throw exception. + (removeDropTargetListener): Added check, removed FIXME. + (dragEnter): Implemented. + (dragOver): Implemented. + (dropActionChanged): Implemented. + (dragExit): Implemented. + (drop): Implemented. + (addNotify): Implemented. + (removeNotify): Implemented. + (createDropTargetContext): Implemented. + (createDropTargetAutoScroller): Implemented. + (initializeAutoscrolling): Implemented. + (updateAutoscroll): Implemented. + (clearAutoscroll): Implemented. + * java/awt/dnd/DropTargetContext.java + (dropComplete): Implemented. + (acceptDrag): Implemented. + (rejectDrag): Implemented. + (acceptDrop): Implemented. + (rejectDrop): Implemented. + (getCurrentDataFlavors): Implemented. + (getTransferable): Partially implemented. + * java/awt/dnd/DropTargetDragEvent.java + (getDropAction): Uncommented correct code. + * java/awt/dnd/DropTargetDropEvent.java + (dropComplete) :Implemented. + * java/awt/dnd/InvalidDnDOperationException.java + (InvalidDnDOperationException): Added call to super. + +2006-07-05 Robert Schuster <robertschuster@fsfe.org> + + * javax/swing/plaf/basic/BasicArrowButton.java: + (paint): Removed getBounds() call, changed center point + calculation. + +2006-07-05 David Gilbert <david.gilbert@object-refinery.com> + + * javax/swing/InputMap.java + (inputMap): Don't initialize yet, + (InputMap): Removed TODO, + (get): Check for null inputMap, + (put): Return immediately for null keyStroke, check for null inputMap + and initialize if necessary, + (remove): Check for null inputMap, + (size): Likewise, + (clear): Likewise, + (keys): Likewise, + (allKeys): Likewise, + (writeObject): Removed, + (readObject): Removed. + +2006-07-05 David Gilbert <david.gilbert@object-refinery.com> + + * gnu/classpath/examples/swing/TabbedPaneDemo.java + (createContent): Use different labels for buttons. + +2006-07-04 Andrew John Hughes <gnu_andrew@member.fsf.org> + + * NEWS: Updated. + * doc/vmintegration.texinfo: Likewise. + * examples/gnu/classpath/examples/management/TestMemoryPool.java, + * gnu/java/lang/management/MemoryPoolMXBeanImpl.java: + New files. + * java/lang/management/ManagementFactory.java: + (getMemoryPoolMXBeans()): Implemented. + * vm/reference/gnu/java/lang/management/VMMemoryPoolMXBeanImpl.java, + * vm/reference/java/lang/management/VMManagementFactory.java: + New files. + +2006-07-04 Lillian Angel <langel@redhat.com> + + * java/awt/dnd/DragSourceContext.java: + Removed FIXMEs from fields. + (DragSourceContext): Added code to initialize cursor and sourceActions. + (getDragSource): Added documentation. + (getComponent): Likewise. + (getTrigger): Likewise. + (getSourceActions): Added documentation and implemented. + (setCursor): Implemented. Added documentation. + (getCursor): Implemented. Added documentation. + (dragEnter): Added code to notify DragSource's listeners. + (dragOver): Likewise. + (dragExit): Likewise. + (dropActionChanged): Likewise. + (dragDropEnd): Likewise. + (dragMouseMoved): Implemented. + (getTransferable): Added API documentation. + (updateCurrentCursor): Added API documentation and partially implemented. + +2006-07-04 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * javax/swing/plaf/basic/BasicTreeUI.java (KeyHandler): Implemented. + +2006-07-04 Lillian Angel <langel@redhat.com> + + * java/awt/dnd/DragSourceContext.java + (DragSourceContext): Implemented fully. Fixed API docs. + (transferablesFlavorsChanged): Implemented. + (dragEnter): Implemented. + (dragOver): Implemented. + (dragExit): Implemented. + (dropActionChanged): Implemented. + (dragDropEnd): Implemented. + +2006-07-04 Lillian Angel <langel@redhat.com> + + * javax/swing/plaf/basic/BasicOptionPaneUI.java: + Fixed name of constant. + (getIconWidth): Changed name of constant returned. + (getIconHeight): Likewise. + (paint): Likewise. + (createSeparator): Marked as unimplemented. + * javax/swing/plaf/basic/BasicTableUI.java + (focusGained): Marked as unimplemented. + (focusLost): Marked as unimplemented. + (mouseEntered): Likewise. + (mouseMoved): Likewise. + (uninstallDefaults): Likewise. + * javax/swing/plaf/basic/BasicToolBarUI.java + (mouseClicked): Changed comment. + (mouseEntered): Likewise. + (mouseExited): Likewise. + (mouseMoved): Likewise. + (setOrientation): Implemented. + (ToolBarFocusListener): Marked as unimplemented. + (focusGained): Marked as unimplemented. + (focusLost): Marked as unimplemented. + +2006-07-04 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + PR 28061 + * javax/swing/plaf/basic/BasicTreeUI.java (isLocationInExpandControl): + Mind the effect of the root visibility on the position of the control. + Quess icon width 18. (paintVerticalPartOfLeg): Do no paint the + vertical line over first level nodes. + +2006-07-04 Lillian Angel <langel@redhat.com> + + * javax/swing/plaf/basic/BasicMenuUI.java + (installKeyboardActions): Implemented to call super. Nothing else + needs to be done here. + (setupPostTimer): Marked as unimplemented. + (uninstallKeyboardActions): Implemented to call super. Nothing else + needs to be done here. + (mouseMoved): Removed TODO. Nothing to be done here. + (ChangeHandler): Implemented. + (menuDragMouseExited): Removed TODO. Nothing to be done here. + (menuDragMouseReleased): Removed TODO. Nothing to be done here. + (menuKeyReleased): Removed TODO. Nothing to be done here. + (menuKeyTyped): Marked as unimplemented. + +2006-07-04 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + PR 28061 + * gnu/javax/swing/plaf/gnu/GNULookAndFeel.java + (getDefaults): Set hash color to black. + * javax/swing/plaf/basic/BasicLookAndFeel.java + (initComponentDefaults): Set hash color to grey blue. + * javax/swing/plaf/basic/BasicTreeUI.java + (instellDefaults): Set hash color. + * javax/swing/plaf/metal/MetalIconFactory.java + (TreeControlIcon.paint): Rewritten. + +2006-07-04 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + PR 28061 + * javax/swing/plaf/basic/BasicTreeUI.java (MouseHandler.mousePressed): + Always cancel the current editing session before doing anything else, + return immediately if this fails. + (TreeHomeAction): Ensure that the lead selection path is visible after + the action is performed. TreeIncrementAction: Likewise. TreeToggleAction: + Likewise. TreeTraverseAction: Likewise. + +2006-07-04 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + PR 28061 + * javax/swing/plaf/basic/BasicTreeUI.java (MouseHandler.mousePressed): + Returned back the code to handle the start of the click-pause-click + editing initiation, explained about this code. + (TreeStartEditingAction): New inner class. + (stopEditingInCompleteEditing): Explained about this field. + (completeEditing(boolean, boolean, boolean): Only return early + if there is no current editing session. + (createDefaultActions): Install TreeStartEditingAction and + TreeCancelEditingAction. + +2006-07-04 Mario Torre <neugens@limasoftware.net> + + * configure.ac: Added new option --enable-default-preferences-peer + to pass user specified default preference backend. + If the GConf peer is built, GConf become the default backend. + * resource/META-INF/services/java.util.prefs.PreferencesFactory.in: + new file. + * lib/Makefile.am: excludes files terminating in 'in' from + the metafiles list. + * lib/copy-vmresources.sh.in: excludes files terminating in 'in' + from copy into META-INF. + * java/util/prefs/Preferences.java: added two new import + classes gnu.classpath.ServiceFactory and java.util.Iterator. + (getFactory): Now try to check for + a system defined default preference backend before to fall back on + FileBasedPreference. + +2006-07-04 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + PR 28061 + * javax/swing/JTree.java (COLLAPSED): Initialise to Boolean.FALSE. + (EXPANDED): Initialise to Boolean.TRUE. + * javax/swing/plaf/basic/BasicTreeUI.java (completeUIInstall): + First configure layout cache and then set the assigned value + as row mapper. Set the root visibility property. + (toggleExpandState): Obtains expansion state from the layout cache. + +2006-07-03 Andrew John Hughes <gnu_andrew@member.fsf.org> + + * java/lang/management/MemoryPoolMXBean.java: + New file. + +2006-07-03 Raif S. Naffah <raif@swiftdsl.com.au> + + * gnu/javax/crypto/RSACipherImpl.java: Source formatting. + +2006-07-03 Raif S. Naffah <raif@swiftdsl.com.au> + + * gnu/javax/crypto/sasl/anonymous/AnonymousClient.java: Source formatting. + * gnu/javax/crypto/sasl/anonymous/AnonymousServer.java: Likewise. + * gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java: Likewise. + * gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java: Likewise. + * gnu/javax/crypto/sasl/crammd5/CramMD5Client.java: Likewise. + * gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java: Likewise. + * gnu/javax/crypto/sasl/crammd5/CramMD5Server.java: Likewise. + * gnu/javax/crypto/sasl/crammd5/CramMD5Util.java: Likewise. + * gnu/javax/crypto/sasl/crammd5/PasswordFile.java: Likewise. + * gnu/javax/crypto/sasl/plain/PasswordFile.java: Likewise. + * gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java: Likewise. + * gnu/javax/crypto/sasl/plain/PlainClient.java: Likewise. + * gnu/javax/crypto/sasl/plain/PlainRegistry.java: Likewise. + * gnu/javax/crypto/sasl/plain/PlainServer.java: Likewise. + * gnu/javax/crypto/sasl/srp/CALG.java: Likewise. + * gnu/javax/crypto/sasl/srp/ClientStore.java: Likewise. + * gnu/javax/crypto/sasl/srp/IALG.java: Likewise. + * gnu/javax/crypto/sasl/srp/KDF.java: Likewise. + * gnu/javax/crypto/sasl/srp/PasswordFile.java: Likewise. + * gnu/javax/crypto/sasl/srp/SecurityContext.java: Likewise. + * gnu/javax/crypto/sasl/srp/ServerStore.java: Likewise. + * gnu/javax/crypto/sasl/srp/SRP.java: Likewise. + * gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java: Likewise. + * gnu/javax/crypto/sasl/srp/SRPClient.java: Likewise. + * gnu/javax/crypto/sasl/srp/SRPRegistry.java: Likewise. + * gnu/javax/crypto/sasl/srp/SRPServer.java: Likewise. + * gnu/javax/crypto/sasl/srp/StoreEntry.java: Likewise. + * gnu/javax/crypto/sasl/AuthInfo.java: Likewise. + * gnu/javax/crypto/sasl/AuthInfoProviderFactory.java: Likewise. + * gnu/javax/crypto/sasl/ClientFactory.java: Likewise. + * gnu/javax/crypto/sasl/ClientMechanism.java: Likewise. + * gnu/javax/crypto/sasl/ConfidentialityException.java: Likewise. + * gnu/javax/crypto/sasl/IAuthInfoProvider.java: Likewise. + * gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java: Likewise. + * gnu/javax/crypto/sasl/IllegalMechanismStateException.java: Likewise. + * gnu/javax/crypto/sasl/InputBuffer.java: Likewise. + * gnu/javax/crypto/sasl/IntegrityException.java: Likewise. + * gnu/javax/crypto/sasl/NoSuchMechanismException.java: Likewise. + * gnu/javax/crypto/sasl/NoSuchUserException.java: Likewise. + * gnu/javax/crypto/sasl/OutputBuffer.java: Likewise. + * gnu/javax/crypto/sasl/SaslEncodingException.java: Likewise. + * gnu/javax/crypto/sasl/SaslInputStream.java: Likewise. + * gnu/javax/crypto/sasl/SaslOutputStream.java: Likewise. + * gnu/javax/crypto/sasl/SaslUtil.java: Likewise. + * gnu/javax/crypto/sasl/ServerFactory.java: Likewise. + * gnu/javax/crypto/sasl/ServerMechanism.java: Likewise. + * gnu/javax/crypto/sasl/UserAlreadyExistsException.java: Likewise. + +2006-07-02 Anthony Green <green@redhat.com> + + * gnu/javax/sound/midi/file/MidiFileWriter.java (writeTrack): Make + sure that every track written ends with an End Of Track meta + message. + +2006-07-02 Andrew John Hughes <gnu_andrew@member.fsf.org> + + * java/lang/management/MemoryUsage.java: + (toString()): Fix missing MB for maximum memory usage. + 2006-07-02 Andrew John Hughes <gnu_andrew@member.fsf.org> * NEWS: @@ -70,6 +70,18 @@ Runtime interface changes: and the number of objects eligible for garbage collection. * VMCompilationMXBeanImpl is used to allow for optional compilation time support for Just-In-Time compilers. +* VMMemoryPoolMXBeanImpl is used to implement the low-level support + of the memory pool beans. Providing this interface requires + providing memory usage statistics for each supported bean. +* VMManagementFactory provides the names of the memory pools, + memory managers and garbage collectors maintained by the virtual + machine. These are used to create the beans by the ManagementFactory. +* VMMemoryManagerMXBeanImpl and VMGarbageCollectorMXBeanImpl provide + low-level support for memory managers (including the specific subclass + of garbage collecting memory managers). The interfaces for these + require no more than enumerating the number of collections and the + time spent (for garbage collectors) and a relationship to the memory + pools (for all), along with a validity check. New in release 0.91 (May 15, 2006) diff --git a/configure.ac b/configure.ac index cadb814cc..6bee7cff2 100644 --- a/configure.ac +++ b/configure.ac @@ -83,6 +83,18 @@ AC_ARG_ENABLE([core-jni], AM_CONDITIONAL(CREATE_CORE_JNI_LIBRARIES, test "x${COMPILE_CORE_JNI}" = xyes) dnl ----------------------------------------------------------- +dnl Default Preference Backend +dnl ----------------------------------------------------------- +AC_ARG_ENABLE(default-preferences-peer, + AS_HELP_STRING([--enable-default-preferences-peer], + [fully qualified class name of default Preferences API Backend])) +DEFAULT_PREFS_PEER=$enable_default_preferences_peer +if test "$DEFAULT_PREFS_PEER" = ""; then + DEFAULT_PREFS_PEER=gnu.java.util.prefs.FileBasedFactory +fi +dnl AC_SUBST(DEFAULT_PREFS_PEER) + +dnl ----------------------------------------------------------- dnl GConf native peer (enabled by default) dnl ----------------------------------------------------------- AC_ARG_ENABLE([gconf-peer], @@ -100,7 +112,6 @@ dnl GTK native peer error checking dnl ----------------------------------------------------------- AC_ARG_ENABLE([gconf-peers],,AC_MSG_ERROR([No --enable-gconf-peers (or --disable-gconf-peers) option; you want --enable-gconf-peer])) - dnl ------------------------------------------------------------ dnl Whether to compile with -Werror or not (disabled by default) dnl ------------------------------------------------------------ @@ -456,6 +467,13 @@ if test "x${COMPILE_JNI}" = xyes; then PKG_CHECK_MODULES(GCONF, gconf-2.0 >= 2.11.2) AC_SUBST(GCONF_CFLAGS) AC_SUBST(GCONF_LIBS) + dnl check if the config value was given form the command line, + dnl if not, overwrite the default if we have the gconf backend + dnl compiled in + USE_GCONF_PREFS_PEER=$enable_default_preferences_peer + if test "$USE_GCONF_PREFS_PEER" = ""; then + DEFAULT_PREFS_PEER=gnu.java.util.prefs.GConfBasedFactory + fi fi dnl Check for AWT related Qt4 @@ -745,6 +763,10 @@ then fi AM_CONDITIONAL(ENABLE_LOCAL_SOCKETS, test "x$ENABLE_LOCAL_SOCKETS" = "xyes") +dnl ----------------------------------------------------------- +dnl Add the default preference peer +dnl ----------------------------------------------------------- +AC_SUBST(DEFAULT_PREFS_PEER) dnl ----------------------------------------------------------- dnl output files @@ -781,6 +803,7 @@ native/target/Makefile native/target/Linux/Makefile native/target/generic/Makefile resource/Makefile +resource/META-INF/services/java.util.prefs.PreferencesFactory scripts/Makefile scripts/classpath.spec lib/Makefile diff --git a/doc/vmintegration.texinfo b/doc/vmintegration.texinfo index d1e253696..02c81b5cf 100644 --- a/doc/vmintegration.texinfo +++ b/doc/vmintegration.texinfo @@ -203,6 +203,7 @@ implementation. * java.lang.reflect:: * gnu.java.lang:: * gnu.java.lang.management:: +* java.lang.management:: * Classpath Callbacks:: @end menu @@ -1262,7 +1263,7 @@ method calls the @code{VMInstrumentationImpl.redefineClasses} native method which must be implemented by the VM. The implementation should call the @code{InstrumentationImpl.callTransformers} method. -@node gnu.java.lang.management, Classpath Callbacks, gnu.java.lang, Classpath Hooks +@node gnu.java.lang.management, java.lang.management, gnu.java.lang, Classpath Hooks @section @code{gnu.java.lang.management} @code{gnu.java.lang.management} provides the VM interfaces for the GNU @@ -1274,6 +1275,9 @@ implementations of the management beans. * gnu.java.lang.management.VMThreadMXBeanImpl:: * gnu.java.lang.management.VMMemoryMXBeanImpl:: * gnu.java.lang.management.VMCompilationMXBeanImpl:: +* gnu.java.lang.management.VMMemoryPoolMXBeanImpl:: +* gnu.java.lang.management.VMMemoryManagerMXBeanImpl:: +* gnu.java.lang.management.VMGarbageCollectorMXBeanImpl:: @end menu @node gnu.java.lang.management.VMRuntimeMXBeanImpl,gnu.java.lang.management.VMClassLoadingMXBeanImpl,,gnu.java.lang.management @@ -1470,13 +1474,13 @@ output is turned or not, respectively. verbose memory management output to be turned on and off. @end itemize -@node gnu.java.lang.management.VMCompilationMXBeanImpl,,gnu.java.lang.management.VMMemoryMXBeanImpl,gnu.java.lang.management +@node gnu.java.lang.management.VMCompilationMXBeanImpl,gnu.java.lang.management.VMMemoryPoolMXBeanImpl,gnu.java.lang.management.VMMemoryMXBeanImpl,gnu.java.lang.management @subsection @code{gnu.java.lang.management.VMCompilationMXBeanImpl} The @code{gnu.java.lang.management.CompilationMXBeanImpl} provides an implementation of the optional @code{java.lang.management.CompilationMXBean} interface, and is supported by VM functionality in the form of -@code{gnu.java.lang.management.VMCompilatinMXBeanImpl}. This provides a +@code{gnu.java.lang.management.VMCompilationMXBeanImpl}. This provides a single method for returning the number of milliseconds the virtual machine's Just-In-Time (JIT) compiler has spent compiling. Even if a JIT compiler is available and an instance of the bean supplied, this @@ -1503,7 +1507,137 @@ Time support is implemented by the following method: number of milliseconds the JIT compiler has spent compiling. @end itemize -@node Classpath Callbacks, , gnu.java.lang.management, Classpath Hooks +@node gnu.java.lang.management.VMMemoryPoolMXBeanImpl,gnu.java.lang.management.VMMemoryManagerMXBeanImpl,gnu.java.lang.management.VMCompilationMXBeanImpl,gnu.java.lang.management +@subsection @code{gnu.java.lang.management.VMMemoryPoolMXBeanImpl} + +The @code{gnu.java.lang.management.MemoryPoolMXBeanImpl} provides an +implementation of the optional @code{java.lang.management.MemoryPoolMXBean} +interface, and is supported by VM functionality in the form of +@code{gnu.java.lang.management.VMMemoryPoolMXBeanImpl}. Providing +this interface requires implementing a number of methods for each supported +pool. These return statistics on memory usage, and, optionally, allows +monitoring of when memory usage exceedes a preset threshold. + +Optional support is determined by the following properties: + +@itemize @bullet +@item @code{gnu.java.lang.management.CollectionUsageThresholdSupport} -- +This property should be present if the VM supports setting a collection +usage threshold and monitoring when it is matched or exceeded. Collection +usage thresholds are related to the remaining memory usage following a +garbage collection cycle. +@item @code{gnu.java.lang.management.UsageThresholdSupport} -- +This property should be present if the VM supports setting a +usage threshold and monitoring when it is matched or exceeded. +@end itemize + +The methods are as follows (all take a pool name as their +first parameter): + +@itemize @bullet +@item @code{(getCollectionUsage(String))} -- Returns a +@code{java.lang.management.MemoryUsage} object, containing the +memory usage statistics following a garbage collection cycle +for the specified pool. This may also return @code{null} if +the pool isn't an appropriate pool for this particular task. +@item @code{(getCollectionUsageThreshold(String))} -- Returns +the pool's collection usage threshold, if supported. +@item @code{(getCollectionUsageThresholdCount(String))} -- Returns +the number of times the specified pool has matched or exceeded +its collection usage threshold, if supported. +@item @code{(getMemoryManagerNames(String))} -- Returns a list +of names of memory managers which manage the specified pool. +@item @code{(getPeakUsage(String))} -- Returns a +@code{java.lang.management.MemoryUsage} object for the peak +usage level of the specified pool. +@item @code{(getUsage(String))} -- Returns a +@code{java.lang.management.MemoryUsage} object for the current +usage level of the specified pool. +@item @code{(getUsageThreshold(String))} -- Returns +the pool's usage threshold, if supported. +@item @code{(getUsageThresholdCount(String))} -- Returns +the number of times the specified pool has matched or exceeded +its usage threshold, if supported. +@item @code{(isValid(String))} -- Returns true if the pool +is still in use by the virtual machine. +@item @code{(resetPeakUsage(String))} -- Resets the peak usage +levels to the current usage levels for the specified pool. +@item @code{(setCollectionUsageThreshold(String, long))} -- Sets +the pool's collection usage threshold, if supported. +@item @code{(setUsageThreshold(String, long))} -- Sets +the pool's usage threshold, if supported. +@end itemize + +@node gnu.java.lang.management.VMMemoryManagerMXBeanImpl,gnu.java.lang.management.VMGarbageCollectorMXBeanImpl,gnu.java.lang.management.VMMemoryPoolMXBeanImpl,gnu.java.lang.management +@subsection @code{gnu.java.lang.management.VMMemoryManagerMXBeanImpl} + +The @code{gnu.java.lang.management.MemoryManagerMXBeanImpl} provides an +implementation of the optional @code{java.lang.management.MemoryManagerMXBean} +interface, and is supported by VM functionality in the form of +@code{gnu.java.lang.management.VMMemoryManagerMXBeanImpl}. Providing +this interface requires implementing two methods (each takes the name +of the manager as the first argument): + +@itemize @bullet +@item @code{(getMemoryPoolNames(String))} -- Returns a list of the +memory pools that the manager maintains. A default implementation +which scans the results of @code{getMemoryManagerNames()} for each +pool is provided. +@item @code{(isValid(String))} -- Returns true if the specified +manager is still valid i.e. it is still in use by the virtual machine. +@end itemize + +@node gnu.java.lang.management.VMGarbageCollectorMXBeanImpl,,gnu.java.lang.management.VMMemoryManagerMXBeanImpl,gnu.java.lang.management +@subsection @code{gnu.java.lang.management.VMGarbageCollectorMXBeanImpl} + +The @code{gnu.java.lang.management.GarbageCollectorMXBeanImpl} provides an +implementation of the optional @code{java.lang.management.GarbageCollectorMXBean} +interface, and is supported by VM functionality in the form of +@code{gnu.java.lang.management.VMGarbageCollectorMXBeanImpl}. Providing +this interface requires implementing two methods (each takes the name +of the garbage collector as the first argument): + +@itemize @bullet +@item @code{(getCollectionCount(String))} -- Returns the number of +times the specified garbage collector has run. +@item @code{(getCollectionTime(String))} -- Returns the accumulated +number of milliseconds for which the garbage collector has run. +@end itemize + +Note that each garbage collector is also a memory manager, and so an +implementation of the @xref{gnu.java.lang.management.VMMemoryManagerMXBeanImpl} +methods for its name should also be provided. + +@node java.lang.management, Classpath Callbacks, gnu.java.lang.management, Classpath Hooks +@section @code{java.lang.management} + +@code{gnu.java.lang.management} provides the VM interfaces for the GNU +implementations of the management beans. + +@menu +* java.lang.management.VMManagementFactory:: +@end menu + +@node java.lang.management.VMManagementFactory,,,java.lang.management +@subsection @code{java.lang.management.VMManagementFactory} + +This VM interface provides the names of the memory pools, memory managers +and garbage collectors for use by the @code{java.lang.management.ManagementFactory} +in creating lists of appropriate beans for these types of managed object. + +The methods are as follows: + +@itemize @bullet +@item @code{(getMemoryPoolNames())} -- Returns a list of the names +of the current memory pools in use by the virtual machine. +@item @code{(getMemoryManagerNames())} -- Returns a list of the names +of the current memory managers in use by the virtual machine. This +should not include those that are also garbage collectors. +@item @code{(getGarbageCollectorNames())} -- Returns a list of the names +of the current garbage collectors in use by the virtual machine. +@end itemize + +@node Classpath Callbacks, , java.lang.management, Classpath Hooks Some of the classes you implement for the VM will need to call back to package-private methods in Classpath: diff --git a/examples/gnu/classpath/examples/management/TestGarbageCollector.java b/examples/gnu/classpath/examples/management/TestGarbageCollector.java new file mode 100644 index 000000000..5d6d56797 --- /dev/null +++ b/examples/gnu/classpath/examples/management/TestGarbageCollector.java @@ -0,0 +1,53 @@ +/* TestGarbageCollector.java -- Tests the garbage collector beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; + +import java.util.Arrays; +import java.util.Iterator; + +public class TestGarbageCollector +{ + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getGarbageCollectorMXBeans().iterator(); + while (beans.hasNext()) + { + GarbageCollectorMXBean bean = (GarbageCollectorMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Memory pool names: " + + Arrays.toString(bean.getMemoryPoolNames())); + System.out.println("Is valid: " + + (bean.isValid() ? "yes" : "no")); + System.out.println("Collection count: " + + bean.getCollectionCount()); + System.out.println("Collection time: " + + bean.getCollectionTime() + "ms"); + } + } +} + + + diff --git a/examples/gnu/classpath/examples/management/TestMemoryManager.java b/examples/gnu/classpath/examples/management/TestMemoryManager.java new file mode 100644 index 000000000..30a0c985b --- /dev/null +++ b/examples/gnu/classpath/examples/management/TestMemoryManager.java @@ -0,0 +1,49 @@ +/* TestMemoryManager.java -- Tests the memory manager beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryManagerMXBean; + +import java.util.Arrays; +import java.util.Iterator; + +public class TestMemoryManager +{ + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getMemoryManagerMXBeans().iterator(); + while (beans.hasNext()) + { + MemoryManagerMXBean bean = (MemoryManagerMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Memory pool names: " + + Arrays.toString(bean.getMemoryPoolNames())); + System.out.println("Is valid: " + + (bean.isValid() ? "yes" : "no")); + } + } +} + + + diff --git a/examples/gnu/classpath/examples/management/TestMemoryPool.java b/examples/gnu/classpath/examples/management/TestMemoryPool.java new file mode 100644 index 000000000..2476ed76f --- /dev/null +++ b/examples/gnu/classpath/examples/management/TestMemoryPool.java @@ -0,0 +1,93 @@ +/* TestMemoryPool.java -- Tests the memory pool beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryPoolMXBean; +import java.lang.management.MemoryUsage; + +import java.util.Arrays; +import java.util.Iterator; + +public class TestMemoryPool +{ + + /** + * 1mb in bytes + */ + private static final int MB = 1 << 20; + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getMemoryPoolMXBeans().iterator(); + while (beans.hasNext()) + { + MemoryPoolMXBean bean = (MemoryPoolMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Collection usage: " + bean.getCollectionUsage()); + boolean collectionUsage = bean.isCollectionUsageThresholdSupported(); + System.out.println("Collection usage threshold supported: " + + collectionUsage); + if (collectionUsage) + { + System.out.println("Collection usage threshold: " + + bean.getCollectionUsageThreshold()); + System.out.println("Setting collection usage threshold to 1MB (" + + MB + " bytes)"); + bean.setCollectionUsageThreshold(MB); + System.out.println("Collection usage threshold: " + + bean.getCollectionUsageThreshold()); + System.out.println("Collection usage threshold count: " + + bean.getCollectionUsageThresholdCount()); + System.out.println("Collection usage threshold exceeded: " + + (bean.isCollectionUsageThresholdExceeded() + ? "yes" : "no")); + } + System.out.println("Memory manager names: " + + Arrays.toString(bean.getMemoryManagerNames())); + System.out.println("Peak usage: " + bean.getPeakUsage()); + System.out.println("Current usage: " + bean.getUsage()); + System.out.println("Resetting peak usage..."); + bean.resetPeakUsage(); + System.out.println("Peak usage: " + bean.getPeakUsage()); + System.out.println("Current usage: " + bean.getUsage()); + boolean usage = bean.isUsageThresholdSupported(); + System.out.println("Usage threshold supported: " + usage); + if (usage) + { + System.out.println("Usage threshold: " + + bean.getUsageThreshold()); + System.out.println("Setting usage threshold to 1MB (" + + MB + " bytes)"); + bean.setUsageThreshold(MB); + System.out.println("Usage threshold: " + + bean.getUsageThreshold()); + System.out.println("Usage threshold count: " + + bean.getUsageThresholdCount()); + System.out.println("Usage threshold exceeded: " + + (bean.isUsageThresholdExceeded() + ? "yes" : "no")); + } + System.out.println("Valid: " + (bean.isValid() ? "yes" : "no")); + } + } +} diff --git a/examples/gnu/classpath/examples/swing/HtmlDemo.java b/examples/gnu/classpath/examples/swing/HtmlDemo.java index 6ac626717..988b0bd0e 100644 --- a/examples/gnu/classpath/examples/swing/HtmlDemo.java +++ b/examples/gnu/classpath/examples/swing/HtmlDemo.java @@ -63,8 +63,12 @@ public class HtmlDemo extends JPanel JTextPane html = new JTextPane(); - //JTextArea text = new JTextArea("<html><body><p><img src='' alt='alt txt'></p></body></html>"); - JTextArea text = new JTextArea("<html><body><p>nor<font color=red>ma</font>l<sup>sup</sup>normal<sub>sub</sub>normal</p></body></html>"); + JTextArea text = new JTextArea("<html><body><p>" + + "123456789HR!<hr>987654321"+ + "123456789BR!<br>987654321"+ + "<font color=red>ma</font>"+ + "<sup>sup</sup>normal<sub>sub</sub>normal</p><p>Table:"+ + "<table><tr>a<td>b<td>c<tr>x<td>y<td>z</table></body></html>"); JPanel buttons; diff --git a/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java b/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java index 9d797d203..527fe455e 100644 --- a/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java +++ b/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java @@ -66,17 +66,17 @@ public class TabbedPaneDemo JPanel p = new JPanel(); p.setLayout(new GridLayout(2, 2)); JTabbedPane tabs1 = new JTabbedPane(SwingConstants.TOP); - tabs1.add("Top Item 1", new JButton("Button")); - tabs1.add("Top Item 2", new JButton("Button")); + tabs1.add("Top Item 1", new JButton("Content: Top Item 1")); + tabs1.add("Top Item 2", new JButton("Content: Top Item 2")); JTabbedPane tabs2 = new JTabbedPane(SwingConstants.LEFT); - tabs2.add("Left Item 1", new JButton("Button")); - tabs2.add("Left Item 2", new JButton("Button")); + tabs2.add("Left Item 1", new JButton("Content: Left Item 1")); + tabs2.add("Left Item 2", new JButton("Content: Left Item 2")); JTabbedPane tabs3 = new JTabbedPane(SwingConstants.BOTTOM); - tabs3.add("Bottom Item 1", new JButton("Button")); - tabs3.add("Bottom Item 2", new JButton("Button")); + tabs3.add("Bottom Item 1", new JButton("Content: Bottom Item 1")); + tabs3.add("Bottom Item 2", new JButton("Content: Bottom Item 2")); JTabbedPane tabs4 = new JTabbedPane(SwingConstants.RIGHT); - tabs4.add("Right Item 1", new JButton("Button")); - tabs4.add("Right Item 2", new JButton("Button")); + tabs4.add("Right Item 1", new JButton("Content: Right Item 1")); + tabs4.add("Right Item 2", new JButton("Content: Right Item 2")); p.add(tabs1); p.add(tabs2); p.add(tabs3); diff --git a/external/jsr166/.cvsignore b/external/jsr166/.cvsignore new file mode 100644 index 000000000..70845e08e --- /dev/null +++ b/external/jsr166/.cvsignore @@ -0,0 +1 @@ +Makefile.in diff --git a/gnu/java/awt/dnd/GtkMouseDragGestureRecognizer.java b/gnu/java/awt/dnd/GtkMouseDragGestureRecognizer.java new file mode 100644 index 000000000..889f258fb --- /dev/null +++ b/gnu/java/awt/dnd/GtkMouseDragGestureRecognizer.java @@ -0,0 +1,110 @@ +/* GtkMouseDragGestureRecognizer.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.java.awt.dnd; + +import java.awt.Component; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.MouseDragGestureRecognizer; +import java.awt.event.MouseEvent; + +public class GtkMouseDragGestureRecognizer + extends MouseDragGestureRecognizer +{ + + DragSource ds; + Component c; + int actions; + DragGestureListener dgl; + + GtkMouseDragGestureRecognizer() + { + super(null); + } + + public GtkMouseDragGestureRecognizer (DragSource ds, Component c, int act, + DragGestureListener dgl) + { + super (ds, c, act, dgl); + + registerListeners(); + + this.ds = ds; + this.c = c; + this.actions = act; + this.dgl = dgl; + } + + public void mouseClicked (MouseEvent e) + { + // FIXME: Not Implemented + } + + public void mousePressed (MouseEvent e) + { + // FIXME: Not Implemented + } + + public void mouseReleased (MouseEvent e) + { + // FIXME: Not Implemented + } + + public void mouseEntered (MouseEvent e) + { + // FIXME: Not Implemented + } + + public void mouseExited (MouseEvent e) + { + // FIXME: Not Implemented + } + + public void mouseDragged(MouseEvent e) + { + dgl.dragGestureRecognized(new DragGestureEvent(this, actions, e.getPoint(), + events)); + } + + public void mouseMoved (MouseEvent e) + { + // FIXME: Not Implemented + } +} diff --git a/gnu/java/awt/dnd/peer/gtk/GtkDragSourceContextPeer.java b/gnu/java/awt/dnd/peer/gtk/GtkDragSourceContextPeer.java new file mode 100644 index 000000000..873027290 --- /dev/null +++ b/gnu/java/awt/dnd/peer/gtk/GtkDragSourceContextPeer.java @@ -0,0 +1,81 @@ +/* GtkDragSourceContextPeer.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.java.awt.dnd.peer.gtk; + +import java.awt.Cursor; +import java.awt.Image; +import java.awt.Point; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragSourceContext; +import java.awt.dnd.InvalidDnDOperationException; +import java.awt.dnd.peer.DragSourceContextPeer; + +public class GtkDragSourceContextPeer + implements DragSourceContextPeer +{ + + private DragGestureEvent dge; + + public GtkDragSourceContextPeer(DragGestureEvent e) + { + dge = e; + } + + public void startDrag(DragSourceContext context, Cursor c, Image i, Point p) + throws InvalidDnDOperationException + { + // FIXME: Not Implemented + } + + public Cursor getCursor() + { + // FIXME: Not Implemented + return null; + } + + public void setCursor(Cursor c) throws InvalidDnDOperationException + { + // FIXME: Not Implemented + } + + public void transferablesFlavorsChanged() + { + // FIXME: Not Implemented + } +} diff --git a/gnu/java/awt/dnd/peer/gtk/GtkDropTargetContextPeer.java b/gnu/java/awt/dnd/peer/gtk/GtkDropTargetContextPeer.java new file mode 100644 index 000000000..421503e43 --- /dev/null +++ b/gnu/java/awt/dnd/peer/gtk/GtkDropTargetContextPeer.java @@ -0,0 +1,117 @@ +/* GtkDropTargetContextPeer.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.java.awt.dnd.peer.gtk; + +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.dnd.DropTarget; +import java.awt.dnd.InvalidDnDOperationException; +import java.awt.dnd.peer.DropTargetContextPeer; + +public class GtkDropTargetContextPeer + implements DropTargetContextPeer +{ + + public void setTargetActions(int actions) + { + // FIXME: Not Implemented + + } + + public int getTargetActions() + { + // FIXME: Not Implemented + return 0; + } + + public DropTarget getDropTarget() + { + // FIXME: Not Implemented + return null; + } + + public DataFlavor[] getTransferDataFlavors() + { + // FIXME: Not Implemented + return null; + } + + public Transferable getTransferable() throws InvalidDnDOperationException + { + // FIXME: Not Implemented + return null; + } + + public boolean isTransferableJVMLocal() + { + // FIXME: Not Implemented + return false; + } + + public void acceptDrag(int dragAction) + { + // FIXME: Not Implemented + + } + + public void rejectDrag() + { + // FIXME: Not Implemented + + } + + public void acceptDrop(int dropAction) + { + // FIXME: Not Implemented + + } + + public void rejectDrop() + { + // FIXME: Not Implemented + + } + + public void dropComplete(boolean success) + { + // FIXME: Not Implemented + + } + +} diff --git a/gnu/java/awt/dnd/peer/gtk/GtkDropTargetPeer.java b/gnu/java/awt/dnd/peer/gtk/GtkDropTargetPeer.java new file mode 100644 index 000000000..d7ed26dae --- /dev/null +++ b/gnu/java/awt/dnd/peer/gtk/GtkDropTargetPeer.java @@ -0,0 +1,60 @@ +/* GtkDropTargetPeer.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.java.awt.dnd.peer.gtk; + +import java.awt.dnd.DropTarget; +import java.awt.dnd.peer.DropTargetPeer; + +public class GtkDropTargetPeer + implements DropTargetPeer +{ + + public void addDropTarget(DropTarget target) + { + // FIXME: Not Implemented + + } + + public void removeDropTarget(DropTarget target) + { + // FIXME: Not Implemented + + } + +} diff --git a/gnu/java/awt/peer/gtk/GtkToolkit.java b/gnu/java/awt/peer/gtk/GtkToolkit.java index f0ac471f9..fdd7e09cb 100644 --- a/gnu/java/awt/peer/gtk/GtkToolkit.java +++ b/gnu/java/awt/peer/gtk/GtkToolkit.java @@ -39,31 +39,82 @@ exception statement from your version. */ package gnu.java.awt.peer.gtk; -import gnu.classpath.Configuration; import gnu.java.awt.EmbeddedWindow; +import gnu.java.awt.dnd.GtkMouseDragGestureRecognizer; +import gnu.java.awt.dnd.peer.gtk.GtkDragSourceContextPeer; import gnu.java.awt.peer.ClasspathFontPeer; import gnu.java.awt.peer.EmbeddedWindowPeer; -import java.awt.*; +import java.awt.AWTException; +import java.awt.Button; +import java.awt.Canvas; +import java.awt.Checkbox; +import java.awt.CheckboxMenuItem; +import java.awt.Choice; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.FileDialog; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Frame; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Image; +import java.awt.Label; +import java.awt.List; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.Panel; +import java.awt.Point; +import java.awt.PopupMenu; +import java.awt.PrintJob; +import java.awt.Rectangle; +import java.awt.ScrollPane; +import java.awt.Scrollbar; +import java.awt.TextArea; +import java.awt.TextField; +import java.awt.Window; import java.awt.datatransfer.Clipboard; import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragGestureRecognizer; +import java.awt.dnd.DragSource; import java.awt.dnd.peer.DragSourceContextPeer; -import java.awt.font.FontRenderContext; import java.awt.im.InputMethodHighlight; -import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DirectColorModel; -import java.awt.image.ImageConsumer; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; -import java.awt.peer.*; +import java.awt.peer.ButtonPeer; +import java.awt.peer.CanvasPeer; +import java.awt.peer.CheckboxMenuItemPeer; +import java.awt.peer.CheckboxPeer; +import java.awt.peer.ChoicePeer; +import java.awt.peer.DialogPeer; +import java.awt.peer.FileDialogPeer; +import java.awt.peer.FontPeer; +import java.awt.peer.FramePeer; +import java.awt.peer.LabelPeer; +import java.awt.peer.ListPeer; +import java.awt.peer.MenuBarPeer; +import java.awt.peer.MenuItemPeer; +import java.awt.peer.MenuPeer; +import java.awt.peer.PanelPeer; +import java.awt.peer.PopupMenuPeer; +import java.awt.peer.RobotPeer; +import java.awt.peer.ScrollPanePeer; +import java.awt.peer.ScrollbarPeer; +import java.awt.peer.TextAreaPeer; +import java.awt.peer.TextFieldPeer; +import java.awt.peer.WindowPeer; import java.io.InputStream; import java.net.URL; -import java.text.AttributedString; import java.util.HashMap; -import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; @@ -553,7 +604,18 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent e) { - throw new Error("not implemented"); + return new GtkDragSourceContextPeer(e); + } + + public DragGestureRecognizer createDragGestureRecognizer(Class recognizer, + DragSource ds, + Component comp, + int actions, + DragGestureListener l) + { + if (recognizer.getName().equals("java.awt.dnd.MouseDragGestureRecognizer")) + return new GtkMouseDragGestureRecognizer(ds, comp, actions, l); + return null; } public Map mapInputMethodHighlight(InputMethodHighlight highlight) diff --git a/gnu/java/lang/management/GarbageCollectorMXBeanImpl.java b/gnu/java/lang/management/GarbageCollectorMXBeanImpl.java new file mode 100644 index 000000000..19db8df1b --- /dev/null +++ b/gnu/java/lang/management/GarbageCollectorMXBeanImpl.java @@ -0,0 +1,77 @@ +/* GarbageCollectorMXBeanImpl.java - Implementation of a GC bean + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.java.lang.management; + +import java.lang.management.GarbageCollectorMXBean; + +/** + * Provides access to information about one of the garbage + * collectors used by the current invocation of the + * virtual machine. An instance of this bean for each garbage + * collector is obtained by calling + * {@link ManagementFactory#getGarbageCollectorMXBeans()}. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public final class GarbageCollectorMXBeanImpl + extends MemoryManagerMXBeanImpl + implements GarbageCollectorMXBean +{ + + /** + * Constructs a new <code>GarbageCollectorMXBeanImpl</code>. + * + * @param name the name of the garbage collector this bean represents. + */ + public GarbageCollectorMXBeanImpl(String name) + { + super(name); + } + + public long getCollectionCount() + { + return VMGarbageCollectorMXBeanImpl.getCollectionCount(name); + } + + public long getCollectionTime() + { + return VMGarbageCollectorMXBeanImpl.getCollectionTime(name); + } + +} diff --git a/gnu/java/lang/management/MemoryManagerMXBeanImpl.java b/gnu/java/lang/management/MemoryManagerMXBeanImpl.java new file mode 100644 index 000000000..2c6d4472a --- /dev/null +++ b/gnu/java/lang/management/MemoryManagerMXBeanImpl.java @@ -0,0 +1,87 @@ +/* MemoryManagerMXBeanImpl.java - Implementation of a memory manager bean + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.java.lang.management; + +import java.lang.management.MemoryManagerMXBean; + +/** + * Provides access to information about one of the memory + * managers used by the current invocation of the + * virtual machine. An instance of this bean for each memory + * manager is obtained by calling + * {@link ManagementFactory#getMemoryPoolMXBeans()}. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public class MemoryManagerMXBeanImpl + extends BeanImpl + implements MemoryManagerMXBean +{ + + /** + * The name of the memory manager. + */ + protected String name; + + /** + * Constructs a new <code>MemoryManagerMXBeanImpl</code>. + * + * @param name the name of the manager this bean represents. + */ + public MemoryManagerMXBeanImpl(String name) + { + this.name = name; + } + + public String[] getMemoryPoolNames() + { + return VMMemoryManagerMXBeanImpl.getMemoryPoolNames(name); + } + + public String getName() + { + return name; + } + + public boolean isValid() + { + return VMMemoryManagerMXBeanImpl.isValid(name); + } + +} diff --git a/gnu/java/lang/management/MemoryPoolMXBeanImpl.java b/gnu/java/lang/management/MemoryPoolMXBeanImpl.java new file mode 100644 index 000000000..af718e3ff --- /dev/null +++ b/gnu/java/lang/management/MemoryPoolMXBeanImpl.java @@ -0,0 +1,212 @@ +/* MemoryPoolMXBeanImpl.java - Implementation of a memory pool bean + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.java.lang.management; + +import gnu.classpath.SystemProperties; + +import java.lang.management.MemoryPoolMXBean; +import java.lang.management.MemoryUsage; + +/** + * Provides access to information about one of the memory + * resources or pools used by the current invocation of the + * virtual machine. An instance of this bean for each memory + * pool is obtained by calling + * {@link ManagementFactory#getMemoryPoolMXBeans()}. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public final class MemoryPoolMXBeanImpl + extends BeanImpl + implements MemoryPoolMXBean +{ + + /** + * The name of the pool. + */ + private String name; + + /** + * Constant for collection usage threshold. + */ + private static final String COLLECTION_USAGE_THRESHOLD = + "gnu.java.lang.management.CollectionUsageThresholdSupport"; + + /** + * Constant for thread time support. + */ + private static final String USAGE_THRESHOLD = + "gnu.java.lang.management.UsageThresholdSupport"; + + /** + * Constructs a new <code>MemoryPoolMXBeanImpl</code>. + * + * @param name the name of the pool this bean represents. + */ + public MemoryPoolMXBeanImpl(String name) + { + this.name = name; + } + + public MemoryUsage getCollectionUsage() + { + return VMMemoryPoolMXBeanImpl.getCollectionUsage(name); + } + + public long getCollectionUsageThreshold() + { + if (isCollectionUsageThresholdSupported()) + return VMMemoryPoolMXBeanImpl.getCollectionUsageThreshold(name); + else + throw new UnsupportedOperationException("A collection usage "+ + "threshold is not supported."); + } + + public long getCollectionUsageThresholdCount() + { + if (isCollectionUsageThresholdSupported()) + return VMMemoryPoolMXBeanImpl.getCollectionUsageThresholdCount(name); + else + throw new UnsupportedOperationException("A collection usage "+ + "threshold is not supported."); + } + + public String[] getMemoryManagerNames() + { + return VMMemoryPoolMXBeanImpl.getMemoryManagerNames(name); + } + + public String getName() + { + return name; + } + + public MemoryUsage getPeakUsage() + { + if (isValid()) + return VMMemoryPoolMXBeanImpl.getPeakUsage(name); + else + return null; + } + + public MemoryUsage getUsage() + { + if (isValid()) + return VMMemoryPoolMXBeanImpl.getUsage(name); + else + return null; + } + + public long getUsageThreshold() + { + if (isUsageThresholdSupported()) + return VMMemoryPoolMXBeanImpl.getUsageThreshold(name); + else + throw new UnsupportedOperationException("A usage threshold " + + "is not supported."); + } + + public long getUsageThresholdCount() + { + if (isUsageThresholdSupported()) + return VMMemoryPoolMXBeanImpl.getUsageThresholdCount(name); + else + throw new UnsupportedOperationException("A usage threshold " + + "is not supported."); + } + + public boolean isCollectionUsageThresholdExceeded() + { + return getCollectionUsage().getUsed() >= getCollectionUsageThreshold(); + } + + public boolean isCollectionUsageThresholdSupported() + { + return SystemProperties.getProperty(COLLECTION_USAGE_THRESHOLD) != null; + } + + public boolean isUsageThresholdExceeded() + { + return getUsage().getUsed() >= getUsageThreshold(); + } + + public boolean isUsageThresholdSupported() + { + return SystemProperties.getProperty(USAGE_THRESHOLD) != null; + } + + public boolean isValid() + { + return VMMemoryPoolMXBeanImpl.isValid(name); + } + + public void resetPeakUsage() + { + checkControlPermissions(); + VMMemoryPoolMXBeanImpl.resetPeakUsage(name); + } + + public void setCollectionUsageThreshold(long threshold) + { + checkControlPermissions(); + if (threshold < 0) + throw new IllegalArgumentException("Threshold of " + threshold + + "is less than zero."); + if (isCollectionUsageThresholdSupported()) + VMMemoryPoolMXBeanImpl.setCollectionUsageThreshold(name, threshold); + else + throw new UnsupportedOperationException("A collection usage "+ + "threshold is not supported."); + } + + public void setUsageThreshold(long threshold) + { + checkControlPermissions(); + if (threshold < 0) + throw new IllegalArgumentException("Threshold of " + threshold + + "is less than zero."); + if (isUsageThresholdSupported()) + VMMemoryPoolMXBeanImpl.setUsageThreshold(name, threshold); + else + throw new UnsupportedOperationException("A usage threshold " + + "is not supported."); + } + +} + diff --git a/gnu/java/rmi/server/ActivatableServerRef.java b/gnu/java/rmi/server/ActivatableServerRef.java index 09595ec5f..5b7dadfd2 100644 --- a/gnu/java/rmi/server/ActivatableServerRef.java +++ b/gnu/java/rmi/server/ActivatableServerRef.java @@ -178,7 +178,7 @@ public class ActivatableServerRef extends UnicastServerRef Class cls = aClass; // where ist the _Stub? (check superclasses also) - Class expCls = expCls = findStubSkelClass(cls); + Class expCls = findStubSkelClass(cls); if (expCls != null) { diff --git a/gnu/java/rmi/server/UnicastServerRef.java b/gnu/java/rmi/server/UnicastServerRef.java index cd891a1aa..2f7cb9a2d 100644 --- a/gnu/java/rmi/server/UnicastServerRef.java +++ b/gnu/java/rmi/server/UnicastServerRef.java @@ -150,7 +150,7 @@ public class UnicastServerRef Class cls = obj.getClass(); // where ist the _Stub? (check superclasses also) - Class expCls = expCls = findStubSkelClass(cls); + Class expCls = findStubSkelClass(cls); if (expCls != null) { diff --git a/gnu/java/util/prefs/EventDispatcher.java b/gnu/java/util/prefs/EventDispatcher.java index feabe4dce..ecddd3a55 100644 --- a/gnu/java/util/prefs/EventDispatcher.java +++ b/gnu/java/util/prefs/EventDispatcher.java @@ -74,7 +74,7 @@ public class EventDispatcher extends Thread { try { - wait(); + queue.wait(); } catch (InterruptedException _) { @@ -107,6 +107,7 @@ public class EventDispatcher extends Thread synchronized (queue) { queue.add(runner); + queue.notify(); } } } diff --git a/gnu/java/util/prefs/GConfBasedPreferences.java b/gnu/java/util/prefs/GConfBasedPreferences.java index cbedac5c8..5702751cf 100644 --- a/gnu/java/util/prefs/GConfBasedPreferences.java +++ b/gnu/java/util/prefs/GConfBasedPreferences.java @@ -72,6 +72,7 @@ import java.util.prefs.BackingStoreException; * <br /> * * @author Mario Torre <neugens@limasoftware.net> + * @version 1.0.1 */ public class GConfBasedPreferences extends AbstractPreferences @@ -84,7 +85,7 @@ public class GConfBasedPreferences private static GConfNativePeer backend = new GConfNativePeer(); /** Default user root path */ - private static final String DEFAULT_USER_ROOT = "/apps/java"; + private static final String DEFAULT_USER_ROOT = "/apps/classpath"; /** Default system root path */ private static final String DEFAULT_SYSTEM_ROOT = "/system"; @@ -129,7 +130,13 @@ public class GConfBasedPreferences this.isUser = isUser; // stores the fully qualified name of this node - this.node = this.getRealRoot(isUser) + this.absolutePath(); + String absolutePath = this.absolutePath(); + if (absolutePath != null && absolutePath.endsWith("/")) + { + absolutePath = absolutePath.substring(0, absolutePath.length() - 1); + } + + this.node = this.getRealRoot(isUser) + absolutePath; boolean nodeExist = backend.nodeExist(this.node); @@ -356,9 +363,8 @@ public class GConfBasedPreferences */ private String getGConfKey(String key) { - String nodeName = ""; - + if (this.node.endsWith("/")) { nodeName = this.node + key; diff --git a/gnu/java/util/prefs/gconf/GConfNativePeer.java b/gnu/java/util/prefs/gconf/GConfNativePeer.java index 8d773f916..f1cb62787 100644 --- a/gnu/java/util/prefs/gconf/GConfNativePeer.java +++ b/gnu/java/util/prefs/gconf/GConfNativePeer.java @@ -45,7 +45,7 @@ import java.util.prefs.BackingStoreException; * Native peer for GConf based preference backend. * * @author Mario Torre <neugens@limasoftware.net> - * @version 1.0 + * @version 1.0.1 */ public final class GConfNativePeer { @@ -73,10 +73,6 @@ public final class GConfNativePeer */ public boolean nodeExist(String node) { - if (node.endsWith("/")) - { - node = node.substring(0, node.length() - 1); - } return gconf_client_dir_exists(node); } @@ -89,10 +85,6 @@ public final class GConfNativePeer */ public void startWatchingNode(String node) { - if (node.endsWith("/")) - { - node = node.substring(0, node.length() - 1); - } gconf_client_add_dir(node); } @@ -105,16 +97,14 @@ public final class GConfNativePeer */ public void stopWatchingNode(String node) { - if (node.endsWith("/")) - { - node = node.substring(0, node.length() - 1); - } gconf_client_remove_dir(node); } /** * Change the value of key to val. Automatically creates the key if it didn't * exist before (ie it was unset or it only had a default value). + * Key names must be valid GConf key names, that is, there can be more + * restrictions than for normal Preference Backend. * * @param key the key to alter (or add). * @param value the new value for this key. @@ -122,10 +112,6 @@ public final class GConfNativePeer */ public boolean setString(String key, String value) { - if (key.endsWith("/")) - { - key = key.substring(0, key.length() - 1); - } return gconf_client_set_string(key, value); } @@ -139,10 +125,6 @@ public final class GConfNativePeer */ public boolean unset(String key) { - if (key.endsWith("/")) - { - key = key.substring(0, key.length() - 1); - } return gconf_client_unset(key); } @@ -154,16 +136,12 @@ public final class GConfNativePeer */ public String getKey(String key) { - if (key.endsWith("/")) - { - key = key.substring(0, key.length() - 1); - } return gconf_client_get_string(key); } /** * Lists the key in the given node. Does not list subnodes. Keys names are the - * stripped names (name relative to the current node) of the kyes stored in + * stripped names (name relative to the current node) of the keys stored in * this node. * * @param node the node where keys are stored. @@ -172,10 +150,6 @@ public final class GConfNativePeer */ public List getKeys(String node) throws BackingStoreException { - if (node.endsWith("/")) - { - node = node.substring(0, node.length() - 1); - } return gconf_client_gconf_client_all_keys(node); } @@ -188,10 +162,6 @@ public final class GConfNativePeer */ public List getChildrenNodes(String node) throws BackingStoreException { - if (node.endsWith("/")) - { - node = node.substring(0, node.length() - 1); - } return gconf_client_gconf_client_all_nodes(node); } @@ -226,33 +196,99 @@ public final class GConfNativePeer * the main java class. */ - /** */ + /** + * Initialize the GConf native peer and enable the object cache. + * It is meant to be used by the static initializer. + */ native static final private void init_id_cache(); + /** + * Initialize the GConf native peer. This is meant to be used by the + * class constructor. + */ native static final private void init_class(); + /** + * Class finalizer. + */ native static final private void finalize_class(); + /** + * Queries the GConf database to see if the given node exists, returning + * true if the node exist, false otherwise. + * + * @param node the node to query for existence. + * @return true if the node exist, false otherwise. + */ native static final protected boolean gconf_client_dir_exists(String node); + /** + * Adds the given node to the list of nodes that GConf watches for + * changes. + * + * @param node the node to watch for changes. + */ native static final protected void gconf_client_add_dir(String node); + /** + * Removes the given node from the list of nodes that GConf watches for + * changes. + * + * @param node the node to remove from from the list of watched nodes. + */ native static final protected void gconf_client_remove_dir(String node); + /** + * Sets the given key/value pair into the GConf database. + * The key must be a valid GConf key. + * + * @param key the key to store in the GConf database + * @param value the value to associate to the given key. + * @return true if the change has effect, false otherwise. + */ native static final protected boolean gconf_client_set_string(String key, String value); + /** + * Returns the key associated to the given key. Null is returned if the + * key is not valid. + * + * @param key the key to return the value of. + * @return The value associated to the given key, or null. + */ native static final protected String gconf_client_get_string(String key); + /** + * Usets the given key, removing the key from the database. + * + * @param key the key to remove. + * @return true if the operation success, false otherwise. + */ native static final protected boolean gconf_client_unset(String key); + /** + * Suggest to the GConf native peer a sync with the database. + * + */ native static final protected void gconf_client_suggest_sync(); - native static final protected List gconf_client_gconf_client_all_nodes( - String node); + /** + * Returns a list of all nodes under the given node. + * + * @param node the source node. + * @return A list of nodes under the given source node. + */ + native + static final protected List gconf_client_gconf_client_all_nodes(String node); - native static final protected List gconf_client_gconf_client_all_keys( - String node); + /** + * Returns a list of all keys stored in the given node. + * + * @param node the source node. + * @return A list of all keys stored in the given node. + */ + native + static final protected List gconf_client_gconf_client_all_keys(String node); static { diff --git a/gnu/javax/crypto/RSACipherImpl.java b/gnu/javax/crypto/RSACipherImpl.java index 9c8c52931..90fde9d7b 100644 --- a/gnu/javax/crypto/RSACipherImpl.java +++ b/gnu/javax/crypto/RSACipherImpl.java @@ -1,5 +1,5 @@ -/* DiffieHellmanImpl.java -- implementation of the Diffie-Hellman key agreement. - Copyright (C) 2005 Free Software Foundation, Inc. +/* RSACipherImpl.java -- + Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -43,21 +43,16 @@ import gnu.classpath.debug.Component; import gnu.classpath.debug.SystemLogger; import java.math.BigInteger; - import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; - import java.security.interfaces.RSAKey; -import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; - import java.security.spec.AlgorithmParameterSpec; - import java.util.logging.Logger; import javax.crypto.BadPaddingException; @@ -67,10 +62,10 @@ import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; -public class RSACipherImpl extends CipherSpi +public class RSACipherImpl + extends CipherSpi { private static final Logger logger = SystemLogger.SYSTEM; - private static final byte[] EMPTY = new byte[0]; private int opmode = -1; private RSAPrivateKey decipherKey = null; @@ -80,48 +75,44 @@ public class RSACipherImpl extends CipherSpi private byte[] dataBuffer = null; private int pos = 0; - protected void engineSetMode (String mode) throws NoSuchAlgorithmException + protected void engineSetMode(String mode) throws NoSuchAlgorithmException { - throw new NoSuchAlgorithmException ("only one mode available"); + throw new NoSuchAlgorithmException("only one mode available"); } - protected void engineSetPadding (String pad) throws NoSuchPaddingException + protected void engineSetPadding(String pad) throws NoSuchPaddingException { - throw new NoSuchPaddingException ("only one padding available"); + throw new NoSuchPaddingException("only one padding available"); } - protected int engineGetBlockSize () + protected int engineGetBlockSize() { return 1; } - protected int engineGetOutputSize (int inputLen) + protected int engineGetOutputSize(int inputLen) { int outputLen = 0; if (decipherKey != null) - { - outputLen = (decipherKey.getModulus ().bitLength () + 7) / 8; - } + outputLen = (decipherKey.getModulus().bitLength() + 7) / 8; else if (encipherKey != null) - { - outputLen = (encipherKey.getModulus ().bitLength () + 7) / 8; - } + outputLen = (encipherKey.getModulus().bitLength() + 7) / 8; else - throw new IllegalStateException ("not initialized"); + throw new IllegalStateException("not initialized"); if (inputLen > outputLen) - throw new IllegalArgumentException ("not configured to encode " + inputLen - + "bytes; at most " + outputLen); + throw new IllegalArgumentException("not configured to encode " + inputLen + + "bytes; at most " + outputLen); return outputLen; } - protected int engineGetKeySize (final Key key) throws InvalidKeyException + protected int engineGetKeySize(final Key key) throws InvalidKeyException { - if (!(key instanceof RSAKey)) - throw new InvalidKeyException ("not an RSA key"); - return ((RSAKey) key).getModulus ().bitLength (); + if (! (key instanceof RSAKey)) + throw new InvalidKeyException("not an RSA key"); + return ((RSAKey) key).getModulus().bitLength(); } - protected byte[] engineGetIV () + protected byte[] engineGetIV() { return null; } @@ -131,18 +122,18 @@ public class RSACipherImpl extends CipherSpi return null; } - protected void engineInit (int opmode, Key key, SecureRandom random) - throws InvalidKeyException + protected void engineInit(int opmode, Key key, SecureRandom random) + throws InvalidKeyException { int outputLen = 0; if (opmode == Cipher.ENCRYPT_MODE) { - if (!(key instanceof RSAPublicKey)) - throw new InvalidKeyException ("expecting a RSAPublicKey"); + if (! (key instanceof RSAPublicKey)) + throw new InvalidKeyException("expecting a RSAPublicKey"); encipherKey = (RSAPublicKey) key; decipherKey = null; blindingKey = null; - outputLen = (encipherKey.getModulus ().bitLength () + 7) / 8; + outputLen = (encipherKey.getModulus().bitLength() + 7) / 8; } else if (opmode == Cipher.DECRYPT_MODE) { @@ -151,75 +142,78 @@ public class RSACipherImpl extends CipherSpi decipherKey = (RSAPrivateKey) key; encipherKey = null; blindingKey = null; - outputLen = (decipherKey.getModulus ().bitLength () + 7) / 8; + outputLen = (decipherKey.getModulus().bitLength() + 7) / 8; } else if (key instanceof RSAPublicKey) { if (decipherKey == null) - throw new IllegalStateException ("must configure decryption key first"); - if (!decipherKey.getModulus ().equals (((RSAPublicKey) key).getModulus ())) - throw new InvalidKeyException ("blinding key is not compatible"); + throw new IllegalStateException("must configure decryption key first"); + if (! decipherKey.getModulus().equals(((RSAPublicKey) key).getModulus())) + throw new InvalidKeyException("blinding key is not compatible"); blindingKey = (RSAPublicKey) key; return; } else - throw new InvalidKeyException ("expecting either an RSAPrivateKey or an RSAPublicKey (for blinding)"); + throw new InvalidKeyException( + "expecting either an RSAPrivateKey or an RSAPublicKey (for blinding)"); } else - throw new IllegalArgumentException ("only encryption and decryption supported"); + throw new IllegalArgumentException("only encryption and decryption supported"); this.random = random; this.opmode = opmode; pos = 0; dataBuffer = new byte[outputLen]; } - protected void engineInit (int opmode, Key key, AlgorithmParameterSpec spec, SecureRandom random) - throws InvalidKeyException + protected void engineInit(int opmode, Key key, AlgorithmParameterSpec spec, + SecureRandom random) throws InvalidKeyException { - engineInit (opmode, key, random); + engineInit(opmode, key, random); } - protected void engineInit (int opmode, Key key, AlgorithmParameters params, SecureRandom random) - throws InvalidKeyException + protected void engineInit(int opmode, Key key, AlgorithmParameters params, + SecureRandom random) throws InvalidKeyException { - engineInit (opmode, key, random); + engineInit(opmode, key, random); } - protected byte[] engineUpdate (byte[] in, int offset, int length) + protected byte[] engineUpdate(byte[] in, int offset, int length) { if (opmode != Cipher.ENCRYPT_MODE && opmode != Cipher.DECRYPT_MODE) - throw new IllegalStateException ("not initialized"); - System.arraycopy (in, offset, dataBuffer, pos, length); + throw new IllegalStateException("not initialized"); + System.arraycopy(in, offset, dataBuffer, pos, length); pos += length; return EMPTY; } - protected int engineUpdate (byte[] in, int offset, int length, byte[] out, int outOffset) + protected int engineUpdate(byte[] in, int offset, int length, byte[] out, + int outOffset) { - engineUpdate (in, offset, length); + engineUpdate(in, offset, length); return 0; } - protected byte[] engineDoFinal (byte[] in, int offset, int length) - throws IllegalBlockSizeException, BadPaddingException + protected byte[] engineDoFinal(byte[] in, int offset, int length) + throws IllegalBlockSizeException, BadPaddingException { - engineUpdate (in, offset, length); + engineUpdate(in, offset, length); if (opmode == Cipher.DECRYPT_MODE) { if (pos < dataBuffer.length) - throw new IllegalBlockSizeException ("expecting exactly " + dataBuffer.length + " bytes"); - BigInteger enc = new BigInteger (1, dataBuffer); - byte[] dec = rsaDecrypt (enc); - logger.log (Component.CRYPTO, "RSA: decryption produced\n{0}", - new ByteArray (dec)); + throw new IllegalBlockSizeException("expecting exactly " + + dataBuffer.length + " bytes"); + BigInteger enc = new BigInteger(1, dataBuffer); + byte[] dec = rsaDecrypt(enc); + logger.log(Component.CRYPTO, "RSA: decryption produced\n{0}", + new ByteArray(dec)); if (dec[0] != 0x02) - throw new BadPaddingException ("expected padding type 2"); + throw new BadPaddingException("expected padding type 2"); int i; for (i = 1; i < dec.length && dec[i] != 0x00; i++) ; // keep incrementing i int len = dec.length - i - 1; // skip the 0x00 byte byte[] result = new byte[len]; - System.arraycopy (dec, i + 1, result, 0, len); + System.arraycopy(dec, i + 1, result, 0, len); pos = 0; return result; } @@ -227,29 +221,29 @@ public class RSACipherImpl extends CipherSpi { offset = dataBuffer.length - pos; if (offset < 3) - throw new IllegalBlockSizeException ("input is too large to encrypt"); + throw new IllegalBlockSizeException("input is too large to encrypt"); byte[] dec = new byte[dataBuffer.length]; dec[0] = 0x02; if (random == null) - random = new SecureRandom (); - byte[] pad = new byte[offset - 2]; - random.nextBytes (pad); - for (int i = 0; i < pad.length; i++) - if (pad[i] == 0) - pad[i] = 1; - System.arraycopy (pad, 0, dec, 1, pad.length); + random = new SecureRandom(); + byte[] pad = new byte[offset - 2]; + random.nextBytes(pad); + for (int i = 0; i < pad.length; i++) + if (pad[i] == 0) + pad[i] = 1; + System.arraycopy(pad, 0, dec, 1, pad.length); dec[dec.length - pos] = 0x00; - System.arraycopy (dataBuffer, 0, dec, offset, pos); - logger.log (Component.CRYPTO, "RSA: produced padded plaintext\n{0}", - new ByteArray (dec)); - BigInteger x = new BigInteger (1, dec); - BigInteger y = x.modPow (encipherKey.getPublicExponent (), - encipherKey.getModulus ()); - byte[] enc = y.toByteArray (); + System.arraycopy(dataBuffer, 0, dec, offset, pos); + logger.log(Component.CRYPTO, "RSA: produced padded plaintext\n{0}", + new ByteArray(dec)); + BigInteger x = new BigInteger(1, dec); + BigInteger y = x.modPow(encipherKey.getPublicExponent(), + encipherKey.getModulus()); + byte[] enc = y.toByteArray(); if (enc[0] == 0x00) { byte[] tmp = new byte[enc.length - 1]; - System.arraycopy (enc, 1, tmp, 0, tmp.length); + System.arraycopy(enc, 1, tmp, 0, tmp.length); enc = tmp; } pos = 0; @@ -257,56 +251,54 @@ public class RSACipherImpl extends CipherSpi } } - protected int engineDoFinal (byte[] out, int offset) - throws ShortBufferException, IllegalBlockSizeException, BadPaddingException + protected int engineDoFinal(byte[] out, int offset) + throws ShortBufferException, IllegalBlockSizeException, + BadPaddingException { - byte[] result = engineDoFinal (EMPTY, 0, 0); + byte[] result = engineDoFinal(EMPTY, 0, 0); if (out.length - offset < result.length) - throw new ShortBufferException ("need " + result.length + ", have " - + (out.length - offset)); - System.arraycopy (result, 0, out, offset, result.length); + throw new ShortBufferException("need " + result.length + ", have " + + (out.length - offset)); + System.arraycopy(result, 0, out, offset, result.length); return result.length; } - protected int engineDoFinal (final byte[] input, final int offset, final int length, - final byte[] output, final int outputOffset) - throws ShortBufferException, IllegalBlockSizeException, BadPaddingException + protected int engineDoFinal(final byte[] input, final int offset, + final int length, final byte[] output, + final int outputOffset) + throws ShortBufferException, IllegalBlockSizeException, + BadPaddingException { - byte[] result = engineDoFinal (input, offset, length); + byte[] result = engineDoFinal(input, offset, length); if (output.length - outputOffset < result.length) - throw new ShortBufferException ("need " + result.length + ", have " - + (output.length - outputOffset)); - System.arraycopy (result, 0, output, outputOffset, result.length); + throw new ShortBufferException("need " + result.length + ", have " + + (output.length - outputOffset)); + System.arraycopy(result, 0, output, outputOffset, result.length); return result.length; } /** * Decrypts the ciphertext, employing RSA blinding if possible. */ - private byte[] rsaDecrypt (BigInteger enc) + private byte[] rsaDecrypt(BigInteger enc) { if (random == null) - random = new SecureRandom (); - BigInteger n = decipherKey.getModulus (); + random = new SecureRandom(); + BigInteger n = decipherKey.getModulus(); BigInteger r = null; BigInteger pubExp = null; if (blindingKey != null) - pubExp = blindingKey.getPublicExponent (); + pubExp = blindingKey.getPublicExponent(); if (pubExp != null && (decipherKey instanceof RSAPrivateCrtKey)) - pubExp = ((RSAPrivateCrtKey) decipherKey).getPublicExponent (); + pubExp = ((RSAPrivateCrtKey) decipherKey).getPublicExponent(); if (pubExp != null) { - r = new BigInteger (n.bitLength () - 1, random); - enc = r.modPow (pubExp, n).multiply (enc).mod (n); + r = new BigInteger(n.bitLength() - 1, random); + enc = r.modPow(pubExp, n).multiply(enc).mod(n); } - - BigInteger dec = enc.modPow (decipherKey.getPrivateExponent (), n); - + BigInteger dec = enc.modPow(decipherKey.getPrivateExponent(), n); if (pubExp != null) - { - dec = dec.multiply (r.modInverse (n)).mod (n); - } - - return dec.toByteArray (); + dec = dec.multiply(r.modInverse(n)).mod(n); + return dec.toByteArray(); } } diff --git a/gnu/javax/crypto/sasl/AuthInfo.java b/gnu/javax/crypto/sasl/AuthInfo.java index 1e942559d..733d2f0bf 100644 --- a/gnu/javax/crypto/sasl/AuthInfo.java +++ b/gnu/javax/crypto/sasl/AuthInfo.java @@ -56,10 +56,6 @@ import java.util.StringTokenizer; */ public class AuthInfo { - - // Constants and variables - // ------------------------------------------------------------------------- - private static final ArrayList factories = new ArrayList(); static { @@ -72,14 +68,14 @@ public class AuthInfo { for (StringTokenizer st = new StringTokenizer(pkgs, "|"); st.hasMoreTokens();) { - clazz = st.nextToken(); - if (!"gnu.crypto.sasl".equals(clazz)) + clazz = st.nextToken().trim(); + if (! "gnu.javax.crypto.sasl".equals(clazz)) { clazz += ".AuthInfoProviderFactory"; try { - IAuthInfoProviderFactory factory = (IAuthInfoProviderFactory) Class.forName( - clazz).newInstance(); + IAuthInfoProviderFactory factory = + (IAuthInfoProviderFactory) Class.forName(clazz).newInstance(); factories.add(factory); } catch (ClassCastException ignored) @@ -99,33 +95,25 @@ public class AuthInfo } // always add ours last; unless it's already there if (!factories.contains(ours)) - { - factories.add(ours); - } + factories.add(ours); } - // Constructor(s) - // ------------------------------------------------------------------------- - /** Trivial constructor to enforce Singleton pattern. */ private AuthInfo() { super(); } - // Class methods - // ------------------------------------------------------------------------- - /** - * A convenience method to return the authentication information provider - * for a designated SASL mechnanism. It goes through all the installed - * provider factories, one at a time, and attempts to return a new instance - * of the provider for the designated mechanism. It stops at the first - * factory returning a non-null provider. - * + * A convenience method to return the authentication information provider for + * a designated SASL mechnanism. It goes through all the installed provider + * factories, one at a time, and attempts to return a new instance of the + * provider for the designated mechanism. It stops at the first factory + * returning a non-null provider. + * * @param mechanism the name of a SASL mechanism. * @return an implementation that provides {@link IAuthInfoProvider} for that - * mechanism; or <code>null</code> if none found. + * mechanism; or <code>null</code> if none found. */ public static IAuthInfoProvider getProvider(String mechanism) { @@ -134,9 +122,7 @@ public class AuthInfo IAuthInfoProviderFactory factory = (IAuthInfoProviderFactory) it.next(); IAuthInfoProvider result = factory.getInstance(mechanism); if (result != null) - { - return result; - } + return result; } return null; } diff --git a/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java b/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java index 6ba5fc562..c4fc816dc 100644 --- a/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java +++ b/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java @@ -46,44 +46,22 @@ import gnu.javax.crypto.sasl.srp.SRPAuthInfoProvider; /** * The concrete SASL authentication information provider factory. */ -public class AuthInfoProviderFactory implements IAuthInfoProviderFactory +public class AuthInfoProviderFactory + implements IAuthInfoProviderFactory { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-args constructor - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // IAuthInfoProviderFactory interface implementation ----------------------- - public IAuthInfoProvider getInstance(String mechanism) { if (mechanism == null) - { - return null; - } + return null; mechanism = mechanism.trim().toUpperCase(); if (mechanism.startsWith(Registry.SASL_SRP_MECHANISM)) - { - return new SRPAuthInfoProvider(); - } + return new SRPAuthInfoProvider(); if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM)) - { - return new CramMD5AuthInfoProvider(); - } + return new CramMD5AuthInfoProvider(); if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM)) - { - return new PlainAuthInfoProvider(); - } + return new PlainAuthInfoProvider(); return null; } } diff --git a/gnu/javax/crypto/sasl/ClientFactory.java b/gnu/javax/crypto/sasl/ClientFactory.java index ef184632c..84acfcd14 100644 --- a/gnu/javax/crypto/sasl/ClientFactory.java +++ b/gnu/javax/crypto/sasl/ClientFactory.java @@ -47,11 +47,11 @@ import gnu.javax.crypto.sasl.srp.SRPClient; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.HashMap; import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; @@ -62,53 +62,32 @@ import javax.security.sasl.SaslException; /** * The implementation of {@link SaslClientFactory}. */ -public class ClientFactory implements SaslClientFactory +public class ClientFactory + implements SaslClientFactory { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-arguments constructor - // Class methods - // ------------------------------------------------------------------------- - public static final Set getNames() { - return Collections.unmodifiableSet(new HashSet( - Arrays.asList(getNamesInternal(null)))); + return Collections.unmodifiableSet(new HashSet(Arrays.asList(getNamesInternal(null)))); } private static final String[] getNamesInternal(Map props) { - String[] all = new String[] { Registry.SASL_SRP_MECHANISM, - Registry.SASL_CRAM_MD5_MECHANISM, - Registry.SASL_PLAIN_MECHANISM, - Registry.SASL_ANONYMOUS_MECHANISM }; - + String[] all = new String[] { + Registry.SASL_SRP_MECHANISM, + Registry.SASL_CRAM_MD5_MECHANISM, + Registry.SASL_PLAIN_MECHANISM, + Registry.SASL_ANONYMOUS_MECHANISM }; if (props == null) - { - return all; - } + return all; if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props)) - { - return new String[0]; - } - + return new String[0]; List result = new ArrayList(all.length); - ; for (int i = 0; i < all.length;) - { - result.add(all[i++]); - } - + result.add(all[i++]); if (hasPolicy(Sasl.POLICY_NOPLAINTEXT, props)) - { - result.remove(Registry.SASL_PLAIN_MECHANISM); - } + result.remove(Registry.SASL_PLAIN_MECHANISM); if (hasPolicy(Sasl.POLICY_NOACTIVE, props)) { result.remove(Registry.SASL_CRAM_MD5_MECHANISM); @@ -135,32 +114,19 @@ public class ClientFactory implements SaslClientFactory public static final ClientMechanism getInstance(String mechanism) { if (mechanism == null) - { - return null; - } + return null; mechanism = mechanism.trim().toUpperCase(); if (mechanism.equals(Registry.SASL_SRP_MECHANISM)) - { - return new SRPClient(); - } + return new SRPClient(); if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM)) - { - return new CramMD5Client(); - } + return new CramMD5Client(); if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM)) - { - return new PlainClient(); - } + return new PlainClient(); if (mechanism.equals(Registry.SASL_ANONYMOUS_MECHANISM)) - { - return new AnonymousClient(); - } + return new AnonymousClient(); return null; } - // Instance methods - // ------------------------------------------------------------------------- - public SaslClient createSaslClient(String[] mechanisms, String authorisationID, String protocol, String serverName, Map props, @@ -173,29 +139,21 @@ public class ClientFactory implements SaslClientFactory mechanism = mechanisms[i]; result = getInstance(mechanism); if (result != null) - { - break; - } + break; } - if (result != null) { HashMap attributes = new HashMap(); if (props != null) - { - attributes.putAll(props); - } + attributes.putAll(props); attributes.put(Registry.SASL_AUTHORISATION_ID, authorisationID); attributes.put(Registry.SASL_PROTOCOL, protocol); attributes.put(Registry.SASL_SERVER_NAME, serverName); attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh); - result.init(attributes); return result; } - - throw new SaslException( - "No supported mechanism found in given mechanism list"); + throw new SaslException("No supported mechanism found in given mechanism list"); } public String[] getMechanismNames(Map props) @@ -207,4 +165,4 @@ public class ClientFactory implements SaslClientFactory { return "true".equalsIgnoreCase(String.valueOf(props.get(propertyName))); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/ClientMechanism.java b/gnu/javax/crypto/sasl/ClientMechanism.java index 45873ae6b..7f8e9c120 100644 --- a/gnu/javax/crypto/sasl/ClientMechanism.java +++ b/gnu/javax/crypto/sasl/ClientMechanism.java @@ -42,50 +42,37 @@ import gnu.java.security.Registry; import java.util.HashMap; import java.util.Map; + import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; /** - * <p>A base class to facilitate implementing SASL client-side mechanisms.</p> + * A base class to facilitate implementing SASL client-side mechanisms. */ -public abstract class ClientMechanism implements SaslClient +public abstract class ClientMechanism + implements SaslClient { - - // Constants and variables - // ------------------------------------------------------------------------- - /** Name of this mechanism. */ protected String mechanism; - /** The authorisation identity. */ protected String authorizationID; - /** Name of protocol using this mechanism. */ protected String protocol; - /** Name of server to authenticate to. */ protected String serverName; - /** Properties of qualities desired for this mechanism. */ protected Map properties; - /** Callback handler to use with this mechanism instance. */ protected CallbackHandler handler; - /** Channel binding data to use with this mechanism instance. */ protected byte[] channelBinding; - /** Whether authentication phase is completed (true) or not (false). */ protected boolean complete = false; - /** The state of the authentication automaton. */ protected int state = -1; - // Constructor(s) - // ------------------------------------------------------------------------- - protected ClientMechanism(final String mechanism) { super(); @@ -94,20 +81,10 @@ public abstract class ClientMechanism implements SaslClient this.state = -1; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods to be implemented by concrete subclasses --------------- - protected abstract void initMechanism() throws SaslException; protected abstract void resetMechanism() throws SaslException; - // javax.security.sasl.SaslClient interface implementation ----------------- - public abstract byte[] evaluateChallenge(byte[] challenge) throws SaslException; @@ -121,20 +98,16 @@ public abstract class ClientMechanism implements SaslClient public byte[] unwrap(final byte[] incoming, final int offset, final int len) throws SaslException { - if (!isComplete()) - { - throw new IllegalMechanismStateException(); - } + if (! isComplete()) + throw new IllegalMechanismStateException(); return this.engineUnwrap(incoming, offset, len); } public byte[] wrap(final byte[] outgoing, final int offset, final int len) throws SaslException { - if (!isComplete()) - { - throw new IllegalMechanismStateException(); - } + if (! isComplete()) + throw new IllegalMechanismStateException(); return this.engineWrap(outgoing, offset, len); } @@ -145,58 +118,32 @@ public abstract class ClientMechanism implements SaslClient public Object getNegotiatedProperty(final String propName) { - if (!isComplete()) - { - throw new IllegalStateException(); - } + if (! isComplete()) + throw new IllegalStateException(); if (Sasl.QOP.equals(propName)) - { - return getNegotiatedQOP(); - } + return getNegotiatedQOP(); if (Sasl.STRENGTH.equals(propName)) - { - return getNegotiatedStrength(); - } + return getNegotiatedStrength(); if (Sasl.SERVER_AUTH.equals(propName)) - { - return getNegotiatedServerAuth(); - } + return getNegotiatedServerAuth(); if (Sasl.MAX_BUFFER.equals(propName)) - { - return getNegotiatedMaxBuffer(); - } + return getNegotiatedMaxBuffer(); if (Sasl.RAW_SEND_SIZE.equals(propName)) - { - return getNegotiatedRawSendSize(); - } + return getNegotiatedRawSendSize(); if (Sasl.POLICY_NOPLAINTEXT.equals(propName)) - { - return getNegotiatedPolicyNoPlainText(); - } + return getNegotiatedPolicyNoPlainText(); if (Sasl.POLICY_NOACTIVE.equals(propName)) - { - return getNegotiatedPolicyNoActive(); - } + return getNegotiatedPolicyNoActive(); if (Sasl.POLICY_NODICTIONARY.equals(propName)) - { - return getNegotiatedPolicyNoDictionary(); - } + return getNegotiatedPolicyNoDictionary(); if (Sasl.POLICY_NOANONYMOUS.equals(propName)) - { - return getNegotiatedPolicyNoAnonymous(); - } + return getNegotiatedPolicyNoAnonymous(); if (Sasl.POLICY_FORWARD_SECRECY.equals(propName)) - { - return getNegotiatedPolicyForwardSecrecy(); - } + return getNegotiatedPolicyForwardSecrecy(); if (Sasl.POLICY_PASS_CREDENTIALS.equals(propName)) - { - return getNegotiatedPolicyPassCredentials(); - } + return getNegotiatedPolicyPassCredentials(); if (Sasl.REUSE.equals(propName)) - { - return getReuse(); - } + return getReuse(); return null; } @@ -204,8 +151,6 @@ public abstract class ClientMechanism implements SaslClient { } - // other Instance methods -------------------------------------------------- - public String getAuthorizationID() { return authorizationID; @@ -288,30 +233,23 @@ public abstract class ClientMechanism implements SaslClient } /** - * <p>Initialises the mechanism with designated attributes. Permissible names - * and values are mechanism specific.</p> - * + * Initialises the mechanism with designated attributes. Permissible names and + * values are mechanism specific. + * * @param attributes a set of name-value pairs that describes the desired - * future behaviour of this instance. + * future behaviour of this instance. * @throws IllegalMechanismStateException if the instance is already - * initialised. + * initialised. * @throws SaslException if an exception occurs during the process. */ public void init(final Map attributes) throws SaslException { if (state != -1) - { - throw new IllegalMechanismStateException("init()"); - } - + throw new IllegalMechanismStateException("init()"); if (properties == null) - { - properties = new HashMap(); - } + properties = new HashMap(); else - { - properties.clear(); - } + properties.clear(); if (attributes != null) { authorizationID = (String) attributes.get(Registry.SASL_AUTHORISATION_ID); @@ -322,35 +260,25 @@ public abstract class ClientMechanism implements SaslClient properties.putAll(attributes); } else - { - handler = null; - } + handler = null; if (authorizationID == null) - { - authorizationID = ""; - } + authorizationID = ""; if (protocol == null) - { - protocol = ""; - } + protocol = ""; if (serverName == null) - { - serverName = ""; - } + serverName = ""; if (channelBinding == null) - { - channelBinding = new byte[0]; - } + channelBinding = new byte[0]; initMechanism(); complete = false; state = 0; } /** - * <p>Resets the mechanism instance for re-initialisation and use with other - * characteristics.</p> - * + * Resets the mechanism instance for re-initialisation and use with other + * characteristics. + * * @throws SaslException if an exception occurs during the process. */ public void reset() throws SaslException @@ -362,4 +290,4 @@ public abstract class ClientMechanism implements SaslClient complete = false; state = -1; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/ConfidentialityException.java b/gnu/javax/crypto/sasl/ConfidentialityException.java index adfc06593..62b685725 100644 --- a/gnu/javax/crypto/sasl/ConfidentialityException.java +++ b/gnu/javax/crypto/sasl/ConfidentialityException.java @@ -45,12 +45,12 @@ import javax.security.sasl.SaslException; * exception is thrown to indicate that a violation has occured during the * processing of a <i>confidentiality</i> protection filter. */ -public class ConfidentialityException extends SaslException +public class ConfidentialityException + extends SaslException { - /** - * Constructs a new instance of <code>ConfidentialityException</code> with no - * detail message. + * Constructs a new instance of <code>ConfidentialityException</code> with + * no detail message. */ public ConfidentialityException() { @@ -60,7 +60,7 @@ public class ConfidentialityException extends SaslException /** * Constructs a new instance of <code>ConfidentialityException</code> with * the specified detail message. - * + * * @param s the detail message. */ public ConfidentialityException(String s) @@ -71,7 +71,7 @@ public class ConfidentialityException extends SaslException /** * Constructs a new instance of <code>ConfidentialityException</code> with a * detailed message and a root exception. - * + * * @param s possibly null additional detail about the exception. * @param x a possibly null root exception that caused this one. */ diff --git a/gnu/javax/crypto/sasl/IAuthInfoProvider.java b/gnu/javax/crypto/sasl/IAuthInfoProvider.java index 2b913a137..60c50d5d4 100644 --- a/gnu/javax/crypto/sasl/IAuthInfoProvider.java +++ b/gnu/javax/crypto/sasl/IAuthInfoProvider.java @@ -47,71 +47,70 @@ import javax.security.sasl.AuthenticationException; */ public interface IAuthInfoProvider { - - // Constants - // ------------------------------------------------------------------------- - - // Methods - // ------------------------------------------------------------------------- - /** * Activates (initialises) this provider instance. SHOULD be the first method * invoked on the provider. - * + * * @param context a collection of name-value bindings describing the - * activation context. - * @throws AuthenticationException if an exception occurs during the operation. + * activation context. + * @throws AuthenticationException if an exception occurs during the + * operation. */ void activate(Map context) throws AuthenticationException; /** * Passivates (releases) this provider instance. SHOULD be the last method - * invoked on the provider. Once it is done, no other method may be invoked - * on the same instance before it is <i>activated</i> agains. - * - * @throws AuthenticationException if an exception occurs during the operation. + * invoked on the provider. Once it is done, no other method may be invoked on + * the same instance before it is <i>activated</i> agains. + * + * @throws AuthenticationException if an exception occurs during the + * operation. */ void passivate() throws AuthenticationException; /** * Checks if a user with a designated name is known to this provider. - * + * * @param userName the name of a user to check. - * @return <code>true</code> if the user with the designated name is known to - * this provider; <code>false</code> otherwise. - * @throws AuthenticationException if an exception occurs during the operation. + * @return <code>true</code> if the user with the designated name is known + * to this provider; <code>false</code> otherwise. + * @throws AuthenticationException if an exception occurs during the + * operation. */ boolean contains(String userName) throws AuthenticationException; /** * Returns a collection of information about a designated user. The contents * of the returned map is provider-specific of name-to-value mappings. - * + * * @param userID a map of name-to-value bindings that fully describe a user. * @return a collection of information about the designated user. - * @throws AuthenticationException if an exception occurs during the operation. + * @throws AuthenticationException if an exception occurs during the + * operation. */ Map lookup(Map userID) throws AuthenticationException; /** * Updates the credentials of a designated user. - * + * * @param userCredentials a map of name-to-value bindings that fully describe - * a user, including per new credentials. - * @throws AuthenticationException if an exception occurs during the operation. + * a user, including per new credentials. + * @throws AuthenticationException if an exception occurs during the + * operation. */ void update(Map userCredentials) throws AuthenticationException; /** * A provider may operate in more than mode; e.g. SRP-II caters for user - * credentials computed in more than one message digest algorithm. This - * method returns the set of name-to-value bindings describing the mode of - * the provider. - * + * credentials computed in more than one message digest algorithm. This method + * returns the set of name-to-value bindings describing the mode of the + * provider. + * * @param mode a unique identifier describing the operational mode. * @return a collection of name-to-value bindings describing the designated - * mode. - * @throws AuthenticationException if an exception occurs during the operation. + * mode. + * @throws AuthenticationException if an exception occurs during the + * operation. */ Map getConfiguration(String mode) throws AuthenticationException; -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java b/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java index e630b8da1..b6dc775d8 100644 --- a/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java +++ b/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java @@ -43,20 +43,13 @@ package gnu.javax.crypto.sasl; */ public interface IAuthInfoProviderFactory { - - // Constants - // ------------------------------------------------------------------------- - - // Methods - // ------------------------------------------------------------------------- - /** - * Returns an implementation of a provider for a designated mechanism - * capable of honouring {@link IAuthInfoProvider} requests. - * + * Returns an implementation of a provider for a designated mechanism capable + * of honouring {@link IAuthInfoProvider} requests. + * * @param mechanism the unique name of a mechanism. * @return an implementation of {@link IAuthInfoProvider} for that mechanism - * or <code>null</code> if none found. + * or <code>null</code> if none found. */ IAuthInfoProvider getInstance(String mechanism); -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/IllegalMechanismStateException.java b/gnu/javax/crypto/sasl/IllegalMechanismStateException.java index b46ad98e3..547ac4103 100644 --- a/gnu/javax/crypto/sasl/IllegalMechanismStateException.java +++ b/gnu/javax/crypto/sasl/IllegalMechanismStateException.java @@ -47,9 +47,9 @@ import javax.security.sasl.AuthenticationException; * invoked on incomplete mechanisms was invoked but the authentication phase of * that mechanism was already completed. */ -public class IllegalMechanismStateException extends AuthenticationException +public class IllegalMechanismStateException + extends AuthenticationException { - /** * Constructs a new instance of <code>IllegalMechanismStateException</code> * with no detail message. @@ -62,7 +62,7 @@ public class IllegalMechanismStateException extends AuthenticationException /** * Constructs a new instance of <code>IllegalMechanismStateException</code> * with the specified detail message. - * + * * @param detail the detail message. */ public IllegalMechanismStateException(String detail) @@ -73,7 +73,7 @@ public class IllegalMechanismStateException extends AuthenticationException /** * Constructs a new instance of <code>IllegalMechanismStateException</code> * with the specified detail message, and cause. - * + * * @param detail the detail message. * @param ex the original cause. */ diff --git a/gnu/javax/crypto/sasl/InputBuffer.java b/gnu/javax/crypto/sasl/InputBuffer.java index a64ea3e0e..d676a595d 100644 --- a/gnu/javax/crypto/sasl/InputBuffer.java +++ b/gnu/javax/crypto/sasl/InputBuffer.java @@ -45,39 +45,33 @@ import java.io.IOException; import java.math.BigInteger; /** - * <p>The implementation of an incoming SASL buffer.</p> - * - * <p>The data elements this class caters for are described in [1].</p> - * - * <p>References:</p> + * The implementation of an incoming SASL buffer. + * <p> + * The data elements this class caters for are described in [1]. + * <p> + * References: * <ol> - * <li><a href="http://www.ietf.org/internet-drafts/draft-burdis-cat-srp-sasl-09.txt"> - * Secure Remote Password Authentication Mechanism</a>;<br/> - * draft-burdis-cat-srp-sasl-09,<br/> - * <a href="mailto:keith@rucus.ru.ac.za">Keith Burdis</a> and - * <a href="mailto:raif@forge.com.au">Raïf S. Naffah</a>.</li> + * <li><a + * href="http://www.ietf.org/internet-drafts/draft-burdis-cat-srp-sasl-09.txt"> + * Secure Remote Password Authentication Mechanism</a>;<br/> + * draft-burdis-cat-srp-sasl-09,<br/> <a + * href="mailto:keith@rucus.ru.ac.za">Keith Burdis</a> and <a + * href="mailto:raif@forge.com.au">Raïf S. Naffah</a>.</li> * </ol> */ public class InputBuffer { - - // Constants and variables - // ------------------------------------------------------------------------- - /** The internal buffer stream containing the buffer's contents. */ protected ByteArrayInputStream in; - /** The length of the buffer, according to its header. */ protected int length; - // Constructor(s) - // ------------------------------------------------------------------------- - /** - * <p>Constructs a SASL buffer given the buffer's encoded form, including its - * header bytes.</p> - * - * @param frame the encoded form, including the header bytes, of a SASL buffer. + * Constructs a SASL buffer given the buffer's encoded form, including its + * header bytes. + * + * @param frame the encoded form, including the header bytes, of a SASL + * buffer. * @throws SaslEncodingException if the buffer is malformed. */ public InputBuffer(byte[] frame) throws SaslEncodingException @@ -85,17 +79,13 @@ public class InputBuffer this(); if (frame.length < 4) - { - throw new SaslEncodingException("SASL buffer header too short"); - } - - length = (frame[0] & 0xFF) << 24 | (frame[1] & 0xFF) << 16 - | (frame[2] & 0xFF) << 8 | (frame[3] & 0xFF); + throw new SaslEncodingException("SASL buffer header too short"); + length = (frame[0] & 0xFF) << 24 + | (frame[1] & 0xFF) << 16 + | (frame[2] & 0xFF) << 8 + | (frame[3] & 0xFF); if (length > Registry.SASL_BUFFER_MAX_LIMIT || length < 0) - { - throw new SaslEncodingException("SASL buffer size limit exceeded"); - } - + throw new SaslEncodingException("SASL buffer size limit exceeded"); in = new ByteArrayInputStream(frame, 4, length); } @@ -105,16 +95,13 @@ public class InputBuffer super(); } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns an instance of a SASL buffer given the buffer's encoded contents, - * excluding the buffer's header bytes.</p> - * - * <p>Calls the method with the same name and three arguments as: + * Returns an instance of a SASL buffer given the buffer's encoded contents, + * excluding the buffer's header bytes. + * <p> + * Calls the method with the same name and three arguments as: * <code>getInstance(raw, 0, raw.length)</code>. - * + * * @param raw the encoded form, excluding the header bytes, of a SASL buffer. * @return a new instance of {@link InputBuffer}. */ @@ -124,9 +111,9 @@ public class InputBuffer } /** - * <p>Returns an instance of a SASL buffer given the buffer's encoded - * contents, excluding the buffer's header bytes.</p> - * + * Returns an instance of a SASL buffer given the buffer's encoded contents, + * excluding the buffer's header bytes. + * * @param raw the encoded form, excluding the header bytes, of a SASL buffer. * @param offset offset where to start using raw bytes from. * @param len number of bytes to use. @@ -140,21 +127,8 @@ public class InputBuffer } /** - * <p>Converts four octets into the number that they represent.</p> - * - * @param b the four octets. - * @return the length. - */ - // public static int fourBytesToLength(byte[] b) throws SaslEncodingException { - // int result = b[0] << 24 | (b[1] & 0xFF) << 16 | (b[2] & 0xFF) << 8 | (b[3] & 0xFF); - // if (result > Registry.SASL_FOUR_BYTE_MAX_LIMIT || result < 0) { - // throw new SaslEncodingException("SASL EOS size limit exceeded"); - // } - // return result; - // } - /** - * <p>Converts two octets into the number that they represent.</p> - * + * Converts two octets into the number that they represent. + * * @param b the two octets. * @return the length. */ @@ -162,49 +136,37 @@ public class InputBuffer { final int result = (b[0] & 0xFF) << 8 | (b[1] & 0xFF); if (result > Registry.SASL_TWO_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL MPI/Text size limit exceeded"); - } + throw new SaslEncodingException("SASL MPI/Text size limit exceeded"); return result; } - // Instance methods - // ------------------------------------------------------------------------- - public boolean hasMoreElements() { return (in.available() > 0); } /** - * <p>Decodes a SASL scalar quantity, <code>count</code>-octet long, from the - * current buffer.</p> - * + * Decodes a SASL scalar quantity, <code>count</code>-octet long, from the + * current buffer. + * * @param count the number of octets of this scalar quantity. - * @return a native representation of a SASL scalar (unsigned integer) quantity. + * @return a native representation of a SASL scalar (unsigned integer) + * quantity. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws IOException if any other I/O exception occurs during the operation. */ public long getScalar(int count) throws IOException { if (count < 0 || count > 4) - { - throw new SaslEncodingException("Invalid SASL scalar octet count: " - + String.valueOf(count)); - } - if (!hasMoreElements()) - { - throw new SaslEncodingException( - "Not enough bytes for a scalar in buffer"); - } + throw new SaslEncodingException("Invalid SASL scalar octet count: " + + String.valueOf(count)); + if (! hasMoreElements()) + throw new SaslEncodingException("Not enough bytes for a scalar in buffer"); if (in.available() < count) - { - throw new SaslEncodingException("Illegal SASL scalar encoding"); - } + throw new SaslEncodingException("Illegal SASL scalar encoding"); byte[] element = new byte[count]; in.read(element); - long result = 0L; for (int i = 0; i < count; i++) { @@ -215,125 +177,96 @@ public class InputBuffer } /** - * <p>Decodes a SASL OS from the current buffer.</p> - * + * Decodes a SASL OS from the current buffer. + * * @return a native representation of a SASL OS. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws IOException if any other I/O exception occurs during the operation. */ public byte[] getOS() throws IOException { - if (!hasMoreElements()) - { - throw new SaslEncodingException( - "Not enough bytes for an octet-sequence in buffer"); - } + if (! hasMoreElements()) + throw new SaslEncodingException( + "Not enough bytes for an octet-sequence in buffer"); final int elementLength = in.read(); if (elementLength > Registry.SASL_ONE_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException( - "SASL octet-sequence size limit exceeded"); - } - + throw new SaslEncodingException("SASL octet-sequence size limit exceeded"); if (in.available() < elementLength) - { - throw new SaslEncodingException("Illegal SASL octet-sequence encoding"); - } - + throw new SaslEncodingException("Illegal SASL octet-sequence encoding"); byte[] result = new byte[elementLength]; in.read(result); - return result; } /** - * <p>Decodes a SASL EOS from the current buffer.</p> - * + * Decodes a SASL EOS from the current buffer. + * * @return a native representation of a SASL EOS. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws IOException if any other I/O exception occurs during the operation. */ public byte[] getEOS() throws IOException { if (in.available() < 2) - { - throw new SaslEncodingException( - "Not enough bytes for an extended octet-sequence in buffer"); - } - + throw new SaslEncodingException( + "Not enough bytes for an extended octet-sequence in buffer"); byte[] elementLengthBytes = new byte[2]; in.read(elementLengthBytes); final int elementLength = twoBytesToLength(elementLengthBytes); if (in.available() < elementLength) - { - throw new SaslEncodingException( - "Illegal SASL extended octet-sequence encoding"); - } - + throw new SaslEncodingException( + "Illegal SASL extended octet-sequence encoding"); byte[] result = new byte[elementLength]; in.read(result); - return result; } /** - * <p>Decodes a SASL MPI from the current buffer.</p> - * + * Decodes a SASL MPI from the current buffer. + * * @return a native representation of a SASL MPI. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws IOException if any other I/O exception occurs during the operation. */ public BigInteger getMPI() throws IOException { if (in.available() < 2) - { - throw new SaslEncodingException("Not enough bytes for an MPI in buffer"); - } + throw new SaslEncodingException("Not enough bytes for an MPI in buffer"); byte[] elementLengthBytes = new byte[2]; in.read(elementLengthBytes); final int elementLength = twoBytesToLength(elementLengthBytes); if (in.available() < elementLength) - { - throw new SaslEncodingException( - "Illegal SASL multi-precision integer encoding"); - } - + throw new SaslEncodingException( + "Illegal SASL multi-precision integer encoding"); byte[] element = new byte[elementLength]; in.read(element); - return new BigInteger(1, element); } /** - * <p>Decodes a SASL Text from the current buffer.</p> - * + * Decodes a SASL Text from the current buffer. + * * @return a native representation of a SASL Text. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws SaslEncodingException if the UTF-8 character encoding is not - * supported on this platform. + * supported on this platform. * @throws IOException if any other I/O exception occurs during the operation. */ public String getText() throws IOException { if (in.available() < 2) - { - throw new SaslEncodingException("Not enough bytes for a text in buffer"); - } + throw new SaslEncodingException("Not enough bytes for a text in buffer"); byte[] elementLengthBytes = new byte[2]; in.read(elementLengthBytes); final int elementLength = twoBytesToLength(elementLengthBytes); if (in.available() < elementLength) - { - throw new SaslEncodingException("Illegal SASL text encoding"); - } - + throw new SaslEncodingException("Illegal SASL text encoding"); byte[] element = new byte[elementLength]; in.read(element); - return new String(element, "UTF8"); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/IntegrityException.java b/gnu/javax/crypto/sasl/IntegrityException.java index 4a56ca2d5..9b793ce3e 100644 --- a/gnu/javax/crypto/sasl/IntegrityException.java +++ b/gnu/javax/crypto/sasl/IntegrityException.java @@ -46,9 +46,9 @@ import javax.security.sasl.SaslException; * processing of an <i>integrity</i> protection filter, including <i>replay * detection</i>. */ -public class IntegrityException extends SaslException +public class IntegrityException + extends SaslException { - /** * Constructs a new instance of <code>IntegrityException</code> with no * detail message. @@ -61,7 +61,7 @@ public class IntegrityException extends SaslException /** * Constructs a new instance of <code>IntegrityException</code> with the * specified detail message. - * + * * @param s the detail message. */ public IntegrityException(String s) @@ -72,7 +72,7 @@ public class IntegrityException extends SaslException /** * Constructs a new instance of <code>IntegrityException</code> with a * detailed message and a root exception. - * + * * @param s possibly null additional detail about the exception. * @param x a possibly null root exception that caused this one. */ @@ -80,4 +80,4 @@ public class IntegrityException extends SaslException { super(s, x); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/NoSuchMechanismException.java b/gnu/javax/crypto/sasl/NoSuchMechanismException.java index 65432082a..5b16a788c 100644 --- a/gnu/javax/crypto/sasl/NoSuchMechanismException.java +++ b/gnu/javax/crypto/sasl/NoSuchMechanismException.java @@ -44,19 +44,19 @@ import javax.security.sasl.SaslException; * A checked exception thrown to indicate that a designated SASL mechanism * implementation was not found. */ -public class NoSuchMechanismException extends SaslException +public class NoSuchMechanismException + extends SaslException { - /** * Constructs a <code>NoSuchMechanismException</code> with the specified * detail message. In the case of this exception, the detail message * designates the offending mechanism name. - * + * * @param arg the detail message, which in this case is the offending - * mechanism name. + * mechanism name. */ public NoSuchMechanismException(String arg) { super(arg); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/NoSuchUserException.java b/gnu/javax/crypto/sasl/NoSuchUserException.java index fe362c742..387339f60 100644 --- a/gnu/javax/crypto/sasl/NoSuchUserException.java +++ b/gnu/javax/crypto/sasl/NoSuchUserException.java @@ -44,9 +44,9 @@ import javax.security.sasl.AuthenticationException; * A checked exception thrown to indicate that a designated user is unknown to * the authentication layer. */ -public class NoSuchUserException extends AuthenticationException +public class NoSuchUserException + extends AuthenticationException { - /** Constructs a <code>NoSuchUserException</code> with no detail message. */ public NoSuchUserException() { @@ -55,9 +55,9 @@ public class NoSuchUserException extends AuthenticationException /** * Constructs a <code>NoSuchUserException</code> with the specified detail - * message. In the case of this exception, the detail message designates - * the offending username. - * + * message. In the case of this exception, the detail message designates the + * offending username. + * * @param arg the detail message, which in this case is the username. */ public NoSuchUserException(String arg) diff --git a/gnu/javax/crypto/sasl/OutputBuffer.java b/gnu/javax/crypto/sasl/OutputBuffer.java index d219e7e9f..92e34dfbf 100644 --- a/gnu/javax/crypto/sasl/OutputBuffer.java +++ b/gnu/javax/crypto/sasl/OutputBuffer.java @@ -46,31 +46,25 @@ import java.io.IOException; import java.math.BigInteger; /** - * <p>The implementation of an outgoing SASL buffer.</p> - * - * <p>The data elements this class caters for are described in [1].</p> - * - * <p>References:</p> + * The implementation of an outgoing SASL buffer. + * <p> + * The data elements this class caters for are described in [1]. + * <p> + * References: * <ol> - * <li><a href="http://www.ietf.org/internet-drafts/draft-burdis-cat-srp-sasl-09.txt"> - * Secure Remote Password Authentication Mechanism</a>;<br/> - * draft-burdis-cat-srp-sasl-09,<br/> - * <a href="mailto:keith@rucus.ru.ac.za">Keith Burdis</a> and - * <a href="mailto:raif@forge.com.au">Raïf S. Naffah</a>.</li> + * <li><a + * href="http://www.ietf.org/internet-drafts/draft-burdis-cat-srp-sasl-09.txt"> + * Secure Remote Password Authentication Mechanism</a>;<br/> + * draft-burdis-cat-srp-sasl-09,<br/> <a + * href="mailto:keith@rucus.ru.ac.za">Keith Burdis</a> and <a + * href="mailto:raif@forge.com.au">Raïf S. Naffah</a>.</li> * </ol> */ public class OutputBuffer { - - // Constants and variables - // ------------------------------------------------------------------------- - /** The internal output stream. */ private ByteArrayOutputStream out; - // Constructor(s) - // ------------------------------------------------------------------------- - public OutputBuffer() { super(); @@ -78,16 +72,10 @@ public class OutputBuffer out = new ByteArrayOutputStream(); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - /** - * <p>Encodes a SASL scalar quantity, <code>count</code>-octet long, to the - * current buffer.</p> - * + * Encodes a SASL scalar quantity, <code>count</code>-octet long, to the + * current buffer. + * * @param count number of octets to encode <code>b</code> with. * @param b the scalar quantity. * @throws SaslEncodingException if an encoding size constraint is violated. @@ -96,21 +84,17 @@ public class OutputBuffer public void setScalar(int count, int b) throws IOException { if (count < 0 || count > 4) - { - throw new SaslEncodingException("Invalid SASL scalar octet count: " - + String.valueOf(count)); - } + throw new SaslEncodingException("Invalid SASL scalar octet count: " + + String.valueOf(count)); byte[] element = new byte[count]; for (int i = count; --i >= 0; b >>>= 8) - { - element[i] = (byte) b; - } + element[i] = (byte) b; out.write(element); } /** - * <p>Encodes a SASL OS to the current buffer.</p> - * + * Encodes a SASL OS to the current buffer. + * * @param b the OS element. * @throws SaslEncodingException if an encoding size constraint is violated. * @throws IOException if any other I/O exception occurs during the operation. @@ -119,16 +103,14 @@ public class OutputBuffer { final int length = b.length; if (length > Registry.SASL_ONE_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL octet-sequence too long"); - } + throw new SaslEncodingException("SASL octet-sequence too long"); out.write(length & 0xFF); out.write(b); } /** - * <p>Encodes a SASL EOS to the current buffer.</p> - * + * Encodes a SASL EOS to the current buffer. + * * @param b the EOS element. * @throws SaslEncodingException if an encoding size constraint is violated. * @throws IOException if any other I/O exception occurs during the operation. @@ -137,17 +119,15 @@ public class OutputBuffer { final int length = b.length; if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL extended octet-sequence too long"); - } - byte[] lengthBytes = { (byte) (length >>> 8), (byte) length }; + throw new SaslEncodingException("SASL extended octet-sequence too long"); + byte[] lengthBytes = { (byte)(length >>> 8), (byte) length }; out.write(lengthBytes); out.write(b); } /** - * <p>Encodes a SASL MPI to the current buffer.</p> - * + * Encodes a SASL MPI to the current buffer. + * * @param val the MPI element. * @throws SaslEncodingException if an encoding size constraint is violated. * @throws IOException if any other I/O exception occurs during the operation. @@ -157,21 +137,19 @@ public class OutputBuffer byte[] b = Util.trim(val); final int length = b.length; if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL multi-precision integer too long"); - } - byte[] lengthBytes = { (byte) (length >>> 8), (byte) length }; + throw new SaslEncodingException("SASL multi-precision integer too long"); + byte[] lengthBytes = { (byte)(length >>> 8), (byte) length }; out.write(lengthBytes); out.write(b); } /** - * <p>Encodes a SASL Text to the current buffer.</p> - * + * Encodes a SASL Text to the current buffer. + * * @param str the Text element. * @throws SaslEncodingException if an encoding size constraint is violated. * @throws SaslEncodingException if the UTF-8 encoding is not supported on - * this platform. + * this platform. * @throws IOException if any other I/O exception occurs during the operation. */ public void setText(String str) throws IOException @@ -179,18 +157,16 @@ public class OutputBuffer byte[] b = str.getBytes("UTF8"); final int length = b.length; if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL text too long"); - } - byte[] lengthBytes = { (byte) (length >>> 8), (byte) length }; + throw new SaslEncodingException("SASL text too long"); + byte[] lengthBytes = { (byte)(length >>> 8), (byte) length }; out.write(lengthBytes); out.write(b); } /** - * <p>Returns the encoded form of the current buffer including the 4-byte - * length header.</p> - * + * Returns the encoded form of the current buffer including the 4-byte length + * header. + * * @throws SaslEncodingException if an encoding size constraint is violated. */ public byte[] encode() throws SaslEncodingException @@ -198,28 +174,25 @@ public class OutputBuffer byte[] buffer = wrap(); final int length = buffer.length; byte[] result = new byte[length + 4]; - result[0] = (byte) (length >>> 24); - result[1] = (byte) (length >>> 16); - result[2] = (byte) (length >>> 8); + result[0] = (byte)(length >>> 24); + result[1] = (byte)(length >>> 16); + result[2] = (byte)(length >>> 8); result[3] = (byte) length; System.arraycopy(buffer, 0, result, 4, length); - return result; } /** - * <p>Returns the encoded form of the current buffer excluding the 4-byte - * length header.</p> - * + * Returns the encoded form of the current buffer excluding the 4-byte length + * header. + * * @throws SaslEncodingException if an encoding size constraint is violated. */ public byte[] wrap() throws SaslEncodingException { final int length = out.size(); if (length > Registry.SASL_BUFFER_MAX_LIMIT || length < 0) - { - throw new SaslEncodingException("SASL buffer too long"); - } + throw new SaslEncodingException("SASL buffer too long"); return out.toByteArray(); } } diff --git a/gnu/javax/crypto/sasl/SaslEncodingException.java b/gnu/javax/crypto/sasl/SaslEncodingException.java index 9f4c59f1c..f6a74641d 100644 --- a/gnu/javax/crypto/sasl/SaslEncodingException.java +++ b/gnu/javax/crypto/sasl/SaslEncodingException.java @@ -44,9 +44,9 @@ import javax.security.sasl.SaslException; * A checked exception, thrown when an exception occurs while decoding a SASL * buffer and/or a SASL data element from/to a buffer. */ -public class SaslEncodingException extends SaslException +public class SaslEncodingException + extends SaslException { - /** Constructs a <code>SaslEncodingException</code> with no detail message. */ public SaslEncodingException() { @@ -56,11 +56,11 @@ public class SaslEncodingException extends SaslException /** * Constructs a <code>SaslEncodingException</code> with the specified detail * message. - * + * * @param s the detail message. */ public SaslEncodingException(String s) { super(s); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/SaslInputStream.java b/gnu/javax/crypto/sasl/SaslInputStream.java index 1bd305f5f..d127bf5ba 100644 --- a/gnu/javax/crypto/sasl/SaslInputStream.java +++ b/gnu/javax/crypto/sasl/SaslInputStream.java @@ -54,7 +54,8 @@ import javax.security.sasl.SaslServer; * An input stream that uses either a {@link SaslClient} or a {@link SaslServer} * to process the data through these entities' security layer filter(s). */ -public class SaslInputStream extends InputStream +public class SaslInputStream + extends InputStream { private static final Logger log = Logger.getLogger(SaslInputStream.class.getName()); private SaslClient client; @@ -63,16 +64,14 @@ public class SaslInputStream extends InputStream private InputStream source; private byte[] internalBuf; - // Constructor(s) - // ------------------------------------------------------------------------- - public SaslInputStream(SaslClient client, InputStream source) throws IOException { super(); this.client = client; - maxRawSendSize = Integer.parseInt((String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE)); + String size = (String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE); + maxRawSendSize = Integer.parseInt(size); server = null; this.source = source; } @@ -83,19 +82,12 @@ public class SaslInputStream extends InputStream super(); this.server = server; - maxRawSendSize = Integer.parseInt((String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE)); + String size = (String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE); + maxRawSendSize = Integer.parseInt(size); client = null; this.source = source; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // Overloaded java.io.InputStream methods ---------------------------------- - public int available() throws IOException { return (internalBuf == null) ? 0 : internalBuf.length; @@ -107,25 +99,25 @@ public class SaslInputStream extends InputStream } /** - * <p>Reads the next byte of data from the input stream. The value byte is + * Reads the next byte of data from the input stream. The value byte is * returned as an <code>int</code> in the range <code>0</code> to * <code>255</code>. If no byte is available because the end of the stream * has been reached, the value <code>-1</code> is returned. This method - * blocks until input data is available, the end of the stream is detected, - * or an exception is thrown.</p> - * - * <p>From a SASL mechanism provider's perspective, if a security layer has - * been negotiated, the underlying <i>source</i> is expected to contain SASL + * blocks until input data is available, the end of the stream is detected, or + * an exception is thrown. + * <p> + * From a SASL mechanism provider's perspective, if a security layer has been + * negotiated, the underlying <i>source</i> is expected to contain SASL * buffers, as defined in RFC 2222. Four octets in network byte order in the * front of each buffer identify the length of the buffer. The provider is * responsible for performing any integrity checking or other processing on * the buffer before returning the data as a stream of octets. For example, * the protocol driver's request for a single octet from the stream might; * i.e. an invocation of this method, may result in an entire SASL buffer - * being read and processed before that single octet can be returned.</p> - * - * @return the next byte of data, or <code>-1</code> if the end of the stream - * is reached. + * being read and processed before that single octet can be returned. + * + * @return the next byte of data, or <code>-1</code> if the end of the + * stream is reached. * @throws IOException if an I/O error occurs. */ public int read() throws IOException @@ -149,75 +141,74 @@ public class SaslInputStream extends InputStream int check = read(buf); result = (check > 0) ? (buf[0] & 0xFF) : -1; } - return result; } /** - * <p>Reads up to <code>len</code> bytes of data from the underlying - * <i>source</i> input stream into an array of bytes. An attempt is made to - * read as many as <code>len</code> bytes, but a smaller number may be read, - * possibly zero. The number of bytes actually read is returned as an - * integer.</p> - * - * <p>This method blocks until input data is available, end of file is - * detected, or an exception is thrown.</p> - * - * <p>If <code>b</code> is <code>null</code>, a {@link NullPointerException} is - * thrown.</p> - * - * <p>If <code>off</code> is negative, or <code>len</code> is negative, or - * <code>off+len</code> is greater than the length of the array <code>b</code>, - * then an {@link IndexOutOfBoundsException} is thrown.</p> - * - * <p>If <code>len</code> is zero, then no bytes are read and <code>0</code> + * Reads up to <code>len</code> bytes of data from the underlying <i>source</i> + * input stream into an array of bytes. An attempt is made to read as many as + * <code>len</code> bytes, but a smaller number may be read, possibly zero. + * The number of bytes actually read is returned as an integer. + * <p> + * This method blocks until input data is available, end of file is detected, + * or an exception is thrown. + * <p> + * If <code>b</code> is <code>null</code>, a {@link NullPointerException} + * is thrown. + * <p> + * If <code>off</code> is negative, or <code>len</code> is negative, or + * <code>off+len</code> is greater than the length of the array + * <code>b</code>, then an {@link IndexOutOfBoundsException} is thrown. + * <p> + * If <code>len</code> is zero, then no bytes are read and <code>0</code> * is returned; otherwise, there is an attempt to read at least one byte. If * no byte is available because the stream is at end of file, the value * <code>-1</code> is returned; otherwise, at least one byte is read and - * stored into <code>b</code>.</p> - * - * <p>The first byte read is stored into element <code>b[off]</code>, the - * next one into <code>b[off+1]</code>, and so on. The number of bytes read - * is, at most, equal to <code>len</code>. Let <code>k</code> be the number + * stored into <code>b</code>. + * <p> + * The first byte read is stored into element <code>b[off]</code>, the next + * one into <code>b[off+1]</code>, and so on. The number of bytes read is, + * at most, equal to <code>len</code>. Let <code>k</code> be the number * of bytes actually read; these bytes will be stored in elements * <code>b[off]</code> through <code>b[off+k-1]</code>, leaving elements - * <code>b[off+k]</code> through <code>b[off+len-1]</code> unaffected.</p> - * - * <p>In every case, elements <code>b[0]</code> through <code>b[off]</code> + * <code>b[off+k]</code> through <code>b[off+len-1]</code> unaffected. + * <p> + * In every case, elements <code>b[0]</code> through <code>b[off]</code> * and elements <code>b[off+len]</code> through <code>b[b.length-1]</code> - * are unaffected.</p> - * - * <p>If the first byte cannot be read for any reason other than end of file, - * then an {@link IOException} is thrown. In particular, an {@link IOException} - * is thrown if the input stream has been closed.</p> - * - * <p>From the SASL mechanism provider's perspective, if a security layer has + * are unaffected. + * <p> + * If the first byte cannot be read for any reason other than end of file, + * then an {@link IOException} is thrown. In particular, an + * {@link IOException} is thrown if the input stream has been closed. + * <p> + * From the SASL mechanism provider's perspective, if a security layer has * been negotiated, the underlying <i>source</i> is expected to contain SASL * buffers, as defined in RFC 2222. Four octets in network byte order in the * front of each buffer identify the length of the buffer. The provider is * responsible for performing any integrity checking or other processing on * the buffer before returning the data as a stream of octets. The protocol * driver's request for a single octet from the stream might result in an - * entire SASL buffer being read and processed before that single octet can - * be returned.</p> - * + * entire SASL buffer being read and processed before that single octet can be + * returned. + * * @param b the buffer into which the data is read. * @param off the start offset in array <code>b</code> at which the data is - * wricodeen. + * wricodeen. * @param len the maximum number of bytes to read. * @return the total number of bytes read into the buffer, or <code>-1</code> - * if there is no more data because the end of the stream has been reached. + * if there is no more data because the end of the stream has been + * reached. * @throws IOException if an I/O error occurs. */ public int read(byte[] b, int off, int len) throws IOException { if (Configuration.DEBUG) - log.entering(this.getClass().getName(), "read", - new Object[] { b, Integer.valueOf(off), Integer.valueOf(len) }); + log.entering(this.getClass().getName(), "read", new Object[] { + b, Integer.valueOf(off), Integer.valueOf(len) + }); if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) - throw new IndexOutOfBoundsException("off=" + off - + ", len=" + len + throw new IndexOutOfBoundsException("off=" + off + ", len=" + len + ", b.length=" + b.length); if (len == 0) { @@ -254,7 +245,6 @@ public class SaslInputStream extends InputStream } return -1; } - if (len <= internalBuf.length) { result = len; @@ -274,10 +264,8 @@ public class SaslInputStream extends InputStream result = internalBuf.length; System.arraycopy(internalBuf, 0, b, off, result); internalBuf = null; - off += result; len -= result; - int remaining; // count of bytes remaining in buffer after an iteration int delta; // count of bytes moved to b after an iteration int datalen; @@ -295,9 +283,7 @@ public class SaslInputStream extends InputStream log.finer("Underlying stream exhausted. Breaking..."); break; } - datalen = data.length; - // copy [part of] the result to b remaining = (datalen <= len) ? 0 : datalen - len; delta = datalen - remaining; @@ -307,7 +293,6 @@ public class SaslInputStream extends InputStream internalBuf = new byte[remaining]; System.arraycopy(data, delta, internalBuf, 0, remaining); } - // update off, result and len off += delta; result += delta; @@ -322,20 +307,19 @@ public class SaslInputStream extends InputStream } if (Configuration.DEBUG) { - log.finer("Remaining: " + (internalBuf == null ? 0 : internalBuf.length)); + log.finer("Remaining: " + + (internalBuf == null ? 0 : internalBuf.length)); log.exiting(this.getClass().getName(), "read()", String.valueOf(result)); } return result; } - // other nstance methods --------------------------------------------------- - /** * Reads a SASL buffer from the underlying source if at least 4 bytes are * available. - * + * * @return the byte[] of decoded buffer contents, or null if the underlying - * source was exhausted. + * source was exhausted. * @throws IOException if an I/O exception occurs during the operation. */ private byte[] readSaslBuffer() throws IOException @@ -360,12 +344,12 @@ public class SaslInputStream extends InputStream log.throwing(this.getClass().getName(), "readSaslBuffer", x); throw x; } - if (realLength != 4) throw new IOException("Was expecting 4 but found " + realLength); - int bufferLength = result[0] << 24 | (result[1] & 0xFF) << 16 - | (result[2] & 0xFF) << 8 | (result[3] & 0xFF); - + int bufferLength = result[0] << 24 + | (result[1] & 0xFF) << 16 + | (result[2] & 0xFF) << 8 + | (result[3] & 0xFF); if (Configuration.DEBUG) log.finer("SASL buffer size: " + bufferLength); if (bufferLength > maxRawSendSize || bufferLength < 0) @@ -382,10 +366,9 @@ public class SaslInputStream extends InputStream log.throwing(this.getClass().getName(), "readSaslBuffer", x); throw x; } - if (realLength != bufferLength) - throw new IOException("Was expecting " + bufferLength - + " but found " + realLength); + throw new IOException("Was expecting " + bufferLength + " but found " + + realLength); if (Configuration.DEBUG) { log.finer("Incoming buffer (before security) (hex): " @@ -397,7 +380,6 @@ public class SaslInputStream extends InputStream result = client.unwrap(result, 0, realLength); else result = server.unwrap(result, 0, realLength); - if (Configuration.DEBUG) { log.finer("Incoming buffer (after security) (hex): " @@ -408,4 +390,4 @@ public class SaslInputStream extends InputStream } return result; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/SaslOutputStream.java b/gnu/javax/crypto/sasl/SaslOutputStream.java index ce9d93242..d21f1f37a 100644 --- a/gnu/javax/crypto/sasl/SaslOutputStream.java +++ b/gnu/javax/crypto/sasl/SaslOutputStream.java @@ -53,7 +53,8 @@ import javax.security.sasl.SaslServer; * An output stream that uses either a {@link SaslClient} or a {@link SaslServer} * to process the data through these entities' security layer filter(s). */ -public class SaslOutputStream extends OutputStream +public class SaslOutputStream + extends OutputStream { private static final Logger log = Logger.getLogger(SaslOutputStream.class.getName()); private SaslClient client; @@ -61,16 +62,14 @@ public class SaslOutputStream extends OutputStream private int maxRawSendSize; private OutputStream dest; - // Constructor(s) - // ------------------------------------------------------------------------- - public SaslOutputStream(SaslClient client, OutputStream dest) throws IOException { super(); this.client = client; - maxRawSendSize = Integer.parseInt((String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE)); + String size = (String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE); + maxRawSendSize = Integer.parseInt(size); server = null; this.dest = dest; } @@ -81,17 +80,12 @@ public class SaslOutputStream extends OutputStream super(); this.server = server; - maxRawSendSize = Integer.parseInt((String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE)); + String size = (String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE); + maxRawSendSize = Integer.parseInt(size); client = null; this.dest = dest; } - // Class methods - // ------------------------------------------------------------------------- - - // Overloaded java.io.OutputStream methods - // ------------------------------------------------------------------------- - public void close() throws IOException { dest.flush(); @@ -126,8 +120,7 @@ public class SaslOutputStream extends OutputStream log.entering(this.getClass().getName(), "write"); if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) - throw new IndexOutOfBoundsException("off=" + off - + ", len=" + len + throw new IndexOutOfBoundsException("off=" + off + ", len=" + len + ", b.length=" + b.length); if (len == 0) { @@ -163,14 +156,12 @@ public class SaslOutputStream extends OutputStream } length = output.length; result = new byte[length + 4]; - result[0] = (byte) (length >>> 24); - result[1] = (byte) (length >>> 16); - result[2] = (byte) (length >>> 8); + result[0] = (byte)(length >>> 24); + result[1] = (byte)(length >>> 16); + result[2] = (byte)(length >>> 8); result[3] = (byte) length; System.arraycopy(output, 0, result, 4, length); - dest.write(result); - off += chunckSize; len -= chunckSize; if (Configuration.DEBUG) @@ -181,4 +172,4 @@ public class SaslOutputStream extends OutputStream if (Configuration.DEBUG) log.exiting(this.getClass().getName(), "write"); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/SaslUtil.java b/gnu/javax/crypto/sasl/SaslUtil.java index cb8d88e69..4b0b697fe 100644 --- a/gnu/javax/crypto/sasl/SaslUtil.java +++ b/gnu/javax/crypto/sasl/SaslUtil.java @@ -47,30 +47,17 @@ import java.security.MessageDigest; */ public class SaslUtil { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - private SaslUtil() { super(); } - // Class methods - // ------------------------------------------------------------------------- - public static final boolean validEmailAddress(String address) { // need to do better than this return (address.indexOf("@") != -1); } - // Visualisation methods - // ------------------------------------------------------------------------- - /** Returns the context of the designated hash as a string. */ public static final String dump(MessageDigest md) { @@ -85,4 +72,4 @@ public class SaslUtil } return result; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/ServerFactory.java b/gnu/javax/crypto/sasl/ServerFactory.java index e9b08dbd4..7aa379628 100644 --- a/gnu/javax/crypto/sasl/ServerFactory.java +++ b/gnu/javax/crypto/sasl/ServerFactory.java @@ -62,53 +62,33 @@ import javax.security.sasl.SaslServerFactory; /** * The implementation of the {@link SaslServerFactory}. */ -public class ServerFactory implements SaslServerFactory +public class ServerFactory + implements SaslServerFactory { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-arguments constructor - // Class methods - // ------------------------------------------------------------------------- - public static final Set getNames() { - return Collections.unmodifiableSet(new HashSet( - Arrays.asList(getNamesInternal(null)))); + return Collections.unmodifiableSet(new HashSet(Arrays.asList(getNamesInternal(null)))); } private static final String[] getNamesInternal(Map props) { - String[] all = new String[] { Registry.SASL_SRP_MECHANISM, - Registry.SASL_CRAM_MD5_MECHANISM, - Registry.SASL_PLAIN_MECHANISM, - Registry.SASL_ANONYMOUS_MECHANISM }; - + String[] all = new String[] { + Registry.SASL_SRP_MECHANISM, + Registry.SASL_CRAM_MD5_MECHANISM, + Registry.SASL_PLAIN_MECHANISM, + Registry.SASL_ANONYMOUS_MECHANISM }; List result = new ArrayList(4); int i; for (i = 0; i < all.length;) - { - result.add(all[i++]); - } - + result.add(all[i++]); if (props == null) - { - return (String[]) result.toArray(new String[0]); // all - } - if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props)) - { // none - return new String[0]; - } - + return (String[]) result.toArray(new String[0]); // all + if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props)) // none + return new String[0]; if (hasPolicy(Sasl.POLICY_NOPLAINTEXT, props)) - { - result.remove(Registry.SASL_PLAIN_MECHANISM); - } + result.remove(Registry.SASL_PLAIN_MECHANISM); if (hasPolicy(Sasl.POLICY_NOACTIVE, props)) { result.remove(Registry.SASL_CRAM_MD5_MECHANISM); @@ -135,32 +115,19 @@ public class ServerFactory implements SaslServerFactory public static final ServerMechanism getInstance(String mechanism) { if (mechanism == null) - { - return null; - } + return null; mechanism = mechanism.trim().toUpperCase(); if (mechanism.equals(Registry.SASL_SRP_MECHANISM)) - { - return new SRPServer(); - } + return new SRPServer(); if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM)) - { - return new CramMD5Server(); - } + return new CramMD5Server(); if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM)) - { - return new PlainServer(); - } + return new PlainServer(); if (mechanism.equals(Registry.SASL_ANONYMOUS_MECHANISM)) - { - return new AnonymousServer(); - } + return new AnonymousServer(); return null; } - // Instance methods - // ------------------------------------------------------------------------- - public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map props, CallbackHandler cbh) throws SaslException @@ -170,13 +137,10 @@ public class ServerFactory implements SaslServerFactory { HashMap attributes = new HashMap(); if (props != null) - { - attributes.putAll(props); - } + attributes.putAll(props); attributes.put(Registry.SASL_PROTOCOL, protocol); attributes.put(Registry.SASL_SERVER_NAME, serverName); attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh); - result.init(attributes); } return result; @@ -191,4 +155,4 @@ public class ServerFactory implements SaslServerFactory { return "true".equalsIgnoreCase(String.valueOf(props.get(propertyName))); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/ServerMechanism.java b/gnu/javax/crypto/sasl/ServerMechanism.java index f12a075d9..75603a14a 100644 --- a/gnu/javax/crypto/sasl/ServerMechanism.java +++ b/gnu/javax/crypto/sasl/ServerMechanism.java @@ -45,51 +45,36 @@ import java.util.Map; import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; -import javax.security.sasl.SaslServer; import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; /** - * <p>A base class to facilitate implementing SASL server-side mechanisms.</p> + * A base class to facilitate implementing SASL server-side mechanisms. */ -public abstract class ServerMechanism implements SaslServer +public abstract class ServerMechanism + implements SaslServer { - - // Constants and variables - // ------------------------------------------------------------------------- - /** Name of this mechanism. */ protected String mechanism; - /** Name of protocol using this mechanism. */ protected String protocol; - /** Name of server to authenticate to. */ protected String serverName; - /** Properties of qualities desired for this mechanism. */ protected Map properties; - /** Callback handler to use with this mechanism instance. */ protected CallbackHandler handler; - /** Whether authentication phase is completed (true) or not (false). */ protected boolean complete = false; - /** The authorisation identity. */ protected String authorizationID; - /** Channel binding data to use with this mechanism instance. */ protected byte[] channelBinding; - /** The state of the authentication automaton. -1 means uninitialised. */ protected int state = -1; - /** The provider for authentication information. */ protected IAuthInfoProvider authenticator; - // Constructor(s) - // ------------------------------------------------------------------------- - protected ServerMechanism(final String mechanism) { super(); @@ -99,20 +84,10 @@ public abstract class ServerMechanism implements SaslServer this.state = -1; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods to be implemented by concrete subclasses --------------- - protected abstract void initMechanism() throws SaslException; protected abstract void resetMechanism() throws SaslException; - // javax.security.sasl.SaslServer interface implementation ----------------- - public abstract byte[] evaluateResponse(byte[] response) throws SaslException; public boolean isComplete() @@ -123,20 +98,16 @@ public abstract class ServerMechanism implements SaslServer public byte[] unwrap(final byte[] incoming, final int offset, final int len) throws SaslException { - if (!isComplete()) - { - throw new IllegalMechanismStateException(); - } + if (! isComplete()) + throw new IllegalMechanismStateException(); return this.engineUnwrap(incoming, offset, len); } public byte[] wrap(final byte[] outgoing, final int offset, final int len) throws SaslException { - if (!isComplete()) - { - throw new IllegalMechanismStateException(); - } + if (! isComplete()) + throw new IllegalMechanismStateException(); return this.engineWrap(outgoing, offset, len); } @@ -152,58 +123,32 @@ public abstract class ServerMechanism implements SaslServer public Object getNegotiatedProperty(final String propName) { - if (!isComplete()) - { - throw new IllegalStateException(); - } + if (! isComplete()) + throw new IllegalStateException(); if (Sasl.QOP.equals(propName)) - { - return getNegotiatedQOP(); - } + return getNegotiatedQOP(); if (Sasl.STRENGTH.equals(propName)) - { - return getNegotiatedStrength(); - } + return getNegotiatedStrength(); if (Sasl.SERVER_AUTH.equals(propName)) - { - return getNegotiatedServerAuth(); - } + return getNegotiatedServerAuth(); if (Sasl.MAX_BUFFER.equals(propName)) - { - return getNegotiatedMaxBuffer(); - } + return getNegotiatedMaxBuffer(); if (Sasl.RAW_SEND_SIZE.equals(propName)) - { - return getNegotiatedRawSendSize(); - } + return getNegotiatedRawSendSize(); if (Sasl.POLICY_NOPLAINTEXT.equals(propName)) - { - return getNegotiatedPolicyNoPlainText(); - } + return getNegotiatedPolicyNoPlainText(); if (Sasl.POLICY_NOACTIVE.equals(propName)) - { - return getNegotiatedPolicyNoActive(); - } + return getNegotiatedPolicyNoActive(); if (Sasl.POLICY_NODICTIONARY.equals(propName)) - { - return getNegotiatedPolicyNoDictionary(); - } + return getNegotiatedPolicyNoDictionary(); if (Sasl.POLICY_NOANONYMOUS.equals(propName)) - { - return getNegotiatedPolicyNoAnonymous(); - } + return getNegotiatedPolicyNoAnonymous(); if (Sasl.POLICY_FORWARD_SECRECY.equals(propName)) - { - return getNegotiatedPolicyForwardSecrecy(); - } + return getNegotiatedPolicyForwardSecrecy(); if (Sasl.POLICY_PASS_CREDENTIALS.equals(propName)) - { - return getNegotiatedPolicyPassCredentials(); - } + return getNegotiatedPolicyPassCredentials(); if (Sasl.REUSE.equals(propName)) - { - return getReuse(); - } + return getReuse(); return null; } @@ -212,8 +157,6 @@ public abstract class ServerMechanism implements SaslServer reset(); } - // other Instance methods -------------------------------------------------- - protected String getNegotiatedQOP() { return Registry.QOP_AUTH; @@ -291,30 +234,23 @@ public abstract class ServerMechanism implements SaslServer } /** - * <p>Initialises the mechanism with designated attributes. Permissible names - * and values are mechanism specific.</p> - * + * Initialises the mechanism with designated attributes. Permissible names and + * values are mechanism specific. + * * @param attributes a set of name-value pairs that describes the desired - * future behaviour of this instance. + * future behaviour of this instance. * @throws IllegalMechanismStateException if the instance is already - * initialised. + * initialised. * @throws SaslException if an exception occurs during the process. */ public void init(final Map attributes) throws SaslException { if (state != -1) - { - throw new IllegalMechanismStateException("init()"); - } - + throw new IllegalMechanismStateException("init()"); if (properties == null) - { - properties = new HashMap(); - } + properties = new HashMap(); else - { - properties.clear(); - } + properties.clear(); if (attributes != null) { protocol = (String) attributes.get(Registry.SASL_PROTOCOL); @@ -324,35 +260,24 @@ public abstract class ServerMechanism implements SaslServer properties.putAll(attributes); } else - { - handler = null; - } - + handler = null; if (protocol == null) - { - protocol = ""; - } + protocol = ""; if (serverName == null) - { - serverName = ""; - } + serverName = ""; if (authenticator != null) - { - authenticator.activate(properties); - } + authenticator.activate(properties); if (channelBinding == null) - { - channelBinding = new byte[0]; - } + channelBinding = new byte[0]; initMechanism(); complete = false; state = 0; } /** - * <p>Resets the mechanism instance for re-initialisation and use with other - * characteristics.</p> - * + * Resets the mechanism instance for re-initialisation and use with other + * characteristics. + * * @throws SaslException if an exception occurs during the process. */ public void reset() throws SaslException @@ -360,12 +285,10 @@ public abstract class ServerMechanism implements SaslServer resetMechanism(); properties.clear(); if (authenticator != null) - { - authenticator.passivate(); - } + authenticator.passivate(); protocol = serverName = null; channelBinding = null; complete = false; state = -1; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/UserAlreadyExistsException.java b/gnu/javax/crypto/sasl/UserAlreadyExistsException.java index 764a36df3..1563be917 100644 --- a/gnu/javax/crypto/sasl/UserAlreadyExistsException.java +++ b/gnu/javax/crypto/sasl/UserAlreadyExistsException.java @@ -44,9 +44,9 @@ import javax.security.sasl.SaslException; * A checked exception thrown to indicate that a designated user is already * known to the the authentication layer. */ -public class UserAlreadyExistsException extends SaslException +public class UserAlreadyExistsException + extends SaslException { - /** * Constructs a <code>UserAlreadyExistsException</code> with no detail * message. @@ -60,7 +60,7 @@ public class UserAlreadyExistsException extends SaslException * Constructs a <code>UserAlreadyExistsException</code> with the specified * detail message. In the case of this exception, the detail message * designates the offending username. - * + * * @param userName the detail message, which in this case is the username. */ public UserAlreadyExistsException(String userName) diff --git a/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java b/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java index f5b1faab2..87f5e5fb5 100644 --- a/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java +++ b/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java @@ -44,35 +44,22 @@ import gnu.javax.crypto.sasl.IllegalMechanismStateException; import java.io.UnsupportedEncodingException; +import javax.security.sasl.AuthenticationException; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; -import javax.security.sasl.AuthenticationException; /** - * <p>The ANONYMOUS client-side mechanism.</p> + * The ANONYMOUS client-side mechanism. */ -public class AnonymousClient extends ClientMechanism implements SaslClient +public class AnonymousClient + extends ClientMechanism + implements SaslClient { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public AnonymousClient() { super(Registry.SASL_ANONYMOUS_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -81,8 +68,6 @@ public class AnonymousClient extends ClientMechanism implements SaslClient { } - // javax.security.sasl.SaslClient interface implementation ----------------- - public boolean hasInitialResponse() { return true; @@ -99,13 +84,10 @@ public class AnonymousClient extends ClientMechanism implements SaslClient private byte[] response() throws SaslException { - if (!AnonymousUtil.isValidTraceInformation(authorizationID)) - { - throw new AuthenticationException( - "Authorisation ID is not a valid email address"); - } + if (! AnonymousUtil.isValidTraceInformation(authorizationID)) + throw new AuthenticationException( + "Authorisation ID is not a valid email address"); complete = true; - // return authorizationID.getBytes(); final byte[] result; try { @@ -117,4 +99,4 @@ public class AnonymousClient extends ClientMechanism implements SaslClient } return result; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java b/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java index 2c10f78a7..76456044c 100644 --- a/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java +++ b/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java @@ -50,28 +50,15 @@ import javax.security.sasl.SaslServer; /** * The ANONYMOUS server-side mechanism. */ -public class AnonymousServer extends ServerMechanism implements SaslServer +public class AnonymousServer + extends ServerMechanism + implements SaslServer { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public AnonymousServer() { super(Registry.SASL_ANONYMOUS_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -80,14 +67,10 @@ public class AnonymousServer extends ServerMechanism implements SaslServer { } - // javax.security.sasl.SaslServer interface implementation ----------------- - public byte[] evaluateResponse(final byte[] response) throws SaslException { if (response == null) - { - return null; - } + return null; try { authorizationID = new String(response, "UTF-8"); @@ -104,4 +87,4 @@ public class AnonymousServer extends ServerMechanism implements SaslServer authorizationID = null; throw new AuthenticationException("Invalid email address"); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java b/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java index 99e95eaec..9047ebd5c 100644 --- a/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java +++ b/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java @@ -45,65 +45,39 @@ import gnu.javax.crypto.sasl.SaslUtil; */ public class AnonymousUtil { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - /** Trivial private constructor to enforce Singleton pattern. */ private AnonymousUtil() { super(); } - // Class methods - // ------------------------------------------------------------------------- - static boolean isValidTraceInformation(String traceInformation) { if (traceInformation == null) - { - return false; - } + return false; if (traceInformation.length() == 0) - { - return true; - } + return true; if (SaslUtil.validEmailAddress(traceInformation)) - { - return true; - } + return true; return isValidToken(traceInformation); } static boolean isValidToken(String token) { if (token == null) - { - return false; - } + return false; if (token.length() == 0) - { - return false; - } + return false; if (token.length() > 255) - { - return false; - } + return false; if (token.indexOf('@') != -1) - { - return false; - } + return false; for (int i = 0; i < token.length(); i++) { char c = token.charAt(i); if (c < 0x20 || c > 0x7E) - { - return false; - } + return false; } return true; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java b/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java index cf73b6f98..dec0366c0 100644 --- a/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java +++ b/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java @@ -51,44 +51,26 @@ import javax.security.sasl.AuthenticationException; /** * The CRAM-MD5 mechanism authentication information provider implementation. */ -public class CramMD5AuthInfoProvider implements IAuthInfoProvider +public class CramMD5AuthInfoProvider + implements IAuthInfoProvider { - - // Constants and variables - // ------------------------------------------------------------------------- - private PasswordFile passwordFile = null; - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-args constrcutor - // Class methods - // ------------------------------------------------------------------------- - - // IAuthInfoProvider interface implementation - // ------------------------------------------------------------------------- - public void activate(Map context) throws AuthenticationException { try { if (context == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else { String pfn = (String) context.get(CramMD5Registry.PASSWORD_FILE); if (pfn == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else - { - passwordFile = new PasswordFile(pfn); - } + passwordFile = new PasswordFile(pfn); } } catch (IOException x) @@ -105,10 +87,8 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("contains()", - new IllegalStateException()); - } + throw new AuthenticationException("contains()", + new IllegalStateException()); boolean result = false; try { @@ -124,18 +104,13 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("lookup()", - new IllegalStateException()); - } + throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null) - { - throw new NoSuchUserException(""); - } + throw new NoSuchUserException(""); String[] data = passwordFile.lookup(userName); result.put(Registry.SASL_USERNAME, data[0]); result.put(Registry.SASL_PASSWORD, data[1]); @@ -148,9 +123,7 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("lookup()", x); } return result; @@ -159,10 +132,7 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider public void update(Map userCredentials) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("update()", - new IllegalStateException()); - } + throw new AuthenticationException("update()", new IllegalStateException()); try { String userName = (String) userCredentials.get(Registry.SASL_USERNAME); @@ -174,9 +144,7 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider String shell = (String) userCredentials.get(CramMD5Registry.SHELL_FIELD); if (uid == null || gid == null || gecos == null || dir == null || shell == null) - { - passwordFile.changePasswd(userName, password); - } + passwordFile.changePasswd(userName, password); else { String[] attributes = new String[] { uid, gid, gecos, dir, shell }; @@ -186,9 +154,7 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("update()", x); } } @@ -197,4 +163,4 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider { throw new AuthenticationException("", new UnsupportedOperationException()); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java b/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java index 094109ff9..c90cbe986 100644 --- a/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java +++ b/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java @@ -56,25 +56,15 @@ import javax.security.sasl.SaslException; /** * The CRAM-MD5 SASL client-side mechanism. */ -public class CramMD5Client extends ClientMechanism implements SaslClient +public class CramMD5Client + extends ClientMechanism + implements SaslClient { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public CramMD5Client() { super(Registry.SASL_CRAM_MD5_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -83,8 +73,6 @@ public class CramMD5Client extends ClientMechanism implements SaslClient { } - // javax.security.sasl.SaslClient interface implementation ----------------- - public boolean hasInitialResponse() { return false; @@ -93,30 +81,22 @@ public class CramMD5Client extends ClientMechanism implements SaslClient public byte[] evaluateChallenge(final byte[] challenge) throws SaslException { if (challenge == null) - { - throw new SaslException("null challenge"); - } + throw new SaslException("null challenge"); try { final String username; final char[] password; Callback[] callbacks; - - if ((!properties.containsKey(Registry.SASL_USERNAME)) - && (!properties.containsKey(Registry.SASL_PASSWORD))) + if ((! properties.containsKey(Registry.SASL_USERNAME)) + && (! properties.containsKey(Registry.SASL_PASSWORD))) { callbacks = new Callback[2]; - final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); final PasswordCallback pwdCB = new PasswordCallback("password: ", false); callbacks[0] = nameCB; @@ -128,47 +108,35 @@ public class CramMD5Client extends ClientMechanism implements SaslClient else { if (properties.containsKey(Registry.SASL_USERNAME)) - { - username = (String) properties.get(Registry.SASL_USERNAME); - } + username = (String) properties.get(Registry.SASL_USERNAME); else { callbacks = new Callback[1]; final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); callbacks[0] = nameCB; this.handler.handle(callbacks); username = nameCB.getName(); } if (properties.containsKey(Registry.SASL_PASSWORD)) - { - password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray(); - } + password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray(); else { callbacks = new Callback[1]; - final PasswordCallback pwdCB = new PasswordCallback( - "password: ", + final PasswordCallback pwdCB = new PasswordCallback("password: ", false); callbacks[0] = pwdCB; this.handler.handle(callbacks); password = pwdCB.getPassword(); } } - if (password == null) - { - throw new SaslException("null password supplied"); - } + throw new SaslException("null password supplied"); final byte[] digest; try { @@ -181,7 +149,6 @@ public class CramMD5Client extends ClientMechanism implements SaslClient final String response = username + " " + Util.toString(digest).toLowerCase(); this.complete = true; - return response.getBytes("UTF-8"); } catch (UnsupportedCallbackException x) @@ -198,4 +165,4 @@ public class CramMD5Client extends ClientMechanism implements SaslClient { return Registry.QOP_AUTH; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java b/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java index 1c61cace4..bbd46a3f2 100644 --- a/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java +++ b/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java @@ -45,22 +45,16 @@ public interface CramMD5Registry { /** Name of the password file (used by the server) property. */ String PASSWORD_FILE = "gnu.crypto.sasl.crammd5.password.file"; - /** Default password file (used by the server) pathname. */ String DEFAULT_PASSWORD_FILE = "/etc/passwd"; - /** Name of the UID field in the plain password file. */ String UID_FIELD = "crammd5.uid"; - /** Name of the GID field in the plain password file. */ String GID_FIELD = "crammd5.gid"; - /** Name of the GECOS field in the plain password file. */ String GECOS_FIELD = "crammd5.gecos"; - /** Name of the DIR field in the plain password file. */ String DIR_FIELD = "crammd5.dir"; - /** Name of the SHELL field in the plain password file. */ String SHELL_FIELD = "crammd5.shell"; -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java b/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java index d6622b6db..9be03414b 100644 --- a/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java +++ b/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java @@ -55,29 +55,19 @@ import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; /** - * <p>The CRAM-MD5 SASL server-side mechanism.</p> + * The CRAM-MD5 SASL server-side mechanism. */ -public class CramMD5Server extends ServerMechanism implements SaslServer +public class CramMD5Server + extends ServerMechanism + implements SaslServer { - - // Constants and variables - // ------------------------------------------------------------------------- - private byte[] msgID; - // Constructor(s) - // ------------------------------------------------------------------------- - public CramMD5Server() { super(Registry.SASL_CRAM_MD5_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -86,8 +76,6 @@ public class CramMD5Server extends ServerMechanism implements SaslServer { } - // javax.security.sasl.SaslServer interface implementation ----------------- - public byte[] evaluateResponse(final byte[] response) throws SaslException { if (state == 0) @@ -96,7 +84,6 @@ public class CramMD5Server extends ServerMechanism implements SaslServer state++; return msgID; } - final String responseStr = new String(response); final int index = responseStr.lastIndexOf(" "); final String username = responseStr.substring(0, index); @@ -109,10 +96,8 @@ public class CramMD5Server extends ServerMechanism implements SaslServer { throw new AuthenticationException("evaluateResponse()", x); } - // Look up the password final char[] password = lookupPassword(username); - // Compute the digest byte[] digest; try @@ -125,19 +110,15 @@ public class CramMD5Server extends ServerMechanism implements SaslServer } try { - // digest = (new String(Util.toString(digest).toLowerCase())).getBytes("UTF-8"); digest = Util.toString(digest).toLowerCase().getBytes("UTF-8"); } catch (UnsupportedEncodingException x) { throw new AuthenticationException("evaluateResponse()", x); } - // Compare the received and computed digests - if (!Arrays.equals(digest, responseDigest)) - { - throw new AuthenticationException("Digest mismatch"); - } + if (! Arrays.equals(digest, responseDigest)) + throw new AuthenticationException("Digest mismatch"); state++; return null; } @@ -152,34 +133,26 @@ public class CramMD5Server extends ServerMechanism implements SaslServer return Registry.QOP_AUTH; } - // Other instance methods -------------------------------------------------- - private char[] lookupPassword(final String userName) throws SaslException { try { - if (!authenticator.contains(userName)) - { - throw new NoSuchUserException(userName); - } + if (! authenticator.contains(userName)) + throw new NoSuchUserException(userName); final Map userID = new HashMap(); userID.put(Registry.SASL_USERNAME, userName); final Map credentials = authenticator.lookup(userID); final String password = (String) credentials.get(Registry.SASL_PASSWORD); if (password == null) - { - throw new AuthenticationException("lookupPassword()", - new InternalError()); - } + throw new AuthenticationException("lookupPassword()", + new InternalError()); return password.toCharArray(); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("lookupPassword()", x); } } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java b/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java index 6e7539349..214551221 100644 --- a/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java +++ b/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java @@ -56,29 +56,17 @@ import javax.security.sasl.SaslException; */ class CramMD5Util { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - private CramMD5Util() { super(); } - // Class methods - // ------------------------------------------------------------------------- - static byte[] createMsgID() throws SaslException { - // <process-ID.clock@hostname> final String encoded; try { - encoded = Util.toBase64(Thread.currentThread().getName().getBytes( - "UTF-8")); + encoded = Util.toBase64(Thread.currentThread().getName().getBytes("UTF-8")); } catch (UnsupportedEncodingException x) { @@ -92,20 +80,15 @@ class CramMD5Util catch (UnknownHostException ignored) { } - final byte[] result; try { - result = new StringBuffer().append("<").append( - encoded.substring( - 0, - encoded.length())).append( - ".").append( - String.valueOf(System.currentTimeMillis())).append( - "@").append( - hostname).append( - ">").toString().getBytes( - "UTF-8"); + result = new StringBuffer("<") + .append(encoded.substring(0,encoded.length())) + .append(".").append(String.valueOf(System.currentTimeMillis())) + .append("@").append(hostname).append(">") + .toString() + .getBytes("UTF-8"); } catch (UnsupportedEncodingException x) { @@ -134,4 +117,4 @@ class CramMD5Util mac.update(data, 0, data.length); return mac.digest(); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/crammd5/PasswordFile.java b/gnu/javax/crypto/sasl/crammd5/PasswordFile.java index 081af4615..df9521116 100644 --- a/gnu/javax/crypto/sasl/crammd5/PasswordFile.java +++ b/gnu/javax/crypto/sasl/crammd5/PasswordFile.java @@ -59,26 +59,16 @@ import java.util.StringTokenizer; */ public class PasswordFile { - - // Constants and variables - // ------------------------------------------------------------------------- - private static String DEFAULT_FILE; static { DEFAULT_FILE = System.getProperty(CramMD5Registry.PASSWORD_FILE, CramMD5Registry.DEFAULT_PASSWORD_FILE); } - private HashMap entries; - private File passwdFile; - private long lastmod; - // Constructor(s) - // ------------------------------------------------------------------------- - public PasswordFile() throws IOException { this(DEFAULT_FILE); @@ -95,25 +85,14 @@ public class PasswordFile update(); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - public synchronized void add(final String user, final String passwd, final String[] attributes) throws IOException { checkCurrent(); // check if the entry exists if (entries.containsKey(user)) - { - throw new UserAlreadyExistsException(user); - } + throw new UserAlreadyExistsException(user); if (attributes.length != 5) - { - throw new IllegalArgumentException("Wrong number of attributes"); - } - + throw new IllegalArgumentException("Wrong number of attributes"); final String[] fields = new String[7]; // create the new entry fields[0] = user; fields[1] = passwd; @@ -126,33 +105,26 @@ public class PasswordFile throws IOException { checkCurrent(); - if (!entries.containsKey(user)) - { // check if the entry exists - throw new NoSuchUserException(user); - } - - final String[] fields = (String[]) entries.get(user); // get the existing entry + if (! entries.containsKey(user)) + throw new NoSuchUserException(user); + final String[] fields = (String[]) entries.get(user); // get existing entry fields[1] = passwd; // modify the password field entries.remove(user); // delete the existing entry entries.put(user, fields); // add the new entry - savePasswd(); } public synchronized String[] lookup(final String user) throws IOException { checkCurrent(); - if (!entries.containsKey(user)) - { - throw new NoSuchUserException(user); - } + if (! entries.containsKey(user)) + throw new NoSuchUserException(user); return (String[]) entries.get(user); } public synchronized boolean contains(final String s) throws IOException { checkCurrent(); - return entries.containsKey(s); } @@ -165,9 +137,7 @@ public class PasswordFile private void checkCurrent() throws IOException { if (passwdFile.lastModified() > lastmod) - { - update(); - } + update(); } private synchronized void readPasswd(final InputStream in) throws IOException @@ -183,68 +153,39 @@ public class PasswordFile { fields[0] = st.nextToken(); // username st.nextToken(); - fields[1] = st.nextToken(); // passwd if (fields[1].equals(":")) - { - fields[1] = ""; - } + fields[1] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[2] = st.nextToken(); // uid if (fields[2].equals(":")) - { - fields[2] = ""; - } + fields[2] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[3] = st.nextToken(); // gid if (fields[3].equals(":")) - { - fields[3] = ""; - } + fields[3] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[4] = st.nextToken(); // gecos if (fields[4].equals(":")) - { - fields[4] = ""; - } + fields[4] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[5] = st.nextToken(); // dir if (fields[5].equals(":")) - { - fields[5] = ""; - } + fields[5] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[6] = st.nextToken(); // shell if (fields[6].equals(":")) - { - fields[6] = ""; - } + fields[6] = ""; } catch (NoSuchElementException x) { continue; } - entries.put(fields[0], fields); } } @@ -268,25 +209,21 @@ public class PasswordFile fields = (String[]) entries.get(key); sb = new StringBuffer(fields[0]); for (i = 1; i < fields.length; i++) - { - sb.append(":").append(fields[i]); - } + sb.append(":").append(fields[i]); pw.println(sb.toString()); } } finally { if (pw != null) - { - try - { - pw.flush(); - } - finally - { - pw.close(); - } - } + try + { + pw.flush(); + } + finally + { + pw.close(); + } try { fos.close(); @@ -298,4 +235,4 @@ public class PasswordFile } } } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/plain/PasswordFile.java b/gnu/javax/crypto/sasl/plain/PasswordFile.java index 4ef6b8541..8ad225ab9 100644 --- a/gnu/javax/crypto/sasl/plain/PasswordFile.java +++ b/gnu/javax/crypto/sasl/plain/PasswordFile.java @@ -39,7 +39,6 @@ exception statement from your version. */ package gnu.javax.crypto.sasl.plain; import gnu.classpath.SystemProperties; - import gnu.javax.crypto.sasl.NoSuchUserException; import gnu.javax.crypto.sasl.UserAlreadyExistsException; @@ -47,41 +46,30 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Hashtable; -import java.util.StringTokenizer; import java.util.NoSuchElementException; +import java.util.StringTokenizer; /** * A representation of a Plain password file. */ public class PasswordFile { - - // Constants and variables - // ------------------------------------------------------------------------- - private static String DEFAULT_FILE; static { DEFAULT_FILE = SystemProperties.getProperty(PlainRegistry.PASSWORD_FILE, PlainRegistry.DEFAULT_PASSWORD_FILE); } - private Hashtable entries; - private File passwdFile; - - // private String[] last_params; private long lastmod; - // Constructor(s) - // ------------------------------------------------------------------------- - public PasswordFile() throws IOException { this(DEFAULT_FILE); @@ -98,31 +86,20 @@ public class PasswordFile update(); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - public synchronized void add(String user, String passwd, String[] attributes) throws IOException { checkCurrent(); if (entries.containsKey(user)) - { - throw new UserAlreadyExistsException(user); - } + throw new UserAlreadyExistsException(user); if (attributes.length != 5) - { - throw new IllegalArgumentException("Wrong number of attributes"); - } + throw new IllegalArgumentException("Wrong number of attributes"); // create the new entry String[] fields = new String[7]; fields[0] = user; fields[1] = passwd; System.arraycopy(attributes, 0, fields, 2, 5); entries.put(user, fields); - savePasswd(); } @@ -130,26 +107,20 @@ public class PasswordFile throws IOException { checkCurrent(); - if (!entries.containsKey(user)) - { - throw new NoSuchUserException(user); - } - + if (! entries.containsKey(user)) + throw new NoSuchUserException(user); String[] fields = (String[]) entries.get(user); // get the existing entry fields[1] = passwd; // modify the password field entries.remove(user); // delete the existing entry entries.put(user, fields); // add the new entry - savePasswd(); } public synchronized String[] lookup(String user) throws IOException { checkCurrent(); - if (!entries.containsKey(user)) - { - throw new NoSuchUserException(user); - } + if (! entries.containsKey(user)) + throw new NoSuchUserException(user); return (String[]) entries.get(user); } @@ -159,8 +130,6 @@ public class PasswordFile return entries.containsKey(s); } - //----------------------------------------------------------------// - private synchronized void update() throws IOException { lastmod = passwdFile.lastModified(); @@ -170,9 +139,7 @@ public class PasswordFile private void checkCurrent() throws IOException { if (passwdFile.lastModified() > lastmod) - { - update(); - } + update(); } private synchronized void readPasswd(InputStream in) throws IOException @@ -188,68 +155,39 @@ public class PasswordFile { fields[0] = st.nextToken(); // username st.nextToken(); - fields[1] = st.nextToken(); // passwd if (fields[1].equals(":")) - { - fields[1] = ""; - } + fields[1] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[2] = st.nextToken(); // uid if (fields[2].equals(":")) - { - fields[2] = ""; - } + fields[2] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[3] = st.nextToken(); // gid if (fields[3].equals(":")) - { - fields[3] = ""; - } + fields[3] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[4] = st.nextToken(); // gecos if (fields[4].equals(":")) - { - fields[4] = ""; - } + fields[4] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[5] = st.nextToken(); // dir if (fields[5].equals(":")) - { - fields[5] = ""; - } + fields[5] = ""; else - { - st.nextToken(); - } - + st.nextToken(); fields[6] = st.nextToken(); // shell if (fields[6].equals(":")) - { - fields[6] = ""; - } + fields[6] = ""; } catch (NoSuchElementException ignored) { continue; } - entries.put(fields[0], fields); } } @@ -273,37 +211,31 @@ public class PasswordFile fields = (String[]) entries.get(key); sb = new StringBuffer(fields[0]); for (int i = 1; i < fields.length; i++) - { - sb.append(":" + fields[i]); - } + sb.append(":" + fields[i]); pw.println(sb.toString()); } } finally { if (pw != null) - { - try - { - pw.flush(); - } - finally - { - pw.close(); - } - } + try + { + pw.flush(); + } + finally + { + pw.close(); + } if (fos != null) - { - try - { - fos.close(); - } - catch (IOException ignored) - { - } - } + try + { + fos.close(); + } + catch (IOException ignored) + { + } lastmod = passwdFile.lastModified(); } } } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java b/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java index 9882ce9bb..e0cf82fb6 100644 --- a/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java +++ b/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java @@ -51,44 +51,26 @@ import javax.security.sasl.AuthenticationException; /** * The PLAIN mechanism authentication information provider implementation. */ -public class PlainAuthInfoProvider implements IAuthInfoProvider, PlainRegistry +public class PlainAuthInfoProvider + implements IAuthInfoProvider, PlainRegistry { - - // Constants and variables - // ------------------------------------------------------------------------- - private PasswordFile passwordFile = null; - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-args constrcutor - // Class methods - // ------------------------------------------------------------------------- - - // IAuthInfoProvider interface implementation - // ------------------------------------------------------------------------- - public void activate(Map context) throws AuthenticationException { try { if (context == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else { String pfn = (String) context.get(PASSWORD_FILE); if (pfn == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else - { - passwordFile = new PasswordFile(pfn); - } + passwordFile = new PasswordFile(pfn); } } catch (IOException x) @@ -105,10 +87,8 @@ public class PlainAuthInfoProvider implements IAuthInfoProvider, PlainRegistry public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("contains()", - new IllegalStateException()); - } + throw new AuthenticationException("contains()", + new IllegalStateException()); boolean result = false; try { @@ -124,18 +104,13 @@ public class PlainAuthInfoProvider implements IAuthInfoProvider, PlainRegistry public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("lookup()", - new IllegalStateException()); - } + throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null) - { - throw new NoSuchUserException(""); - } + throw new NoSuchUserException(""); String[] data = passwordFile.lookup(userName); result.put(Registry.SASL_USERNAME, data[0]); result.put(Registry.SASL_PASSWORD, data[1]); @@ -148,13 +123,8 @@ public class PlainAuthInfoProvider implements IAuthInfoProvider, PlainRegistry catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } - else - { - throw new AuthenticationException("lookup()", x); - } + throw (AuthenticationException) x; + throw new AuthenticationException("lookup()", x); } return result; } @@ -162,10 +132,7 @@ public class PlainAuthInfoProvider implements IAuthInfoProvider, PlainRegistry public void update(Map userCredentials) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("update()", - new IllegalStateException()); - } + throw new AuthenticationException("update()", new IllegalStateException()); try { String userName = (String) userCredentials.get(Registry.SASL_USERNAME); @@ -177,9 +144,7 @@ public class PlainAuthInfoProvider implements IAuthInfoProvider, PlainRegistry String shell = (String) userCredentials.get(SHELL_FIELD); if (uid == null || gid == null || gecos == null || dir == null || shell == null) - { - passwordFile.changePasswd(userName, password); - } + passwordFile.changePasswd(userName, password); else { String[] attributes = new String[] { uid, gid, gecos, dir, shell }; @@ -189,13 +154,8 @@ public class PlainAuthInfoProvider implements IAuthInfoProvider, PlainRegistry catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } - else - { - throw new AuthenticationException("update()", x); - } + throw (AuthenticationException) x; + throw new AuthenticationException("update()", x); } } @@ -203,4 +163,4 @@ public class PlainAuthInfoProvider implements IAuthInfoProvider, PlainRegistry { throw new AuthenticationException("", new UnsupportedOperationException()); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/plain/PlainClient.java b/gnu/javax/crypto/sasl/plain/PlainClient.java index 066db3770..5c60578db 100644 --- a/gnu/javax/crypto/sasl/plain/PlainClient.java +++ b/gnu/javax/crypto/sasl/plain/PlainClient.java @@ -48,30 +48,17 @@ import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; /** - * <p>The PLAIN SASL client-side mechanism.</p> + * The PLAIN SASL client-side mechanism. */ -public class PlainClient extends ClientMechanism implements SaslClient +public class PlainClient + extends ClientMechanism + implements SaslClient { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public PlainClient() { super(Registry.SASL_PLAIN_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -80,8 +67,6 @@ public class PlainClient extends ClientMechanism implements SaslClient { } - // javax.security.sasl.SaslClient interface implementation ----------------- - public boolean hasInitialResponse() { return true; @@ -94,22 +79,16 @@ public class PlainClient extends ClientMechanism implements SaslClient final String username; final char[] password; Callback[] callbacks; - - if ((!properties.containsKey(Registry.SASL_USERNAME)) - && (!properties.containsKey(Registry.SASL_PASSWORD))) + if ((! properties.containsKey(Registry.SASL_USERNAME)) + && (! properties.containsKey(Registry.SASL_PASSWORD))) { callbacks = new Callback[2]; - final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); final PasswordCallback pwdCB = new PasswordCallback("password: ", false); callbacks[0] = nameCB; @@ -121,67 +100,49 @@ public class PlainClient extends ClientMechanism implements SaslClient else { if (properties.containsKey(Registry.SASL_USERNAME)) - { - username = (String) properties.get(Registry.SASL_USERNAME); - } + username = (String) properties.get(Registry.SASL_USERNAME); else { callbacks = new Callback[1]; final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); callbacks[0] = nameCB; this.handler.handle(callbacks); username = nameCB.getName(); } - if (properties.containsKey(Registry.SASL_PASSWORD)) - { - password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray(); - } + password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray(); else { callbacks = new Callback[1]; - final PasswordCallback pwdCB = new PasswordCallback( - "password: ", + final PasswordCallback pwdCB = new PasswordCallback("password: ", false); callbacks[0] = pwdCB; this.handler.handle(callbacks); password = pwdCB.getPassword(); } } - if (password == null) - { - throw new SaslException("null password supplied"); - } + throw new SaslException("null password supplied"); final StringBuffer sb = new StringBuffer(); if (authorizationID != null) - { - sb.append(authorizationID); - } + sb.append(authorizationID); sb.append('\0'); sb.append(username); sb.append('\0'); sb.append(password); this.complete = true; - final byte[] response = sb.toString().getBytes("UTF-8"); return response; } catch (Exception x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("evaluateChallenge()", x); } } @@ -190,4 +151,4 @@ public class PlainClient extends ClientMechanism implements SaslClient { return Registry.QOP_AUTH; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/plain/PlainRegistry.java b/gnu/javax/crypto/sasl/plain/PlainRegistry.java index 0b48c0ad3..84e176053 100644 --- a/gnu/javax/crypto/sasl/plain/PlainRegistry.java +++ b/gnu/javax/crypto/sasl/plain/PlainRegistry.java @@ -40,28 +40,18 @@ package gnu.javax.crypto.sasl.plain; public interface PlainRegistry { - - // Constants - // ------------------------------------------------------------------------- - /** Name of PLAIN password file property. */ String PASSWORD_FILE = "gnu.crypto.sasl.plain.password.file"; - /** Default fully qualified pathname of the PLAIN password file. */ String DEFAULT_PASSWORD_FILE = "/etc/tpasswd"; - /** Name of the UID field in the plain password file. */ String UID_FIELD = "plain.uid"; - /** Name of the GID field in the plain password file. */ String GID_FIELD = "plain.gid"; - /** Name of the GECOS field in the plain password file. */ String GECOS_FIELD = "plain.gecos"; - /** Name of the DIR field in the plain password file. */ String DIR_FIELD = "plain.dir"; - /** Name of the SHELL field in the plain password file. */ String SHELL_FIELD = "plain.shell"; -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/plain/PlainServer.java b/gnu/javax/crypto/sasl/plain/PlainServer.java index 205688473..52deef51e 100644 --- a/gnu/javax/crypto/sasl/plain/PlainServer.java +++ b/gnu/javax/crypto/sasl/plain/PlainServer.java @@ -54,30 +54,17 @@ import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; /** - * <p>The PLAIN SASL server-side mechanism.</p> + * The PLAIN SASL server-side mechanism. */ -public class PlainServer extends ServerMechanism implements SaslServer +public class PlainServer + extends ServerMechanism + implements SaslServer { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public PlainServer() { super(Registry.SASL_PLAIN_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -86,43 +73,27 @@ public class PlainServer extends ServerMechanism implements SaslServer { } - // javax.security.sasl.SaslServer interface implementation ----------------- - public byte[] evaluateResponse(final byte[] response) throws SaslException { if (response == null) - { - return null; - } + return null; try { final String nullStr = new String("\0"); - final StringTokenizer strtok = new StringTokenizer( - new String(response), + final StringTokenizer strtok = new StringTokenizer(new String(response), nullStr, true); - authorizationID = strtok.nextToken(); - if (!authorizationID.equals(nullStr)) - { - strtok.nextToken(); - } + if (! authorizationID.equals(nullStr)) + strtok.nextToken(); else - { - authorizationID = null; - } + authorizationID = null; final String id = strtok.nextToken(); if (id.equals(nullStr)) - { - throw new SaslException("No identity given"); - } + throw new SaslException("No identity given"); if (authorizationID == null) - { - authorizationID = id; - } - if ((!authorizationID.equals(nullStr)) && (!authorizationID.equals(id))) - { - throw new SaslException("Delegation not supported"); - } + authorizationID = id; + if ((! authorizationID.equals(nullStr)) && (! authorizationID.equals(id))) + throw new SaslException("Delegation not supported"); strtok.nextToken(); final byte[] pwd; try @@ -134,9 +105,7 @@ public class PlainServer extends ServerMechanism implements SaslServer throw new SaslException("evaluateResponse()", x); } if (pwd == null) - { - throw new SaslException("No password given"); - } + throw new SaslException("No password given"); final byte[] password; try { @@ -146,10 +115,8 @@ public class PlainServer extends ServerMechanism implements SaslServer { throw new SaslException("evaluateResponse()", x); } - if (!Arrays.equals(pwd, password)) - { - throw new SaslException("Password incorrect"); - } + if (! Arrays.equals(pwd, password)) + throw new SaslException("Password incorrect"); this.complete = true; return null; } @@ -164,33 +131,25 @@ public class PlainServer extends ServerMechanism implements SaslServer return Registry.QOP_AUTH; } - // other methods ----------------------------------------------------------- - private char[] lookupPassword(final String userName) throws SaslException { try { - if (!authenticator.contains(userName)) - { - throw new NoSuchUserException(userName); - } + if (! authenticator.contains(userName)) + throw new NoSuchUserException(userName); final Map userID = new HashMap(); userID.put(Registry.SASL_USERNAME, userName); final Map credentials = authenticator.lookup(userID); final String password = (String) credentials.get(Registry.SASL_PASSWORD); if (password == null) - { - throw new SaslException("lookupPassword()", new InternalError()); - } + throw new SaslException("lookupPassword()", new InternalError()); return password.toCharArray(); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("lookupPassword()", x); } } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/CALG.java b/gnu/javax/crypto/sasl/srp/CALG.java index 6215783d6..308543230 100644 --- a/gnu/javax/crypto/sasl/srp/CALG.java +++ b/gnu/javax/crypto/sasl/srp/CALG.java @@ -58,65 +58,55 @@ import java.util.HashMap; import javax.security.sasl.SaslException; /** - * <p>A Factory class that returns CALG (Confidentiality Algorithm) instances - * that operate as described in the draft-burdis-cat-sasl-srp-08.</p> - * - * <p>The designated CALG block cipher should be used in OFB (Output Feedback + * A Factory class that returns CALG (Confidentiality Algorithm) instances that + * operate as described in the draft-burdis-cat-sasl-srp-08. + * <p> + * The designated CALG block cipher should be used in OFB (Output Feedback * Block) mode in the ISO variant, as described in <i>The Handbook of Applied - * Cryptography</i>, algorithm 7.20.</p> - * - * <p>Let <code>k</code> be the block size of the chosen symmetric key block - * cipher algorithm; e.g. for AES this is <code>128</code> bits or <code>16</code> - * octets. The OFB mode used shall be of length/size <code>k</code>.</p> - * - * <p>It is recommended that block ciphers operating in OFB mode be used with an + * Cryptography</i>, algorithm 7.20. + * <p> + * Let <code>k</code> be the block size of the chosen symmetric key block + * cipher algorithm; e.g. for AES this is <code>128</code> bits or + * <code>16</code> octets. The OFB mode used shall be of length/size + * <code>k</code>. + * <p> + * It is recommended that block ciphers operating in OFB mode be used with an * Initial Vector (the mode's IV). In such a mode of operation - OFB with key * re-use - the IV need not be secret. For the mechanism in question the IVs - * shall be a random octet sequence of <code>k</code> bytes.</p> - * - * The input data to the confidentiality protection algorithm shall be - * a multiple of the symmetric cipher block size <code>k</code>. When the input + * shall be a random octet sequence of <code>k</code> bytes. + * <p> + * The input data to the confidentiality protection algorithm shall be a + * multiple of the symmetric cipher block size <code>k</code>. When the input * length is not a multiple of <code>k</code> octets, the data shall be padded - * according to the following scheme:</p> - * - * <p>Assuming the length of the input is <code>l</code> octets, + * according to the following scheme: + * <p> + * Assuming the length of the input is <code>l</code> octets, * <code>(k - (l mod k))</code> octets, all having the value * <code>(k - (l mod k))</code>, shall be appended to the original data. In * other words, the input is padded at the trailing end with one of the - * following sequences:</p> - * + * following sequences: * <pre> - * - * 01 -- if l mod k = k-1 - * 02 02 -- if l mod k = k-2 - * ... - * ... - * ... - * k k ... k k -- if l mod k = 0 - *</pre> - * - * <p>The padding can be removed unambiguously since all input is padded and no + * + * 01 -- if l mod k = k-1 + * 02 02 -- if l mod k = k-2 + * ... + * ... + * ... + * k k ... k k -- if l mod k = 0 + * </pre> + * <p> + * The padding can be removed unambiguously since all input is padded and no * padding sequence is a suffix of another. This padding method is well-defined * if and only if <code>k < 256</code> octets, which is the case with - * symmetric key block ciphers today, and in the forseeable future.</p> + * symmetric key block ciphers today, and in the forseeable future. */ public final class CALG { - - // Constants and variables - // -------------------------------------------------------------------------- - private Assembly assembly; - private Object modeNdx; // initialisation key of the cascade's attributes - private int blockSize; // the underlying cipher's blocksize == IV length - private int keySize; // the underlying cipher's key size (in bytes). - // Constructor(s) - // -------------------------------------------------------------------------- - /** Private constructor to enforce instantiation through Factory method. */ private CALG(final int blockSize, final int keySize, final Object modeNdx, final Assembly assembly) @@ -129,12 +119,9 @@ public final class CALG this.assembly = assembly; } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns an instance of a SASL-SRP CALG implementation.</p> - * + * Returns an instance of a SASL-SRP CALG implementation. + * * @param algorithm the name of the symmetric cipher algorithm. * @return an instance of this object. */ @@ -144,118 +131,60 @@ public final class CALG final int blockSize = cipher.defaultBlockSize(); final int keySize = cipher.defaultKeySize(); final Cascade ofbCipher = new Cascade(); - final Object modeNdx = ofbCipher.append(Stage.getInstance( - ModeFactory.getInstance( - Registry.OFB_MODE, - cipher, - blockSize), - Direction.FORWARD)); + IMode ofbMode = ModeFactory.getInstance(Registry.OFB_MODE, + cipher, + blockSize); + Stage modeStage = Stage.getInstance(ofbMode, Direction.FORWARD); + final Object modeNdx = ofbCipher.append(modeStage); final IPad pkcs7 = PadFactory.getInstance(Registry.PKCS7_PAD); - // the passed IV may be longer that what we need. ensure correct length - // byte[] realIV = null; - // if (iv.length == blockSize) { - // realIV = iv; - // } else { - // realIV = new byte[blockSize]; - // if (iv.length > blockSize) { - // System.arraycopy(iv, 0, realIV, 0, blockSize); - // } else { // shouldnt happen - // System.arraycopy(iv, 0, realIV, 0, iv.length); - // } - // } - - // HashMap modeAttributes = new HashMap(); - // modeAttributes.put(IBlockCipher.KEY_MATERIAL, K.clone()); - // modeAttributes.put(IMode.IV, realIV); - final Assembly asm = new Assembly(); asm.addPreTransformer(Transformer.getCascadeTransformer(ofbCipher)); asm.addPreTransformer(Transformer.getPaddingTransformer(pkcs7)); - - // HashMap attributes = new HashMap(); - // attributes.put(Assembly.DIRECTION, dir); - // attributes.put(modeNdx, modeAttributes); - // try { - // asm.init(attributes); - // } catch (TransformerException x) { - // throw new SaslException("getInstance()", x); - // } - return new CALG(blockSize, keySize, modeNdx, asm); } - // Instance methods - // ------------------------------------------------------------------------- - /** - * <p>Initialises a SASL-SRP CALG implementation.</p> - * + * Initialises a SASL-SRP CALG implementation. + * * @param kdf the key derivation function. * @param iv the initial vector value to use. * @param dir whether this CALG is used for encryption or decryption. */ - // public void init(byte[] K, byte[] iv, Direction dir) throws SaslException { public void init(final KDF kdf, final byte[] iv, final Direction dir) throws SaslException { - // IBlockCipher cipher = CipherFactory.getInstance(algorithm); - // int blockSize = cipher.defaultBlockSize(); - // Cascade ofbCipher = new Cascade(); - // Object modeNdx = ofbCipher.append( - // Stage.getInstace( - // ModeFactory.getInstance(Registry.OFB_MODE, cipher, blockSize), - // Direction.FORWARD)); - // IPad pkcs7 = PadFactory.getInstance(Registry.PKCS7_PAD); - // the passed IV may be longer that what we need. ensure correct length final byte[] realIV; if (iv.length == blockSize) - { - realIV = iv; - } + realIV = iv; else { realIV = new byte[blockSize]; if (iv.length > blockSize) - { - System.arraycopy(iv, 0, realIV, 0, blockSize); - } - else - { // shouldnt happen - System.arraycopy(iv, 0, realIV, 0, iv.length); - } + System.arraycopy(iv, 0, realIV, 0, blockSize); + else // shouldnt happen + System.arraycopy(iv, 0, realIV, 0, iv.length); } - final HashMap modeAttributes = new HashMap(); - // modeAttributes.put(IBlockCipher.KEY_MATERIAL, K.clone()); final byte[] sk = kdf.derive(keySize); modeAttributes.put(IBlockCipher.KEY_MATERIAL, sk); - //System.out.println("**** Initialised CALG with: "+gnu.crypto.util.Util.dumpString(sk)); modeAttributes.put(IMode.IV, realIV); - - // Assembly asm = new Assembly(); - // asm.addPreTransformer(Transformer.getCascadeTransformer(ofbCipher)); - // asm.addPreTransformer(Transformer.getPaddingTransformer(pkcs7)); - final HashMap attributes = new HashMap(); attributes.put(Assembly.DIRECTION, dir); attributes.put(modeNdx, modeAttributes); try { - // asm.init(attributes); assembly.init(attributes); } catch (TransformerException x) { throw new SaslException("getInstance()", x); } - - // return new CALG(asm); } /** - * <p>Encrypts or decrypts, depending on the mode already set, a designated - * array of bytes and returns the result.</p> - * + * Encrypts or decrypts, depending on the mode already set, a designated array + * of bytes and returns the result. + * * @param data the data to encrypt/decrypt. * @return the decrypted/encrypted result. * @throws ConfidentialityException if an exception occurs duirng the process. @@ -266,9 +195,9 @@ public final class CALG } /** - * <p>Encrypts or decrypts, depending on the mode already set, a designated - * array of bytes and returns the result.</p> - * + * Encrypts or decrypts, depending on the mode already set, a designated array + * of bytes and returns the result. + * * @param data the data to encrypt/decrypt. * @param offset where to start in <code>data</code>. * @param length how many bytes to consider in <code>data</code>. @@ -289,4 +218,4 @@ public final class CALG } return result; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/ClientStore.java b/gnu/javax/crypto/sasl/srp/ClientStore.java index ce16f4aa7..866e610d8 100644 --- a/gnu/javax/crypto/sasl/srp/ClientStore.java +++ b/gnu/javax/crypto/sasl/srp/ClientStore.java @@ -41,29 +41,19 @@ package gnu.javax.crypto.sasl.srp; import java.util.HashMap; /** - * <p>The client-side implementation of the SRP security context store.</p> + * The client-side implementation of the SRP security context store. */ public class ClientStore { - - // Constants and variables - // ------------------------------------------------------------------------- - /** The underlying singleton. */ private static ClientStore singleton = null; - /** The map of uid --> SASL Security Context record. */ private static final HashMap uid2ssc = new HashMap(); - /** The map of sid --> Session timing record. */ private static final HashMap uid2ttl = new HashMap(); - /** A synchronisation lock. */ private static final Object lock = new Object(); - // Constructor(s) - // ------------------------------------------------------------------------- - /** Private constructor to enforce Singleton pattern. */ private ClientStore() { @@ -72,33 +62,25 @@ public class ClientStore // TODO: add a cleaning timer thread } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns the classloader Singleton.</p> - * + * Returns the classloader Singleton. + * * @return the classloader Singleton instance. */ static synchronized final ClientStore instance() { if (singleton == null) - { - singleton = new ClientStore(); - } + singleton = new ClientStore(); return singleton; } - // Instance methods - // ------------------------------------------------------------------------- - /** - * <p>Returns a boolean flag indicating if the designated client's session is - * still alive or not.</p> - * + * Returns a boolean flag indicating if the designated client's session is + * still alive or not. + * * @param uid the identifier of the client whose session to check. * @return <code>true</code> if the designated client's session is still - * alive. <code>false</code> otherwise. + * alive. <code>false</code> otherwise. */ boolean isAlive(final String uid) { @@ -107,11 +89,11 @@ public class ClientStore { final Object obj = uid2ssc.get(uid); result = (obj != null); - if (result) - { // is it still alive? + if (result) // is it still alive? + { final StoreEntry sto = (StoreEntry) uid2ttl.get(uid); - if (!sto.isAlive()) - { // invalidate it + if (! sto.isAlive()) // invalidate it + { uid2ssc.remove(uid); uid2ttl.remove(uid); } @@ -121,11 +103,11 @@ public class ClientStore } /** - * <p>Records a mapping between a client's unique identifier and its security - * context.</p> - * - * @param uid the unique identifier of the SRP client for which the session - * is to be cached. + * Records a mapping between a client's unique identifier and its security + * context. + * + * @param uid the unique identifier of the SRP client for which the session is + * to be cached. * @param ttl the session's Time-To-Live indicator (in seconds). * @param ctx the client's security context. */ @@ -139,9 +121,9 @@ public class ClientStore } /** - * <p>Removes the mapping between the designated SRP client unique identifier - * and the its session security context (and other timing information).</p> - * + * Removes the mapping between the designated SRP client unique identifier and + * the its session security context (and other timing information). + * * @param uid the identifier of the client whose session is to invalidate. */ void invalidateSession(final String uid) @@ -154,9 +136,9 @@ public class ClientStore } /** - * <p>Returns an SRP client's security context record mapped by that client's - * unique identifier.</p> - * + * Returns an SRP client's security context record mapped by that client's + * unique identifier. + * * @param uid the identifier of the client whose session is to restore. * @return the SRP client's security context. */ @@ -170,4 +152,4 @@ public class ClientStore } return result; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/IALG.java b/gnu/javax/crypto/sasl/srp/IALG.java index 51492f977..85c93700f 100644 --- a/gnu/javax/crypto/sasl/srp/IALG.java +++ b/gnu/javax/crypto/sasl/srp/IALG.java @@ -48,20 +48,14 @@ import java.util.HashMap; import javax.security.sasl.SaslException; /** - * <p>A Factory class that returns IALG (Integrity Algorithm) instances that - * operate as described in the draft-burdis-cat-sasl-srp-04 and later.</p> + * A Factory class that returns IALG (Integrity Algorithm) instances that + * operate as described in the draft-burdis-cat-sasl-srp-04 and later. */ -public final class IALG implements Cloneable +public final class IALG + implements Cloneable { - - // Constants and variables - // -------------------------------------------------------------------------- - private IMac hmac; - // Constructor(s) - // -------------------------------------------------------------------------- - /** Private constructor to enforce instantiation through Factory method. */ private IALG(final IMac hmac) { @@ -70,12 +64,9 @@ public final class IALG implements Cloneable this.hmac = hmac; } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns an instance of a SASL-SRP IALG implementation.</p> - * + * Returns an instance of a SASL-SRP IALG implementation. + * * @param algorithm the name of the HMAC algorithm. * @return an instance of this object. */ @@ -85,44 +76,24 @@ public final class IALG implements Cloneable final IMac hmac; hmac = MacFactory.getInstance(algorithm); if (hmac == null) - { - throw new SaslException("getInstance()", - new NoSuchAlgorithmException(algorithm)); - } - // try { - // byte[] sk = (byte[]) K.clone(); - // HashMap map = new HashMap(); - // map.put(IMac.MAC_KEY_MATERIAL, sk); - // hmac.init(map); - // } catch (InvalidKeyException x) { - // throw new SaslException("getInstance()", x); - // } + throw new SaslException("getInstance()", + new NoSuchAlgorithmException(algorithm)); return new IALG(hmac); } - // Instance methods - // ------------------------------------------------------------------------- - - // Cloneable interface implementation -------------------------------------- - public Object clone() throws CloneNotSupportedException { return new IALG((IMac) hmac.clone()); } - // other methdds ----------------------------------------------------------- - - // public void init(final byte[] K) throws SaslException { public void init(final KDF kdf) throws SaslException { try { - // final byte[] sk = (byte[]) K.clone(); final byte[] sk = kdf.derive(hmac.macSize()); final HashMap map = new HashMap(); map.put(IMac.MAC_KEY_MATERIAL, sk); hmac.init(map); - //System.out.println("**** Initialised IALG with: "+gnu.crypto.util.Util.dumpString(sk)); } catch (InvalidKeyException x) { @@ -146,8 +117,8 @@ public final class IALG implements Cloneable } /** - * <p>Returns the length (in bytes) of this SASL SRP Integrity Algorithm.</p> - * + * Returns the length (in bytes) of this SASL SRP Integrity Algorithm. + * * @return the length, in bytes, of this integrity protection algorithm. */ public int length() diff --git a/gnu/javax/crypto/sasl/srp/KDF.java b/gnu/javax/crypto/sasl/srp/KDF.java index 7a761cc06..aa3edac0c 100644 --- a/gnu/javax/crypto/sasl/srp/KDF.java +++ b/gnu/javax/crypto/sasl/srp/KDF.java @@ -47,45 +47,29 @@ import gnu.javax.crypto.prng.UMacGenerator; import java.util.HashMap; /** - * <p>The SASL-SRP KDF implementation, which is also used, depending on how it - * was instantiated, as a secure Pseudo Random Number Generator.</p> + * The SASL-SRP KDF implementation, which is also used, depending on how it was + * instantiated, as a secure Pseudo Random Number Generator. */ public class KDF { - - // Constants and variables - // ------------------------------------------------------------------------- - - private static final int AES_BLOCK_SIZE = 16; // default block size for the AES - + private static final int AES_BLOCK_SIZE = 16; // default block size for AES private static final int AES_KEY_SIZE = 16; // default key size for the AES - private static final byte[] buffer = new byte[1]; - /** Our default source of randomness. */ private static final PRNG prng = PRNG.getInstance(); - - /** The shared secret K to use. */ - // private byte[] keyMaterial; /** The underlying UMAC Generator instance. */ private UMacGenerator umac = null; - // Constructor(s) - // ------------------------------------------------------------------------- - /** - * <p>Constructs an instance of the <code>KDF</code> initialised with the - * designated shared secret bytes.</p> - * + * Constructs an instance of the <code>KDF</code> initialised with the + * designated shared secret bytes. + * * @param keyMaterial the SASL SRP shared secret (K) bytes. */ private KDF(final byte[] keyMaterial, final int ndx) { super(); - // if (ndx != 0) { - // this.keyMaterial = (byte[]) keyMaterial.clone(); - // } final HashMap map = new HashMap(); map.put(UMacGenerator.CIPHER, Registry.AES_CIPHER); map.put(UMacGenerator.INDEX, Integer.valueOf(ndx)); @@ -93,21 +77,16 @@ public class KDF final byte[] key = new byte[AES_KEY_SIZE]; System.arraycopy(keyMaterial, 0, key, 0, AES_KEY_SIZE); map.put(IBlockCipher.KEY_MATERIAL, key); - umac = new UMacGenerator(); umac.init(map); - //System.out.println("**** Initialised KDF with: "+gnu.crypto.util.Util.dumpString(key)); } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>A Factory mehod that returns an instance of a <code>KDF</code> based on - * supplied seed data.</p> - * + * A Factory mehod that returns an instance of a <code>KDF</code> based on + * supplied seed data. + * * @param K the SASL SRP shared secret for a <code>KDF</code> to be used for - * <i>CALG</i> and <i>IALG</i> setup. <code>null</code> otherwise. + * <i>CALG</i> and <i>IALG</i> setup. <code>null</code> otherwise. * @return an instance of a <code>KDF</code>. */ static final KDF getInstance(final byte[] K) @@ -134,36 +113,28 @@ public class KDF return (buffer[0] & 0xFF); } - // Instance methods - // ------------------------------------------------------------------------- - /** - * <p>Returns a designated number of bytes suitable for use in the SASL SRP - * mechanism.</p> - * + * Returns a designated number of bytes suitable for use in the SASL SRP + * mechanism. + * * @param length the number of bytes needed. * @return a byte array containing the generated/selected bytes. */ public synchronized byte[] derive(final int length) { final byte[] result = new byte[length]; - // if (keyMaterial == null || length > keyMaterial.length) { try { umac.nextBytes(result, 0, length); } - catch (IllegalStateException x) - { // should not happen + catch (IllegalStateException x) // should not happen + { x.printStackTrace(System.err); } - catch (LimitReachedException x) - { // idem + catch (LimitReachedException x) // idem + { x.printStackTrace(System.err); } - // } else { - // System.arraycopy(keyMaterial, 0, result, 0, length); - // } - return result; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/PasswordFile.java b/gnu/javax/crypto/sasl/srp/PasswordFile.java index 70a4bb65c..36888df87 100644 --- a/gnu/javax/crypto/sasl/srp/PasswordFile.java +++ b/gnu/javax/crypto/sasl/srp/PasswordFile.java @@ -61,70 +61,58 @@ import java.util.NoSuchElementException; import java.util.StringTokenizer; /** - * <p>The implementation of SRP password files.</p> - * - * <p>For SRP, there are three (3) files: + * The implementation of SRP password files. + * <p> + * For SRP, there are three (3) files: * <ol> - * <li>The password configuration file: tpasswd.conf. It contains the pairs - * <N,g> indexed by a number for each pair used for a user. By default, - * this file's pathname is constructed from the base password file pathname - * by prepending it with the ".conf" suffix.</li> - * - * <li>The base password file: tpasswd. It contains the related password - * entries for all the users with values computed using SRP's default - * message digest algorithm: SHA-1 (with 160-bit output block size).</li> - * - * <li>The extended password file: tpasswd2. Its name, by default, is - * constructed by adding the suffix "2" to the fully qualified pathname of - * the base password file. It contains, in addition to the same fields as - * the base password file, albeit with a different verifier value, an extra - * field identifying the message digest algorithm used to compute this - * (verifier) value.</li> - * </ol></p> - * - * <p>This implementation assumes the following message digest algorithm codes: + * <li>The password configuration file: tpasswd.conf. It contains the pairs + * <N,g> indexed by a number for each pair used for a user. By default, this + * file's pathname is constructed from the base password file pathname by + * prepending it with the ".conf" suffix.</li> + * <li>The base password file: tpasswd. It contains the related password + * entries for all the users with values computed using SRP's default message + * digest algorithm: SHA-1 (with 160-bit output block size).</li> + * <li>The extended password file: tpasswd2. Its name, by default, is + * constructed by adding the suffix "2" to the fully qualified pathname of the + * base password file. It contains, in addition to the same fields as the base + * password file, albeit with a different verifier value, an extra field + * identifying the message digest algorithm used to compute this (verifier) + * value.</li> + * </ol> + * <p> + * This implementation assumes the following message digest algorithm codes: * <ul> - * <li>0: the default hash algorithm, which is SHA-1 (or its alias SHA-160).</li> - * <li>1: MD5.</li> - * <li>2: RIPEMD-128.</li> - * <li>3: RIPEMD-160.</li> - * <li>4: SHA-256.</li> - * <li>5: SHA-384.</li> - * <li>6: SHA-512.</li> - * </ul></p> - * - * <p><b>IMPORTANT:</b> This method computes the verifiers as described in - * RFC-2945, which differs from the description given on the web page for - * SRP-6.</p> - * - * <p>Reference:</p> + * <li>0: the default hash algorithm, which is SHA-1 (or its alias SHA-160).</li> + * <li>1: MD5.</li> + * <li>2: RIPEMD-128.</li> + * <li>3: RIPEMD-160.</li> + * <li>4: SHA-256.</li> + * <li>5: SHA-384.</li> + * <li>6: SHA-512.</li> + * </ul> + * <p> + * <b>IMPORTANT:</b> This method computes the verifiers as described in + * RFC-2945, which differs from the description given on the web page for SRP-6. + * <p> + * Reference: * <ol> - * <li><a href="http://srp.stanford.edu/design.html">SRP Protocol Design</a><br> - * Thomas J. Wu.</li> + * <li><a href="http://srp.stanford.edu/design.html">SRP Protocol Design</a><br> + * Thomas J. Wu.</li> * </ol> */ public class PasswordFile { - - // Constants and variables - // ------------------------------------------------------------------------- - // names of property keys used in this class private static final String USER_FIELD = "user"; - private static final String VERIFIERS_FIELD = "verifier"; - private static final String SALT_FIELD = "salt"; - private static final String CONFIG_FIELD = "config"; - private static String DEFAULT_FILE; static { DEFAULT_FILE = System.getProperty(SRPRegistry.PASSWORD_FILE, SRPRegistry.DEFAULT_PASSWORD_FILE); } - /** The SRP algorithm instances used by this object. */ private static final HashMap srps; static @@ -149,27 +137,19 @@ public class PasswordFile } private String confName, pwName, pw2Name; - private File configFile, passwdFile, passwd2File; - private long lastmodPasswdFile, lastmodPasswd2File; - private HashMap entries = new HashMap(); - private HashMap configurations = new HashMap(); - // default N values to use when creating a new password.conf file private static final BigInteger[] Nsrp = new BigInteger[] { - SRPAlgorithm.N_2048, - SRPAlgorithm.N_1536, - SRPAlgorithm.N_1280, - SRPAlgorithm.N_1024, - SRPAlgorithm.N_768, - SRPAlgorithm.N_640, - SRPAlgorithm.N_512 }; - - // Constructor(s) - // ------------------------------------------------------------------------- + SRPAlgorithm.N_2048, + SRPAlgorithm.N_1536, + SRPAlgorithm.N_1280, + SRPAlgorithm.N_1024, + SRPAlgorithm.N_768, + SRPAlgorithm.N_640, + SRPAlgorithm.N_512 }; public PasswordFile() throws IOException { @@ -205,63 +185,43 @@ public class PasswordFile update(); } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns a string representing the decimal value of an integer - * identifying the message digest algorithm to use for the SRP computations. - * </p> - * + * Returns a string representing the decimal value of an integer identifying + * the message digest algorithm to use for the SRP computations. + * * @param mdName the canonical name of a message digest algorithm. * @return a string representing the decimal value of an ID for that - * algorithm. + * algorithm. */ private static final String nameToID(final String mdName) { if (Registry.SHA_HASH.equalsIgnoreCase(mdName) || Registry.SHA1_HASH.equalsIgnoreCase(mdName) || Registry.SHA160_HASH.equalsIgnoreCase(mdName)) - { - return "0"; - } + return "0"; else if (Registry.MD5_HASH.equalsIgnoreCase(mdName)) - { - return "1"; - } + return "1"; else if (Registry.RIPEMD128_HASH.equalsIgnoreCase(mdName)) - { - return "2"; - } + return "2"; else if (Registry.RIPEMD160_HASH.equalsIgnoreCase(mdName)) - { - return "3"; - } + return "3"; else if (Registry.SHA256_HASH.equalsIgnoreCase(mdName)) - { - return "4"; - } + return "4"; else if (Registry.SHA384_HASH.equalsIgnoreCase(mdName)) - { - return "5"; - } + return "5"; else if (Registry.SHA512_HASH.equalsIgnoreCase(mdName)) - { - return "6"; - } + return "6"; return "0"; } - // SRP password configuration file methods --------------------------------- - /** - * <p>Checks if the current configuration file contains the <N, g> pair - * for the designated <code>index</code>.</p> - * + * Checks if the current configuration file contains the <N, g> pair for + * the designated <code>index</code>. + * * @param index a string representing 1-digit identification of an <N, g> - * pair used. - * @return <code>true</code> if the designated <code>index</code> is that of - * a known <N, g> pair, and <code>false</code> otherwise. + * pair used. + * @return <code>true</code> if the designated <code>index</code> is that + * of a known <N, g> pair, and <code>false</code> otherwise. * @throws IOException if an exception occurs during the process. * @see SRPRegistry#N_2048_BITS * @see SRPRegistry#N_1536_BITS @@ -279,16 +239,16 @@ public class PasswordFile } /** - * <p>Returns a pair of strings representing the pair of <code>N</code> and - * <code>g</code> MPIs for the designated <code>index</code>.</p> - * + * Returns a pair of strings representing the pair of <code>N</code> and + * <code>g</code> MPIs for the designated <code>index</code>. + * * @param index a string representing 1-digit identification of an <N, g> - * pair to look up. + * pair to look up. * @return a pair of strings, arranged in an array, where the first (at index - * position #0) is the repesentation of the MPI <code>N</code>, and the - * second (at index position #1) is the representation of the MPI - * <code>g</code>. If the <code>index</code> refers to an unknown pair, then - * an empty string array is returned. + * position #0) is the repesentation of the MPI <code>N</code>, and + * the second (at index position #1) is the representation of the MPI + * <code>g</code>. If the <code>index</code> refers to an unknown + * pair, then an empty string array is returned. * @throws IOException if an exception occurs during the process. */ public synchronized String[] lookupConfig(final String index) @@ -297,14 +257,10 @@ public class PasswordFile checkCurrent(); String[] result = null; if (configurations.containsKey(index)) - { - result = (String[]) configurations.get(index); - } + result = (String[]) configurations.get(index); return result; } - // SRP base and extended password configuration files methods -------------- - public synchronized boolean contains(final String user) throws IOException { checkCurrent(); @@ -317,9 +273,7 @@ public class PasswordFile { checkCurrent(); if (entries.containsKey(user)) - { - throw new UserAlreadyExistsException(user); - } + throw new UserAlreadyExistsException(user); final HashMap fields = new HashMap(4); fields.put(USER_FIELD, user); // 0 fields.put(VERIFIERS_FIELD, newVerifiers(user, salt, passwd, index)); // 1 @@ -333,10 +287,8 @@ public class PasswordFile throws IOException { checkCurrent(); - if (!entries.containsKey(user)) - { - throw new NoSuchUserException(user); - } + if (! entries.containsKey(user)) + throw new NoSuchUserException(user); final HashMap fields = (HashMap) entries.get(user); final byte[] salt; try @@ -368,27 +320,23 @@ public class PasswordFile finally { if (pw1 != null) - { - try - { - pw1.flush(); - } - finally - { - pw1.close(); - } - } + try + { + pw1.flush(); + } + finally + { + pw1.close(); + } if (pw2 != null) - { - try - { - pw2.flush(); - } - finally - { - pw2.close(); - } - } + try + { + pw2.flush(); + } + finally + { + pw2.close(); + } try { f1.close(); @@ -409,24 +357,22 @@ public class PasswordFile } /** - * <p>Returns the triplet: verifier, salt and configuration file index, of a + * Returns the triplet: verifier, salt and configuration file index, of a * designated user, and a designated message digest algorithm name, as an - * array of strings.</p> - * + * array of strings. + * * @param user the username. * @param mdName the canonical name of the SRP's message digest algorithm. * @return a string array containing, in this order, the BASE-64 encodings of - * the verifier, the salt and the index in the password configuration file of - * the MPIs N and g of the designated user. + * the verifier, the salt and the index in the password configuration + * file of the MPIs N and g of the designated user. */ public synchronized String[] lookup(final String user, final String mdName) throws IOException { checkCurrent(); - if (!entries.containsKey(user)) - { - throw new NoSuchUserException(user); - } + if (! entries.containsKey(user)) + throw new NoSuchUserException(user); final HashMap fields = (HashMap) entries.get(user); final HashMap verifiers = (HashMap) fields.get(VERIFIERS_FIELD); final String salt = (String) fields.get(SALT_FIELD); @@ -435,8 +381,6 @@ public class PasswordFile return new String[] { verifier, salt, index }; } - // Other instance methods -------------------------------------------------- - private synchronized void readOrCreateConf() throws IOException { configurations.clear(); @@ -468,13 +412,9 @@ public class PasswordFile finally { if (pw0 != null) - { - pw0.close(); - } + pw0.close(); else if (f0 != null) - { - f0.close(); - } + f0.close(); } } } @@ -510,26 +450,27 @@ public class PasswordFile { ndx = (String) it.next(); mpi = (String[]) configurations.get(ndx); - sb = new StringBuffer(ndx).append(":").append(mpi[0]).append(":").append( - mpi[1]); + sb = new StringBuffer(ndx) + .append(":").append(mpi[0]) + .append(":").append(mpi[1]); pw.println(sb.toString()); } } /** - * <p>Compute the new verifiers for the designated username and password.</p> - * - * <p><b>IMPORTANT:</b> This method computes the verifiers as described in + * Compute the new verifiers for the designated username and password. + * <p> + * <b>IMPORTANT:</b> This method computes the verifiers as described in * RFC-2945, which differs from the description given on the web page for - * SRP-6.</p> - * + * SRP-6. + * * @param user the user's name. * @param s the user's salt. * @param password the user's password * @param index the index of the <N, g> pair to use for this user. * @return a {@link java.util.Map} of user verifiers. * @throws UnsupportedEncodingException if the US-ASCII decoder is not - * available on this platform. + * available on this platform. */ private HashMap newVerifiers(final String user, final byte[] s, final String password, final String index) @@ -539,7 +480,6 @@ public class PasswordFile final String[] mpi = (String[]) configurations.get(index); final BigInteger N = new BigInteger(1, Util.fromBase64(mpi[0])); final BigInteger g = new BigInteger(1, Util.fromBase64(mpi[1])); - final HashMap result = new HashMap(srps.size()); BigInteger x, v; SRP srp; @@ -550,7 +490,6 @@ public class PasswordFile x = new BigInteger(1, srp.computeX(s, user, password)); v = g.modPow(x, N); final String verifier = Util.toBase64(v.toByteArray()); - result.put(digestID, verifier); } return result; @@ -559,7 +498,6 @@ public class PasswordFile private synchronized void update() throws IOException { entries.clear(); - FileInputStream fis; passwdFile = new File(pwName); lastmodPasswdFile = passwdFile.lastModified(); @@ -587,9 +525,7 @@ public class PasswordFile { if (passwdFile.lastModified() > lastmodPasswdFile || passwd2File.lastModified() > lastmodPasswd2File) - { - update(); - } + update(); } private void readPasswd(final InputStream in) throws IOException @@ -611,16 +547,13 @@ public class PasswordFile { throw new IOException("SRP base password file corrupt"); } - final HashMap verifiers = new HashMap(6); verifiers.put("0", verifier); - final HashMap fields = new HashMap(4); fields.put(USER_FIELD, user); fields.put(VERIFIERS_FIELD, verifiers); fields.put(SALT_FIELD, salt); fields.put(CONFIG_FIELD, index); - entries.put(user, fields); } } @@ -644,7 +577,6 @@ public class PasswordFile { throw new IOException("SRP extended password file corrupt"); } - fields = (HashMap) entries.get(user); if (fields != null) { @@ -666,33 +598,28 @@ public class PasswordFile { user = (String) i.next(); fields = (HashMap) entries.get(user); - if (!user.equals(fields.get(USER_FIELD))) - { - throw new IOException("Inconsistent SRP password data"); - } + if (! user.equals(fields.get(USER_FIELD))) + throw new IOException("Inconsistent SRP password data"); verifiers = (HashMap) fields.get(VERIFIERS_FIELD); - sb1 = new StringBuffer().append(user).append(":").append( - (String) verifiers.get("0")).append( - ":").append( - (String) fields.get(SALT_FIELD)).append( - ":").append( - (String) fields.get(CONFIG_FIELD)); + sb1 = new StringBuffer(user) + .append(":").append((String) verifiers.get("0")) + .append(":").append((String) fields.get(SALT_FIELD)) + .append(":").append((String) fields.get(CONFIG_FIELD)); pw1.println(sb1.toString()); // write extended information j = verifiers.keySet().iterator(); while (j.hasNext()) { digestID = (String) j.next(); - if (!"0".equals(digestID)) + if (! "0".equals(digestID)) { // #0 is the default digest, already present in tpasswd! - sb2 = new StringBuffer().append(digestID).append(":").append( - user).append( - ":").append( - (String) verifiers.get(digestID)); + sb2 = new StringBuffer(digestID) + .append(":").append(user) + .append(":").append((String) verifiers.get(digestID)); pw2.println(sb2.toString()); } } } } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/SRP.java b/gnu/javax/crypto/sasl/srp/SRP.java index d3eb596d4..437e42a5a 100644 --- a/gnu/javax/crypto/sasl/srp/SRP.java +++ b/gnu/javax/crypto/sasl/srp/SRP.java @@ -47,27 +47,18 @@ import java.math.BigInteger; import java.util.HashMap; /** - * <p>A Factory class that returns SRP Singletons that know all SRP-related + * A Factory class that returns SRP Singletons that know all SRP-related * mathematical computations and protocol-related operations for both the - * client- and server-sides.</p> + * client- and server-sides. */ public final class SRP { - - // Constants and variables - // -------------------------------------------------------------------------- - /** The map of already instantiated SRP algorithm instances. */ private static final HashMap algorithms = new HashMap(); - private static final byte COLON = (byte) 0x3A; - /** The underlying message digest algorithm used for all SRP calculations. */ private IMessageDigest mda; - // Constructor(s) - // -------------------------------------------------------------------------- - /** Trivial private constructor to enforce Singleton pattern. */ private SRP(final IMessageDigest mda) { @@ -76,25 +67,18 @@ public final class SRP this.mda = mda; } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns an instance of this object that uses the designated message - * digest algorithm as its digest function.</p> - * + * Returns an instance of this object that uses the designated message digest + * algorithm as its digest function. + * * @return an instance of this object for the designated digest name. */ public static synchronized SRP instance(String mdName) { if (mdName != null) - { - mdName = mdName.trim().toLowerCase(); - } + mdName = mdName.trim().toLowerCase(); if (mdName == null || mdName.equals("")) - { - mdName = SRPRegistry.SRP_DEFAULT_DIGEST_NAME; - } + mdName = SRPRegistry.SRP_DEFAULT_DIGEST_NAME; SRP result = (SRP) algorithms.get(mdName); if (result == null) { @@ -110,31 +94,24 @@ public final class SRP { final byte[] result = new byte[length]; for (int i = 0; i < length; ++i) - { - result[i] = (byte) (b1[i] ^ b2[i]); - } + result[i] = (byte)(b1[i] ^ b2[i]); return result; } - // Instance methods - // ------------------------------------------------------------------------- - /** @return the message digest algorithm name used by this instance. */ public String getAlgorithm() { return mda.name(); } - // Message Digest algorithm related methods -------------------------------- - /** - * <p>Returns a new instance of the SRP message digest algorithm --which is + * Returns a new instance of the SRP message digest algorithm --which is * SHA-160 by default, but could be anything else provided the proper - * conditions as specified in the SRP specifications.</p> - * + * conditions as specified in the SRP specifications. + * * @return a new instance of the underlying SRP message digest algorithm. * @throws RuntimeException if the implementation of the message digest - * algorithm does not support cloning. + * algorithm does not support cloning. */ public IMessageDigest newDigest() { @@ -142,12 +119,12 @@ public final class SRP } /** - * <p>Convenience method to return the result of digesting the designated - * input with a new instance of the SRP message digest algorithm.</p> - * + * Convenience method to return the result of digesting the designated input + * with a new instance of the SRP message digest algorithm. + * * @param src some bytes to digest. - * @return the bytes constituting the result of digesting the designated - * input with a new instance of the SRP message digest algorithm. + * @return the bytes constituting the result of digesting the designated input + * with a new instance of the SRP message digest algorithm. */ public byte[] digest(final byte[] src) { @@ -157,13 +134,13 @@ public final class SRP } /** - * <p>Convenience method to return the result of digesting the designated - * input with a new instance of the SRP message digest algorithm.</p> - * + * Convenience method to return the result of digesting the designated input + * with a new instance of the SRP message digest algorithm. + * * @param src a String whose bytes (using US-ASCII encoding) are to be - * digested. - * @return the bytes constituting the result of digesting the designated - * input with a new instance of the SRP message digest algorithm. + * digested. + * @return the bytes constituting the result of digesting the designated input + * with a new instance of the SRP message digest algorithm. * @throws UnsupportedEncodingException if US-ASCII charset is not found. */ public byte[] digest(final String src) throws UnsupportedEncodingException @@ -171,17 +148,15 @@ public final class SRP return digest(src.getBytes("US-ASCII")); } - // Other methods ----------------------------------------------------------- - /** - * <p>Convenience method to XOR N bytes from two arrays; N being the output - * size of the SRP message digest algorithm.</p> - * + * Convenience method to XOR N bytes from two arrays; N being the output size + * of the SRP message digest algorithm. + * * @param a the first byte array. * @param b the second one. * @return N bytes which are the result of the XOR operations on the first N - * bytes from the designated arrays. N is the size of the SRP message digest - * algorithm; eg. 20 for SHA-160. + * bytes from the designated arrays. N is the size of the SRP message + * digest algorithm; eg. 20 for SHA-160. */ public byte[] xor(final byte[] a, final byte[] b) { @@ -212,7 +187,6 @@ public final class SRP hash.update(b, 0, b.length); hash.update(cn, 0, cn.length); hash.update(cCB, 0, cCB.length); - return hash.digest(); } @@ -235,14 +209,13 @@ public final class SRP b = digest(o); hash.update(b, 0, b.length); hash.update(sid, 0, sid.length); - hash.update((byte) (ttl >>> 24)); - hash.update((byte) (ttl >>> 16)); - hash.update((byte) (ttl >>> 8)); + hash.update((byte)(ttl >>> 24)); + hash.update((byte)(ttl >>> 16)); + hash.update((byte)(ttl >>> 8)); hash.update((byte) ttl); hash.update(cIV, 0, cIV.length); hash.update(sIV, 0, sIV.length); hash.update(sCB, 0, sCB.length); - return hash.digest(); } @@ -252,7 +225,6 @@ public final class SRP hash.update(K, 0, K.length); hash.update(cn, 0, cn.length); hash.update(sn, 0, sn.length); - return hash.digest(); } @@ -276,10 +248,8 @@ public final class SRP hash.update(COLON); hash.update(p, 0, p.length); final byte[] up = hash.digest(); - hash.update(s, 0, s.length); hash.update(up, 0, up.length); - return hash.digest(); } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java b/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java index 9ea21efb6..3a43a94a0 100644 --- a/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java +++ b/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java @@ -50,37 +50,21 @@ import java.util.Map; import javax.security.sasl.AuthenticationException; /** - * <p>The SRP mechanism authentication information provider implementation.</p> + * The SRP mechanism authentication information provider implementation. */ -public class SRPAuthInfoProvider implements IAuthInfoProvider +public class SRPAuthInfoProvider + implements IAuthInfoProvider { - - // Constants and variables - // ------------------------------------------------------------------------- - private PasswordFile passwordFile = null; - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-args constrcutor - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // IAuthInfoProvider interface implementation ------------------------------ - public void activate(Map context) throws AuthenticationException { try { if (context == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else { passwordFile = (PasswordFile) context.get(SRPRegistry.PASSWORD_DB); @@ -88,13 +72,9 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider { String pfn = (String) context.get(SRPRegistry.PASSWORD_FILE); if (pfn == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else - { - passwordFile = new PasswordFile(pfn); - } + passwordFile = new PasswordFile(pfn); } } } @@ -112,10 +92,8 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("contains()", - new IllegalStateException()); - } + throw new AuthenticationException("contains()", + new IllegalStateException()); boolean result = false; try { @@ -131,20 +109,14 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("lookup()", - new IllegalStateException()); - } + throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null) - { - throw new NoSuchUserException(""); - } + throw new NoSuchUserException(""); String mdName = (String) userID.get(SRPRegistry.MD_NAME_FIELD); - String[] data = passwordFile.lookup(userName, mdName); result.put(SRPRegistry.USER_VERIFIER_FIELD, data[0]); result.put(SRPRegistry.SALT_FIELD, data[1]); @@ -153,9 +125,7 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("lookup()", x); } return result; @@ -165,7 +135,6 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider { if (passwordFile == null) throw new AuthenticationException("update()", new IllegalStateException()); - try { String userName = (String) userCredentials.get(Registry.SASL_USERNAME); @@ -173,20 +142,14 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider String salt = (String) userCredentials.get(SRPRegistry.SALT_FIELD); String config = (String) userCredentials.get(SRPRegistry.CONFIG_NDX_FIELD); if (salt == null || config == null) - { - passwordFile.changePasswd(userName, password); - } + passwordFile.changePasswd(userName, password); else - { - passwordFile.add(userName, password, Util.fromBase64(salt), config); - } + passwordFile.add(userName, password, Util.fromBase64(salt), config); } catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("update()", x); } } @@ -194,10 +157,8 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider public Map getConfiguration(String mode) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("getConfiguration()", - new IllegalStateException()); - } + throw new AuthenticationException("getConfiguration()", + new IllegalStateException()); Map result = new HashMap(); try { @@ -208,11 +169,9 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("getConfiguration()", x); } return result; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/SRPClient.java b/gnu/javax/crypto/sasl/srp/SRPClient.java index 231a49480..f4ef4cc34 100644 --- a/gnu/javax/crypto/sasl/srp/SRPClient.java +++ b/gnu/javax/crypto/sasl/srp/SRPClient.java @@ -81,7 +81,9 @@ import javax.security.sasl.SaslException; /** * The SASL-SRP client-side mechanism. */ -public class SRPClient extends ClientMechanism implements SaslClient +public class SRPClient + extends ClientMechanism + implements SaslClient { private static final Logger log = Logger.getLogger(SRPClient.class.getName()); private String uid; // the unique key for this type of client @@ -107,7 +109,8 @@ public class SRPClient extends ClientMechanism implements SaslClient private int outCounter = 0; private IALG inMac, outMac; // if !null, use for integrity private CALG inCipher, outCipher; // if !null, use for confidentiality - private IKeyAgreementParty clientHandler = KeyAgreementFactory.getPartyAInstance(Registry.SRP_SASL_KA); + private IKeyAgreementParty clientHandler = + KeyAgreementFactory.getPartyAInstance(Registry.SRP_SASL_KA); /** Our default source of randomness. */ private PRNG prng = null; @@ -118,8 +121,8 @@ public class SRPClient extends ClientMechanism implements SaslClient protected void initMechanism() throws SaslException { - // we shall keep track of the sid (and the security context of this - // SRP client) based on the initialisation parameters of an SRP session. + // we shall keep track of the sid (and the security context of this SRP + // client) based on the initialisation parameters of an SRP session. // we shall compute a unique key for those parameters and key the sid // (and the security context) accordingly. // 1. compute the mapping key. use MD5 (the fastest) for this purpose @@ -182,7 +185,6 @@ public class SRPClient extends ClientMechanism implements SaslClient sIV = null; inMac = outMac = null; inCipher = outCipher = null; - sid = null; ttl = 0; cn = null; @@ -243,7 +245,6 @@ public class SRPClient extends ClientMechanism implements SaslClient { // integrity bytes are at the end of the stream final int macBytesCount = inMac.length(); final int payloadLength = len - macBytesCount; - // final byte[] received_mac = frameIn.getOS(); final byte[] received_mac = new byte[macBytesCount]; System.arraycopy(incoming, offset + payloadLength, received_mac, 0, macBytesCount); @@ -255,16 +256,16 @@ public class SRPClient extends ClientMechanism implements SaslClient inCounter++; if (Configuration.DEBUG) log.fine("inCounter=" + inCounter); - inMac.update(new byte[] { (byte) (inCounter >>> 24), - (byte) (inCounter >>> 16), - (byte) (inCounter >>> 8), - (byte) inCounter }); + inMac.update(new byte[] { + (byte)(inCounter >>> 24), + (byte)(inCounter >>> 16), + (byte)(inCounter >>> 8), + (byte) inCounter }); } - final byte[] computed_mac = inMac.doFinal(); if (Configuration.DEBUG) log.fine("Computed MAC: " + Util.dumpString(computed_mac)); - if (!Arrays.equals(received_mac, computed_mac)) + if (! Arrays.equals(received_mac, computed_mac)) throw new IntegrityException("engineUnwrap()"); // deal with the payload, which can be either plain or encrypted if (inCipher != null) @@ -318,10 +319,11 @@ public class SRPClient extends ClientMechanism implements SaslClient outCounter++; if (Configuration.DEBUG) log.fine("outCounter=" + outCounter); - outMac.update(new byte[] { (byte)(outCounter >>> 24), - (byte)(outCounter >>> 16), - (byte)(outCounter >>> 8), - (byte) outCounter }); + outMac.update(new byte[] { + (byte)(outCounter >>> 24), + (byte)(outCounter >>> 16), + (byte)(outCounter >>> 8), + (byte) outCounter }); } final byte[] C = outMac.doFinal(); out.write(C); @@ -342,10 +344,11 @@ public class SRPClient extends ClientMechanism implements SaslClient outCounter++; if (Configuration.DEBUG) log.fine("outCounter=" + outCounter); - outMac.update(new byte[] { (byte)(outCounter >>> 24), - (byte)(outCounter >>> 16), - (byte)(outCounter >>> 8), - (byte) outCounter }); + outMac.update(new byte[] { + (byte)(outCounter >>> 24), + (byte)(outCounter >>> 16), + (byte)(outCounter >>> 8), + (byte) outCounter }); } final byte[] C = outMac.doFinal(); out.write(C); @@ -371,7 +374,6 @@ public class SRPClient extends ClientMechanism implements SaslClient { if (inCipher != null) return Registry.QOP_AUTH_CONF; - return Registry.QOP_AUTH_INT; } return Registry.QOP_AUTH; @@ -383,7 +385,6 @@ public class SRPClient extends ClientMechanism implements SaslClient { if (inCipher != null) return Registry.STRENGTH_HIGH; - return Registry.STRENGTH_MEDIUM; } return Registry.STRENGTH_LOW; @@ -399,8 +400,6 @@ public class SRPClient extends ClientMechanism implements SaslClient return Registry.REUSE_TRUE; } - // other methods ----------------------------------------------------------- - private byte[] sendIdentities() throws SaslException { if (Configuration.DEBUG) @@ -421,7 +420,6 @@ public class SRPClient extends ClientMechanism implements SaslClient } else cn = new byte[0]; - final OutputBuffer frameOut = new OutputBuffer(); try { @@ -465,8 +463,8 @@ public class SRPClient extends ClientMechanism implements SaslClient try { ack = (int) frameIn.getScalar(1); - if (ack == 0x00) - { // new session + if (ack == 0x00) // new session + { N = frameIn.getMPI(); if (Configuration.DEBUG) log.fine("Got N (modulus): " + Util.dump(N)); @@ -483,8 +481,8 @@ public class SRPClient extends ClientMechanism implements SaslClient if (Configuration.DEBUG) log.fine("Got L (available options): \"" + L + "\""); } - else if (ack == 0xFF) - { // session re-use + else if (ack == 0xFF) // session re-use + { sn = frameIn.getOS(); if (Configuration.DEBUG) log.fine("Got sn (server nonce): " + Util.dumpString(sn)); @@ -644,9 +642,8 @@ public class SRPClient extends ClientMechanism implements SaslClient } if (Configuration.DEBUG) log.fine("Expected: " + Util.dumpString(expected)); - if (!Arrays.equals(M2, expected)) + if (! Arrays.equals(M2, expected)) throw new AuthenticationException("M2 mismatch"); - setupSecurityServices(false); if (Configuration.DEBUG) log.exiting(this.getClass().getName(), "receiveEvidence"); @@ -749,13 +746,11 @@ public class SRPClient extends ClientMechanism implements SaslClient if (Configuration.DEBUG) log.fine("mda: <" + option + ">"); for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++) - { - if (SRPRegistry.SRP_ALGORITHMS[i].equals(option)) - { - mdName = option; - break; - } - } + if (SRPRegistry.SRP_ALGORITHMS[i].equals(option)) + { + mdName = option; + break; + } } else if (option.equals(SRPRegistry.OPTION_REPLAY_DETECTION)) replaydetectionAvailable = true; @@ -765,14 +760,12 @@ public class SRPClient extends ClientMechanism implements SaslClient if (Configuration.DEBUG) log.fine("ialg: <" + option + ">"); for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++) - { - if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option)) - { - chosenIntegrityAlgorithm = option; - integrityAvailable = true; - break; - } - } + if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option)) + { + chosenIntegrityAlgorithm = option; + integrityAvailable = true; + break; + } } else if (option.startsWith(SRPRegistry.OPTION_CONFIDENTIALITY + "=")) { @@ -780,14 +773,12 @@ public class SRPClient extends ClientMechanism implements SaslClient if (Configuration.DEBUG) log.fine("calg: <" + option + ">"); for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++) - { - if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option)) - { - chosenConfidentialityAlgorithm = option; - confidentialityAvailable = true; - break; - } - } + if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option)) + { + chosenConfidentialityAlgorithm = option; + confidentialityAvailable = true; + break; + } } else if (option.startsWith(SRPRegistry.OPTION_MANDATORY + "=")) mandatory = option.substring(option.indexOf('=') + 1); @@ -799,22 +790,27 @@ public class SRPClient extends ClientMechanism implements SaslClient rawSendSize = Integer.parseInt(maxBufferSize); if (rawSendSize > Registry.SASL_BUFFER_MAX_LIMIT || rawSendSize < 1) - throw new AuthenticationException("Illegal value for 'maxbuffersize' option"); + throw new AuthenticationException( + "Illegal value for 'maxbuffersize' option"); } catch (NumberFormatException x) { - throw new AuthenticationException(SRPRegistry.OPTION_MAX_BUFFER_SIZE - + "=" + maxBufferSize, - x); + throw new AuthenticationException( + SRPRegistry.OPTION_MAX_BUFFER_SIZE + "=" + maxBufferSize, x); } } } - replayDetection = replaydetectionAvailable - && Boolean.valueOf((String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION)).booleanValue(); - boolean integrity = integrityAvailable - && Boolean.valueOf((String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION)).booleanValue(); - boolean confidentiality = confidentialityAvailable - && Boolean.valueOf((String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY)).booleanValue(); + String s; + Boolean flag; + s = (String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION); + flag = Boolean.valueOf(s); + replayDetection = replaydetectionAvailable && flag.booleanValue(); + s = (String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION); + flag = Boolean.valueOf(s); + boolean integrity = integrityAvailable && flag.booleanValue(); + s = (String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY); + flag = Boolean.valueOf(s); + boolean confidentiality = confidentialityAvailable && flag.booleanValue(); // make sure we do the right thing if (SRPRegistry.OPTION_REPLAY_DETECTION.equals(mandatory)) { @@ -830,7 +826,8 @@ public class SRPClient extends ClientMechanism implements SaslClient { if (chosenIntegrityAlgorithm == null) throw new AuthenticationException( - "Replay detection is required but no integrity protection algorithm was chosen"); + "Replay detection is required but no integrity protection " + + "algorithm was chosen"); } if (integrity) { @@ -950,7 +947,6 @@ public class SRPClient extends ClientMechanism implements SaslClient { if (prng == null) prng = PRNG.getInstance(); - return prng; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/SRPRegistry.java b/gnu/javax/crypto/sasl/srp/SRPRegistry.java index 9f7bba8e9..d474cb6f8 100644 --- a/gnu/javax/crypto/sasl/srp/SRPRegistry.java +++ b/gnu/javax/crypto/sasl/srp/SRPRegistry.java @@ -41,35 +41,29 @@ package gnu.javax.crypto.sasl.srp; import gnu.java.security.Registry; /** - * <p>A list of key names designating the values exchanged between the server - * and client in an SRP communication authentication phase.</p> + * A list of key names designating the values exchanged between the server + * and client in an SRP communication authentication phase. */ public interface SRPRegistry { - /** Indices of (N, g) parameter values for SRP (.conf) password database. */ String N_2048_BITS = "1"; - String N_1536_BITS = "2"; - String N_1280_BITS = "3"; - String N_1024_BITS = "4"; - String N_768_BITS = "5"; - String N_640_BITS = "6"; - String N_512_BITS = "7"; - /** Available hash algorithms for all SRP calculations. */ - String[] SRP_ALGORITHMS = { Registry.SHA160_HASH, // the default one - Registry.MD5_HASH, Registry.RIPEMD128_HASH, - Registry.RIPEMD160_HASH, - - Registry.SHA256_HASH, Registry.SHA384_HASH, - Registry.SHA512_HASH }; - + String[] SRP_ALGORITHMS = { + Registry.SHA160_HASH, // the default one + Registry.MD5_HASH, + Registry.RIPEMD128_HASH, + Registry.RIPEMD160_HASH, + + Registry.SHA256_HASH, + Registry.SHA384_HASH, + Registry.SHA512_HASH }; /** * The name of the default message digest algorithm to use when no name is * explicitely given. In this implementation it is the <b>first</b> among @@ -77,143 +71,95 @@ public interface SRPRegistry * 160-bit output. */ String SRP_DEFAULT_DIGEST_NAME = SRP_ALGORITHMS[0]; - /** * The property name of the message digest algorithm name to use in a given * SRP incarnation. */ String SRP_DIGEST_NAME = "srp.digest.name"; - /** The public shared modulus: n. */ String SHARED_MODULUS = "srp.N"; - /** The GF generator used: g. */ String FIELD_GENERATOR = "srp.g"; - /** The list of server's available security options. */ String AVAILABLE_OPTIONS = "srp.L"; - /** The client's chosen security options. */ String CHOSEN_OPTIONS = "srp.o"; - /** The client's username. */ String USER_NAME = "srp.U"; - /** The client's authorization ID. */ String USER_ROLE = "srp.I"; - /** The user's salt. */ String USER_SALT = "srp.s"; - /** The user's password verifier. */ String PASSWORD_VERIFIER = "srp.v"; - /** The client's public ephemeral exponent: A. */ String CLIENT_PUBLIC_KEY = "srp.A"; - /** The server's public ephemeral exponent: B. */ String SERVER_PUBLIC_KEY = "srp.B"; - /** The client's evidence: M1. */ String CLIENT_EVIDENCE = "srp.M1"; - /** The server's evidence: M2. */ String SERVER_EVIDENCE = "srp.M2"; - /** Name of underlying hash algorithm for use with all SRP calculations. */ String SRP_HASH = "gnu.crypto.sasl.srp.hash"; - /** Name of SRP mandatory service property. */ String SRP_MANDATORY = "gnu.crypto.sasl.srp.mandatory"; - /** Name of SRP replay detection property. */ String SRP_REPLAY_DETECTION = "gnu.crypto.sasl.srp.replay.detection"; - /** Name of SRP integrity protection property. */ String SRP_INTEGRITY_PROTECTION = "gnu.crypto.sasl.srp.integrity"; - /** Name of SRP confidentiality protection property. */ String SRP_CONFIDENTIALITY = "gnu.crypto.sasl.srp.confidentiality"; - /** Name of the main SRP password file pathname property. */ String PASSWORD_FILE = "gnu.crypto.sasl.srp.password.file"; - /** * Name of the SRP password database property --a reference to * {@link PasswordFile} object. */ String PASSWORD_DB = "gnu.crypto.sasl.srp.password.db"; - /** Default fully qualified pathname of the SRP password file. */ String DEFAULT_PASSWORD_FILE = "/etc/tpasswd"; - /** Default value for replay detection security service. */ boolean DEFAULT_REPLAY_DETECTION = true; - /** Default value for integrity protection security service. */ boolean DEFAULT_INTEGRITY = true; // implied by the previous option - /** Default value for confidentiality protection security service. */ boolean DEFAULT_CONFIDENTIALITY = false; - // constants defining HMAC names String HMAC_SHA1 = "hmac-sha1"; - String HMAC_MD5 = "hmac-md5"; - String HMAC_RIPEMD_160 = "hmac-ripemd-160"; - /** Available HMAC algorithms for integrity protection. */ String[] INTEGRITY_ALGORITHMS = { HMAC_SHA1, HMAC_MD5, HMAC_RIPEMD_160 }; - // constants defining Cipher names String AES = "aes"; - String BLOWFISH = "blowfish"; - /** Available Cipher algorithms for confidentiality protection. */ String[] CONFIDENTIALITY_ALGORITHMS = { AES, BLOWFISH }; - /** String for mandatory replay detection. */ String OPTION_MANDATORY = "mandatory"; - /** String for mda: the SRP digest algorithm name. */ String OPTION_SRP_DIGEST = "mda"; - /** String for mandatory replay detection. */ String OPTION_REPLAY_DETECTION = "replay_detection"; - /** String for mandatory integrity protection. */ String OPTION_INTEGRITY = "integrity"; - /** String for mandatory confidentiality protection. */ String OPTION_CONFIDENTIALITY = "confidentiality"; - /** String for mandatory replay detection. */ String OPTION_MAX_BUFFER_SIZE = "maxbuffersize"; - /** String for no mandatory security service. */ String MANDATORY_NONE = "none"; - /** Default mandatory security service required. */ - // String DEFAULT_MANDATORY = MANDATORY_NONE; String DEFAULT_MANDATORY = OPTION_REPLAY_DETECTION; - - // String DEFAULT_MANDATORY = OPTION_INTEGRITY; - // String DEFAULT_MANDATORY = OPTION_CONFIDENTIALITY; - /** Name of the UID field in the plain password file. */ String MD_NAME_FIELD = "srp.md.name"; - /** Name of the GID field in the plain password file. */ String USER_VERIFIER_FIELD = "srp.user.verifier"; - /** Name of the GECOS field in the plain password file. */ String SALT_FIELD = "srp.salt"; - /** Name of the SHELL field in the plain password file. */ String CONFIG_NDX_FIELD = "srp.config.ndx"; - /** Minimum bitlength of the SRP public modulus. */ int MINIMUM_MODULUS_BITLENGTH = 512; -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/SRPServer.java b/gnu/javax/crypto/sasl/srp/SRPServer.java index fa7cdae9c..ff7e4e9d6 100644 --- a/gnu/javax/crypto/sasl/srp/SRPServer.java +++ b/gnu/javax/crypto/sasl/srp/SRPServer.java @@ -73,7 +73,9 @@ import javax.security.sasl.SaslServer; /** * The SASL-SRP server-side mechanism. */ -public class SRPServer extends ServerMechanism implements SaslServer +public class SRPServer + extends ServerMechanism + implements SaslServer { private static final Logger log = Logger.getLogger(SRPServer.class.getName()); private String U = null; // client's username @@ -97,7 +99,8 @@ public class SRPServer extends ServerMechanism implements SaslServer private int outCounter = 0; private IALG inMac, outMac; // if !null, use for integrity private CALG inCipher, outCipher; // if !null, use for confidentiality - private IKeyAgreementParty serverHandler = KeyAgreementFactory.getPartyBInstance(Registry.SRP_SASL_KA); + private IKeyAgreementParty serverHandler = + KeyAgreementFactory.getPartyBInstance(Registry.SRP_SASL_KA); /** Our default source of randomness. */ private PRNG prng = null; @@ -124,7 +127,6 @@ public class SRPServer extends ServerMechanism implements SaslServer K = null; inMac = outMac = null; inCipher = outCipher = null; - sid = null; } @@ -135,7 +137,6 @@ public class SRPServer extends ServerMechanism implements SaslServer case 0: if (response == null) return null; - state++; return sendProtocolElements(response); case 1: @@ -180,17 +181,17 @@ public class SRPServer extends ServerMechanism implements SaslServer inCounter++; if (Configuration.DEBUG) log.fine("inCounter=" + String.valueOf(inCounter)); - inMac.update(new byte[] { (byte)(inCounter >>> 24), - (byte)(inCounter >>> 16), - (byte)(inCounter >>> 8), - (byte) inCounter }); + inMac.update(new byte[] { + (byte)(inCounter >>> 24), + (byte)(inCounter >>> 16), + (byte)(inCounter >>> 8), + (byte) inCounter }); } final byte[] computed_mac = inMac.doFinal(); if (Configuration.DEBUG) log.fine("Computed MAC: " + Util.dumpString(computed_mac)); - if (!Arrays.equals(received_mac, computed_mac)) + if (! Arrays.equals(received_mac, computed_mac)) throw new IntegrityException("engineUnwrap()"); - // deal with the payload, which can be either plain or encrypted if (inCipher != null) result = inCipher.doFinal(incoming, offset, payloadLength); @@ -252,10 +253,11 @@ public class SRPServer extends ServerMechanism implements SaslServer outCounter++; if (Configuration.DEBUG) log.fine("outCounter=" + outCounter); - outMac.update(new byte[] { (byte)(outCounter >>> 24), - (byte)(outCounter >>> 16), - (byte)(outCounter >>> 8), - (byte) outCounter }); + outMac.update(new byte[] { + (byte)(outCounter >>> 24), + (byte)(outCounter >>> 16), + (byte)(outCounter >>> 8), + (byte) outCounter }); } final byte[] C = outMac.doFinal(); out.write(C); @@ -276,10 +278,11 @@ public class SRPServer extends ServerMechanism implements SaslServer outCounter++; if (Configuration.DEBUG) log.fine("outCounter=" + outCounter); - outMac.update(new byte[] { (byte)(outCounter >>> 24), - (byte)(outCounter >>> 16), - (byte)(outCounter >>> 8), - (byte) outCounter }); + outMac.update(new byte[] { + (byte)(outCounter >>> 24), + (byte)(outCounter >>> 16), + (byte)(outCounter >>> 8), + (byte) outCounter }); } final byte[] C = outMac.doFinal(); out.write(C); @@ -305,7 +308,6 @@ public class SRPServer extends ServerMechanism implements SaslServer { if (inCipher != null) return Registry.QOP_AUTH_CONF; - return Registry.QOP_AUTH_INT; } return Registry.QOP_AUTH; @@ -317,7 +319,6 @@ public class SRPServer extends ServerMechanism implements SaslServer { if (inCipher != null) return Registry.STRENGTH_HIGH; - return Registry.STRENGTH_MEDIUM; } return Registry.STRENGTH_LOW; @@ -383,7 +384,6 @@ public class SRPServer extends ServerMechanism implements SaslServer outCipher = ctx.getOutCipher(); if (sn == null || sn.length != 16) sn = new byte[16]; - getDefaultPRNG().nextBytes(sn); setupSecurityServices(false); final OutputBuffer frameOut = new OutputBuffer(); @@ -543,9 +543,8 @@ public class SRPServer extends ServerMechanism implements SaslServer throw new AuthenticationException("sendEvidence()", x); } // Verify client evidence - if (!Arrays.equals(M1, expected)) + if (! Arrays.equals(M1, expected)) throw new AuthenticationException("M1 mismatch"); - setupSecurityServices(true); final byte[] M2; try @@ -673,8 +672,8 @@ public class SRPServer extends ServerMechanism implements SaslServer else if (option.startsWith(SRPRegistry.OPTION_INTEGRITY + "=")) { if (integrity) - throw new AuthenticationException("Only one integrity algorithm may be chosen"); - + throw new AuthenticationException( + "Only one integrity algorithm may be chosen"); option = option.substring(option.indexOf('=') + 1); if (Configuration.DEBUG) log.fine("algorithm: <" + option + ">"); @@ -694,8 +693,8 @@ public class SRPServer extends ServerMechanism implements SaslServer else if (option.startsWith(SRPRegistry.OPTION_CONFIDENTIALITY + "=")) { if (confidentiality) - throw new AuthenticationException("Only one confidentiality algorithm may be chosen"); - + throw new AuthenticationException( + "Only one confidentiality algorithm may be chosen"); option = option.substring(option.indexOf('=') + 1); if (Configuration.DEBUG) log.fine("algorithm: <" + option + ">"); @@ -720,13 +719,13 @@ public class SRPServer extends ServerMechanism implements SaslServer rawSendSize = Integer.parseInt(maxBufferSize); if (rawSendSize > Registry.SASL_BUFFER_MAX_LIMIT || rawSendSize < 1) - throw new AuthenticationException("Illegal value for 'maxbuffersize' option"); + throw new AuthenticationException( + "Illegal value for 'maxbuffersize' option"); } catch (NumberFormatException x) { - throw new AuthenticationException(SRPRegistry.OPTION_MAX_BUFFER_SIZE - + "=" + maxBufferSize, - x); + throw new AuthenticationException( + SRPRegistry.OPTION_MAX_BUFFER_SIZE + "=" + maxBufferSize, x); } } } @@ -734,23 +733,26 @@ public class SRPServer extends ServerMechanism implements SaslServer if (replayDetection) { if (! integrity) - throw new AuthenticationException("Missing integrity protection algorithm " - + "but replay detection is chosen"); + throw new AuthenticationException( + "Missing integrity protection algorithm but replay detection is chosen"); } if (mandatory.equals(SRPRegistry.OPTION_REPLAY_DETECTION)) { if (! replayDetection) - throw new AuthenticationException("Replay detection is mandatory but was not chosen"); + throw new AuthenticationException( + "Replay detection is mandatory but was not chosen"); } if (mandatory.equals(SRPRegistry.OPTION_INTEGRITY)) { if (! integrity) - throw new AuthenticationException("Integrity protection is mandatory but was not chosen"); + throw new AuthenticationException( + "Integrity protection is mandatory but was not chosen"); } if (mandatory.equals(SRPRegistry.OPTION_CONFIDENTIALITY)) { if (! confidentiality) - throw new AuthenticationException("Confidentiality is mandatory but was not chosen"); + throw new AuthenticationException( + "Confidentiality is mandatory but was not chosen"); } int blockSize = 0; if (chosenConfidentialityAlgorithm != null) @@ -833,7 +835,6 @@ public class SRPServer extends ServerMechanism implements SaslServer { if (prng == null) prng = PRNG.getInstance(); - return prng; } } diff --git a/gnu/javax/crypto/sasl/srp/SecurityContext.java b/gnu/javax/crypto/sasl/srp/SecurityContext.java index feca25cad..1111d95b4 100644 --- a/gnu/javax/crypto/sasl/srp/SecurityContext.java +++ b/gnu/javax/crypto/sasl/srp/SecurityContext.java @@ -39,41 +39,23 @@ exception statement from your version. */ package gnu.javax.crypto.sasl.srp; /** - * <p>A package-private placeholder for an SRP security context.</p> + * A package-private placeholder for an SRP security context. */ class SecurityContext { - - // Constants and variables - // ------------------------------------------------------------------------- - private String mdName; - private byte[] sid; - private byte[] K; - private byte[] cIV; - private byte[] sIV; - private boolean replayDetection; - private int inCounter; - private int outCounter; - private IALG inMac; - private IALG outMac; - private CALG inCipher; - private CALG outCipher; - // Constructor(s) - // ------------------------------------------------------------------------- - SecurityContext(final String mdName, final byte[] sid, final byte[] K, final byte[] cIV, final byte[] sIV, final boolean replayDetection, final int inCounter, @@ -96,12 +78,6 @@ class SecurityContext this.outCipher = outCipher; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - String getMdName() { return mdName; @@ -161,4 +137,4 @@ class SecurityContext { return outCipher; } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/ServerStore.java b/gnu/javax/crypto/sasl/srp/ServerStore.java index 99bf96a94..e9b1a7282 100644 --- a/gnu/javax/crypto/sasl/srp/ServerStore.java +++ b/gnu/javax/crypto/sasl/srp/ServerStore.java @@ -41,32 +41,21 @@ package gnu.javax.crypto.sasl.srp; import java.util.HashMap; /** - * <p>The server-side implementation of the SRP security context store.</p> + * The server-side implementation of the SRP security context store. */ public class ServerStore { - - // Constants and variables - // ------------------------------------------------------------------------- - /** The underlying singleton. */ private static ServerStore singleton = null; - /** The map of sid --> Security Context record. */ private static final HashMap sid2ssc = new HashMap(); - /** The map of sid --> Session timing record. */ private static final HashMap sid2ttl = new HashMap(); - /** A synchronisation lock. */ private static final Object lock = new Object(); - /** A counter to generate legible SIDs. */ private static int counter = 0; - // Constructor(s) - // ------------------------------------------------------------------------- - /** Private constructor to enforce Singleton pattern. */ private ServerStore() { @@ -75,48 +64,38 @@ public class ServerStore // TODO: add a cleaning timer thread } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns the classloader Singleton.</p> - * + * Returns the classloader Singleton. + * * @return the classloader Singleton instance. */ static synchronized final ServerStore instance() { if (singleton == null) - { - singleton = new ServerStore(); - } + singleton = new ServerStore(); return singleton; } /** - * <p>Returns a legible new session identifier.</p> - * + * Returns a legible new session identifier. + * * @return a new session identifier. */ static synchronized final byte[] getNewSessionID() { final String sid = String.valueOf(++counter); - return new StringBuffer("SID-").append( - "0000000000".substring( - 0, - 10 - sid.length())).append( - sid).toString().getBytes(); + return new StringBuffer("SID-") + .append("0000000000".substring(0, 10 - sid.length())).append(sid) + .toString().getBytes(); } - // Instance methods - // ------------------------------------------------------------------------- - /** - * <p>Returns a boolean flag indicating if the designated session is still - * alive or not.</p> - * + * Returns a boolean flag indicating if the designated session is still alive + * or not. + * * @param sid the identifier of the session to check. * @return <code>true</code> if the designated session is still alive. - * <code>false</code> otherwise. + * <code>false</code> otherwise. */ boolean isAlive(final byte[] sid) { @@ -130,8 +109,8 @@ public class ServerStore if (ctx != null) { result = ctx.isAlive(); - if (!result) - { // invalidate it en-passant + if (! result) // invalidate it en-passant + { sid2ssc.remove(key); sid2ttl.remove(key); } @@ -142,9 +121,9 @@ public class ServerStore } /** - * <p>Records a mapping between a session identifier and the Security Context - * of the designated SRP server mechanism instance.</p> - * + * Records a mapping between a session identifier and the Security Context of + * the designated SRP server mechanism instance. + * * @param ttl the session's Time-To-Live indicator (in seconds). * @param ctx the server's security context. */ @@ -159,11 +138,11 @@ public class ServerStore } /** - * <p>Updates the mapping between the designated session identifier and the - * designated server's SASL Security Context. In the process, computes - * and return the underlying mechanism server's evidence that shall be - * returned to the client in a session re-use exchange.</p> - * + * Updates the mapping between the designated session identifier and the + * designated server's SASL Security Context. In the process, computes and + * return the underlying mechanism server's evidence that shall be returned to + * the client in a session re-use exchange. + * * @param sid the identifier of the session to restore. * @return an SRP server's security context. */ @@ -180,8 +159,8 @@ public class ServerStore } /** - * <p>Removes all information related to the designated session ID.</p> - * + * Removes all information related to the designated session ID. + * * @param sid the identifier of the seesion to invalidate. */ void invalidateSession(final byte[] sid) @@ -193,4 +172,4 @@ public class ServerStore sid2ttl.remove(key); } } -}
\ No newline at end of file +} diff --git a/gnu/javax/crypto/sasl/srp/StoreEntry.java b/gnu/javax/crypto/sasl/srp/StoreEntry.java index c5041fa4b..130678ebd 100644 --- a/gnu/javax/crypto/sasl/srp/StoreEntry.java +++ b/gnu/javax/crypto/sasl/srp/StoreEntry.java @@ -39,21 +39,13 @@ exception statement from your version. */ package gnu.javax.crypto.sasl.srp; /** - * <p>A simple timing-related object for use by SRP re-use code.</p> + * A simple timing-related object for use by SRP re-use code. */ class StoreEntry { - - // Constants and variables - // ------------------------------------------------------------------------- - private boolean perenial; - private long timeToDie; - // Constructor(s) - // ------------------------------------------------------------------------- - StoreEntry(int ttl) { super(); @@ -70,20 +62,14 @@ class StoreEntry } } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - /** - * <p>Returns <code>true</code> if the Time-To_live period has not elapsed.</p> - * + * Returns <code>true</code> if the Time-To_live period has not elapsed. + * * @return <code>true</code> if the Time-To-Live period (in seconds) has not - * elapsed yet; <code>false</code> otherwise. + * elapsed yet; <code>false</code> otherwise. */ boolean isAlive() { return (perenial ? true : (System.currentTimeMillis() < timeToDie)); } -}
\ No newline at end of file +} diff --git a/gnu/javax/print/ipp/IppRequest.java b/gnu/javax/print/ipp/IppRequest.java index ccfa9b272..05a6faae7 100644 --- a/gnu/javax/print/ipp/IppRequest.java +++ b/gnu/javax/print/ipp/IppRequest.java @@ -794,7 +794,7 @@ public class IppRequest alreadySent = true; - OutputStream stream = stream = connection.getOutputStream(); + OutputStream stream = connection.getOutputStream(); DataOutputStream out = new DataOutputStream(stream); // the header 8 bytes long @@ -849,7 +849,7 @@ public class IppRequest // own thread. connection.setConnectTimeout( timeout ); - int responseCode = responseCode = connection.getResponseCode(); + int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { diff --git a/gnu/javax/sound/midi/file/MidiFileWriter.java b/gnu/javax/sound/midi/file/MidiFileWriter.java index eefcd898c..71970d5ba 100644 --- a/gnu/javax/sound/midi/file/MidiFileWriter.java +++ b/gnu/javax/sound/midi/file/MidiFileWriter.java @@ -44,6 +44,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import javax.sound.midi.MetaMessage; import javax.sound.midi.MidiEvent; import javax.sound.midi.Sequence; import javax.sound.midi.Track; @@ -161,8 +162,22 @@ public class MidiFileWriter pme = me; i++; } - // FIXME: if the last event isn't an end of track.. write that. - return trackLength + 8; + + // We're done if the last event was an End of Track meta message. + if (pme != null && (pme.getMessage() instanceof MetaMessage)) + { + MetaMessage mm = (MetaMessage) pme.getMessage(); + if (mm.getType() == 0x2f) // End of Track message + return trackLength + 8; + } + + // Write End of Track meta message + dos.writeVariableLengthInt(0); // Delta time of 0 + dos.writeByte(0xff); // Meta Message + dos.writeByte(0x2f); // End of Track message + dos.writeVariableLengthInt(0); // Length of 0 + + return trackLength + 8 + 4; } /* Write a Sequence to a file. diff --git a/gnu/javax/sound/sampled/WAV/WAVReader.java b/gnu/javax/sound/sampled/WAV/WAVReader.java new file mode 100644 index 000000000..0cf3c1377 --- /dev/null +++ b/gnu/javax/sound/sampled/WAV/WAVReader.java @@ -0,0 +1,236 @@ +/* WAVReader.java -- Read WAV files. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.javax.sound.sampled.WAV; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.net.URL; + +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioFileFormat; +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.UnsupportedAudioFileException; +import javax.sound.sampled.spi.AudioFileReader; + +/** + * A WAV file reader. + * + * This code reads WAV files. + * + * There are many decent documents on the web describing the WAV file + * format. I didn't bother looking for the official document. If it + * exists, I'm not even sure if it is freely available. We should + * update this comment if we find out anything helpful here. I used + * http://www.sonicspot.com/guide/wavefiles.html + * + * @author Anthony Green (green@redhat.com) + * + */ +public class WAVReader extends AudioFileReader +{ + private static long readUnsignedIntLE (DataInputStream is) + throws IOException + { + byte[] buf = new byte[4]; + is.readFully(buf); + return (buf[0] & 0xFF + | ((buf[1] & 0xFF) << 8) + | ((buf[2] & 0xFF) << 16) + | ((buf[3] & 0xFF) << 24)); + } + + private static short readUnsignedShortLE (DataInputStream is) + throws IOException + { + byte[] buf = new byte[2]; + is.readFully(buf); + return (short) (buf[0] & 0xFF + | ((buf[1] & 0xFF) << 8)); + } + + /* Get an AudioFileFormat from the given File. + * @see javax.sound.sampled.spi.AudioFileReader#getAudioFileFormat(java.io.File) + */ + public AudioFileFormat getAudioFileFormat(File file) + throws UnsupportedAudioFileException, IOException + { + InputStream is = new FileInputStream(file); + try + { + return getAudioFileFormat(is); + } + finally + { + is.close(); + } + } + + /* Get an AudioFileFormat from the given InputStream. + * @see javax.sound.sampled.spi.AudioFileReader#getAudioFileFormat(java.io.InputStream) + */ + public AudioFileFormat getAudioFileFormat(InputStream in) + throws UnsupportedAudioFileException, IOException + { + DataInputStream din; + + if (in instanceof DataInputStream) + din = (DataInputStream) in; + else + din = new DataInputStream(in); + + if (din.readInt() != 0x52494646) // "RIFF" + throw new UnsupportedAudioFileException("Invalid WAV chunk header."); + + // Read the length of this RIFF thing. + readUnsignedIntLE(din); + + if (din.readInt() != 0x57415645) // "WAVE" + throw new UnsupportedAudioFileException("Invalid WAV chunk header."); + + boolean foundFmt = false; + boolean foundData = false; + + short compressionCode = 0, numberChannels = 0, blockAlign = 0, bitsPerSample = 0; + long sampleRate = 0, bytesPerSecond = 0; + long chunkLength = 0; + + while (! foundData) + { + int chunkId = din.readInt(); + chunkLength = readUnsignedIntLE(din); + switch (chunkId) + { + case 0x666D7420: // "fmt " + foundFmt = true; + compressionCode = readUnsignedShortLE(din); + numberChannels = readUnsignedShortLE(din); + sampleRate = readUnsignedIntLE(din); + bytesPerSecond = readUnsignedIntLE(din); + blockAlign = readUnsignedShortLE(din); + bitsPerSample = readUnsignedShortLE(din); + din.skip(chunkLength - 16); + break; + case 0x66616374: // "fact" + // FIXME: hold compression format dependent data. + din.skip(chunkLength); + break; + case 0x64617461: // "data" + if (! foundFmt) + throw new UnsupportedAudioFileException("This implementation requires WAV fmt chunks precede data chunks."); + foundData = true; + break; + default: + // Unrecognized chunk. Skip it. + din.skip(chunkLength); + } + } + + AudioFormat.Encoding encoding; + + switch (compressionCode) + { + case 1: // PCM/uncompressed + if (bitsPerSample <= 8) + encoding = AudioFormat.Encoding.PCM_UNSIGNED; + else + encoding = AudioFormat.Encoding.PCM_SIGNED; + break; + + default: + throw new UnsupportedAudioFileException("Unrecognized WAV compression code: 0x" + + Integer.toHexString(compressionCode)); + } + + return new AudioFileFormat (AudioFileFormat.Type.WAVE, + new AudioFormat(encoding, + (float) sampleRate, + bitsPerSample, + numberChannels, + ((bitsPerSample + 7) / 8) * numberChannels, + (float) bytesPerSecond, false), + (int) chunkLength); + } + + /* Get an AudioFileFormat from the given URL. + * @see javax.sound.sampled.spi.AudioFileReader#getAudioFileFormat(java.net.URL) + */ + public AudioFileFormat getAudioFileFormat(URL url) + throws UnsupportedAudioFileException, IOException + { + InputStream is = url.openStream(); + try + { + return getAudioFileFormat(is); + } + finally + { + is.close(); + } + } + + /* Get an AudioInputStream from the given File. + * @see javax.sound.sampled.spi.AudioFileReader#getAudioInputStream(java.io.File) + */ + public AudioInputStream getAudioInputStream(File file) + throws UnsupportedAudioFileException, IOException + { + return getAudioInputStream(new FileInputStream(file)); + } + + /* Get an AudioInputStream from the given InputStream. + * @see javax.sound.sampled.spi.AudioFileReader#getAudioInputStream(java.io.InputStream) + */ + public AudioInputStream getAudioInputStream(InputStream stream) + throws UnsupportedAudioFileException, IOException + { + AudioFileFormat aff = getAudioFileFormat(stream); + return new AudioInputStream(stream, aff.getFormat(), (long) aff.getFrameLength()); + } + + /* Get an AudioInputStream from the given URL. + * @see javax.sound.sampled.spi.AudioFileReader#getAudioInputStream(java.net.URL) + */ + public AudioInputStream getAudioInputStream(URL url) + throws UnsupportedAudioFileException, IOException + { + return getAudioInputStream(url.openStream()); + } +} diff --git a/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java b/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java index 67d6332df..a9b504a38 100644 --- a/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java +++ b/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java @@ -71,6 +71,7 @@ public class GNULookAndFeel extends BasicLookAndFeel "ScrollBar.background", new ColorUIResource(blueGray), "CheckBox.icon", new CheckBoxIcon(), "RadioButton.icon", new RadioButtonIcon(), + "Tree.hash", new ColorUIResource(Color.black), "Tree.closedIcon", new IconUIResource(new ImageIcon diff --git a/gnu/javax/swing/text/html/CharacterAttributeTranslator.java b/gnu/javax/swing/text/html/CharacterAttributeTranslator.java index 5f7309583..06732e401 100644 --- a/gnu/javax/swing/text/html/CharacterAttributeTranslator.java +++ b/gnu/javax/swing/text/html/CharacterAttributeTranslator.java @@ -83,7 +83,7 @@ public class CharacterAttributeTranslator * @param colorName the color to convert. * @return the matching java.awt.color */ - private static Color getColor(String colorName) + public static Color getColor(String colorName) { colorName = colorName.toLowerCase(); try diff --git a/java/awt/Canvas.java b/java/awt/Canvas.java index b599582ba..2f838d60e 100644 --- a/java/awt/Canvas.java +++ b/java/awt/Canvas.java @@ -68,6 +68,11 @@ public class Canvas * Compatible with Sun's JDK. */ private static final long serialVersionUID = -2284879212465893870L; + + /** + * The number used to generate the name returned by getName. + */ + private static transient long next_canvas_number; /** * The graphics configuration associated with the canvas. @@ -343,4 +348,19 @@ public class Canvas /* Call the paint method */ paint(graphics); } + + /** + * Generate a unique name for this canvas. + * + * @return A unique name for this canvas. + */ + String generateName() + { + return "canvas" + getUniqueLong(); + } + + private static synchronized long getUniqueLong() + { + return next_canvas_number++; + } } diff --git a/java/awt/Component.java b/java/awt/Component.java index d251b2d15..c778c4921 100644 --- a/java/awt/Component.java +++ b/java/awt/Component.java @@ -746,7 +746,9 @@ public abstract class Component */ public boolean isValid() { - return valid; + // Tests show that components are invalid as long as they are not showing, even after validate() + // has been called on them. + return peer != null && valid; } /** @@ -931,7 +933,6 @@ public abstract class Component ComponentPeer currentPeer=peer; if (currentPeer != null) currentPeer.show(); - // The JDK repaints the component before invalidating the parent. // So do we. if (isShowing() && isLightweight()) @@ -1116,16 +1117,13 @@ public abstract class Component */ public void setFont(Font newFont) { - if((newFont != null && (font == null || !font.equals(newFont))) - || newFont == null) - { - Font oldFont = font; - font = newFont; - if (peer != null) - peer.setFont(font); - firePropertyChange("font", oldFont, newFont); - invalidate(); - } + Font oldFont = font; + font = newFont; + if (peer != null) + peer.setFont(font); + firePropertyChange("font", oldFont, newFont); + if (valid) + invalidate(); } /** diff --git a/java/awt/Container.java b/java/awt/Container.java index bd20b9579..daca76efb 100644 --- a/java/awt/Container.java +++ b/java/awt/Container.java @@ -342,7 +342,7 @@ public class Container extends Component if (component == null) component = new Component[4]; // FIXME, better initial size? - + // This isn't the most efficient implementation. We could do less // copying when growing the array. It probably doesn't matter. if (ncomponents >= component.length) @@ -518,7 +518,8 @@ public class Container extends Component public void setLayout(LayoutManager mgr) { layoutMgr = mgr; - invalidate(); + if (valid) + invalidate(); } /** diff --git a/java/awt/LightweightDispatcher.java b/java/awt/LightweightDispatcher.java index 7e33bd4e9..e777145b0 100644 --- a/java/awt/LightweightDispatcher.java +++ b/java/awt/LightweightDispatcher.java @@ -287,13 +287,13 @@ class LightweightDispatcher */ private Component findTarget(Container c, Point loc) { - Component[] children = c.getComponents(); + int numComponents = c.getComponentCount(); Component target = null; if (c != null) { - for (int i = 0; i < children.length; i++) + for (int i = 0; i < numComponents; i++) { - Component child = children[i]; + Component child = c.getComponent(i); if (child.isShowing()) { if (child.contains(loc.x - child.getX(), loc.y - child.getY()) diff --git a/java/awt/TextComponent.java b/java/awt/TextComponent.java index e9a10b0c5..4fc62a951 100644 --- a/java/awt/TextComponent.java +++ b/java/awt/TextComponent.java @@ -445,7 +445,7 @@ public class TextComponent extends Component this.selectionStart = selectionStart; this.selectionEnd = selectionEnd; - + TextComponentPeer tcp = (TextComponentPeer) getPeer(); if (tcp != null) tcp.select(selectionStart, selectionEnd); diff --git a/java/awt/dnd/DragGestureEvent.java b/java/awt/dnd/DragGestureEvent.java index ab03a33c8..2a22abb12 100644 --- a/java/awt/dnd/DragGestureEvent.java +++ b/java/awt/dnd/DragGestureEvent.java @@ -48,13 +48,6 @@ import java.util.EventObject; import java.util.Iterator; import java.util.List; -/** - * STUBBED - * @see DragGestureRecognizer - * @see DragGestureListener - * @see DragSource - * @since 1.2 - */ public class DragGestureEvent extends EventObject { /** @@ -66,52 +59,121 @@ public class DragGestureEvent extends EventObject private Component component; private final Point origin; private final int action; + private List<InputEvent> events; + private DragGestureRecognizer dgr; + /** + * Constructs a new DragGestureEvent. + * @param dgr - DragGestureRecognizer firing this event + * @param action - user's preferred action + * @param origin - origin of the drag + * @param events - List of events that make up the gesture + * @throws IllegalArgumentException - if input parameters are null + */ public DragGestureEvent(DragGestureRecognizer dgr, int action, Point origin, List<? extends InputEvent> events) { super(dgr); - if (origin == null || events == null) + if (origin == null || events == null || dgr == null) throw new IllegalArgumentException(); + this.origin = origin; this.action = action; + this.events = (List<InputEvent>) events; + this.dgr = dgr; + this.component = dgr.getComponent(); + this.dragSource = dgr.getDragSource(); } + /** + * Returns the source casted as a DragGestureRecognizer. + * + * @return the source casted as a DragGestureRecognizer. + */ public DragGestureRecognizer getSourceAsDragGestureRecognizer() { - return (DragGestureRecognizer) source; + return (DragGestureRecognizer) getSource(); } + + /** + * Returns the Component corresponding to this. + * + * @return the Component corresponding to this. + */ public Component getComponent() { - return null; + return component; } + + /** + * Gets the DragSource corresponding to this. + * + * @return the DragSource corresponding to this. + */ public DragSource getDragSource() { - return null; + return dragSource; } + + /** + * Returns the origin of the drag. + * + * @return the origin of the drag. + */ public Point getDragOrigin() { return origin; } + + /** + * Gets an iterator representation of the List of events. + * + * @return an iterator representation of the List of events. + */ public Iterator<InputEvent> iterator() { - return null; + return events.iterator(); } + + /** + * Gets an array representation of the List of events. + * + * @return an array representation of the List of events. + */ public Object[] toArray() { - return null; + return events.toArray(); } + + /** + * Gets an array representation of the List of events. + * + * @param array - the array to store the events in. + * @return an array representation of the List of events. + */ public Object[] toArray(Object[] array) { - return array; + return events.toArray(array); } + + /** + * Gets the user's preferred action. + * + * @return the user's preferred action. + */ public int getDragAction() { - return 0; + return action; } + + /** + * Get the event that triggered this gesture. + * + * @return the event that triggered this gesture. + */ public InputEvent getTriggerEvent() { - return null; + return dgr.getTriggerEvent(); } /** @@ -152,5 +214,6 @@ public class DragGestureEvent extends EventObject public void startDrag(Cursor dragCursor, Image dragImage, Point imageOffset, Transferable trans, DragSourceListener l) { + dragSource.startDrag(this, dragCursor, dragImage, imageOffset, trans, l); } } // class DragGestureEvent diff --git a/java/awt/dnd/DragGestureRecognizer.java b/java/awt/dnd/DragGestureRecognizer.java index 759ec9ac2..1a396f198 100644 --- a/java/awt/dnd/DragGestureRecognizer.java +++ b/java/awt/dnd/DragGestureRecognizer.java @@ -133,6 +133,7 @@ public abstract class DragGestureRecognizer implements Serializable throws NotImplementedException { events = new ArrayList(); + // FIXME: Not implemented fully. } /** diff --git a/java/awt/dnd/DragSource.java b/java/awt/dnd/DragSource.java index 014998913..90b62b5db 100644 --- a/java/awt/dnd/DragSource.java +++ b/java/awt/dnd/DragSource.java @@ -38,6 +38,8 @@ exception statement from your version. */ package java.awt.dnd; +import gnu.classpath.NotImplementedException; + import java.awt.Component; import java.awt.Cursor; import java.awt.GraphicsEnvironment; @@ -49,6 +51,7 @@ import java.awt.datatransfer.FlavorMap; import java.awt.datatransfer.SystemFlavorMap; import java.awt.datatransfer.Transferable; import java.awt.dnd.peer.DragSourceContextPeer; +import java.awt.event.MouseMotionListener; import java.io.Serializable; import java.util.EventListener; @@ -70,9 +73,10 @@ public class DragSource implements Serializable public static final Cursor DefaultLinkNoDrop = null; private transient FlavorMap flavorMap = SystemFlavorMap.getDefaultFlavorMap (); - private transient DragSourceListener dragSourceListener; private transient DragSourceMotionListener dragSourceMotionListener; + + private static DragSource ds; /** * Initializes the drag source. @@ -82,19 +86,34 @@ public class DragSource implements Serializable public DragSource() { if (GraphicsEnvironment.isHeadless()) - throw new HeadlessException (); + { + ds = null; + throw new HeadlessException(); + } } /** + * Gets the default drag source. + * * @exception HeadlessException If GraphicsEnvironment.isHeadless() is true. */ public static DragSource getDefaultDragSource() { - return new DragSource(); + if (GraphicsEnvironment.isHeadless()) + { + ds = null; + throw new HeadlessException(); + } + + if (ds == null) + ds = new DragSource(); + return ds; } public static boolean isDragImageSupported() + throws NotImplementedException { + // FIXME: Implement this return false; } @@ -110,6 +129,38 @@ public class DragSource implements Serializable Transferable trans, DragSourceListener dsl, FlavorMap map) { + // http://www.javaworld.com/javaworld/jw-03-1999/jw-03-dragndrop.html + + // This function creates a DragSourceContext object. This object tracks the + // state of the operation by listening to a native peer. In this situation, + // the DragSource may be obtained from the event or by an instance variable. + // This function also creates a new DragSourceContextPeer. + + // This function sends the same message to the context, which then forwards + // it to the peer, passing itself as a parameter. Now, the native system has + // access to the Transferable through the context. + + try + { + flavorMap = map; + DragSourceContextPeer peer = Toolkit.getDefaultToolkit(). + createDragSourceContextPeer(trigger); + DragSourceContext context = createDragSourceContext(peer, trigger, + dragCursor, + dragImage, + imageOffset, trans, + dsl); + + if (peer == null) + throw new InvalidDnDOperationException(); + + peer.startDrag(context, dragCursor, dragImage, imageOffset); + } + catch (Exception e) + { + throw new InvalidDnDOperationException("Drag and Drop system is " + + "unable to initiate a drag operation."); + } } /** @@ -156,7 +207,7 @@ public class DragSource implements Serializable /** * Creates the DragSourceContext to handle this drag. * - * @exception IllegalArgumentException FIXME + * @exception IllegalArgumentException * @exception NullPointerException If dscp, dgl, dragImage or t is null. */ protected DragSourceContext @@ -164,50 +215,31 @@ public class DragSource implements Serializable Cursor cursor, Image image, Point offset, Transferable t, DragSourceListener dsl) { - return null; + return new DragSourceContext(peer, dge, cursor, image, offset, t, dsl); } public FlavorMap getFlavorMap() { return flavorMap; } - - /** - * Dummy DragGestureRecognizer when Toolkit doesn't support drag and drop. - */ - static class NoDragGestureRecognizer extends DragGestureRecognizer - { - NoDragGestureRecognizer(DragSource ds, Component c, int actions, - DragGestureListener dgl) - { - super(ds, c, actions, dgl); - } - - protected void registerListeners() { } - protected void unregisterListeners() { } - } - + public <T extends DragGestureRecognizer> T - createDragGestureRecognizer(Class<T> recognizer, Component c, int actions, - DragGestureListener dgl) + createDragGestureRecognizer(Class<T> recognizer, + Component c, + int actions, + DragGestureListener dgl) { - DragGestureRecognizer dgr; - dgr = Toolkit.getDefaultToolkit () - .createDragGestureRecognizer (recognizer, this, c, actions, - dgl); - - if (dgr == null) - dgr = new NoDragGestureRecognizer(this, c, actions, dgl); - - return (T) dgr; + return (T) Toolkit.getDefaultToolkit().createDragGestureRecognizer(recognizer, + this, c, + actions, dgl); } - public DragGestureRecognizer - createDefaultDragGestureRecognizer(Component c, int actions, - DragGestureListener dgl) + public DragGestureRecognizer createDefaultDragGestureRecognizer(Component c, + int actions, + DragGestureListener dgl) { - return createDragGestureRecognizer (MouseDragGestureRecognizer.class, c, - actions, dgl); + return createDragGestureRecognizer(MouseDragGestureRecognizer.class, c, + actions, dgl); } /** diff --git a/java/awt/dnd/DragSourceContext.java b/java/awt/dnd/DragSourceContext.java index 88607b090..1fee5c0c3 100644 --- a/java/awt/dnd/DragSourceContext.java +++ b/java/awt/dnd/DragSourceContext.java @@ -70,8 +70,8 @@ public class DragSourceContext private Transferable transferable; private DragGestureEvent trigger; private DragSourceListener dragSourceListener; - private boolean useCustomCursor; // FIXME: currently unused but needed for serialization. - private int sourceActions; // FIXME: currently unused but needed for serialization. + private boolean useCustomCursor; + private int sourceActions; private Image image; private Point offset; @@ -82,16 +82,17 @@ public class DragSourceContext * are null, the drag action for the trigger event is DnDConstants.ACTION_NONE * or if the source actions for the DragGestureRecognizer associated with the * trigger event are equal to DnDConstants.ACTION_NONE. - * @exception NullPointerException If peer or trigger is null. + * @exception NullPointerException If peer, trans or trigger is null or if the + * image is not null but the offset is. */ public DragSourceContext (DragSourceContextPeer peer, DragGestureEvent trigger, Cursor cursor, Image image, Point offset, Transferable trans, DragSourceListener dsl) - throws NotImplementedException - { + { if (peer == null - || trigger == null) + || trigger == null || trans == null + || (image != null && offset == null)) throw new NullPointerException (); if (trigger.getComponent () == null @@ -108,37 +109,77 @@ public class DragSourceContext this.offset = offset; this.transferable = trans; this.dragSourceListener = dsl; + this.sourceActions = trigger.getSourceAsDragGestureRecognizer().getSourceActions(); - throw new Error ("not implemented"); + setCursor(cursor); + updateCurrentCursor(trigger.getDragAction(), sourceActions, DEFAULT); } + /** + * Returns the DragSource object associated with the + * DragGestureEvent. + * + * @return the DragSource associated with the trigger. + */ public DragSource getDragSource() { return trigger.getDragSource (); } + /** + * Returns the component associated with this. + * + * @return the component associated with the trigger. + */ public Component getComponent() { return trigger.getComponent (); } + /** + * Gets the trigger associated with this. + * + * @return the trigger. + */ public DragGestureEvent getTrigger() { return trigger; } + /** + * Returns the source actions for the DragGestureRecognizer. + * + * @return the source actions for DragGestureRecognizer. + */ public int getSourceActions() { - return trigger.getSourceAsDragGestureRecognizer ().getSourceActions (); + if (sourceActions == 0) + sourceActions = trigger.getSourceAsDragGestureRecognizer().getSourceActions(); + return sourceActions; } - public void setCursor (Cursor cursor) - throws NotImplementedException + /** + * Sets the cursor for this drag operation to the specified cursor. + * + * @param cursor c - the Cursor to use, or null to use the default drag + * cursor. + */ + public void setCursor(Cursor cursor) { + if (cursor == null) + useCustomCursor = false; + else + useCustomCursor = true; this.cursor = cursor; - // FIXME: Check if we need to do more here + peer.setCursor(cursor); } + /** + * Returns the current cursor or null if the default + * drag cursor is used. + * + * @return the current cursor or null. + */ public Cursor getCursor() { return cursor; @@ -165,48 +206,160 @@ public class DragSourceContext dragSourceListener = null; } + /** + * This function tells the peer that the DataFlavors have been modified. + */ public void transferablesFlavorsChanged() - throws NotImplementedException { + peer.transferablesFlavorsChanged(); } + /** + * Calls dragEnter on the listeners registered with this + * and with the DragSource. + * + * @param e - the DragSourceDragEvent + */ public void dragEnter(DragSourceDragEvent e) - throws NotImplementedException { + if (dragSourceListener != null) + dragSourceListener.dragEnter(e); + + DragSource ds = getDragSource(); + DragSourceListener[] dsl = ds.getDragSourceListeners(); + for (int i = 0; i < dsl.length; i++) + dsl[i].dragEnter(e); + + updateCurrentCursor(e.getDropAction(), e.getTargetActions(), ENTER); } + /** + * Calls dragOver on the listeners registered with this + * and with the DragSource. + * + * @param e - the DragSourceDragEvent + */ public void dragOver(DragSourceDragEvent e) - throws NotImplementedException { + if (dragSourceListener != null) + dragSourceListener.dragOver(e); + + DragSource ds = getDragSource(); + DragSourceListener[] dsl = ds.getDragSourceListeners(); + for (int i = 0; i < dsl.length; i++) + dsl[i].dragOver(e); + + updateCurrentCursor(e.getDropAction(), e.getTargetActions(), OVER); } - + + /** + * Calls dragExit on the listeners registered with this + * and with the DragSource. + * + * @param e - the DragSourceEvent + */ public void dragExit(DragSourceEvent e) - throws NotImplementedException { + if (dragSourceListener != null) + dragSourceListener.dragExit(e); + + DragSource ds = getDragSource(); + DragSourceListener[] dsl = ds.getDragSourceListeners(); + for (int i = 0; i < dsl.length; i++) + dsl[i].dragExit(e); + + updateCurrentCursor(0, 0, DEFAULT); } + /** + * Calls dropActionChanged on the listeners registered with this + * and with the DragSource. + * + * @param e - the DragSourceDragEvent + */ public void dropActionChanged(DragSourceDragEvent e) - throws NotImplementedException { + if (dragSourceListener != null) + dragSourceListener.dropActionChanged(e); + + DragSource ds = getDragSource(); + DragSourceListener[] dsl = ds.getDragSourceListeners(); + for (int i = 0; i < dsl.length; i++) + dsl[i].dropActionChanged(e); + + updateCurrentCursor(e.getDropAction(), e.getTargetActions(), CHANGED); } + /** + * Calls dragDropEnd on the listeners registered with this + * and with the DragSource. + * + * @param e - the DragSourceDropEvent + */ public void dragDropEnd(DragSourceDropEvent e) - throws NotImplementedException { + if (dragSourceListener != null) + dragSourceListener.dragDropEnd(e); + + DragSource ds = getDragSource(); + DragSourceListener[] dsl = ds.getDragSourceListeners(); + for (int i = 0; i < dsl.length; i++) + dsl[i].dragDropEnd(e); } + /** + * Calls dragMouseMoved on the listeners registered with the DragSource. + * + * @param e - the DragSourceDragEvent + */ public void dragMouseMoved(DragSourceDragEvent e) - throws NotImplementedException { + DragSource ds = getDragSource(); + DragSourceMotionListener[] dsml = ds.getDragSourceMotionListeners(); + for (int i = 0; i < dsml.length; i++) + dsml[i].dragMouseMoved(e); } + /** + * Returns the Transferable set with this object. + * + * @return the transferable. + */ public Transferable getTransferable() { return transferable; } + /** + * This function sets the drag cursor for the specified operation, actions and + * status if the default drag cursor is active. Otherwise, the cursor is not + * updated in any way. + * + * @param dropOp - the current operation. + * @param targetAct - the supported actions. + * @param status - the status of the cursor (constant). + */ protected void updateCurrentCursor(int dropOp, int targetAct, int status) throws NotImplementedException { + // FIXME: Not implemented fully + if (!useCustomCursor) + { + Cursor cursor = null; + switch (status) + { + case ENTER: + break; + case CHANGED: + break; + case OVER: + break; + default: + break; + } + + this.cursor = cursor; + peer.setCursor(cursor); + } } } // class DragSourceContext diff --git a/java/awt/dnd/DropTarget.java b/java/awt/dnd/DropTarget.java index b0d4c2ae7..2698b1dae 100644 --- a/java/awt/dnd/DropTarget.java +++ b/java/awt/dnd/DropTarget.java @@ -38,13 +38,17 @@ exception statement from your version. */ package java.awt.dnd; +import gnu.classpath.NotImplementedException; + import java.awt.Component; import java.awt.GraphicsEnvironment; import java.awt.HeadlessException; import java.awt.Point; import java.awt.datatransfer.FlavorMap; +import java.awt.dnd.peer.DropTargetPeer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.awt.peer.ComponentPeer; import java.io.Serializable; import java.util.EventListener; import java.util.TooManyListenersException; @@ -79,19 +83,25 @@ public class DropTarget } protected void stop () + throws NotImplementedException { + // FIXME: implement this } public void actionPerformed (ActionEvent e) + throws NotImplementedException { + // FIXME: implement this } } private Component component; private FlavorMap flavorMap; private int actions; + private DropTargetPeer peer; private DropTargetContext dropTargetContext; private DropTargetListener dropTargetListener; + private DropTarget.DropTargetAutoScroller autoscroller; private boolean active = true; /** @@ -211,33 +221,46 @@ public class DropTarget public void addDropTargetListener (DropTargetListener dtl) throws TooManyListenersException { + if (dropTargetListener != null) + throw new TooManyListenersException (); + dropTargetListener = dtl; } public void removeDropTargetListener(DropTargetListener dtl) { - // FIXME: Do we need to do something with dtl ? - dropTargetListener = null; + if (dropTargetListener != null) + dropTargetListener = null; } public void dragEnter(DropTargetDragEvent dtde) { + if (dropTargetListener != null) + dropTargetListener.dragEnter(dtde); } public void dragOver(DropTargetDragEvent dtde) { + if (dropTargetListener != null) + dropTargetListener.dragOver(dtde); } public void dropActionChanged(DropTargetDragEvent dtde) { + if (dropTargetListener != null) + dropTargetListener.dropActionChanged(dtde); } public void dragExit(DropTargetEvent dte) { + if (dropTargetListener != null) + dropTargetListener.dragExit(dte); } public void drop(DropTargetDropEvent dtde) { + if (dropTargetListener != null) + dropTargetListener.drop(dtde); } public FlavorMap getFlavorMap() @@ -250,12 +273,22 @@ public class DropTarget flavorMap = fm; } - public void addNotify(java.awt.peer.ComponentPeer peer) + public void addNotify(ComponentPeer p) { + if (p instanceof DropTargetPeer) + { + peer = (DropTargetPeer) p; + peer.addDropTarget(this); + } + else + peer = null; } - public void removeNotify(java.awt.peer.ComponentPeer peer) + public void removeNotify(ComponentPeer p) { + ((DropTargetPeer) peer).removeDropTarget(this); + peer = null; + p = null; } public DropTargetContext getDropTargetContext() @@ -268,24 +301,34 @@ public class DropTarget protected DropTargetContext createDropTargetContext() { - return new DropTargetContext (this); + if (dropTargetContext == null) + dropTargetContext = new DropTargetContext (this); + + return dropTargetContext; } protected DropTarget.DropTargetAutoScroller createDropTargetAutoScroller (Component c, Point p) { - return new DropTarget.DropTargetAutoScroller (c, p); + if (autoscroller == null) + autoscroller = new DropTarget.DropTargetAutoScroller (c, p); + + return autoscroller; } protected void initializeAutoscrolling(Point p) { + createDropTargetAutoScroller (component, p); } protected void updateAutoscroll(Point dragCursorLocn) { + if (autoscroller != null) + autoscroller.updateLocation(dragCursorLocn); } protected void clearAutoscroll() { + autoscroller = null; } } // class DropTarget diff --git a/java/awt/dnd/DropTargetContext.java b/java/awt/dnd/DropTargetContext.java index aade755da..d970e2e08 100644 --- a/java/awt/dnd/DropTargetContext.java +++ b/java/awt/dnd/DropTargetContext.java @@ -37,12 +37,11 @@ exception statement from your version. */ package java.awt.dnd; -import gnu.classpath.NotImplementedException; - import java.awt.Component; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.dnd.peer.DropTargetContextPeer; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; @@ -87,7 +86,7 @@ public class DropTargetContext implements Serializable private DropTarget dropTarget; private int targetActions; - private java.awt.dnd.peer.DropTargetContextPeer dtcp; + private DropTargetContextPeer dtcp; // package private DropTargetContext(DropTarget dropTarget) @@ -105,7 +104,7 @@ public class DropTargetContext implements Serializable return dropTarget.getComponent(); } - public void addNotify(java.awt.dnd.peer.DropTargetContextPeer dtcp) + public void addNotify(DropTargetContextPeer dtcp) { this.dtcp = dtcp; } @@ -131,39 +130,39 @@ public class DropTargetContext implements Serializable * @exception InvalidDnDOperationException If a drop is not outstanding. */ public void dropComplete (boolean success) - throws NotImplementedException { - // FIXME: implement this + if (dtcp != null) + dtcp.dropComplete(success); } protected void acceptDrag (int dragOperation) - throws NotImplementedException { - // FIXME: implement this + if (dtcp != null) + dtcp.acceptDrag(dragOperation); } protected void rejectDrag () - throws NotImplementedException { - // FIXME: implement this + if (dtcp != null) + dtcp.rejectDrag(); } protected void acceptDrop (int dropOperation) - throws NotImplementedException { - // FIXME: implement this + if (dtcp != null) + dtcp.acceptDrop(dropOperation); } protected void rejectDrop () - throws NotImplementedException { - // FIXME: implement this + if (dtcp != null) + dtcp.rejectDrop(); } protected DataFlavor[] getCurrentDataFlavors () - throws NotImplementedException { - // FIXME: implement this + if (dtcp != null) + dtcp.getTransferDataFlavors(); return null; } @@ -183,9 +182,11 @@ public class DropTargetContext implements Serializable * @exception InvalidDnDOperationException If a drag is not outstanding. */ protected Transferable getTransferable() - throws InvalidDnDOperationException, NotImplementedException + throws InvalidDnDOperationException { - // FIXME: implement this + // FIXME: Implement this + if (dtcp != null) + return dtcp.getTransferable(); return null; } diff --git a/java/awt/dnd/DropTargetDragEvent.java b/java/awt/dnd/DropTargetDragEvent.java index 63d62296e..ea5b682d1 100644 --- a/java/awt/dnd/DropTargetDragEvent.java +++ b/java/awt/dnd/DropTargetDragEvent.java @@ -114,8 +114,7 @@ public class DropTargetDragEvent extends DropTargetEvent public int getDropAction() { - return 0; - //return dropAction & ((DropTargetContext) source).getTargetActions(); + return dropAction & ((DropTargetContext) source).getTargetActions(); } public Point getLocation () diff --git a/java/awt/dnd/DropTargetDropEvent.java b/java/awt/dnd/DropTargetDropEvent.java index abdc55fe5..dd85ef712 100644 --- a/java/awt/dnd/DropTargetDropEvent.java +++ b/java/awt/dnd/DropTargetDropEvent.java @@ -37,8 +37,6 @@ exception statement from your version. */ package java.awt.dnd; -import gnu.classpath.NotImplementedException; - import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; @@ -161,9 +159,8 @@ public class DropTargetDropEvent extends DropTargetEvent } public void dropComplete(boolean success) - throws NotImplementedException { - // FIXME: implement this + context.dropComplete(success); } public boolean isLocalTransfer() diff --git a/java/awt/dnd/InvalidDnDOperationException.java b/java/awt/dnd/InvalidDnDOperationException.java index 2fd9767e0..4a75610bf 100644 --- a/java/awt/dnd/InvalidDnDOperationException.java +++ b/java/awt/dnd/InvalidDnDOperationException.java @@ -59,6 +59,7 @@ public class InvalidDnDOperationException extends IllegalStateException */ public InvalidDnDOperationException() { + super(); } /** diff --git a/java/lang/management/GarbageCollectorMXBean.java b/java/lang/management/GarbageCollectorMXBean.java new file mode 100644 index 000000000..5bb0a18d3 --- /dev/null +++ b/java/lang/management/GarbageCollectorMXBean.java @@ -0,0 +1,79 @@ +/* GarbageCollectorMXBean.java - Interface for a garbage collector bean + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.lang.management; + +/** + * Provides access to information about the garbage collectors + * of the virtual machine. Garbage collectors are responsible + * for removing unreferenced objects from memory. A garbage + * collector is a type of memory manager, so this interface + * is combined with that of generic memory managers. An instance + * of this bean for each garbage collector is obtained by calling + * {@link ManagementFactory#getGarbageCollectorMXBeans()}. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public interface GarbageCollectorMXBean + extends MemoryManagerMXBean +{ + + /** + * Returns the number of collections the garbage collector + * represented by this bean has made. -1 is returned if the + * collection count is undefined. + * + * @return the number of collections made, or -1 if this is + * undefined. + */ + long getCollectionCount(); + + /** + * Returns the accumulated number of milliseconds this garbage + * collector has spent freeing the memory used by unreferenced + * objects. -1 is returned if the collection time is undefined. + * Note that the accumulated time may not change, even when the + * collection count increases, if the time taken is sufficiently + * short; this depends on the resolution of the timer used. + * + * @return the accumulated number of milliseconds spent collecting, + * or -1 if this is undefined. + */ + long getCollectionTime(); + +} diff --git a/java/lang/management/ManagementFactory.java b/java/lang/management/ManagementFactory.java index 6e8010089..2de6d3b05 100644 --- a/java/lang/management/ManagementFactory.java +++ b/java/lang/management/ManagementFactory.java @@ -41,11 +41,17 @@ import gnu.classpath.SystemProperties; import gnu.java.lang.management.ClassLoadingMXBeanImpl; import gnu.java.lang.management.CompilationMXBeanImpl; +import gnu.java.lang.management.GarbageCollectorMXBeanImpl; import gnu.java.lang.management.OperatingSystemMXBeanImpl; import gnu.java.lang.management.MemoryMXBeanImpl; +import gnu.java.lang.management.MemoryManagerMXBeanImpl; +import gnu.java.lang.management.MemoryPoolMXBeanImpl; import gnu.java.lang.management.RuntimeMXBeanImpl; import gnu.java.lang.management.ThreadMXBeanImpl; +import java.util.ArrayList; +import java.util.List; + /** * <p> * Provides access to the system's management beans via a series @@ -189,4 +195,53 @@ public class ManagementFactory return compilationBean; } + /** + * Returns the memory pool beans for the running + * virtual machine. These may change during the course + * of execution. + * + * @return a list of memory pool beans, one for each pool. + */ + public static List getMemoryPoolMXBeans() + { + List poolBeans = new ArrayList(); + String[] names = VMManagementFactory.getMemoryPoolNames(); + for (int a = 0; a < names.length; ++a) + poolBeans.add(new MemoryPoolMXBeanImpl(names[a])); + return poolBeans; + } + + /** + * Returns the memory manager beans for the running + * virtual machine. These may change during the course + * of execution. + * + * @return a list of memory manager beans, one for each manager. + */ + public static List getMemoryManagerMXBeans() + { + List managerBeans = new ArrayList(); + String[] names = VMManagementFactory.getMemoryManagerNames(); + for (int a = 0; a < names.length; ++a) + managerBeans.add(new MemoryManagerMXBeanImpl(names[a])); + managerBeans.add(getGarbageCollectorMXBeans()); + return managerBeans; + } + + /** + * Returns the garbage collector beans for the running + * virtual machine. These may change during the course + * of execution. + * + * @return a list of garbage collector beans, one for each pool. + */ + public static List getGarbageCollectorMXBeans() + { + List gcBeans = new ArrayList(); + String[] names = VMManagementFactory.getGarbageCollectorNames(); + for (int a = 0; a < names.length; ++a) + gcBeans.add(new GarbageCollectorMXBeanImpl(names[a])); + return gcBeans; + } + } diff --git a/java/lang/management/MemoryManagerMXBean.java b/java/lang/management/MemoryManagerMXBean.java new file mode 100644 index 000000000..921070539 --- /dev/null +++ b/java/lang/management/MemoryManagerMXBean.java @@ -0,0 +1,77 @@ +/* MemoryManagerMXBean.java - Interface for a memory manager bean + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.lang.management; + +/** + * Provides access to information about the memory managers + * of the virtual machine. An instance of this bean for each + * memory manager is obtained by calling + * {@link ManagementFactory#getMemoryManagerMXBeans()}. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public interface MemoryManagerMXBean +{ + + /** + * Returns an array containing the names of the memory pools + * this memory manager manages. + * + * @return an array containing the name of each memory pool + * this manager is responsible for. + */ + String[] getMemoryPoolNames(); + + /** + * Returns the name of the memory manager. + * + * @return the memory manager name. + */ + String getName(); + + /** + * Returns true if this memory manager is still valid. A memory + * manager becomes invalid when it is removed by the virtual machine + * and no longer used. + * + * @return true if this memory manager is valid. + */ + boolean isValid(); + +} diff --git a/java/lang/management/MemoryPoolMXBean.java b/java/lang/management/MemoryPoolMXBean.java new file mode 100644 index 000000000..29b438c29 --- /dev/null +++ b/java/lang/management/MemoryPoolMXBean.java @@ -0,0 +1,310 @@ +/* MemoryPoolMXBean.java - Interface for a memory pool bean + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.lang.management; + +/** + * <p> + * Provides access to information about one of the memory + * resources or pools used by the virtual machine. Instances + * of this bean are obtained by calling + * {@link ManagementFactory#getMemoryPoolMXBeans()}. One + * bean is returned for each memory pool provided. + * </p> + * <p> + * The memory pool bean allows the usage of the pool to be + * monitored. The bean can provide statistics on the current + * and peak usage of the pool, and on the threshold levels the + * pool uses. + * </p> + * <p> + * {@link getUsage()} returns an approximation of the current + * usage of the pool. Calls to this method are expected to be + * generally quick to perform; if the call is expensive, the + * documentation of the bean should specify so. For memory + * pool beans that represent the memory used by garbage + * collectors, the usage level includes both referenced and + * unreferenced objects. + * </p> + * <p> + * {@link getPeakUsage()} and {@link resetPeakUsage()} enable + * the retrieval of the peak usage level and setting it to the + * current usage level, respectively. Initially, the peak usage + * level is relative to the start of the virtual machine. + * </p> + * <p> + * Memory pools may also include optional support for usage thresholds. + * The usage threshold is a particular level of memory usage. When this + * value is crossed (the current memory usage becomes equal to or greater + * than this threshold level), the usage threshold count is increased. + * This feature is designed for monitoring the trend in memory usage. + * Support for a collection usage threshold is also provided, for + * particular garbage collectors. This is used to monitor the amount + * of memory left uncollected after a garbage collection cycle. There + * is no need to make special garbage collection runs to support this; + * the level following collection just needs to be monitored. + * </p> + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public interface MemoryPoolMXBean +{ + + /** + * Returns memory usage statistics after a best-effort attempt + * has been made to remove unused objects from the pool. This + * method is designed for use by the pools of garbage collectors, + * in order to monitor the amount of memory used after collections. + * It will return <code>null</code> if such functionality is + * unsupported by the memory pool represented by this bean. + * + * @return the memory usage of the memory pool after the most + * recent garbage collection cycle, or <code>null</code> + * if this operation is not supported. + */ + MemoryUsage getCollectionUsage(); + + /** + * Returns the collection usage threshold level in bytes. This + * value is initially zero. + * + * @return the collection usage threshold in bytes. + * @throws UnsupportedOperationException if the collection usage + * threshold is not supported. + * @see #getCollectionUsageThresholdCount() + * @see #isCollectionUsageThresholdExceeded() + * @see #isCollectionUsageThresholdSupported() + * @see #setCollectionUsageThreshold(long) + */ + long getCollectionUsageThreshold(); + + /** + * Returns the number of times the usage level has matched or + * exceeded the collection usage threshold. + * + * @return the number of times the usage level has matched + * or exceeded the collection usage threshold. + * @throws UnsupportedOperationException if the collection usage + * threshold is not supported. + * @see #getCollectionUsageThreshold() + * @see #isCollectionUsageThresholdExceeded() + * @see #isCollectionUsageThresholdSupported() + * @see #setCollectionUsageThreshold(long) + */ + long getCollectionUsageThresholdCount(); + + /** + * Returns the names of the memory managers associated with this + * pool. Each pool has at least one memory manager. + * + * @return an array containing the name of each memory manager + * responsible for this pool. + */ + String[] getMemoryManagerNames(); + + /** + * Returns the name of the memory pool. + * + * @return the memory pool name. + */ + String getName(); + + /** + * Returns memory usage statistics for the peak memory usage + * of the pool. The peak is the maximum memory usage occurring + * since the virtual machine was started or since the peak + * was reset by {@link #resetPeakUsage()}. The return value + * may be <code>null</code> if this pool is no longer valid. + * + * @return the memory usage of the memory pool at its peak, + * or <code>null</code> if this pool is no longer valid. + */ + MemoryUsage getPeakUsage(); + + /** + * Returns memory usage statistics for the current memory usage + * of the pool. The return value may be <code>null</code> if + * this pool is no longer valid. Obtaining these values is + * expected to be a relatively quick operation; if this will + * instead be an expensive operation to perform, the documentation + * of the implementating bean should specify that this is the + * case. The values are intended to be an estimate for monitoring + * purposes. + * + * @return the memory usage of the memory pool at present, + * or <code>null</code> if this pool is no longer valid. + */ + MemoryUsage getUsage(); + + /** + * Returns the usage threshold level in bytes. This + * value is initially defined by the virtual machine. + * + * @return the usage threshold in bytes. + * @throws UnsupportedOperationException if the usage threshold + * is not supported. + * @see #getUsageThresholdCount() + * @see #isUsageThresholdExceeded() + * @see #isUsageThresholdSupported() + * @see #setUsageThreshold(long) + */ + long getUsageThreshold(); + + /** + * Returns the number of times the usage level has matched or + * exceeded the usage threshold. + * + * @return the number of times the usage level has matched + * or exceeded the usage threshold. + * @throws UnsupportedOperationException if the usage threshold + * is not supported. + * @see #getUsageThreshold() + * @see #isUsageThresholdExceeded() + * @see #isUsageThresholdSupported() + * @see #setUsageThreshold(long) + */ + long getUsageThresholdCount(); + + /** + * Returns true if the collection usage level is equal to + * or greater than the collection usage threshold. + * + * @return true if the collection usage threshold has been + * matched or exceeded. + * @throws UnsupportedOperationException if the collection usage + * threshold is not supported. + * @see #getCollectionUsageThreshold() + * @see #getCollectionUsageThresholdCount() + * @see #isCollectionUsageThresholdSupported() + * @see #setCollectionUsageThreshold(long) + */ + boolean isCollectionUsageThresholdExceeded(); + + /** + * Returns true if this memory pool supports a collection usage + * level threshold. + * + * @return true if a collection usage level threshold is supported. + * @see #getCollectionUsageThreshold() + * @see #getCollectionUsageThresholdCount() + * @see #isCollectionUsageThresholdExceeded() + * @see #setCollectionUsageThreshold(long) + */ + boolean isCollectionUsageThresholdSupported(); + + /** + * Returns true if the usage level is equal to + * or greater than the usage threshold. + * + * @return true if the usage threshold has been + * matched or exceeded. + * @throws UnsupportedOperationException if the usage threshold + * is not supported. + * @see #getUsageThreshold() + * @see #getUsageThresholdCount() + * @see #isUsageThresholdSupported() + * @see #setUsageThreshold(long) + */ + boolean isUsageThresholdExceeded(); + + /** + * Returns true if this memory pool supports a usage level threshold. + * + * @return true if a usage level threshold is supported. + * @see #getUsageThreshold() + * @see #getUsageThresholdCount() + * @see #isUsageThresholdExceeded() + * @see #setUsageThreshold(long) + */ + boolean isUsageThresholdSupported(); + + /** + * Returns true if this memory pool is still valid. A memory pool + * becomes invalid when it is removed by the virtual machine and + * no longer used. + * + * @return true if this memory pool is valid. + */ + boolean isValid(); + + /** + * Resets the peak memory usage level to the current memory usage + * level. + * + * @throws SecurityException if a security manager exists and + * denies ManagementPermission("control"). + */ + void resetPeakUsage(); + + /** + * Sets the collection threshold usage level to the given value. + * A value of zero disables the collection threshold. + * + * @param threshold the new threshold level. + * @throws IllegalArgumentException if the threshold hold level + * is negative. + * @throws UnsupportedOperationException if the collection usage + * threshold is not supported. + * @throws SecurityException if a security manager exists and + * denies ManagementPermission("control"). + * @see #getCollectionUsageThreshold() + * @see #getCollectionUsageThresholdCount() + * @see #isCollectionUsageThresholdExceeded() + * @see #isCollectionUsageThresholdSupported() + */ + void setCollectionUsageThreshold(long threshold); + + /** + * Sets the threshold usage level to the given value. A value of + * zero disables the threshold. + * + * @param threshold the new threshold level. + * @throws IllegalArgumentException if the threshold hold level + * is negative. + * @throws UnsupportedOperationException if the usage threshold + * is not supported. + * @throws SecurityException if a security manager exists and + * denies ManagementPermission("control"). + * @see #getUsageThreshold() + * @see #getUsageThresholdCount() + * @see #isUsageThresholdExceeded() + * @see #isUsageThresholdSupported() + */ + void setUsageThreshold(long threshold); + +} diff --git a/java/lang/management/MemoryUsage.java b/java/lang/management/MemoryUsage.java index 667689507..3c2a4cba6 100644 --- a/java/lang/management/MemoryUsage.java +++ b/java/lang/management/MemoryUsage.java @@ -37,6 +37,9 @@ exception statement from your version. */ package java.lang.management; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeType; +import javax.management.openmbean.SimpleType; /** * <p> * Retains information on the usage of a particular memory @@ -146,6 +149,48 @@ public class MemoryUsage } /** + * <p> + * Returns a {@link MemoryUsage} instance using the values + * given in the supplied + * {@link javax.management.openmbean.CompositeData} object. + * The composite data instance should contain the following + * attributes: + * </p> + * <ul> + * <li>init</li> + * <li>used</li> + * <li>committed</li> + * <li>max</li> + * </ul> + * <p> + * All should have the type, <code>java.lang.Long</code>. + * </p> + * + * @param data the composite data structure to take values from. + * @return a new instance containing the values from the + * composite data structure, or <code>null</code> + * if the data structure was also <code>null</code>. + * @throws IllegalArgumentException if the composite data structure + * does not match the structure + * outlined above, or the values + * are invalid. + */ + public static MemoryUsage from(CompositeData data) + { + if (data == null) + return null; + CompositeType type = data.getCompositeType(); + ThreadInfo.checkAttribute(type, "init", SimpleType.LONG); + ThreadInfo.checkAttribute(type, "used", SimpleType.LONG); + ThreadInfo.checkAttribute(type, "committed", SimpleType.LONG); + ThreadInfo.checkAttribute(type, "max", SimpleType.LONG); + return new MemoryUsage(((Long) data.get("init")).longValue(), + ((Long) data.get("used")).longValue(), + ((Long) data.get("committed")).longValue(), + ((Long) data.get("max")).longValue()); + } + + /** * Returns the amount of memory committed for use by this * memory pool (in bytes). This amount is guaranteed to * be available, unlike the maximum. @@ -213,7 +258,7 @@ public class MemoryUsage "MB), used=" + used + " bytes (~" + (used / megabyte) + "MB), committed=" + committed + " bytes (~" + (committed / megabyte) + "MB), maximum=" + maximum + " bytes (~" + (maximum / megabyte) + - "]"; + "MB)]"; } } diff --git a/java/lang/management/ThreadInfo.java b/java/lang/management/ThreadInfo.java index 28a038099..44aff6f1f 100644 --- a/java/lang/management/ThreadInfo.java +++ b/java/lang/management/ThreadInfo.java @@ -37,6 +37,13 @@ exception statement from your version. */ package java.lang.management; +import javax.management.openmbean.ArrayType; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeType; +import javax.management.openmbean.OpenDataException; +import javax.management.openmbean.OpenType; +import javax.management.openmbean.SimpleType; + /** * <p> * A class which maintains information about a particular @@ -83,9 +90,19 @@ public class ThreadInfo { /** - * The thread which this instance concerns. + * The id of the thread which this instance concerns. + */ + private long threadId; + + /** + * The name of the thread which this instance concerns. + */ + private String threadName; + + /** + * The state of the thread which this instance concerns. */ - private Thread thread; + private Thread.State threadState; /** * The number of times the thread has been blocked. @@ -100,17 +117,24 @@ public class ThreadInfo private long blockedTime; /** - * The monitor lock on which this thread is blocked - * (if any). + * The name of the monitor lock on which this thread + * is blocked (if any). */ - private Object lock; + private String lockName; /** - * The thread which owns the monitor lock on which this - * thread is blocked, or <code>null</code> if there is - * no owner. + * The id of the thread which owns the monitor lock on + * which this thread is blocked, or <code>-1</code> + * if there is no owner. */ - private Thread lockOwner; + private long lockOwnerId; + + /** + * The name of the thread which owns the monitor lock on + * which this thread is blocked, or <code>null</code> + * if there is no owner. + */ + private String lockOwnerName; /** * The number of times the thread has been in a waiting @@ -176,11 +200,60 @@ public class ThreadInfo long waitedTime, boolean isInNative, boolean isSuspended, StackTraceElement[] trace) { - this.thread = thread; + this(thread.getId(), thread.getName(), thread.getState(), blockedCount, + blockedTime, lock.getClass().getName() + "@" + + Integer.toHexString(System.identityHashCode(lock)), lockOwner.getId(), + lockOwner.getName(), waitedCount, waitedTime, isInNative, isSuspended, + trace); + } + + /** + * Constructs a new {@link ThreadInfo} corresponding + * to the thread details specified. + * + * @param threadId the id of the thread on which this + * new instance will be based. + * @param threadName the name of the thread on which + * this new instance will be based. + * @param threadState the state of the thread on which + * this new instance will be based. + * @param blockedCount the number of times the thread + * has been blocked. + * @param blockedTime the accumulated number of milliseconds + * the specified thread has been blocked + * (only used with contention monitoring enabled) + * @param lockName the name of the monitor lock the thread is waiting for + * (only used if blocked) + * @param lockOwnerId the id of the thread which owns the monitor + * lock, or <code>-1</code> if it doesn't have an owner + * (only used if blocked) + * @param lockOwnerName the name of the thread which owns the monitor + * lock, or <code>null</code> if it doesn't have an + * owner (only used if blocked) + * @param waitedCount the number of times the thread has been in a + * waiting state. + * @param waitedTime the accumulated number of milliseconds the + * specified thread has been waiting + * (only used with contention monitoring enabled) + * @param isInNative true if the thread is in a native method. + * @param isSuspended true if the thread is suspended. + * @param trace the stack trace of the thread to a pre-determined + * depth (see VMThreadMXBeanImpl) + */ + private ThreadInfo(long threadId, String threadName, Thread.State threadState, + long blockedCount, long blockedTime, String lockName, + long lockOwnerId, String lockOwnerName, long waitedCount, + long waitedTime, boolean isInNative, boolean isSuspended, + StackTraceElement[] trace) + { + this.threadId = threadId; + this.threadName = threadName; + this.threadState = threadState; this.blockedCount = blockedCount; this.blockedTime = blockedTime; - this.lock = lock; - this.lockOwner = lockOwner; + this.lockName = lockName; + this.lockOwnerId = lockOwnerId; + this.lockOwnerName = lockOwnerName; this.waitedCount = waitedCount; this.waitedTime = waitedTime; this.isInNative = isInNative; @@ -189,6 +262,145 @@ public class ThreadInfo } /** + * Checks for an attribute in a {@link CompositeData} structure + * with the correct type. + * + * @param ctype the composite data type to check. + * @param name the name of the attribute. + * @param type the type to check for. + * @throws IllegalArgumentException if the attribute is absent + * or of the wrong type. + */ + static void checkAttribute(CompositeType ctype, String name, + OpenType type) + throws IllegalArgumentException + { + OpenType foundType = ctype.getType(name); + if (foundType == null) + throw new IllegalArgumentException("Could not find a field named " + + name); + if (!(foundType.equals(type))) + throw new IllegalArgumentException("Field " + name + " is not of " + + "type " + type.getClassName()); + } + + /** + * <p> + * Returns a {@link ThreadInfo} instance using the values + * given in the supplied + * {@link javax.management.openmbean.CompositeData} object. + * The composite data instance should contain the following + * attributes with the specified types: + * </p> + * <table> + * <th><td>Name</td><td>Type</td></th> + * <tr><td>threadId</td><td>java.lang.Long</td></tr> + * <tr><td>threadName</td><td>java.lang.String</td></tr> + * <tr><td>threadState</td><td>java.lang.String</td></tr> + * <tr><td>suspended</td><td>java.lang.Boolean</td></tr> + * <tr><td>inNative</td><td>java.lang.Boolean</td></tr> + * <tr><td>blockedCount</td><td>java.lang.Long</td></tr> + * <tr><td>blockedTime</td><td>java.lang.Long</td></tr> + * <tr><td>waitedCount</td><td>java.lang.Long</td></tr> + * <tr><td>waitedTime</td><td>java.lang.Long</td></tr> + * <tr><td>lockName</td><td>java.lang.String</td></tr> + * <tr><td>lockOwnerId</td><td>java.lang.Long</td></tr> + * <tr><td>lockOwnerName</td><td>java.lang.String</td></tr> + * <tr><td>stackTrace</td><td>javax.management.openmbean.CompositeData[] + * </td></tr> + * </table> + * <p> + * The stack trace is further described as: + * </p> + * <table> + * <th><td>Name</td><td>Type</td></th> + * <tr><td>className</td><td>java.lang.String</td></tr> + * <tr><td>methodName</td><td>java.lang.String</td></tr> + * <tr><td>fileName</td><td>java.lang.String</td></tr> + * <tr><td>lineNumber</td><td>java.lang.Integer</td></tr> + * <tr><td>nativeMethod</td><td>java.lang.Boolean</td></tr> + * </table> + * + * @param data the composite data structure to take values from. + * @return a new instance containing the values from the + * composite data structure, or <code>null</code> + * if the data structure was also <code>null</code>. + * @throws IllegalArgumentException if the composite data structure + * does not match the structure + * outlined above. + */ + public static ThreadInfo from(CompositeData data) + { + if (data == null) + return null; + CompositeType type = data.getCompositeType(); + checkAttribute(type, "threadId", SimpleType.LONG); + checkAttribute(type, "threadName", SimpleType.STRING); + checkAttribute(type, "threadState", SimpleType.STRING); + checkAttribute(type, "suspended", SimpleType.BOOLEAN); + checkAttribute(type, "inNative", SimpleType.BOOLEAN); + checkAttribute(type, "blockedCount", SimpleType.LONG); + checkAttribute(type, "blockedTime", SimpleType.LONG); + checkAttribute(type, "waitedCount", SimpleType.LONG); + checkAttribute(type, "waitedTime", SimpleType.LONG); + checkAttribute(type, "lockName", SimpleType.STRING); + checkAttribute(type, "lockOwnerId", SimpleType.LONG); + checkAttribute(type, "lockOwnerName", SimpleType.STRING); + try + { + CompositeType seType = + new CompositeType(StackTraceElement.class.getName(), + "An element of a stack trace", + new String[] { "className", "methodName", + "fileName", "lineNumber", + "nativeMethod" + }, + new String[] { "Name of the class", + "Name of the method", + "Name of the source code file", + "Line number", + "True if this is a native method" + }, + new OpenType[] { + SimpleType.STRING, SimpleType.STRING, + SimpleType.STRING, SimpleType.INTEGER, + SimpleType.BOOLEAN + }); + checkAttribute(type, "stackTrace", new ArrayType(1, seType)); + } + catch (OpenDataException e) + { + throw new IllegalStateException("Something went wrong in creating " + + "the composite data type for the " + + "stack trace element.", e); + } + CompositeData[] dTraces = (CompositeData[]) data.get("stackTrace"); + StackTraceElement[] traces = new StackTraceElement[dTraces.length]; + for (int a = 0; a < dTraces.length; ++a) + /* FIXME: We can't use the boolean as there is no available + constructor. */ + traces[a] = + new StackTraceElement((String) dTraces[a].get("className"), + (String) dTraces[a].get("methodName"), + (String) dTraces[a].get("fileName"), + ((Integer) + dTraces[a].get("lineNumber")).intValue()); + return new ThreadInfo(((Long) data.get("threadId")).longValue(), + (String) data.get("threadName"), + Thread.State.valueOf((String) data.get("threadState")), + ((Long) data.get("blockedCount")).longValue(), + ((Long) data.get("blockedTime")).longValue(), + (String) data.get("lockName"), + ((Long) data.get("lockOwnerId")).longValue(), + (String) data.get("lockOwnerName"), + ((Long) data.get("waitedCount")).longValue(), + ((Long) data.get("waitedTime")).longValue(), + ((Boolean) data.get("inNative")).booleanValue(), + ((Boolean) data.get("suspended")).booleanValue(), + traces); + } + + /** * Returns the number of times this thread has been * in the {@link java.lang.Thread.State#BLOCKED} state. * A thread enters this state when it is waiting to @@ -272,10 +484,9 @@ public class ThreadInfo */ public String getLockName() { - if (thread.getState() == Thread.State.BLOCKED) + if (threadState != Thread.State.BLOCKED) return null; - return lock.getClass().getName() + "@" + - Integer.toHexString(System.identityHashCode(lock)); + return lockName; } /** @@ -291,11 +502,9 @@ public class ThreadInfo */ public long getLockOwnerId() { - if (thread.getState() == Thread.State.BLOCKED) - return -1; - if (lockOwner == null) + if (threadState != Thread.State.BLOCKED) return -1; - return lockOwner.getId(); + return lockOwnerId; } /** @@ -311,11 +520,9 @@ public class ThreadInfo */ public String getLockOwnerName() { - if (thread.getState() == Thread.State.BLOCKED) - return null; - if (lockOwner == null) + if (threadState != Thread.State.BLOCKED) return null; - return lockOwner.getName(); + return lockOwnerName; } /** @@ -350,7 +557,7 @@ public class ThreadInfo */ public long getThreadId() { - return thread.getId(); + return threadId; } /** @@ -361,7 +568,7 @@ public class ThreadInfo */ public String getThreadName() { - return thread.getName(); + return threadName; } /** @@ -372,7 +579,7 @@ public class ThreadInfo */ public Thread.State getThreadState() { - return thread.getState(); + return threadState; } /** @@ -480,17 +687,17 @@ public class ThreadInfo */ public String toString() { - Thread.State state = thread.getState(); return getClass().getName() + - "[id=" + thread.getId() + - ", name=" + thread.getName() + - ", state=" + state + + "[id=" + threadId + + ", name=" + threadName + + ", state=" + threadState + ", blockedCount=" + blockedCount + ", waitedCount=" + waitedCount + ", isInNative=" + isInNative + ", isSuspended=" + isSuspended + - ((state == Thread.State.BLOCKED) ? ", lock=" + lock + - ", lockOwner=" + lockOwner : "") + + (threadState == Thread.State.BLOCKED ? + ", lockOwnerId=" + lockOwnerId + + ", lockOwnerName=" + lockOwnerName : "") + "]"; } diff --git a/java/util/prefs/Preferences.java b/java/util/prefs/Preferences.java index dfcc27b2b..e53e4fc79 100644 --- a/java/util/prefs/Preferences.java +++ b/java/util/prefs/Preferences.java @@ -37,6 +37,7 @@ exception statement from your version. */ package java.util.prefs; +import gnu.classpath.ServiceFactory; import gnu.java.util.prefs.NodeReader; import java.io.IOException; @@ -45,6 +46,7 @@ import java.io.OutputStream; import java.security.AccessController; import java.security.Permission; import java.security.PrivilegedAction; +import java.util.Iterator; /** * Preference node containing key value entries and subnodes. @@ -205,6 +207,17 @@ public abstract class Preferences { } }); + // Still no factory? Try to see if we have one defined + // as a System Preference + if (factory == null) + { + Iterator iter = ServiceFactory.lookupProviders + (PreferencesFactory.class, null); + + if (iter != null && iter.hasNext()) + factory = (PreferencesFactory) iter.next(); + } + // Still no factory? Use our default. if (factory == null) { diff --git a/javax/crypto/spec/PBEKeySpec.java b/javax/crypto/spec/PBEKeySpec.java index d17dc41ee..54b821a79 100644 --- a/javax/crypto/spec/PBEKeySpec.java +++ b/javax/crypto/spec/PBEKeySpec.java @@ -1,5 +1,5 @@ /* PBEKeySpec.java -- Wrapper for password-based keys. - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -76,47 +76,74 @@ public class PBEKeySpec implements KeySpec /** The salt. */ private byte[] salt; + /** The password state */ + private boolean passwordValid = true; + // Constructors. // ------------------------------------------------------------------------ /** * Create a new PBE key spec with just a password. - * + * <p> + * A copy of the password argument is stored instead of the argument itself. + * * @param password The password char array. */ public PBEKeySpec(char[] password) { - this(password, null, 0, 0); + setPassword(password); + + // load the default values for unspecified variables. + salt = null; + iterationCount = 0; + keyLength = 0; } /** * Create a PBE key spec with a password, salt, and iteration count. - * - * @param password The password char array. - * @param salt The salt bytes. + * <p> + * A copy of the password and salt arguments are stored instead of the + * arguments themselves. + * + * @param password The password char array. + * @param salt The salt bytes. * @param iterationCount The iteration count. + * @throws NullPointerException If salt is null + * @throws IllegalArgumentException If salt is an empty array, or + * iterationCount is negative */ public PBEKeySpec(char[] password, byte[] salt, int iterationCount) { - this(password, salt, iterationCount, 0); + setPassword(password); + setSalt(salt); + setIterationCount(iterationCount); + + // load default values into unspecified variables. + keyLength = 0; } /** - * Create a PBE key spec with a password, salt, iteration count, and - * key length. - * - * @param password The password char array. - * @param salt The salt bytes. + * Create a PBE key spec with a password, salt, iteration count, and key + * length. + * <p> + * A copy of the password and salt arguments are stored instead of the + * arguments themselves. + * + * @param password The password char array. + * @param salt The salt bytes. * @param iterationCount The iteration count. - * @param keyLength The generated key length. + * @param keyLength The generated key length. + * @throws NullPointerException If salt is null + * @throws IllegalArgumentException If salt is an empty array, if + * iterationCount or keyLength is negative */ public PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength) { - this.password = password; - this.salt = salt; - this.iterationCount = iterationCount; - this.keyLength = keyLength; + setPassword(password); + setSalt(salt); + setIterationCount(iterationCount); + setKeyLength(keyLength); } // Instance methods. @@ -124,14 +151,19 @@ public class PBEKeySpec implements KeySpec /** * Clear the password array by filling it with null characters. + * <p> + * This clears the stored copy of the password, not the original char array + * used to create the password. */ public final void clearPassword() { - if (password == null) return; + if (password == null) + return; for (int i = 0; i < password.length; i++) - { - password[i] = '\u0000'; - } + password[i] = '\u0000'; + + // since the password is cleared, it is no longer valid + passwordValid = false; } /** @@ -155,22 +187,95 @@ public class PBEKeySpec implements KeySpec } /** - * Get the password character array. - * - * @return The password. + * Get the password character array copy. + * <p> + * This returns a copy of the password, not the password itself. + * + * @return a clone of the password. + * @throws IllegalStateException If {@link #clearPassword()} has already been + * called. */ public final char[] getPassword() { - return password; + if (! passwordValid) + throw new IllegalStateException("clearPassword() has been called, the " + + "password is no longer valid"); + return (char[]) password.clone(); } /** - * Get the salt bytes. - * + * Get the salt bytes array copy. + * <p> + * This returns a copy of the salt, not the salt itself. + * * @return The salt. */ public final byte[] getSalt() { - return salt; + if (salt != null) + return (byte[]) salt.clone(); + return null; + } + + /** + * Set the password char array. + * <p> + * A copy of the password argument is stored instead of the argument itself. + * + * @param password The password to be set + */ + private void setPassword(char[] password) + { + if (password != null) + this.password = (char[]) password.clone(); + else + this.password = new char[0]; + + passwordValid = true; + } + + /** + * Set the salt byte array. + * <p> + * A copy of the salt arguments is stored instead of the argument itself. + * + * @param salt The salt to be set. + * @throws NullPointerException If the salt is null. + * @throws IllegalArgumentException If the salt is an empty array. + */ + private void setSalt(byte[] salt) + { + if (salt.length == 0) + throw new IllegalArgumentException("salt MUST NOT be an empty byte array"); + + this.salt = (byte[]) salt.clone(); + } + + /** + * Set the iterationCount. + * + * @param iterationCount The iteration count to be set. + * @throws IllegalArgumentException If the iterationCount is negative. + */ + private void setIterationCount(int iterationCount) + { + if (iterationCount < 0) + throw new IllegalArgumentException("iterationCount MUST be positive"); + + this.iterationCount = iterationCount; + } + + /** + * Set the keyLength. + * + * @param keyLength The keyLength to be set. + * @throws IllegalArgumentException if the keyLength is negative. + */ + private void setKeyLength(int keyLength) + { + if (keyLength < 0) + throw new IllegalArgumentException("keyLength MUST be positive"); + + this.keyLength = keyLength; } } diff --git a/javax/management/openmbean/ArrayType.java b/javax/management/openmbean/ArrayType.java new file mode 100644 index 000000000..d2fc398d6 --- /dev/null +++ b/javax/management/openmbean/ArrayType.java @@ -0,0 +1,313 @@ +/* ArrayType.java -- Open type descriptor for an array. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package javax.management.openmbean; + +import java.lang.reflect.Array; + +import java.util.Arrays; + +/** + * The open type descriptor for arrays of open data values. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public class ArrayType + extends OpenType +{ + + /** + * Compatible with JDK 1.5 + */ + private static final long serialVersionUID = 720504429830309770L; + + /** + * The number of dimensions arrays of this type has. + */ + private int dimension; + + /** + * The element type of arrays of this type. + */ + private OpenType elementType; + + /** + * The hash code of this instance. + */ + private transient Integer hashCode; + + /** + * The <code>toString()</code> result of this instance. + */ + private transient String string; + + /** + * Returns the class name of the array, given the element + * class name and its dimensions. + * + * @param className the name of the class used by the + * array's elements. + * @param dim the dimensions of the array. + * @return the array's class name. + */ + private static String getArrayClassName(String className, int dim) + { + char[] brackets = new char[dim]; + Arrays.fill(brackets, '['); + return String.valueOf(brackets) + "L" + className; + } + + /** + * <p> + * Constructs a new {@link ArrayType} instance for an array of the + * specified type with the supplied number of dimensions. The attributes + * used by the superclass, {@link OpenType}, are automatically defined, + * based on these values. Both the class name and type name are set + * to the value returned by the {@link java.lang.Class#getName()} of + * the array's class (i.e. the element type, preceded by n instances of + * '[' and an 'L', where n is the number of dimensions the array has). + * The description is based upon the template <code>n-dimension array + * of e</code>, where n is the number of dimensions of the array, and + * e is the element type. The class name of the actual elements is + * obtainable by calling {@link OpenType#getClassName()} on the result + * of {@link #getElementOpenType()}. + * </p> + * <p> + * As an example, the array type returned by + * <code>new ArrayType(6, SimpleType.INTEGER)</code> has the following + * values: + * </p> + * <table> + * <th><td>Attribute</td><td>Value</td></th> + * <tr><td>Class Name</td><td><code>[[[[[[Ljava.lang.Integer;</code> + * </td></tr> + * <tr><td>Type Name</td><td><code>[[[[[[Ljava.lang.Integer;</code> + * </td></tr> + * <tr><td>Description</td><td><code>6-dimension array of + * java.lang.Integer</code></td></tr> + * <tr><td>Element Type Class Name</td><td><code>java.lang.Integer</code> + * </td></tr> + * </table> + * <p> + * The dimensions of the array must be equal to or greater than 1. The + * element type must be an instance of {@link SimpleType}, + * {@link CompositeType} or {@link TabularType}. + * </p> + * + * @param dim the dimensions of the array. + * @param elementType the type of the elements of the array. + * @throws IllegalArgumentException if <code>dim</code> is less than 1. + * @throws OpenDataException if the element type is not an instance of either + * {@link SimpleType}, {@link CompositeType} + * or {@link TabularType}. + */ + public ArrayType(int dim, OpenType elementType) + throws OpenDataException + { + super(getArrayClassName(elementType.getClassName(), dim), + getArrayClassName(elementType.getClassName(), dim), + dim + "-dimension array of " + elementType.getClassName()); + if (dim < 1) + throw new IllegalArgumentException("Dimensions must be greater " + + "than or equal to 1."); + if (!(elementType instanceof SimpleType || + elementType instanceof CompositeType || + elementType instanceof TabularType)) + throw new OpenDataException("The element type must be a simple " + + "type, a composite type or a tabular " + + "type."); + dimension = dim; + this.elementType = elementType; + } + + /** + * <p> + * Compares this array type with another object + * for equality. The objects are judged to be equal if: + * </p> + * <ul> + * <li><code>obj</code> is not null.</li> + * <li><code>obj</code> is an instance of + * {@link ArrayType}.</li> + * <li>The dimensions are equal.</li> + * <li>The element types are equal.</li> + * </ul> + * + * @param obj the object to compare with. + * @return true if the conditions above hold. + */ + public boolean equals(Object obj) + { + if (!(obj instanceof ArrayType)) + return false; + ArrayType atype = (ArrayType) obj; + return (atype.getDimension() == dimension && + atype.getElementOpenType().equals(elementType)); + } + + /** + * Returns the number of dimensions used by arrays + * of this type. + * + * @return the number of dimensions. + */ + public int getDimension() + { + return dimension; + } + + /** + * Returns the open type descriptor which describes + * the type of the elements of this array type. + * + * @return the type of the elements. + */ + public OpenType getElementOpenType() + { + return elementType; + } + + /** + * <p> + * Returns the hash code of the array type. + * This is computed as the sum of the hash code of the + * element type together with the number of dimensions + * the array has. These are the same elements + * of the type that are compared as part of the + * {@link #equals(java.lang.Object)} method, thus ensuring + * that the hashcode is compatible with the equality + * test. + * </p> + * <p> + * As instances of this class are immutable, the hash code + * is computed just once for each instance and reused + * throughout its life. + * </p> + * + * @return the hash code of this instance. + */ + public int hashCode() + { + if (hashCode == null) + hashCode = Integer.valueOf(dimension + elementType.hashCode()); + return hashCode.intValue(); + } + + /** + * <p> + * Returns true if the specified object is a member of this + * array type. The object is judged to be so if it is + * non-null, an array and one of the following two conditions + * holds: + * </p> + * <ul> + * <li>This {@link ArrayType} instance has a {@link SimpleType} + * as its element type. Thus, the object must have the same + * class name as that returned by {@link SimpleType#getClassName()} + * for this class.</li> + * <li>This {@link ArrayType} instance has a {@link CompositeType} + * or a {@link TabularType} as its element type. Thus, the object + * must be assignable to such an array, and have elements which + * are either null or valid values for the element type.</li> + * </ul> + * + * @param obj the object to test for membership. + * @return true if the object is a member of this type. + */ + public boolean isValue(Object obj) + { + if (obj == null) + return false; + Class objClass = obj.getClass(); + if (!(objClass.isArray())) + return false; + if (elementType instanceof SimpleType) + return getClassName().equals(objClass.getName()); + Class elementClass = null; + try + { + elementClass = Class.forName(getClassName()); + } + catch (ClassNotFoundException e) + { + throw new IllegalStateException("The array type's element " + + "class could not be found.", e); + } + if (!(elementClass.isAssignableFrom(objClass))) + return false; + for (int a = 0; a < Array.getLength(obj); ++a) + { + Object elem = Array.get(obj, a); + if (elem != null && + (!(elementType.isValue(elem)))) + return false; + } + return true; + } + + /** + * <p> + * Returns a textual representation of this instance. This + * is constructed using the class name + * (<code>javax.management.openmbean.ArrayType</code>) + * and each element of the instance which is relevant to + * the definition of {@link equals(java.lang.Object)} and + * {@link hashCode()} (i.e. the type name, the number of + * dimensions and the element type). + * </p> + * <p> + * As instances of this class are immutable, the return value + * is computed just once for each instance and reused + * throughout its life. + * </p> + * + * @return a @link{java.lang.String} instance representing + * the instance in textual form. + */ + public String toString() + { + if (string == null) + string = getClass().getName() + + "[name=" + getTypeName() + + ", dimension=" + dimension + + ", elementType=" + elementType + + "]"; + return string; + } + +} diff --git a/javax/management/openmbean/CompositeData.java b/javax/management/openmbean/CompositeData.java new file mode 100644 index 000000000..14b88ff4e --- /dev/null +++ b/javax/management/openmbean/CompositeData.java @@ -0,0 +1,154 @@ +/* CompositeData.java -- A composite data structure. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package javax.management.openmbean; + +import java.util.Collection; + +/** + * Provides an interface to a composite data structure, + * in order to aid interoperability. The composite data + * structure is represented by mapping field names to + * values. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public interface CompositeData +{ + + /** + * Returns true if this {@link CompositeData} instance contains + * the specified key. This method always returns false for + * an input key equal to <code>null</code> or the empty string. + * + * @param key the key to find in the structure. + * @return true if the key exists. + */ + boolean containsKey(String key); + + /** + * Returns true if this {@link CompositeData} instance has + * a value equal to that supplied. + * + * @param value the value to look for. + * @return true if the value exists. + */ + boolean containsValue(Object value); + + /** + * Compares the specified object with this object for equality. + * The object is judged equivalent if it is non-null, and also + * an instance of {@link CompositeData} with the same values + * and types. The two compared instances may be equivalent even + * if they represent different implementations of + * {@link CompositeData}. + * + * @param obj the object to compare for equality. + * @return true if <code>obj</code> is equal to <code>this</code>. + */ + boolean equals(Object obj); + + /** + * Retrieves the value for the specified key. + * + * @param key the key whose value should be returned. + * @return the matching value. + * @throws IllegalArgumentException if the key is <code>null</code> + * or the empty string. + * @throws InvalidKeyException if the key does not exist. + */ + Object get(String key); + + /** + * Returns the appropriate value for each key in the given array, + * using the same ordering. + * + * @param keys the keys whose values should be returned. + * @return the matching values. + * @throws IllegalArgumentException if one of the keys is + * <code>null</code> or the + * empty string. + * @throws InvalidKeyException if one of the keys does not exist. + */ + Object[] getAll(String[] key); + + /** + * Returns the composite type which corresponds to this instance + * of {@link CompositeData}. + * + * @return the composite type for this instance. + */ + CompositeType getCompositeType(); + + /** + * Returns the hash code of this instance. The hash code is + * computed as the sum of the hash codes of all the values plus + * the hash code of the composite type. As equality comparisons + * take place using this same information, this ensures that + * the property, <code>e1.equals(e2)</code> implies + * <code>e1.hashCode() == e2.hashCode(), holds for any pair + * of instances, <code>e1</code> and <code>e2</code>. + * + * @return the hash code of this {@link CompositeData}. + * @see Object#equals(Object) + */ + int hashCode(); + + /** + * Returns a textual representation of this instance. The + * exact format is left up to the implementation, but it + * should contain the name of the implementing class, + * the name of the type and a mapping of the form + * <code>key=value</code> for each pair of key and value. + * + * @return a {@link java.lang.String} representation of the + * object. + */ + String toString(); + + /** + * Returns a read-only collection of the values associated with + * this instance. The values are sorted using the lexicographic + * ordering of the corresponding keys. + * + * @return the values of this instance. + */ + Collection values(); + +} + diff --git a/javax/management/openmbean/CompositeType.java b/javax/management/openmbean/CompositeType.java new file mode 100644 index 000000000..0ae5a4e4b --- /dev/null +++ b/javax/management/openmbean/CompositeType.java @@ -0,0 +1,324 @@ +/* CompositeType.java -- Type descriptor for CompositeData instances. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package javax.management.openmbean; + +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * The open type descriptor for instances of the + * {@link CompositeData} class. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public class CompositeType + extends OpenType +{ + + /** + * Compatible with JDK 1.5 + */ + private static final long serialVersionUID = -5366242454346948798L; + + /** + * A map of item names to their descriptions. + */ + private TreeMap nameToDescription; + + /** + * A map of item names to their types. + */ + private TreeMap nameToType; + + /** + * The hash code of this instance. + */ + private transient Integer hashCode; + + /** + * The <code>toString()</code> result of this instance. + */ + private transient String string; + + /** + * <p> + * Constructs a new {@link CompositeType} instance for the given + * type name with the specified field names, descriptions and types. + * All parameters, and the elements of the array parameters, must be + * non-null and {@link java.lang.String} values must be something other + * than the empty string. The arrays must be non-empty, and be of + * equal size. + * </p> + * <p> + * The result of <code>CompositeData.class.getName()</code> is adopted + * as the class name (see {@link OpenType}) and changes to the array + * elements following construction of the {@link CompositeType} instance + * will <strong>not</strong> affect the values used by the instance. + * The field names are sorted in to ascending alphanumeric order internally, + * and so ordering can not be used to differentiate between two instances. + * </p> + * + * @param name the name of this composite type. + * @param desc a description of this composite type. + * @param names the names of each field within the composite type. + * @param descs the descriptions of each field within the composite type. + * @param types the types of each field within the composite type. + * @throws IllegalArgumentException if any validity constraint listed above + * is broken. + * @throws OpenDataException if duplicate item names are provided. Item names + * are case-sensitive, but whitespace is removed + * before comparison. + */ + public CompositeType(String name, String desc, String[] names, + String[] descs, OpenType[] types) + throws OpenDataException + { + super(CompositeData.class.getName(), name, desc); + if (names.length == 0 + || names.length != descs.length + || names.length != types.length) + throw new IllegalArgumentException("Arrays must be non-empty " + + "and of equal size."); + nameToDescription = new TreeMap(); + for (int a = 0; a < names.length; ++a) + { + if (names[a] == null) + throw new IllegalArgumentException("Name " + a + " is null."); + if (descs[a] == null) + throw new IllegalArgumentException("Description " + a + + " is null."); + String fieldName = names[a].trim(); + if (fieldName.length() == 0) + throw new IllegalArgumentException("Name " + a + " is " + + "the empty string."); + if (descs[a].length() == 0) + throw new IllegalArgumentException("Description " + a + " is " + + "the empty string."); + if (nameToDescription.containsKey(fieldName)) + throw new OpenDataException(fieldName + " appears more " + + "than once."); + nameToDescription.put(fieldName, descs[a]); + } + nameToType = new TreeMap(); + for (int a = 0; a < names.length; ++a) + nameToType.put(names[a].trim(), types[a]); + } + + /** + * Returns true if this composite data type has a field + * with the given name. + * + * @param name the name of the field to check for. + * @return true if a field of that name exists. + */ + public boolean containsKey(String name) + { + return nameToDescription.containsKey(name); + } + + /** + * <p> + * Compares this composite data type with another object + * for equality. The objects are judged to be equal if: + * </p> + * <ul> + * <li><code>obj</code> is not null.</li> + * <li><code>obj</code> is an instance of + * {@link CompositeType}.</li> + * <li>The type names are equal.</li> + * <li>The fields and their types match.</li> + * </ul> + * + * @param obj the object to compare with. + * @return true if the conditions above hold. + */ + public boolean equals(Object obj) + { + if (!(obj instanceof CompositeType)) + return false; + CompositeType ctype = (CompositeType) obj; + if (!(ctype.getTypeName().equals(getTypeName()))) + return false; + Set keys = keySet(); + if (!(ctype.keySet().equals(keys))) + return false; + Iterator it = keys.iterator(); + while (it.hasNext()) + { + String key = (String) it.next(); + if (!(ctype.getType(key).equals(getType(key)))) + return false; + } + return true; + } + + /** + * Returns the description for the given field name, + * or <code>null</code> if the field name does not + * exist within this composite data type. + * + * @param name the name of the field whose description + * should be returned. + * @return the description, or <code>null</code> if the + * field doesn't exist. + */ + public String getDescription(String name) + { + return (String) nameToDescription.get(name); + } + + /** + * Returns the type for the given field name, + * or <code>null</code> if the field name does not + * exist within this composite data type. + * + * @param name the name of the field whose type + * should be returned. + * @return the type, or <code>null</code> if the + * field doesn't exist. + */ + public OpenType getType(String name) + { + return (OpenType) nameToType.get(name); + } + + /** + * <p> + * Returns the hash code of the composite data type. + * This is computed as the sum of the hash codes of + * each field name and its type, together with the hash + * code of the type name. These are the same elements + * of the type that are compared as part of the + * {@link #equals(java.lang.Object)} method, thus ensuring + * that the hashcode is compatible with the equality + * test. + * </p> + * <p> + * As instances of this class are immutable, the hash code + * is computed just once for each instance and reused + * throughout its life. + * </p> + * + * @return the hash code of this instance. + */ + public int hashCode() + { + if (hashCode == null) + { + int elementTotal = 0; + Iterator it = nameToType.entrySet().iterator(); + while (it.hasNext()) + { + Map.Entry entry = (Map.Entry) it.next(); + elementTotal += (entry.getKey().hashCode() + + entry.getValue().hashCode()); + } + hashCode = Integer.valueOf(elementTotal + + getTypeName().hashCode()); + } + return hashCode.intValue(); + } + + /** + * Returns true if the specified object is a member of this + * composite type. The object is judged to be so if it is + * an instance of {@link CompositeData} with an equivalent + * type, according to the definition of + * {@link #equals(java.lang.Object)} for {@link CompositeType}. + * + * @param obj the object to test for membership. + * @return true if the object is a member of this type. + */ + public boolean isValue(Object obj) + { + if (obj instanceof CompositeData) + { + CompositeData data = (CompositeData) obj; + return equals(data.getCompositeType()); + } + return false; + } + + /** + * Returns an unmodifiable {@link java.util.Set}-based + * view of the field names that form part of this + * {@link CompositeType} instance. The names are stored + * in ascending alphanumeric order. + * + * @return a unmodifiable set containing the field + * name {@link java.lang.String}s. + */ + public Set keySet() + { + return Collections.unmodifiableSet(nameToDescription.keySet()); + } + + /** + * <p> + * Returns a textual representation of this instance. This + * is constructed using the class name + * (<code>javax.management.openmbean.CompositeType</code>) + * and each element of the instance which is relevant to + * the definition of {@link equals(java.lang.Object)} and + * {@link hashCode()} (i.e. the type name, and the name + * and type of each field). + * </p> + * <p> + * As instances of this class are immutable, the return value + * is computed just once for each instance and reused + * throughout its life. + * </p> + * + * @return a @link{java.lang.String} instance representing + * the instance in textual form. + */ + public String toString() + { + if (string == null) + string = getClass().getName() + + "[name=" + getTypeName() + + ", fields=" + nameToType + + "]"; + return string; + } + +} diff --git a/javax/management/openmbean/OpenDataException.java b/javax/management/openmbean/OpenDataException.java new file mode 100644 index 000000000..a476cc1d4 --- /dev/null +++ b/javax/management/openmbean/OpenDataException.java @@ -0,0 +1,79 @@ +/* OpenDataException.java -- Thrown by invalid open bean data. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package javax.management.openmbean; + +import javax.management.JMException; + +/** + * Thrown when an instance of one of the open types, open + * data objects or open metadata information objects could + * not be created due to invalid construction parameters. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public class OpenDataException + extends JMException +{ + + /** + * Compatible with JDK 1.5 + */ + private static final long serialVersionUID = 8346311255433349870L; + + /** + * Constructs a new <code>OpenDataException</code>. + */ + public OpenDataException() + { + super(); + } + + /** + * Constructs a new <code>OpenDataException</code> + * with the specified message. + * + * @param message the error message to give to the user. + */ + public OpenDataException(String message) + { + super(message); + } + +} + diff --git a/javax/management/openmbean/OpenType.java b/javax/management/openmbean/OpenType.java new file mode 100644 index 000000000..b08c40ccc --- /dev/null +++ b/javax/management/openmbean/OpenType.java @@ -0,0 +1,230 @@ +/* OpenType.java -- Superclass of all open types. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package javax.management.openmbean; + +import java.io.Serializable; + +/** + * The superclass of all open types, which describe the + * applicable data values for open MBeans. An open type + * is defined by its name and description, and the name + * of the Java class it maps to. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public abstract class OpenType + implements Serializable +{ + + /** + * Compatible with JDK 1.5 + */ + private static final long serialVersionUID = -9195195325186646468L; + + /** + * The name of the Java class this type represents. + */ + private String className; + + /** + * The name of this type. + */ + private String typeName; + + /** + * A description of this type. + */ + private String description; + + /** + * An array which defines the set of Java types which can be + * used as open types. Note that each type is also available + * in array form, possibly with multiple dimensions. + */ + public static final String[] ALLOWED_CLASSNAMES = { + "java.lang.Void", + "java.lang.Boolean", + "java.lang.Character", + "java.lang.Byte", + "java.lang.Short", + "java.lang.Integer", + "java.lang.Long", + "java.lang.Float", + "java.lang.Double", + "java.lang.String", + "java.math.BigDecimal", + "java.math.BigInteger", + "java.util.Date", + "javax.management.ObjectName", + CompositeData.class.getName(), + TabularData.class.getName() + }; + + /** + * Constructs a new {@link OpenType} for the specified class + * with the given name and description. The name of the class + * must be taken from the list of {@link ALLOWED_CLASSNAMES}. + * Arrays are implictly included in this, and follow the usual + * syntax of {@link java.lang.Class#getName()} with the name + * preceded by n instances of '[' (where n is the number of + * dimensions) and an L. The name and description can not be + * <code>null</code> or the empty string. + * + * @param className the name of the Java class this type + * represents. + * @param name the name of the type. + * @param desc the description of the type. + * @throws IllegalArgumentException if either of <code>name</code> + * or <code>desc</code> are + * <code>null</code> or the empty + * string. + * @throws OpenDataException if the class name does not reference + * a listed class (from @{link ALLOWED_CLASSNAMES}) + */ + protected OpenType(String className, String name, String desc) + throws OpenDataException + { + if (name == null || name.equals("")) + throw new IllegalArgumentException("The name can not be null " + + "or the empty string."); + if (desc == null || desc.equals("")) + throw new IllegalArgumentException("The description can not " + + "be null or the empty string."); + String testString; + if (className.startsWith("[")) + testString = className.substring(className.indexOf("L") + 1); + else + testString = className; + boolean openTypeFound = false; + for (int a = 0; a < ALLOWED_CLASSNAMES.length; ++a) + if (ALLOWED_CLASSNAMES[a].equals(className)) + openTypeFound = true; + if (!openTypeFound) + throw new OpenDataException("The class name does not specify " + + "a valid open type."); + this.className = className; + typeName = name; + description = desc; + } + + /** + * Performs an equality test on this object and the one specified. + * + * @param obj the object to test against this one. + * @return true if the two objects are equivalent. + * @see java.lang.Object#hashCode() + */ + public abstract boolean equals(Object obj); + + /** + * Returns the name of the Java class this type represents. This must + * be one of the {@link ALLOWED_CLASSNAMES} or an array of one of them. + * The specification of arrays follows the standard set by + * {@link java.lang.Class#getName()} i.e. the name is the class name + * preceded by n instances of '[' and an 'L', where n is number of + * dimensions used by the array. + * + * @return the class name. + */ + public String getClassName() + { + return className; + } + + /** + * Returns a description of this open type. + * + * @return the description. + */ + public String getDescription() + { + return description; + } + + /** + * Returns the name of this open type. + * + * @return the type name. + */ + public String getTypeName() + { + return typeName; + } + + /** + * Returns a hash code for this open type. The hash code + * should be consistent with the {@link equals()} method. + * Thus, it should continue to return the same value while + * the values used by the {@link equals()} method remain + * the same, and should return different hash codes for + * objects which are judged to be different using the + * {@link equals()} method. + * + * @return the hash code of this instance. + */ + public abstract int hashCode(); + + /** + * Returns true if this open type represents an array type. + * + * @return true if this open type represents an array type. + */ + public boolean isArray() + { + return className.startsWith("["); + } + + /** + * Returns true if the specified object is a member of this + * type. + * + * @param obj the object to test for membership. + * @return true if the object is a member of this type. + */ + public abstract boolean isValue(Object obj); + + /** + * Returns a textual representation of this type. + * + * @return a {@link java.lang.String} representation of this + * type. + */ + public abstract String toString(); + +} diff --git a/javax/management/openmbean/SimpleType.java b/javax/management/openmbean/SimpleType.java new file mode 100644 index 000000000..3962909d4 --- /dev/null +++ b/javax/management/openmbean/SimpleType.java @@ -0,0 +1,342 @@ +/* SimpleType.java -- Open type descriptor for the base types. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package javax.management.openmbean; + +import java.io.InvalidObjectException; +import java.io.ObjectStreamException; + +/** + * The open type descriptor for data values that are members + * of one of the simple types (such as an integer or a string). + * The other open types ({@link ArrayType}, {@link CompositeType}, + * {@link TabularType}) are constructed from one or more of these + * types. The simple types are formed from a small subset of + * basic Java types. As a result, the valid instances of this + * class are predefined, and no constructor is given for creating + * new instances. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public class SimpleType + extends OpenType +{ + + /** + * The {@link SimpleType} representation of + * <code>java.math.BigDecimal</code>. + */ + public static final SimpleType BIGDECIMAL; + + /** + * The {@link SimpleType} representation of + * <code>java.math.BigInteger</code>. + */ + public static final SimpleType BIGINTEGER; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Boolean</code>. + */ + public static final SimpleType BOOLEAN; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Byte</code>. + */ + public static final SimpleType BYTE; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Character</code>. + */ + public static final SimpleType CHARACTER; + + /** + * The {@link SimpleType} representation of + * <code>java.util.Date</code>. + */ + public static final SimpleType DATE; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Double</code>. + */ + public static final SimpleType DOUBLE; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Float</code>. + */ + public static final SimpleType FLOAT; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Integer</code>. + */ + public static final SimpleType INTEGER; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Long</code>. + */ + public static final SimpleType LONG; + + /** + * The {@link SimpleType} representation of + * <code>javax.management.ObjectName</code>. + */ + public static final SimpleType OBJECTNAME; + + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Short</code>. + */ + public static final SimpleType SHORT; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.String</code>. + */ + public static final SimpleType STRING; + + /** + * The {@link SimpleType} representation of + * <code>java.lang.Void</code>. + */ + public static final SimpleType VOID; + + /** + * Compatible with JDK 1.5 + */ + private static final long serialVersionUID = 2215577471957694503L; + + /** + * The hash code of this instance. + */ + private transient Integer hashCode; + + /** + * The <code>toString()</code> result of this instance. + */ + private transient String string; + + /** + * Static construction of the {@link SimpleType} instances. + */ + static + { + try + { + BIGDECIMAL = new SimpleType("java.math.BigDecimal"); + BIGINTEGER = new SimpleType("java.math.BigInteger"); + BOOLEAN = new SimpleType("java.lang.Boolean"); + BYTE = new SimpleType("java.lang.Byte"); + CHARACTER = new SimpleType("java.lang.Character"); + DATE = new SimpleType("java.util.Date"); + DOUBLE = new SimpleType("java.lang.Double"); + FLOAT = new SimpleType("java.lang.Float"); + INTEGER = new SimpleType("java.lang.Integer"); + LONG = new SimpleType("java.lang.Long"); + OBJECTNAME = new SimpleType("javax.management.ObjectName"); + SHORT = new SimpleType("java.lang.Short"); + STRING = new SimpleType("java.lang.String"); + VOID = new SimpleType("java.lang.Void"); + } + catch (OpenDataException e) + { + /* In normal circumstances, this shouldn't be possible. */ + throw new IllegalStateException("A invalid class name " + + "was passed to the SimpleType " + + "constructor."); + } + } + + /** + * Constructs a new {@link SimpleType} instance for the given + * class name. The class name is also used as the type name + * and description of the {@link OpenType} instance. + * + * @param name the name of the class this instance should + * represent. + * @throws OpenDataException if somehow the constructor of the + * superclass is passed an invalid + * class name. + */ + private SimpleType(String name) + throws OpenDataException + { + super(name, name, name); + } + + /** + * <p> + * Compares this simple data type with another object + * for equality. The objects are judged to be equal if: + * </p> + * <ul> + * <li><code>obj</code> is not null.</li> + * <li><code>obj</code> is an instance of + * {@link SimpleType}.</li> + * <li>The class names are equal.</li> + * </ul> + * + * @param obj the object to compare with. + * @return true if the conditions above hold. + */ + public boolean equals(Object obj) + { + if (!(obj instanceof SimpleType)) + return false; + SimpleType sType = (SimpleType) obj; + return sType.getClassName().equals(getClassName()); + } + + /** + * <p> + * Returns the hash code of the simple data type. + * This is simply the hash code of the class name, + * which is the same element of the type compared + * as part of the + * {@link #equals(java.lang.Object)} method, thus ensuring + * that the hashcode is compatible with the equality + * test. + * </p> + * <p> + * As instances of this class are immutable, the hash code + * is computed just once for each instance and reused + * throughout its life. + * </p> + * + * @return the hash code of this instance. + */ + public int hashCode() + { + if (hashCode == null) + hashCode = Integer.valueOf(getClassName().hashCode()); + return hashCode.intValue(); + } + + /** + * Returns true if the specified object is a member of this + * simple type. The object is judged to be so if it is + * non-null and its class name is the same as that returned + * by {@link SimpleType#getClassName()}. + * + * @param obj the object to test for membership. + * @return true if the object is a member of this type. + */ + public boolean isValue(Object obj) + { + if (obj == null) + return false; + return obj.getClass().getName().equals(getClassName()); + } + + /** + * Replaces instances of this class read from an + * {@link java.io.ObjectInputStream} with one of the predefined + * values. This ensures that each existing instance of + * this class is one of these unique instances. + * + * @return the replacement object. + * @throws ObjectStreamException if the object can not be + * resolved. + */ + public Object readResolve() + throws ObjectStreamException + { + if (equals(BIGDECIMAL)) + return BIGDECIMAL; + if (equals(BIGINTEGER)) + return BIGINTEGER; + if (equals(BOOLEAN)) + return BOOLEAN; + if (equals(BYTE)) + return BYTE; + if (equals(CHARACTER)) + return CHARACTER; + if (equals(DATE)) + return DATE; + if (equals(DOUBLE)) + return DOUBLE; + if (equals(FLOAT)) + return FLOAT; + if (equals(INTEGER)) + return INTEGER; + if (equals(LONG)) + return LONG; + if (equals(OBJECTNAME)) + return OBJECTNAME; + if (equals(SHORT)) + return SHORT; + if (equals(STRING)) + return STRING; + if (equals(VOID)) + return VOID; + throw new InvalidObjectException("Invalid simple type instance " + + "deserialized."); + } + + /** + * <p> + * Returns a textual representation of this instance. This + * is constructed using the class name + * (<code>javax.management.openmbean.SimpleType</code>) + * and the name of the class the type represents. + * </p> + * <p> + * As instances of this class are immutable, the return value + * is computed just once for each instance and reused + * throughout its life. + * </p> + * + * @return a @link{java.lang.String} instance representing + * the instance in textual form. + */ + public String toString() + { + if (string == null) + string = getClass().getName() + + "[name=" + getClassName() + + "]"; + return string; + } + +} diff --git a/javax/management/openmbean/TabularData.java b/javax/management/openmbean/TabularData.java new file mode 100644 index 000000000..17c8de981 --- /dev/null +++ b/javax/management/openmbean/TabularData.java @@ -0,0 +1,258 @@ +/* TabularData.java -- Tables of composite data structures. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package javax.management.openmbean; + +import java.util.Collection; +import java.util.Set; + +/** + * Provides an interface to a specific type of composite + * data structure, where keys (the columns) map to the + * {@link CompositeData} objects that form the rows of + * the table. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public interface TabularData +{ + + /** + * Calculates the index the specified {@link CompositeData} value + * would have, if it was to be added to this {@link TabularData} + * instance. This method includes a check that the type of + * the given value is the same as the row type of this instance, + * but not a check for existing instances of the given value. + * The value must also not be <code>null</code>. Possible indices + * are returned by the {@link TabularType#getIndexNames()} method + * of this instance's tabular type. + * + * @param val the {@link CompositeData} value whose index should + * be calculated. + * @return the index the value would take on, if it were to be added. + * @throws NullPointerException if the value is <code>null</code>. + * @throws InvalidOpenTypeException if the value does not match the + * row type of this instance. + */ + Object[] calculateIndex(CompositeData val); + + /** + * Removes all {@link CompositeData} values from the table. + */ + void clear(); + + /** + * Returns true iff this instance of the {@link TabularData} class + * contains a {@link CompositeData} value at the specified index. + * In any other circumstance, including if the given key + * is <code>null</code> or of the incorrect type, according to + * the {@link TabularType} of this instance, this method returns + * false. + * + * @param key the key to test for. + * @return true if the key maps to a {@link CompositeData} value. + */ + boolean containsKey(Object[] key); + + /** + * Returns true iff this instance of the {@link TabularData} class + * contains the specified {@link CompositeData} value. + * In any other circumstance, including if the given value + * is <code>null</code> or of the incorrect type, according to + * the {@link TabularType} of this instance, this method returns + * false. + * + * @param val the value to test for. + * @return true if the value exists. + */ + boolean containsValue(CompositeData val); + + /** + * Compares the specified object with this object for equality. + * The object is judged equivalent if it is non-null, and also + * an instance of {@link TabularData} with the same row type, + * and index to value mappings. The two compared instances may + * be equivalent even if they represent different implementations + * of {@link TabularData}. + * + * @param obj the object to compare for equality. + * @return true if <code>obj</code> is equal to <code>this</code>. + */ + boolean equals(Object obj); + + /** + * Retrieves the {@link CompositeData} value for the specified + * key, or <code>null</code> if no such mapping exists. + * + * @param key the key whose value should be returned. + * @return the matching {@link CompositeData} value, or + * <code>null</code> if one does not exist. + * @throws NullPointerException if the key is <code>null</code>. + * @throws InvalidOpenTypeException if the key does not match + * the {@link TabularType} of this + * instance. + */ + CompositeData get(Object[] key); + + /** + * Returns the tabular type which corresponds to this instance + * of {@link TabularData}. + * + * @return the tabular type for this instance. + */ + TabularType getTabularType(); + + /** + * Returns the hash code of the composite data type. + * This is computed as the sum of the hash codes of the + * each index and its value, together with the hash + * code of the tabular type. These are the same elements + * of the type that are compared as part of the + * {@link #equals(java.lang.Object)} method, thus ensuring + * that the hashcode is compatible with the equality + * test. + * + * @return the hash code of this instance. + */ + int hashCode(); + + /** + * Returns true if this {@link TabularData} instance + * contains no {@link CompositeData} values. + * + * @return true if the instance is devoid of rows. + */ + boolean isEmpty(); + + /** + * Returns a {@link java.util.Set} view of the keys or + * indices of this {@link TabularData} instance. + * + * @return a set containing the keys of this instance. + */ + Set keySet(); + + /** + * Adds the specified {@link CompositeData} value to the + * table. The value must be non-null, of the same type + * as the row type of this instance, and must not have + * the same index as an existing value. The index is + * calculated using the index names of the + * {@link TabularType} for this instance. + * + * @param val the {@link CompositeData} value to add. + * @throws NullPointerException if <code>val</code> is + * <code>null</code>. + * @throws InvalidOpenTypeException if the type of the + * given value does not + * match the row type. + * @throws KeyAlreadyExistsException if the value has the + * same calculated index + * as an existing value. + */ + void put(CompositeData val); + + /** + * Adds each of the specified {@link CompositeData} values + * to the table. Each element of the array must meet the + * conditions given for the {@link #put(CompositeData)} + * method. In addition, the index of each value in the + * array must be distinct from the index of the other + * values in the array, as well as from the existing values + * in the table. The operation should be atomic; if one + * value can not be added, then none of the values should + * be. + * + * @param vals the {@link CompositeData} values to add. + * @throws NullPointerException if <code>val</code> is + * <code>null</code>. + * @throws InvalidOpenTypeException if the type of the + * given value does not + * match the row type. + * @throws KeyAlreadyExistsException if the value has the + * same calculated index + * as an existing value or + * of one of the other + * specified values. + */ + void putAll(CompositeData[] vals); + + /** + * Removes the {@link CompositeData} value located at the + * specified index. <code>null</code> is returned if the + * value does not exist. Otherwise, the removed value is + * returned. + * + * @param key the key of the value to remove. + * @return the removed value, or <code>null</code> if + * there is no value for the given key. + * @throws NullPointerException if the key is <code>null</code>. + * @throws InvalidOpenTypeException if the key does not match + * the {@link TabularType} of this + * instance. + */ + CompositeData remove(Object[] key); + + /** + * Returns the number of {@link CompositeData} values or rows + * in the table. + * + * @return the number of rows in the table. + */ + int size(); + + /** + * Returns a textual representation of this instance. The + * exact format is left up to the implementation, but it + * should contain the name of the implementing class and + * the tabular type. + * + * @return a {@link java.lang.String} representation of the + * object. + */ + String toString(); + + /** + * Returns the values associated with this instance. + * + * @return the values of this instance. + */ + Collection values(); + +} + diff --git a/javax/management/openmbean/TabularType.java b/javax/management/openmbean/TabularType.java new file mode 100644 index 000000000..c38f5ea62 --- /dev/null +++ b/javax/management/openmbean/TabularType.java @@ -0,0 +1,269 @@ +/* TabularType.java -- Type descriptor for TabularData instances. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package javax.management.openmbean; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +/** + * The open type descriptor for instances of the + * {@link TabularData} class. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +public class TabularType + extends OpenType +{ + + /** + * Compatible with JDK 1.5 + */ + private static final long serialVersionUID = 6554071860220659261L; + + /** + * The composite type used by the rows of the table. + */ + private CompositeType rowType; + + /** + * The list of index names, which form the columns of the table. + * They are retained in the order given by the user, and is + * unmodifiable. + */ + private List indexNames; + + /** + * The hash code of this instance. + */ + private transient Integer hashCode; + + /** + * The <code>toString()</code> result of this instance. + */ + private transient String string; + + /** + * <p> + * Constructs a new {@link TabularType} instance for the given + * type name, description, row type and index names. All parameters + * (including the individual elements of the array of index names) + * must be non-null and those that are of type {@link java.lang.String} + * must be non-empty. The array of index names must also be non-empty. + * </p> + * <p> + * The result of <code>TabularData.class.getName()</code> is adopted + * as the class name (see {@link OpenType}). The ordering of the array + * elements is relevant in determining the indicies of the values in the + * table, and thus in the use of the + * {@link TabularData#get(java.lang.Object[])} and + * {@link TabularData#remove(java.lang.Object[])} methods of the + * {@link TabularData} class. + * </p> + * + * @param name the name of this tabular type. + * @param desc a description of this tabular type. + * @param rowType the type of the rows of the table. + * @param indexNames the names used to index the rows within the table. + * @throws IllegalArgumentException if any validity constraint listed above + * is broken. + * @throws OpenDataException if an index name does not match a corresponding + * name in the given row type. + */ + public TabularType(String name, String desc, CompositeType rowType, + String[] indexNames) + throws OpenDataException + { + super(TabularData.class.getName(), name, desc); + if (rowType == null) + throw new IllegalArgumentException("A null row type was given."); + for (int a = 0; a < indexNames.length; ++a) + { + if (indexNames[a] == null) + throw new IllegalArgumentException("Name " + a + + " is null."); + if (indexNames[a].length() == 0) + throw new IllegalArgumentException("Name " + a + + " is the empty string."); + if (!(rowType.containsKey(indexNames[a]))) + throw new OpenDataException("No matching key for " + + indexNames[a] + " was found in " + + "the supplied row type."); + } + this.rowType = rowType; + this.indexNames = Collections.unmodifiableList(Arrays.asList(indexNames)); + } + + /** + * <p> + * Compares this tabular data type with another object + * for equality. The objects are judged to be equal if: + * </p> + * <ul> + * <li><code>obj</code> is not null.</li> + * <li><code>obj</code> is an instance of + * {@link TabularType}.</li> + * <li>The type names are equal.</li> + * <li>The row types are equal.</li> + * <li>The index names are equal and in the same order.</li> + * </ul> + * + * @param obj the object to compare with. + * @return true if the conditions above hold. + */ + public boolean equals(Object obj) + { + if (!(obj instanceof TabularType)) + return false; + TabularType ttype = (TabularType) obj; + return (ttype.getTypeName().equals(getTypeName()) + && (ttype.getRowType().equals(getRowType())) + && (ttype.getIndexNames().equals(getIndexNames()))); + } + + /** + * Returns an unmodifiable list containing the index names. + * The ordering of these names is used to determine the indicies + * of the {@link CompositeData} values, and is retained from that + * used in the call to this object's constructor. + * + * @return an unmodifiable list of the index names used by this + * tabular data structure. + */ + public List getIndexNames() + { + return indexNames; + } + + /** + * Returns the type of the rows used by this tabular data structure. + * + * @return the row type. + */ + public CompositeType getRowType() + { + return rowType; + } + + /** + * <p> + * Returns the hash code of the tabular data type. + * This is computed as the sum of the hash codes of the + * index names together with the hash code of the type + * name and row type. These are the same elements + * of the type that are compared as part of the + * {@link #equals(java.lang.Object)} method, thus ensuring + * that the hashcode is compatible with the equality + * test. + * </p> + * <p> + * As instances of this class are immutable, the hash code + * is computed just once for each instance and reused + * throughout its life. + * </p> + * + * @return the hash code of this instance. + */ + public int hashCode() + { + if (hashCode == null) + { + int elementTotal = 0; + Iterator it = indexNames.iterator(); + while (it.hasNext()) + elementTotal += it.next().hashCode(); + hashCode = Integer.valueOf(elementTotal + + getTypeName().hashCode() + + rowType.hashCode()); + } + return hashCode.intValue(); + } + + /** + * Returns true if the specified object is a member of this + * tabular type. The object is judged to be so if it is + * an instance of {@link TabularData} with an equivalent + * type, according to the definition of + * {@link #equals(java.lang.Object)} for {@link TabularType}. + * + * @param obj the object to test for membership. + * @return true if the object is a member of this type. + */ + public boolean isValue(Object obj) + { + if (obj instanceof TabularData) + { + TabularData data = (TabularData) obj; + return equals(data.getTabularType()); + } + return false; + } + + /** + * <p> + * Returns a textual representation of this instance. This + * is constructed using the class name + * (<code>javax.management.openmbean.TabularType</code>) + * and each element of the instance which is relevant to + * the definition of {@link equals(java.lang.Object)} and + * {@link hashCode()} (i.e. the type name, the row type + * and the index names). + * </p> + * <p> + * As instances of this class are immutable, the return value + * is computed just once for each instance and reused + * throughout its life. + * </p> + * + * @return a @link{java.lang.String} instance representing + * the instance in textual form. + */ + public String toString() + { + if (string == null) + string = getClass().getName() + + "[name=" + getTypeName() + + ", rowType=" + rowType + + ", indexNames=" + indexNames + + "]"; + return string; + } + +} diff --git a/javax/management/openmbean/package.html b/javax/management/openmbean/package.html new file mode 100644 index 000000000..d915007d4 --- /dev/null +++ b/javax/management/openmbean/package.html @@ -0,0 +1,64 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> +<!-- package.html - describes classes in java.lang.management package. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. --> + +<html> +<head><title>GNU Classpath - javax.management.openmbean</title></head> + +<body> + +<p> +Provides the data types and descriptor classes for the +<emph>Open MBean</emph>s. Open MBeans are provided in +order to aid interoperability with non-Java management +systems. Unlike normal MBeans, which make use of any +Java data type, Open MBeans use a restricted set of types +which can then be mapped over remote connections, including +to non-Java systems. +</p> +<p> +Normal MBeans are described using an instance of +{@link javax.management.MBeanInfo} with appropriate representations +of the attributes, constructors and operators associated with +the bean. Open MBeans are described in the same way, but by +using subtypes of these entities, which type the bean data using +instances of {@link javax.management.openmbean.OpenType}. Open +types differ from Java types, and are explicitly specified in order +to obtain interoperability with other systems. +</p> +</body> +</html> diff --git a/javax/swing/AbstractButton.java b/javax/swing/AbstractButton.java index 82dc61e59..a9ec0c037 100644 --- a/javax/swing/AbstractButton.java +++ b/javax/swing/AbstractButton.java @@ -1297,9 +1297,11 @@ public abstract class AbstractButton extends JComponent * alignment is a numeric constant from {@link SwingConstants}. It must * be one of: <code>RIGHT</code>, <code>LEFT</code>, <code>CENTER</code>, * <code>LEADING</code> or <code>TRAILING</code>. The default is - * <code>RIGHT</code>. + * <code>CENTER</code>. * * @return The current horizontal alignment + * + * @see #setHorizontalAlignment(int) */ public int getHorizontalAlignment() { @@ -1311,17 +1313,21 @@ public abstract class AbstractButton extends JComponent * alignment is a numeric constant from {@link SwingConstants}. It must * be one of: <code>RIGHT</code>, <code>LEFT</code>, <code>CENTER</code>, * <code>LEADING</code> or <code>TRAILING</code>. The default is - * <code>RIGHT</code>. + * <code>CENTER</code>. * * @param a The new horizontal alignment * @throws IllegalArgumentException If alignment is not one of the legal * constants. + * + * @see #getHorizontalAlignment() */ public void setHorizontalAlignment(int a) { if (horizontalAlignment == a) return; - + if (a != LEFT && a != CENTER && a != RIGHT && a != LEADING + && a != TRAILING) + throw new IllegalArgumentException("Invalid alignment."); int old = horizontalAlignment; horizontalAlignment = a; firePropertyChange(HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY, old, a); @@ -1373,6 +1379,8 @@ public abstract class AbstractButton extends JComponent * <code>BOTTOM</code>. The default is <code>CENTER</code>. * * @return The current vertical alignment + * + * @see #setVerticalAlignment(int) */ public int getVerticalAlignment() { @@ -1388,12 +1396,16 @@ public abstract class AbstractButton extends JComponent * @param a The new vertical alignment * @throws IllegalArgumentException If alignment is not one of the legal * constants. + * + * @see #getVerticalAlignment() */ public void setVerticalAlignment(int a) { if (verticalAlignment == a) return; - + if (a != TOP && a != CENTER && a != BOTTOM) + throw new IllegalArgumentException("Invalid alignment."); + int old = verticalAlignment; verticalAlignment = a; firePropertyChange(VERTICAL_ALIGNMENT_CHANGED_PROPERTY, old, a); @@ -2092,7 +2104,8 @@ public abstract class AbstractButton extends JComponent } /** - * Set the button's rollover icon. The look and feel class should + * Set the button's rollover icon and sets the <code>rolloverEnabled</code> + * property to <code>true</code>. The look and feel class should * paint this icon when the "rolloverEnabled" property of the button is * <code>true</code> and the mouse rolls over the button. * @@ -2106,6 +2119,7 @@ public abstract class AbstractButton extends JComponent Icon old = rolloverIcon; rolloverIcon = r; firePropertyChange(ROLLOVER_ICON_CHANGED_PROPERTY, old, rolloverIcon); + setRolloverEnabled(true); revalidate(); repaint(); } @@ -2124,12 +2138,13 @@ public abstract class AbstractButton extends JComponent } /** - * Set the button's rollover selected icon. The look and feel class - * should paint this icon when the "rolloverEnabled" property of the button - * is <code>true</code>, the "selected" property of the button's model is - * <code>true</code>, and the mouse rolls over the button. + * Set the button's rollover selected icon and sets the + * <code>rolloverEnabled</code> property to <code>true</code>. The look and + * feel class should paint this icon when the "rolloverEnabled" property of + * the button is <code>true</code>, the "selected" property of the button's + * model is <code>true</code>, and the mouse rolls over the button. * - * @param r The new rollover selected icon + * @param r The new rollover selected icon. */ public void setRolloverSelectedIcon(Icon r) { @@ -2139,6 +2154,7 @@ public abstract class AbstractButton extends JComponent Icon old = rolloverSelectedIcon; rolloverSelectedIcon = r; firePropertyChange(ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY, old, r); + setRolloverEnabled(true); revalidate(); repaint(); } diff --git a/javax/swing/InputMap.java b/javax/swing/InputMap.java index 28fccd9b9..19a75f4e9 100644 --- a/javax/swing/InputMap.java +++ b/javax/swing/InputMap.java @@ -1,5 +1,5 @@ /* InputMap.java -- - Copyright (C) 2002, 2004 Free Software Foundation, Inc. + Copyright (C) 2002, 2004, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -37,9 +37,6 @@ exception statement from your version. */ package javax.swing; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; @@ -47,14 +44,13 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; - /** * Maps {@link KeyStroke}s to arbitrary objects, usually Strings. This * is used in combination with {@link ActionMap}s. * * If a component receives an input event, this is looked up in * the component's <code>InputMap</code>. The result is an object which - * serves as a key to the components <code>ActionMap</code>. Finally + * serves as a key to the component's <code>ActionMap</code>. Finally * the <code>Action</code> that is stored is executed. * * @author Andrew Selkirk @@ -68,33 +64,37 @@ public class InputMap private static final long serialVersionUID = -5429059542008604257L; /** - * inputMap + * Storage for the KeyStroke --> Object mappings. */ - private Map inputMap = new HashMap(); + private Map inputMap; /** - * parent + * An optional parent map. */ private InputMap parent; /** - * Creates a new <code>InputMap</code> instance. + * Creates a new <code>InputMap</code> instance. This default instance + * contains no mappings and has no parent. */ public InputMap() { - // TODO + // nothing to do } /** - * Returns the binding for keystroke. + * Returns the binding for the specified keystroke, if there is one. * - * @param keystroke the key of the enty + * @param keystroke the key of the entry (<code>null</code> is ignored). * - * @return the binding associated with keystroke may be null + * @return The binding associated with the specified keystroke (or + * <code>null</code>). */ public Object get(KeyStroke keystroke) { - Object result = inputMap.get(keystroke); + Object result = null; + if (inputMap != null) + result = inputMap.get(keystroke); if (result == null && parent != null) result = parent.get(keystroke); @@ -102,14 +102,20 @@ public class InputMap } /** - * Puts a new entry into the <code>InputMap</code>. - * If actionMapKey is null an existing entry will be removed. + * Puts a new entry into the <code>InputMap</code>. If + * <code>actionMapKey</code> is <code>null</code> any existing entry will be + * removed. * - * @param keystroke the keystroke for the entry - * @param actionMapKey the action. + * @param keystroke the keystroke for the entry (<code>null</code> is + * ignored). + * @param actionMapKey the action (<code>null</code> permitted). */ public void put(KeyStroke keystroke, Object actionMapKey) { + if (keystroke == null) + return; + if (inputMap == null) + inputMap = new HashMap(); if (actionMapKey == null) inputMap.remove(keystroke); else @@ -117,19 +123,25 @@ public class InputMap } /** - * Remove an entry from the <code>InputMap</code>. + * Removes an entry from this <code>InputMap</code>. Note that this will + * not remove any entry from the parent map, if there is one. * - * @param keystroke the key of the entry to remove + * @param keystroke the key of the entry to remove (<code>null</code> is + * ignored). */ public void remove(KeyStroke keystroke) { - inputMap.remove(keystroke); + if (inputMap != null) + inputMap.remove(keystroke); } /** - * Returns the parent of this <code>InputMap</code>. + * Returns the parent of this <code>InputMap</code>. The default value + * is <code>null</code>. * - * @return the parent, may be null. + * @return The parent map (possibly <code>null</code>). + * + * @see #setParent(InputMap) */ public InputMap getParent() { @@ -137,9 +149,13 @@ public class InputMap } /** - * Sets a parent for this <code>InputMap</code>. + * Sets a parent for this <code>InputMap</code>. If a parent is specified, + * the {@link #get(KeyStroke)} method will look in the parent if it cannot + * find an entry in this map. * - * @param parentMap the new parent + * @param parentMap the new parent (<code>null</code> permitted). + * + * @see #getParent() */ public void setParent(InputMap parentMap) { @@ -147,31 +163,44 @@ public class InputMap } /** - * Returns the number of entries in this <code>InputMap</code>. + * Returns the number of entries in this <code>InputMap</code>. This count + * does not include any entries from the parent map, if there is one. * - * @return the number of entries + * @return The number of entries. */ public int size() { - return inputMap.size(); + int result = 0; + if (inputMap != null) + result = inputMap.size(); + return result; } /** - * Clears the <code>InputMap</code>. + * Clears the entries from this <code>InputMap</code>. The parent map, if + * there is one, is not cleared. */ public void clear() { - inputMap.clear(); + if (inputMap != null) + inputMap.clear(); } /** - * Returns all keys of entries in this <code>InputMap</code>. + * Returns all keys of entries in this <code>InputMap</code>. This does not + * include keys defined in the parent, if there is one (use the + * {@link #allKeys()} method for that case). + * <br><br> + * Following the behaviour of the reference implementation, this method will + * return <code>null</code> when no entries have been added to the map, + * and a zero length array if entries have been added but subsequently + * removed (or cleared) from the map. * - * @return an array of keys + * @return An array of keys (may be <code>null</code> or have zero length). */ public KeyStroke[] keys() { - if (size() != 0) + if (inputMap != null) { KeyStroke[] array = new KeyStroke[size()]; return (KeyStroke[]) inputMap.keySet().toArray(array); @@ -180,10 +209,10 @@ public class InputMap } /** - * Returns all keys of entries in this <code>InputMap</code> - * and all its parents. + * Returns all keys of entries in this <code>InputMap</code> and all its + * parents. * - * @return an array of keys + * @return An array of keys (may be <code>null</code> or have zero length). */ public KeyStroke[] allKeys() { @@ -195,36 +224,12 @@ public class InputMap if (parentKeys != null) set.addAll(Arrays.asList(parentKeys)); } - set.addAll(inputMap.keySet()); + if (inputMap != null) + set.addAll(inputMap.keySet()); if (set.size() == 0) return null; KeyStroke[] array = new KeyStroke[set.size()]; return (KeyStroke[]) set.toArray(array); } - /** - * writeObject - * - * @param stream the stream to write to - * - * @exception IOException If an error occurs - */ - private void writeObject(ObjectOutputStream stream) throws IOException - { - // TODO - } - - /** - * readObject - * - * @param stream the stream to read from - * - * @exception ClassNotFoundException If the serialized class cannot be found - * @exception IOException If an error occurs - */ - private void readObject(ObjectInputStream stream) - throws ClassNotFoundException, IOException - { - // TODO - } } diff --git a/javax/swing/JComponent.java b/javax/swing/JComponent.java index 151ccd5df..1ab80f691 100644 --- a/javax/swing/JComponent.java +++ b/javax/swing/JComponent.java @@ -1961,13 +1961,13 @@ public abstract class JComponent extends Container implements Serializable Shape originalClip = g.getClip(); Rectangle inner = SwingUtilities.calculateInnerArea(this, rectCache); g.clipRect(inner.x, inner.y, inner.width, inner.height); - Component[] children = getComponents(); // Find the rectangles that need to be painted for each child component. // We push on this list arrays that have the Rectangles to be painted as // the first elements and the component to be painted as the last one. // Later we go through that list in reverse order and paint the rectangles. - ArrayList paintRegions = new ArrayList(children.length); + int numChildren = getComponentCount(); + ArrayList paintRegions = new ArrayList(numChildren); ArrayList paintRectangles = new ArrayList(); ArrayList newPaintRects = new ArrayList(); paintRectangles.add(g.getClipBounds()); @@ -1975,10 +1975,9 @@ public abstract class JComponent extends Container implements Serializable // Go through children from top to bottom and find out their paint // rectangles. - for (int index = 0; paintRectangles.size() > 0 && - index < children.length; index++) + for (int index = 0; paintRectangles.size() > 0 && index < numChildren; index++) { - Component comp = children[index]; + Component comp = getComponent(index); if (! comp.isVisible() || ! comp.isLightweight()) continue; @@ -2137,28 +2136,29 @@ public abstract class JComponent extends Container implements Serializable { Rectangle inner = SwingUtilities.calculateInnerArea(this, rectCache); g.clipRect(inner.x, inner.y, inner.width, inner.height); - Component[] children = getComponents(); // paintingTile becomes true just before we start painting the component's // children. paintingTile = true; - for (int i = children.length - 1; i >= 0; i--) //children.length; i++) + int numChildren = getComponentCount(); + for (int i = numChildren - 1; i >= 0; i--) //children.length; i++) { + Component child = getComponent(i); // paintingTile must be set to false before we begin to start painting // the last tile. - if (i == children.length - 1) + if (i == numChildren - 1) paintingTile = false; - if (!children[i].isVisible() || ! children[i].isLightweight()) + if (!child.isVisible() || ! child.isLightweight()) continue; - Rectangle bounds = children[i].getBounds(rectCache); + Rectangle bounds = child.getBounds(rectCache); if (!g.hitClip(bounds.x, bounds.y, bounds.width, bounds.height)) continue; Graphics g2 = g.create(bounds.x, bounds.y, bounds.width, bounds.height); - children[i].paint(g2); + child.paint(g2); g2.dispose(); } } @@ -3689,12 +3689,13 @@ public abstract class JComponent extends Container implements Serializable } } // Dispatch event to all children. - Component[] children = getComponents(); - for (int i = 0; i < children.length; i++) + int numChildren = getComponentCount(); + for (int i = 0; i < numChildren; i++) { - if (!(children[i] instanceof JComponent)) + Component child = getComponent(i); + if (! (child instanceof JComponent)) continue; - JComponent jc = (JComponent) children[i]; + JComponent jc = (JComponent) child; jc.fireAncestorEvent(ancestor, id); } } @@ -3777,10 +3778,10 @@ public abstract class JComponent extends Container implements Serializable ! SwingUtilities.isRectangleContainingRectangle(parentRect, target); if (! haveOverlap) { - Component[] children = newParent.getComponents(); - for (int i = 0; children[i] != parent && !haveOverlap; i++) + Component child; + for (int i = 0; (child = newParent.getComponent(i)) != parent && !haveOverlap; i++) { - Rectangle childRect = children[i].getBounds(); + Rectangle childRect = child.getBounds(); haveOverlap = target.intersects(childRect); } } diff --git a/javax/swing/JTree.java b/javax/swing/JTree.java index 47dae1075..8120863e8 100644 --- a/javax/swing/JTree.java +++ b/javax/swing/JTree.java @@ -1392,9 +1392,9 @@ public class JTree extends JComponent implements Scrollable, Accessible public static final String EXPANDS_SELECTED_PATHS_PROPERTY = "expandsSelectedPaths"; - private static final Object EXPANDED = new Object(); + private static final Object EXPANDED = Boolean.TRUE; - private static final Object COLLAPSED = new Object(); + private static final Object COLLAPSED = Boolean.FALSE; private boolean dragEnabled; diff --git a/javax/swing/Timer.java b/javax/swing/Timer.java index c6ed8842f..acd1eb493 100644 --- a/javax/swing/Timer.java +++ b/javax/swing/Timer.java @@ -1,5 +1,5 @@ /* Timer.java -- - Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2002, 2004, 2005, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -264,9 +264,13 @@ public class Timer * firing the first event. * * @param d The time gap between the subsequent events, in milliseconds + * + * @throws IllegalArgumentException if <code>d</code> is less than zero. */ public void setDelay(int d) { + if (d < 0) + throw new IllegalArgumentException("Invalid delay: " + d); delay = d; } @@ -287,9 +291,13 @@ public class Timer * subsequent events. * * @param i the initial delay, in milliseconds + * + * @throws IllegalArgumentException if <code>i</code> is less than zero. */ public void setInitialDelay(int i) { + if (i < 0) + throw new IllegalArgumentException("Invalid initial delay: " + i); initialDelay = i; } diff --git a/javax/swing/ToolTipManager.java b/javax/swing/ToolTipManager.java index c7de4db83..963ccf881 100644 --- a/javax/swing/ToolTipManager.java +++ b/javax/swing/ToolTipManager.java @@ -1,5 +1,5 @@ /* ToolTipManager.java -- - Copyright (C) 2002, 2004 Free Software Foundation, Inc. + Copyright (C) 2002, 2004, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -267,10 +267,12 @@ public class ToolTipManager extends MouseAdapter implements MouseMotionListener } /** - * This method sets the initial delay before the ToolTip is shown when the + * Sets the initial delay before the ToolTip is shown when the * mouse enters a Component. * * @param delay The initial delay before the ToolTip is shown. + * + * @throws IllegalArgumentException if <code>delay</code> is less than zero. */ public void setInitialDelay(int delay) { @@ -289,9 +291,11 @@ public class ToolTipManager extends MouseAdapter implements MouseMotionListener } /** - * This method sets the time the ToolTip will be shown before being hidden. + * Sets the time the ToolTip will be shown before being hidden. * - * @param delay The time the ToolTip will be shown before being hidden. + * @param delay the delay (in milliseconds) before tool tips are hidden. + * + * @throws IllegalArgumentException if <code>delay</code> is less than zero. */ public void setDismissDelay(int delay) { @@ -310,10 +314,12 @@ public class ToolTipManager extends MouseAdapter implements MouseMotionListener } /** - * This method sets the amount of delay where if the mouse re-enters a + * Sets the amount of delay where if the mouse re-enters a * Component, the tooltip will be shown immediately. * - * @param delay The reshow delay. + * @param delay The reshow delay (in milliseconds). + * + * @throws IllegalArgumentException if <code>delay</code> is less than zero. */ public void setReshowDelay(int delay) { diff --git a/javax/swing/border/TitledBorder.java b/javax/swing/border/TitledBorder.java index 56146e01d..38ccd720f 100644 --- a/javax/swing/border/TitledBorder.java +++ b/javax/swing/border/TitledBorder.java @@ -1,5 +1,5 @@ /* TitledBorder.java -- - Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2003, 2004, 2005, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -961,7 +961,8 @@ public class TitledBorder extends AbstractBorder public void setTitlePosition(int titlePosition) { if ((titlePosition < DEFAULT_POSITION) || (titlePosition > BELOW_BOTTOM)) - throw new IllegalArgumentException(); + throw new IllegalArgumentException(titlePosition + + " is not a valid title position."); // Swing borders are not JavaBeans, thus no need to fire an event. this.titlePosition = titlePosition; @@ -982,7 +983,8 @@ public class TitledBorder extends AbstractBorder { if ((titleJustification < DEFAULT_JUSTIFICATION) || (titleJustification > TRAILING)) - throw new IllegalArgumentException(); + throw new IllegalArgumentException(titleJustification + + " is not a valid title justification."); // Swing borders are not JavaBeans, thus no need to fire an event. this.titleJustification = titleJustification; diff --git a/javax/swing/plaf/basic/BasicArrowButton.java b/javax/swing/plaf/basic/BasicArrowButton.java index cbdba032e..781269b2a 100644 --- a/javax/swing/plaf/basic/BasicArrowButton.java +++ b/javax/swing/plaf/basic/BasicArrowButton.java @@ -1,5 +1,5 @@ /* BasicArrowButton.java -- - Copyright (C) 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -42,7 +42,6 @@ import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Polygon; -import java.awt.Rectangle; import javax.swing.ButtonModel; import javax.swing.JButton; @@ -86,7 +85,9 @@ public class BasicArrowButton extends JButton implements SwingConstants transient Color highlight = Color.WHITE; /** - * Creates a new <code>BasicArrowButton</code> object. + * Creates a new <code>BasicArrowButton</code> object with an arrow pointing + * in the specified direction. If the <code>direction</code> is not one of + * the specified constants, no arrow is drawn. * * @param direction The direction the arrow points in (one of: * {@link #NORTH}, {@link #SOUTH}, {@link #EAST} and {@link #WEST}). @@ -162,28 +163,22 @@ public class BasicArrowButton extends JButton implements SwingConstants public void paint(Graphics g) { super.paint(g); - Rectangle bounds = getBounds(); - int size = bounds.height / 4; - int x = bounds.x + (bounds.width - size) / 2; - int y = (bounds.height - size) / 4; + + int height = getHeight(); + int size = height / 4; + + int x = (getWidth() - size) / 2; + int y = (height - size) / 2; + ButtonModel m = getModel(); if (m.isArmed()) { x++; y++; } + paintTriangle(g, x, y, size, direction, isEnabled()); } - - /** The preferred size for the button. */ - private static final Dimension PREFERRED_SIZE = new Dimension(16, 16); - - /** The minimum size for the button. */ - private static final Dimension MINIMUM_SIZE = new Dimension(5, 5); - - /** The maximum size for the button. */ - private static final Dimension MAXIMUM_SIZE - = new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); /** * Returns the preferred size of the arrow button. @@ -192,7 +187,10 @@ public class BasicArrowButton extends JButton implements SwingConstants */ public Dimension getPreferredSize() { - return PREFERRED_SIZE; + // since Dimension is NOT immutable, we must return a new instance + // every time (if we return a cached value, the caller might modify it) + // - tests show that the reference implementation does the same. + return new Dimension(16, 16); } /** @@ -202,17 +200,23 @@ public class BasicArrowButton extends JButton implements SwingConstants */ public Dimension getMinimumSize() { - return MINIMUM_SIZE; + // since Dimension is NOT immutable, we must return a new instance + // every time (if we return a cached value, the caller might modify it) + // - tests show that the reference implementation does the same. + return new Dimension(5, 5); } /** * Returns the maximum size of the arrow button. * - * @return The maximum size. + * @return The maximum size (always Integer.MAX_VALUE x Integer.MAX_VALUE). */ public Dimension getMaximumSize() { - return MAXIMUM_SIZE; + // since Dimension is NOT immutable, we must return a new instance + // every time (if we return a cached value, the caller might modify it) + // - tests show that the reference implementation does the same. + return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** diff --git a/javax/swing/plaf/basic/BasicLookAndFeel.java b/javax/swing/plaf/basic/BasicLookAndFeel.java index f2a6dd3cb..1fffcddca 100644 --- a/javax/swing/plaf/basic/BasicLookAndFeel.java +++ b/javax/swing/plaf/basic/BasicLookAndFeel.java @@ -1610,7 +1610,7 @@ public abstract class BasicLookAndFeel extends LookAndFeel }), "Tree.font", new FontUIResource("Dialog", Font.PLAIN, 12), "Tree.foreground", new ColorUIResource(Color.black), - "Tree.hash", new ColorUIResource(new Color(128, 128, 128)), + "Tree.hash", new ColorUIResource(new Color(184, 207, 228)), "Tree.leftChildIndent", new Integer(7), "Tree.rightChildIndent", new Integer(13), "Tree.rowHeight", new Integer(16), diff --git a/javax/swing/plaf/basic/BasicMenuUI.java b/javax/swing/plaf/basic/BasicMenuUI.java index 1473b5912..7d8784fd1 100644 --- a/javax/swing/plaf/basic/BasicMenuUI.java +++ b/javax/swing/plaf/basic/BasicMenuUI.java @@ -220,9 +220,8 @@ public class BasicMenuUI extends BasicMenuItemUI * */ protected void installKeyboardActions() - throws NotImplementedException { - // FIXME: Need to implement + super.installKeyboardActions(); } /** @@ -235,6 +234,7 @@ public class BasicMenuUI extends BasicMenuItemUI } protected void setupPostTimer(JMenu menu) + throws NotImplementedException { // TODO: Implement this properly. } @@ -263,9 +263,8 @@ public class BasicMenuUI extends BasicMenuItemUI * Basic look and feel's defaults. */ protected void uninstallKeyboardActions() - throws NotImplementedException { - // FIXME: Need to implement + super.installKeyboardActions(); } /** @@ -348,7 +347,7 @@ public class BasicMenuUI extends BasicMenuItemUI public void mouseMoved(MouseEvent e) { - // TODO: What should be done here, if anything? + // Nothing to do here. } public void mousePressed(MouseEvent e) @@ -469,7 +468,8 @@ public class BasicMenuUI extends BasicMenuItemUI */ public ChangeHandler(JMenu m, BasicMenuUI ui) { - // Not used. + menu = m; + this.ui = ui; } /** @@ -517,7 +517,7 @@ public class BasicMenuUI extends BasicMenuItemUI */ public void menuDragMouseExited(MenuDragMouseEvent e) { - // TODO: What should be done here, if anything? + // Nothing to do here. } /** @@ -528,7 +528,7 @@ public class BasicMenuUI extends BasicMenuItemUI */ public void menuDragMouseReleased(MenuDragMouseEvent e) { - // TODO: What should be done here, if anything? + // Nothing to do here. } } @@ -545,7 +545,7 @@ public class BasicMenuUI extends BasicMenuItemUI */ public void menuKeyPressed(MenuKeyEvent e) { - // TODO: What should be done here, if anything? + // Nothing to do here. } /** @@ -555,7 +555,7 @@ public class BasicMenuUI extends BasicMenuItemUI */ public void menuKeyReleased(MenuKeyEvent e) { - // TODO: What should be done here, if anything? + // Nothing to do here. } /** @@ -565,6 +565,7 @@ public class BasicMenuUI extends BasicMenuItemUI * @param e A {@link MenuKeyEvent}. */ public void menuKeyTyped(MenuKeyEvent e) + throws NotImplementedException { // TODO: What should be done here, if anything? } diff --git a/javax/swing/plaf/basic/BasicOptionPaneUI.java b/javax/swing/plaf/basic/BasicOptionPaneUI.java index 9acf8210d..27bcb8c46 100644 --- a/javax/swing/plaf/basic/BasicOptionPaneUI.java +++ b/javax/swing/plaf/basic/BasicOptionPaneUI.java @@ -460,8 +460,7 @@ public class BasicOptionPaneUI extends OptionPaneUI protected JOptionPane optionPane; /** The size of the icons. */ - // FIXME: wrong name for a constant. - private static final int iconSize = 36; + private static final int ICON_SIZE = 36; /** The foreground color for the message area. */ private transient Color messageForeground; @@ -505,7 +504,7 @@ public class BasicOptionPaneUI extends OptionPaneUI */ public int getIconWidth() { - return iconSize; + return ICON_SIZE; } /** @@ -515,7 +514,7 @@ public class BasicOptionPaneUI extends OptionPaneUI */ public int getIconHeight() { - return iconSize; + return ICON_SIZE; } /** @@ -566,7 +565,7 @@ public class BasicOptionPaneUI extends OptionPaneUI // Should be purple. g.setColor(Color.RED); - g.fillOval(0, 0, iconSize, iconSize); + g.fillOval(0, 0, ICON_SIZE, ICON_SIZE); g.setColor(Color.BLACK); g.drawOval(16, 6, 4, 4); @@ -615,7 +614,7 @@ public class BasicOptionPaneUI extends OptionPaneUI Color saved = g.getColor(); g.setColor(Color.GREEN); - g.fillRect(0, 0, iconSize, iconSize); + g.fillRect(0, 0, ICON_SIZE, ICON_SIZE); g.setColor(Color.BLACK); @@ -623,7 +622,7 @@ public class BasicOptionPaneUI extends OptionPaneUI g.drawOval(14, 5, 10, 10); g.setColor(Color.GREEN); - g.fillRect(0, 10, iconSize, iconSize - 10); + g.fillRect(0, 10, ICON_SIZE, ICON_SIZE - 10); g.setColor(Color.BLACK); @@ -640,10 +639,6 @@ public class BasicOptionPaneUI extends OptionPaneUI } }; - // FIXME: Uncomment when the ImageIcons are fixed. - - /* IconUIResource warningIcon, questionIcon, infoIcon, errorIcon;*/ - /** * Creates a new BasicOptionPaneUI object. */ @@ -940,6 +935,7 @@ public class BasicOptionPaneUI extends OptionPaneUI * @return A Container that will separate the message and button areas. */ protected Container createSeparator() + throws NotImplementedException { // FIXME: Figure out what this method is supposed to return and where // this should be added to the OptionPane. diff --git a/javax/swing/plaf/basic/BasicTableUI.java b/javax/swing/plaf/basic/BasicTableUI.java index cdd44a711..85c6b574d 100644 --- a/javax/swing/plaf/basic/BasicTableUI.java +++ b/javax/swing/plaf/basic/BasicTableUI.java @@ -164,12 +164,12 @@ public class BasicTableUI extends TableUI public class FocusHandler implements FocusListener { - public void focusGained(FocusEvent e) + public void focusGained(FocusEvent e) throws NotImplementedException { // TODO: Implement this properly. } - public void focusLost(FocusEvent e) + public void focusLost(FocusEvent e) throws NotImplementedException { // TODO: Implement this properly. } @@ -243,16 +243,17 @@ public class BasicTableUI extends TableUI } public void mouseEntered(MouseEvent e) + throws NotImplementedException { // TODO: What should be done here, if anything? } - public void mouseExited(MouseEvent e) + public void mouseExited(MouseEvent e) throws NotImplementedException { // TODO: What should be done here, if anything? } - public void mouseMoved(MouseEvent e) + public void mouseMoved(MouseEvent e) throws NotImplementedException { // TODO: What should be done here, if anything? } @@ -1167,7 +1168,7 @@ public class BasicTableUI extends TableUI table.addPropertyChangeListener(propertyChangeListener); } - protected void uninstallDefaults() + protected void uninstallDefaults() throws NotImplementedException { // TODO: this method used to do the following which is not // quite right (at least it breaks apps that run fine with the @@ -1187,8 +1188,7 @@ public class BasicTableUI extends TableUI // though. / Roman Kennke } - protected void uninstallKeyboardActions() - throws NotImplementedException + protected void uninstallKeyboardActions() throws NotImplementedException { // TODO: Implement this properly. } diff --git a/javax/swing/plaf/basic/BasicToolBarUI.java b/javax/swing/plaf/basic/BasicToolBarUI.java index 8fce2f08a..a4ed0c87d 100644 --- a/javax/swing/plaf/basic/BasicToolBarUI.java +++ b/javax/swing/plaf/basic/BasicToolBarUI.java @@ -998,7 +998,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants */ public void mouseClicked(MouseEvent e) { - // Don't care. + // Nothing to do here. } /** @@ -1020,7 +1020,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants */ public void mouseEntered(MouseEvent e) { - // Don't care (yet). + // Nothing to do here. } /** @@ -1030,7 +1030,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants */ public void mouseExited(MouseEvent e) { - // Don't care (yet). + // Nothing to do here. } /** @@ -1040,7 +1040,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants */ public void mouseMoved(MouseEvent e) { - // TODO: What should be done here, if anything? + // Nothing to do here. } /** @@ -1203,13 +1203,17 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants } /** - * FIXME: Do something. + * Sets the orientation of the toolbar and the + * drag window. * - * @param o DOCUMENT ME! + * @param o - the new orientation of the toolbar and drag + * window. */ public void setOrientation(int o) { - // FIXME: implement. + toolBar.setOrientation(o); + if (dragWindow != null) + dragWindow.setOrientation(o); } } @@ -1330,27 +1334,27 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants /** * Creates a new ToolBarFocusListener object. */ - protected ToolBarFocusListener() + protected ToolBarFocusListener() throws NotImplementedException { // FIXME: implement. } /** * DOCUMENT ME! - * + * * @param e DOCUMENT ME! */ - public void focusGained(FocusEvent e) + public void focusGained(FocusEvent e) throws NotImplementedException { // FIXME: implement. } /** * DOCUMENT ME! - * + * * @param e DOCUMENT ME! */ - public void focusLost(FocusEvent e) + public void focusLost(FocusEvent e) throws NotImplementedException { // FIXME: implement. } diff --git a/javax/swing/plaf/basic/BasicTreeUI.java b/javax/swing/plaf/basic/BasicTreeUI.java index e6ffd83cd..c8407925f 100644 --- a/javax/swing/plaf/basic/BasicTreeUI.java +++ b/javax/swing/plaf/basic/BasicTreeUI.java @@ -174,6 +174,9 @@ public class BasicTreeUI /** * Set to false when editing and shouldSelectCall() returns true meaning the * node should be selected before editing, used in completeEditing. + * GNU Classpath editing is implemented differently, so this value is not + * actually read anywhere. However it is always set correctly to maintain + * interoperability with the derived classes that read this field. */ protected boolean stopEditingInCompleteEditing; @@ -845,9 +848,9 @@ public class BasicTreeUI updateRenderer(); updateDepthOffset(); setSelectionModel(tree.getSelectionModel()); - treeState = createLayoutCache(); - treeSelectionModel.setRowMapper(treeState); configureLayoutCache(); + treeState.setRootVisible(tree.isRootVisible()); + treeSelectionModel.setRowMapper(treeState); updateSize(); } @@ -1237,6 +1240,11 @@ public class BasicTreeUI { LookAndFeel.installColorsAndFont(tree, "Tree.background", "Tree.foreground", "Tree.font"); + + hashColor = UIManager.getColor("Tree.hash"); + if (hashColor == null) + hashColor = Color.black; + tree.setOpaque(true); rightChildIndent = UIManager.getInt("Tree.rightChildIndent"); @@ -1349,6 +1357,13 @@ public class BasicTreeUI am.put(action.getValue(Action.NAME), action); action = new TreePageAction(1, "scrollDownChangeLead"); am.put(action.getValue(Action.NAME), action); + + // Tree editing actions + action = new TreeStartEditingAction("startEditing"); + am.put(action.getValue(Action.NAME), action); + action = new TreeCancelEditingAction("cancel"); + am.put(action.getValue(Action.NAME), action); + return am; } @@ -1703,9 +1718,10 @@ public class BasicTreeUI protected void completeEditing(boolean messageStop, boolean messageCancel, boolean messageTree) { - if (! stopEditingInCompleteEditing || editingComponent == null) + // Make no attempt to complete the non existing editing session. + if (!isEditing(tree)) return; - + if (messageStop) { getCellEditor().stopCellEditing(); @@ -1812,14 +1828,25 @@ public class BasicTreeUI boolean cntlClick = false; if (! treeModel.isLeaf(path.getLastPathComponent())) { - int width = 8; // Only guessing. + int width; Icon expandedIcon = getExpandedIcon(); if (expandedIcon != null) width = expandedIcon.getIconWidth(); + else + // Only guessing. This is the width of + // the tree control icon in Metal L&F. + width = 18; Insets i = tree.getInsets(); - int left = getRowX(tree.getRowForPath(path), path.getPathCount() - 1) - - getRightChildIndent() - width / 2 + i.left; + + int depth; + if (isRootVisible()) + depth = path.getPathCount()-1; + else + depth = path.getPathCount()-2; + + int left = getRowX(tree.getRowForPath(path), depth) + - width + i.left; cntlClick = mouseX >= left && mouseX <= left + width; } return cntlClick; @@ -1848,7 +1875,8 @@ public class BasicTreeUI */ protected void toggleExpandState(TreePath path) { - if (tree.isExpanded(path)) + // tree.isExpanded(path) would do the same, but treeState knows faster. + if (treeState.isExpanded(path)) tree.collapsePath(path); else tree.expandPath(path); @@ -1975,6 +2003,35 @@ public class BasicTreeUI Object node = pathForRow.getLastPathComponent(); return treeModel.isLeaf(node); } + + /** + * The action to start editing at the current lead selection path. + */ + class TreeStartEditingAction + extends AbstractAction + { + /** + * Creates the new tree cancel editing action. + * + * @param name the name of the action (used in toString). + */ + public TreeStartEditingAction(String name) + { + super(name); + } + + /** + * Start editing at the current lead selection path. + * + * @param e the ActionEvent that caused this action. + */ + public void actionPerformed(ActionEvent e) + { + TreePath lead = tree.getLeadSelectionPath(); + if (!tree.isEditing()) + tree.startEditingAtPath(lead); + } + } /** * This class implements the actions that we want to happen when specific keys @@ -2290,9 +2347,49 @@ public class BasicTreeUI * @param e the key typed */ public void keyTyped(KeyEvent e) - throws NotImplementedException { - // TODO: What should be done here, if anything? + char typed = Character.toLowerCase(e.getKeyChar()); + for (int row = tree.getLeadSelectionRow() + 1; + row < tree.getRowCount(); row++) + { + if (checkMatch(row, typed)) + { + tree.setSelectionRow(row); + tree.scrollRowToVisible(row); + return; + } + } + + // Not found below, search above: + for (int row = 0; row < tree.getLeadSelectionRow(); row++) + { + if (checkMatch(row, typed)) + { + tree.setSelectionRow(row); + tree.scrollRowToVisible(row); + return; + } + } + } + + /** + * Check if the given tree row starts with this character + * + * @param row the tree row + * @param typed the typed char, must be converted to lowercase + * @return true if the given tree row starts with this character + */ + boolean checkMatch(int row, char typed) + { + TreePath path = treeState.getPathForRow(row); + String node = path.getLastPathComponent().toString(); + if (node.length() > 0) + { + char x = node.charAt(0); + if (typed == Character.toLowerCase(x)) + return true; + } + return false; } /** @@ -2301,9 +2398,8 @@ public class BasicTreeUI * @param e the key pressed */ public void keyPressed(KeyEvent e) - throws NotImplementedException { - // TODO: What should be done here, if anything? + // Nothing to do here. } /** @@ -2312,9 +2408,8 @@ public class BasicTreeUI * @param e the key released */ public void keyReleased(KeyEvent e) - throws NotImplementedException { - // TODO: What should be done here, if anything? + // Nothing to do here. } } @@ -2341,14 +2436,23 @@ public class BasicTreeUI */ public void mousePressed(MouseEvent e) { + // Any mouse click cancels the previous waiting edit action, initiated + // by the single click on the selected node. + if (startEditTimer != null) + { + startEditTimer.stop(); + startEditTimer = null; + } if (tree != null && tree.isEnabled()) { - // Maybe stop editing and return. - if (isEditing(tree) && tree.getInvokesStopCellEditing() - && !stopEditing(tree)) - return; - + // Always end the current editing session if clicked on the + // tree and outside the bounds of the editing component. + if (isEditing(tree)) + if (!stopEditing(tree)) + // Return if we have failed to cancel the editing session. + return; + int x = e.getX(); int y = e.getY(); TreePath path = getClosestPathForLocation(tree, x, y); @@ -2361,8 +2465,41 @@ public class BasicTreeUI if (x > bounds.x && x <= (bounds.x + bounds.width)) { - if (! startEditing(path, e)) - selectPathForEvent(path, e); + TreePath currentLead = tree.getLeadSelectionPath(); + if (currentLead != null && currentLead.equals(path) + && e.getClickCount() == 1 && tree.isEditable()) + { + // Schedule the editing session. + final TreePath editPath = path; + + // The code below handles the required click-pause-click + // functionality which must be present in the tree UI. + // If the next click comes after the + // time longer than the double click interval AND + // the same node stays focused for the WAIT_TILL_EDITING + // duration, the timer starts the editing session. + if (startEditTimer != null) + startEditTimer.stop(); + + startEditTimer = new Timer(WAIT_TILL_EDITING, + new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + startEditing(editPath, EDIT); + } + }); + + startEditTimer.setRepeats(false); + startEditTimer.start(); + } + else + { + if (e.getClickCount() == 2) + toggleExpandState(path); + else + selectPathForEvent(path, e); + } } } } @@ -2830,6 +2967,9 @@ public class BasicTreeUI } } } + + // Ensure that the lead path is visible after the increment action. + tree.scrollPathToVisible(tree.getLeadSelectionPath()); } /** @@ -2945,6 +3085,9 @@ public class BasicTreeUI tree.setAnchorSelectionPath(newPath); tree.setLeadSelectionPath(newPath); } + + // Ensure that the lead path is visible after the increment action. + tree.scrollPathToVisible(tree.getLeadSelectionPath()); } /** @@ -3249,6 +3392,9 @@ public class BasicTreeUI // and anchor. tree.setLeadSelectionPath(leadPath); tree.setAnchorSelectionPath(anchorPath); + + // Ensure that the lead path is visible after the increment action. + tree.scrollPathToVisible(tree.getLeadSelectionPath()); } } @@ -3336,6 +3482,9 @@ public class BasicTreeUI tree.expandPath(current); } } + + // Ensure that the lead path is visible after the increment action. + tree.scrollPathToVisible(tree.getLeadSelectionPath()); } /** @@ -3644,7 +3793,13 @@ public class BasicTreeUI { Rectangle bounds = getPathBounds(tree, path); TreePath parent = path.getParentPath(); - if (parent != null) + + boolean paintLine; + if (isRootVisible()) + paintLine = parent != null; + else + paintLine = parent != null && parent.getPathCount() > 1; + if (paintLine) { Rectangle parentBounds = getPathBounds(tree, parent); paintVerticalLine(g, tree, parentBounds.x + 2 * gap, diff --git a/javax/swing/plaf/metal/MetalIconFactory.java b/javax/swing/plaf/metal/MetalIconFactory.java index a317e3fc0..30ec7e72b 100644 --- a/javax/swing/plaf/metal/MetalIconFactory.java +++ b/javax/swing/plaf/metal/MetalIconFactory.java @@ -1,5 +1,5 @@ /* MetalIconFactory.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -54,6 +54,7 @@ import javax.swing.JRadioButtonMenuItem; import javax.swing.JSlider; import javax.swing.SwingConstants; import javax.swing.UIManager; +import javax.swing.plaf.IconUIResource; import javax.swing.plaf.UIResource; @@ -78,7 +79,8 @@ public class MetalIconFactory implements Serializable /** * An icon displayed for {@link JCheckBoxMenuItem} components. */ - private static class CheckBoxMenuItemIcon implements Icon, Serializable + private static class CheckBoxMenuItemIcon + implements Icon, UIResource, Serializable { /** * Creates a new icon instance. @@ -153,7 +155,8 @@ public class MetalIconFactory implements Serializable * * @see MetalIconFactory#getFileChooserDetailViewIcon() */ - private static class FileChooserDetailViewIcon implements Icon, Serializable + private static class FileChooserDetailViewIcon + implements Icon, UIResource, Serializable { /** @@ -233,7 +236,8 @@ public class MetalIconFactory implements Serializable * * @see MetalIconFactory#getFileChooserHomeFolderIcon() */ - private static class FileChooserHomeFolderIcon implements Icon, Serializable + private static class FileChooserHomeFolderIcon + implements Icon, UIResource, Serializable { /** @@ -322,7 +326,8 @@ public class MetalIconFactory implements Serializable * * @see MetalIconFactory#getFileChooserListViewIcon() */ - private static class FileChooserListViewIcon implements Icon, Serializable + private static class FileChooserListViewIcon + implements Icon, UIResource, Serializable { /** * Creates a new icon. @@ -418,7 +423,8 @@ public class MetalIconFactory implements Serializable * * @see MetalIconFactory#getFileChooserNewFolderIcon() */ - private static class FileChooserNewFolderIcon implements Icon, Serializable + private static class FileChooserNewFolderIcon + implements Icon, UIResource, Serializable { /** * Creates a new icon. @@ -490,8 +496,7 @@ public class MetalIconFactory implements Serializable * * @see MetalIconFactory#getFileChooserNewFolderIcon() */ - private static class FileChooserUpFolderIcon extends FileChooserNewFolderIcon - implements Icon, Serializable + private static class FileChooserUpFolderIcon extends FileChooserNewFolderIcon { /** * Creates a new icon. @@ -883,7 +888,8 @@ public class MetalIconFactory implements Serializable /** * An icon displayed for {@link JRadioButtonMenuItem} components. */ - private static class RadioButtonMenuItemIcon implements Icon, Serializable + private static class RadioButtonMenuItemIcon + implements Icon, UIResource, Serializable { /** * Creates a new icon instance. @@ -960,7 +966,8 @@ public class MetalIconFactory implements Serializable * The icon used to display the thumb control on a horizontally oriented * {@link JSlider} component. */ - private static class HorizontalSliderThumbIcon implements Icon, Serializable + private static class HorizontalSliderThumbIcon + implements Icon, UIResource, Serializable { /** @@ -1102,7 +1109,8 @@ public class MetalIconFactory implements Serializable * An icon used for the 'close' button in the title frame of a * {@link JInternalFrame}. */ - private static class InternalFrameCloseIcon implements Icon, Serializable + private static class InternalFrameCloseIcon + implements Icon, UIResource, Serializable { /** The icon size in pixels. */ private int size; @@ -1219,7 +1227,7 @@ public class MetalIconFactory implements Serializable * The icon displayed at the top-left corner of a {@link JInternalFrame}. */ private static class InternalFrameDefaultMenuIcon - implements Icon, Serializable + implements Icon, UIResource, Serializable { /** @@ -1291,7 +1299,7 @@ public class MetalIconFactory implements Serializable * provide a 'restore' option. */ private static class InternalFrameAltMaximizeIcon - implements Icon, Serializable + implements Icon, UIResource, Serializable { /** The icon size in pixels. */ private int size; @@ -1401,7 +1409,8 @@ public class MetalIconFactory implements Serializable * An icon used for the 'maximize' button in the title frame of a * {@link JInternalFrame}. */ - private static class InternalFrameMaximizeIcon implements Icon, Serializable + private static class InternalFrameMaximizeIcon + implements Icon, UIResource, Serializable { /** @@ -1513,7 +1522,8 @@ public class MetalIconFactory implements Serializable /** * An icon used in the title frame of a {@link JInternalFrame}. */ - private static class InternalFrameMinimizeIcon implements Icon, Serializable + private static class InternalFrameMinimizeIcon + implements Icon, UIResource, Serializable { /** @@ -1617,7 +1627,8 @@ public class MetalIconFactory implements Serializable * The icon used to display the thumb control on a horizontally oriented * {@link JSlider} component. */ - private static class VerticalSliderThumbIcon implements Icon, Serializable + private static class VerticalSliderThumbIcon + implements Icon, UIResource, Serializable { /** * This mask is used to paint the gradient in the shape of the thumb. @@ -1801,78 +1812,36 @@ public class MetalIconFactory implements Serializable /** * Paints the icon at the location (x, y). * - * @param c the component. - * @param g the graphics device. - * @param x the x coordinate. - * @param y the y coordinate. + * @param c the component. + * @param g the graphics device. + * @param x the x coordinate. + * @param y the y coordinate. */ - public void paintIcon(Component c, Graphics g, int x, int y) + public void paintIcon(Component c, Graphics g, int x, int y) { - x = x + 5; - y = y + 5; - if (collapsed) - { - // TODO: pick up appropriate UI colors - g.setColor(Color.black); - g.drawLine(x + 2, y, x + 5, y); - g.drawLine(x + 6, y + 1, x + 7, y + 2); - g.fillRect(x + 7, y + 3, 5, 2); - g.drawLine(x + 7, y + 5, x + 6, y + 6); - g.drawLine(x + 1, y + 1, x + 1, y + 1); - g.drawLine(x, y + 2, x, y + 5); - g.drawLine(x + 1, y + 6, x + 1, y + 6); - g.drawLine(x + 2, y + 7, x + 5, y + 7); - g.fillRect(x + 3, y + 3, 2, 2); - - g.setColor(new Color(204, 204, 255)); - g.drawLine(x + 3, y + 2, x + 4, y + 2); - g.drawLine(x + 2, y + 3, x + 2, y + 4); - g.drawLine(x + 3, y + 5, x + 3, y + 5); - g.drawLine(x + 5, y + 3, x + 5, y + 3); - - g.setColor(new Color(153, 153, 204)); - g.drawLine(x + 2, y + 2, x + 2, y + 2); - g.drawLine(x + 2, y + 5, x + 2, y + 5); - g.drawLine(x + 2, y + 6, x + 5, y + 6); - g.drawLine(x + 5, y + 2, x + 5, y + 2); - g.drawLine(x + 6, y + 2, x + 6, y + 5); - - g.setColor(new Color(102, 102, 153)); - g.drawLine(x + 2, y + 1, x + 5, y + 1); - g.drawLine(x + 1, y + 2, x + 1, y + 5); - } + // TODO: pick up appropriate UI colors + Color dark = new Color(99, 130, 191); + Color light = new Color(163, 184, 204); + Color white = Color.white; + + x += 8; + y += 6; + + final int w = 6; + final int wHalf = (w >> 2); + g.setColor(light); + g.drawOval(x, y, w, w); + g.setColor(dark); + g.fillOval(x + 1, y + 1, w - 1, w - 1); + + if (collapsed) + g.fillRect(x + w, y + wHalf + 1, w, 2); else - { - // TODO: pick up appropriate UI colors - g.setColor(Color.black); - g.drawLine(x + 2, y, x + 5, y); - g.drawLine(x + 6, y + 1, x + 7, y + 2); - g.drawLine(x + 7, y + 2, x + 7, y + 5); - g.fillRect(x + 3, y + 7, 2, 5); - g.drawLine(x + 7, y + 5, x + 6, y + 6); - g.drawLine(x + 1, y + 1, x + 1, y + 1); - g.drawLine(x, y + 2, x, y + 5); - g.drawLine(x + 1, y + 6, x + 1, y + 6); - g.drawLine(x + 2, y + 7, x + 5, y + 7); - g.fillRect(x + 3, y + 3, 2, 2); - - g.setColor(new Color(204, 204, 255)); - g.drawLine(x + 3, y + 2, x + 4, y + 2); - g.drawLine(x + 2, y + 3, x + 2, y + 4); - g.drawLine(x + 3, y + 5, x + 3, y + 5); - g.drawLine(x + 5, y + 3, x + 5, y + 3); - - g.setColor(new Color(153, 153, 204)); - g.drawLine(x + 2, y + 2, x + 2, y + 2); - g.drawLine(x + 2, y + 5, x + 2, y + 5); - g.drawLine(x + 2, y + 6, x + 5, y + 6); - g.drawLine(x + 5, y + 2, x + 5, y + 2); - g.drawLine(x + 6, y + 2, x + 6, y + 5); - - g.setColor(new Color(102, 102, 153)); - g.drawLine(x + 2, y + 1, x + 5, y + 1); - g.drawLine(x + 1, y + 2, x + 1, y + 5); - } + g.fillRect(x + wHalf + 1, y + w, 2, w); + + g.setColor(white); + g.fillRect(x + wHalf + 1, y + wHalf + 1, 2, 2); + } /** @@ -1964,7 +1933,8 @@ public class MetalIconFactory implements Serializable * * @see MetalIconFactory#getTreeHardDriveIcon() */ - private static class TreeHardDriveIcon implements Icon, Serializable + private static class TreeHardDriveIcon + implements Icon, UIResource, Serializable { /** @@ -2074,7 +2044,8 @@ public class MetalIconFactory implements Serializable * * @see MetalIconFactory#getTreeFloppyDriveIcon() */ - private static class TreeFloppyDriveIcon implements Icon, Serializable + private static class TreeFloppyDriveIcon + implements Icon, UIResource, Serializable { /** @@ -2150,7 +2121,8 @@ public class MetalIconFactory implements Serializable * * @see MetalIconFactory#getTreeComputerIcon() */ - private static class TreeComputerIcon implements Icon, Serializable + private static class TreeComputerIcon + implements Icon, UIResource, Serializable { /** @@ -2255,6 +2227,12 @@ public class MetalIconFactory implements Serializable /** The icon instance returned by {@link #getTreeHardDriveIcon()}. */ private static Icon treeHardDriveIcon; + /** The icon instance returned by {@link #getHorizontalSliderThumbIcon()}. */ + private static Icon horizontalSliderThumbIcon; + + /** The icon instance returned by {@link #getVerticalSliderThumbIcon()}. */ + private static Icon verticalSliderThumbIcon; + /** * Creates a new instance. All the methods are static, so creating an * instance isn't necessary. @@ -2383,7 +2361,9 @@ public class MetalIconFactory implements Serializable */ public static Icon getHorizontalSliderThumbIcon() { - return new HorizontalSliderThumbIcon(); + if (horizontalSliderThumbIcon == null) + horizontalSliderThumbIcon = new HorizontalSliderThumbIcon(); + return horizontalSliderThumbIcon; } /** @@ -2462,7 +2442,9 @@ public class MetalIconFactory implements Serializable */ public static Icon getVerticalSliderThumbIcon() { - return new VerticalSliderThumbIcon(); + if (verticalSliderThumbIcon == null) + verticalSliderThumbIcon = new VerticalSliderThumbIcon(); + return verticalSliderThumbIcon; } /** diff --git a/javax/swing/plaf/metal/MetalLookAndFeel.java b/javax/swing/plaf/metal/MetalLookAndFeel.java index 73b0a64bd..b496a2b0e 100644 --- a/javax/swing/plaf/metal/MetalLookAndFeel.java +++ b/javax/swing/plaf/metal/MetalLookAndFeel.java @@ -85,7 +85,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel } /** - * Sets the current theme to a new instance of {@link DefaultMetalTheme}. + * Sets the current theme to a new instance of {@link OceanTheme}. */ protected void createDefaultTheme() { @@ -709,6 +709,8 @@ public class MetalLookAndFeel extends BasicLookAndFeel * @param theme the theme (<code>null</code> not permitted). * * @throws NullPointerException if <code>theme</code> is <code>null</code>. + * + * @see #getCurrentTheme() */ public static void setCurrentTheme(MetalTheme theme) { @@ -1243,6 +1245,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel "TextPane.selectionBackground", getTextHighlightColor(), "TextPane.selectionForeground", getHighlightedTextColor(), + "TitledBorder.border", new LineBorderUIResource(getPrimaryControl(), 1), "TitledBorder.font", new FontUIResource("Dialog", Font.BOLD, 12), "TitledBorder.titleColor", getSystemTextColor(), @@ -1335,12 +1338,17 @@ public class MetalLookAndFeel extends BasicLookAndFeel } /** - * Returns the current theme setting for the Metal L&F. + * Returns the current theme for the Metal look and feel. The default is + * an instance of {@link OceanTheme}. * - * @return the current theme setting for the Metal L&F + * @return The current theme (never <code>null</code>). + * + * @see #setCurrentTheme(MetalTheme) */ public static MetalTheme getCurrentTheme() { + if (theme == null) + theme = new OceanTheme(); return theme; } diff --git a/javax/swing/text/FlowView.java b/javax/swing/text/FlowView.java index 8ca55d834..89fcc6fcd 100644 --- a/javax/swing/text/FlowView.java +++ b/javax/swing/text/FlowView.java @@ -159,20 +159,18 @@ public abstract class FlowView extends BoxView } /** - * Lays out one row of the flow view. This is called by {@link #layout} - * to fill one row with child views until the available span is exhausted. - * - * The default implementation fills the row by calling - * {@link #createView(FlowView, int, int, int)} until the available space - * is exhausted, a forced break is encountered or there are no more views - * in the logical view. If the available space is exhausted, - * {@link #adjustRow(FlowView, int, int, int)} is called to fit the row - * into the available span. - * + * Lays out one row of the flow view. This is called by {@link #layout} to + * fill one row with child views until the available span is exhausted. The + * default implementation fills the row by calling + * {@link #createView(FlowView, int, int, int)} until the available space is + * exhausted, a forced break is encountered or there are no more views in + * the logical view. If the available space is exhausted, + * {@link #adjustRow(FlowView, int, int, int)} is called to fit the row into + * the available span. + * * @param fv the flow view for which we perform the layout * @param rowIndex the index of the row * @param pos the model position for the beginning of the row - * * @return the start position of the next row */ protected int layoutRow(FlowView fv, int rowIndex, int pos) @@ -188,34 +186,39 @@ public abstract class FlowView extends BoxView if (span == 0) span = Integer.MAX_VALUE; - while (span > 0) + Row: while (span > 0) { - if (logicalView.getViewIndex(offset, Position.Bias.Forward) == -1) + if (logicalView.getViewIndex(offset, Position.Bias.Forward) == - 1) break; View view = createView(fv, offset, span, rowIndex); if (view == null) break; + int viewSpan = (int) view.getPreferredSpan(axis); - row.append(view); int breakWeight = view.getBreakWeight(axis, x, span); - if (breakWeight >= View.ForcedBreakWeight) - break; + + row.append(view); + offset += (view.getEndOffset() - view.getStartOffset()); x += viewSpan; span -= viewSpan; - offset += (view.getEndOffset() - view.getStartOffset()); - } - if (span < 0) - { - int flowStart = fv.getFlowStart(axis); - int flowSpan = fv.getFlowSpan(axis); - adjustRow(fv, rowIndex, flowSpan, flowStart); - int rowViewCount = row.getViewCount(); - if (rowViewCount > 0) - offset = row.getView(rowViewCount - 1).getEndOffset(); - else - offset = -1; + + // Break if the line if the view does not fit in this row or the + // line just must be broken. + if (span < 0 || breakWeight >= View.ForcedBreakWeight) + { + int flowStart = fv.getFlowStart(axis); + int flowSpan = fv.getFlowSpan(axis); + adjustRow(fv, rowIndex, flowSpan, flowStart); + int rowViewCount = row.getViewCount(); + if (rowViewCount > 0) + offset = row.getView(rowViewCount - 1).getEndOffset(); + else + offset = - 1; + break Row; + } } - return offset != pos ? offset : -1; + + return offset != pos ? offset : - 1; } /** diff --git a/javax/swing/text/html/BRView.java b/javax/swing/text/html/BRView.java new file mode 100644 index 000000000..5521fed8e --- /dev/null +++ b/javax/swing/text/html/BRView.java @@ -0,0 +1,71 @@ +/* BRView.java -- HTML BR tag view + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.swing.text.html; + +import javax.swing.text.Element; + +/** + * Handled the HTML BR tag. + */ +class BRView + extends NullView + +{ + /** + * Creates the new BR view. + * + * @param elem the HTML element, representing the view. + */ + public BRView(Element elem) + { + super(elem); + } + + /** + * Always return ForcedBreakWeight for the X_AXIS, BadBreakWeight for the + * Y_AXIS. + */ + public int getBreakWeight(int axis, float pos, float len) + { + if (axis == X_AXIS) + return ForcedBreakWeight; + else + return BadBreakWeight; + } +} diff --git a/javax/swing/text/html/HRuleView.java b/javax/swing/text/html/HRuleView.java new file mode 100644 index 000000000..3bae5eb8e --- /dev/null +++ b/javax/swing/text/html/HRuleView.java @@ -0,0 +1,189 @@ +/* HRuleView.java -- Horizontal dash in HTML documents. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.swing.text.html; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.Shape; + +import javax.swing.text.Element; +import javax.swing.text.View; + +/** + * Represents the long horizontal separating dash that can be inserted into the + * HTML documents with HR tag. + */ +class HRuleView extends InlineView +{ + /** + * The null view, indicating, that nothing should be painted ahead the + * breaking point. + */ + View nullView; + + /** + * The height of the horizontal dash area. + */ + static int HEIGHT = 4; + + /** + * The imaginary invisible view that stays after end of line after the + * breaking procedure. It occupies on character. + */ + class Beginning extends NullView + { + /** + * The break offset that becomes the views start offset. + */ + int breakOffset; + + /** + * Return the end offset that is always one char after the break offset. + */ + public int getEndOffset() + { + return breakOffset + 1; + } + + /** + * Return the start offset that has been passed in a constructor. + */ + public int getStartOffset() + { + return breakOffset; + } + + /** + * Create the new instance of this view. + * + * @param element the element (inherited from the HR view) + * @param offset the position where the HR view has been broken + */ + public Beginning(Element element, int offset) + { + super(element); + breakOffset = offset; + } + } + + /** + * Creates the new HR view. + */ + public HRuleView(Element element) + { + super(element); + } + + /** + * Returns the ForcedBreakWeight for the vertical axis, indicating, the the + * view must be broken to be displayed correctly. The horizontal dash is + * not breakeable along the Y axis. + */ + public int getBreakWeight(int axis, float pos, float len) + { + if (axis == X_AXIS && ((getEndOffset() - getStartOffset()) > 1)) + return ForcedBreakWeight; + else + return BadBreakWeight; + } + + /** + * Draws the double line, upped black and the lower light gray. + */ + public void paint(Graphics g, Shape a) + { + Rectangle bounds = a.getBounds(); + + int x = bounds.x; + int y = bounds.y; + + int w = bounds.x + bounds.width; + + // We move "half pixel up" from the actual horizontal position - + // this will be rounded to the closest actual int co-ordinate. + int h = bounds.y + (int) Math.round(bounds.height * 0.5 - 0.5); + + g.setColor(Color.black); + g.drawLine(x, y++, w, h++); + g.setColor(Color.lightGray); + g.drawLine(x, y, w, h); + } + + /** + * Break the view into this view and the invisible imaginary view that + * stays on the end of line that is broken by HR dash. The view is broken + * only if its length is longer than one (the two characters are expected + * in the initial length). + */ + public View breakView(int axis, int offset, float pos, float len) + { + if (getEndOffset() - getStartOffset() > 1) + return new Beginning(getElement(), offset); + else + return this; + } + + /** + * Returns the width of the container for the horizontal axis and the + * thickness of the dash area for the vertical axis. + */ + public float getMaximumSpan(int axis) + { + if (axis == X_AXIS) + { + Component container = getContainer(); + if (container != null) + return getContainer().getWidth(); + else + return 640; + } + else + return HEIGHT; + } + + /** + * Returns the same values as {@link #getMaximumSpan(int)} + */ + public float getPreferredSpan(int axis) + { + return getMaximumSpan(axis); + } +} diff --git a/javax/swing/text/html/HTMLDocument.java b/javax/swing/text/html/HTMLDocument.java index a9f267271..354ec6c0c 100644 --- a/javax/swing/text/html/HTMLDocument.java +++ b/javax/swing/text/html/HTMLDocument.java @@ -1433,14 +1433,14 @@ public class HTMLDocument extends DefaultStyledDocument // Migrate from the rather htmlAttributeSet to the faster, lighter and // unchangeable alternative implementation. AttributeSet copy = a.copyAttributes(); - - // TODO: Figure out why we must always insert this single character - // (otherwise the element does not appear). Either fix or add explaining - // comment or at least report a normal bug. - DefaultStyledDocument.ElementSpec spec; - spec = new DefaultStyledDocument.ElementSpec(copy, - DefaultStyledDocument.ElementSpec.ContentType, - new char[] {' '}, 0, 1 ); + + // The two spaces are required because some special elements like HR + // must be broken. At least two characters are needed to break into the + // two parts. + DefaultStyledDocument.ElementSpec spec = + new DefaultStyledDocument.ElementSpec(copy, + DefaultStyledDocument.ElementSpec.ContentType, + new char[] {' ', ' '}, 0, 2 ); parseBuffer.add(spec); } diff --git a/javax/swing/text/html/HTMLEditorKit.java b/javax/swing/text/html/HTMLEditorKit.java index d5e355bdf..68f2b1571 100644 --- a/javax/swing/text/html/HTMLEditorKit.java +++ b/javax/swing/text/html/HTMLEditorKit.java @@ -557,19 +557,18 @@ public class HTMLEditorKit else if (tag == HTML.Tag.HEAD) view = new NullView(element); else if (tag.equals(HTML.Tag.TABLE)) - view = new HTMLTableView(element); + view = new javax.swing.text.html.TableView(element); else if (tag.equals(HTML.Tag.TD)) view = new ParagraphView(element); - + else if (tag.equals(HTML.Tag.HR)) + view = new HRuleView(element); + else if (tag.equals(HTML.Tag.BR)) + view = new BRView(element); /* else if (tag.equals(HTML.Tag.MENU) || tag.equals(HTML.Tag.DIR) || tag.equals(HTML.Tag.UL) || tag.equals(HTML.Tag.OL)) view = new ListView(element); - else if (tag.equals(HTML.Tag.HR)) - view = new HRuleView(element); - else if (tag.equals(HTML.Tag.BR)) - view = new BRView(element); else if (tag.equals(HTML.Tag.INPUT) || tag.equals(HTML.Tag.SELECT) || tag.equals(HTML.Tag.TEXTAREA)) view = new FormView(element); diff --git a/javax/swing/text/html/StyleSheet.java b/javax/swing/text/html/StyleSheet.java index f1e8f7da6..01853d163 100644 --- a/javax/swing/text/html/StyleSheet.java +++ b/javax/swing/text/html/StyleSheet.java @@ -38,6 +38,8 @@ exception statement from your version. */ package javax.swing.text.html; +import gnu.javax.swing.text.html.CharacterAttributeTranslator; + import java.awt.Color; import java.awt.Font; import java.awt.Graphics; @@ -585,47 +587,15 @@ public class StyleSheet extends StyleContext } /** - * Converst a color string to a color. If it is not found, null is returned. - * - * @param color - the color string such as "RED" or "#NNNNNN" - * @return the Color, or null if not found. - */ - public Color stringToColor(String color) - { - color = color.toLowerCase(); - if (color.equals("black") || color.equals("#000000")) - return Color.BLACK; - else if (color.equals("aqua") || color.equals("#00FFFF")) - return new Color(127, 255, 212); - else if (color.equals("gray") || color.equals("#808080")) - return Color.GRAY; - else if (color.equals("navy") || color.equals("#000080")) - return new Color(0, 0, 128); - else if (color.equals("silver") || color.equals("#C0C0C0")) - return Color.LIGHT_GRAY; - else if (color.equals("green") || color.equals("#008000")) - return Color.GREEN; - else if (color.equals("olive") || color.equals("#808000")) - return new Color(128, 128, 0); - else if (color.equals("teal") || color.equals("#008080")) - return new Color(0, 128, 128); - else if (color.equals("blue") || color.equals("#0000FF")) - return Color.BLUE; - else if (color.equals("lime") || color.equals("#00FF00")) - return new Color(0, 255, 0); - else if (color.equals("purple") || color.equals("#800080")) - return new Color(128, 0, 128); - else if (color.equals("white") || color.equals("#FFFFFF")) - return Color.WHITE; - else if (color.equals("fuchsia") || color.equals("#FF00FF")) - return Color.MAGENTA; - else if (color.equals("maroon") || color.equals("#800000")) - return new Color(128, 0, 0); - else if (color.equals("Red") || color.equals("#FF0000")) - return Color.RED; - else if (color.equals("Yellow") || color.equals("#FFFF00")) - return Color.YELLOW; - return null; + * Convert the color string represenation into java.awt.Color. The valid + * values are like "aqua" , "#00FFFF" or "rgb(1,6,44)". + * + * @param colorName the color to convert. + * @return the matching java.awt.color + */ + public Color stringToColor(String colorName) + { + return CharacterAttributeTranslator.getColor(colorName); } /** diff --git a/javax/swing/text/html/TableView.java b/javax/swing/text/html/TableView.java new file mode 100644 index 000000000..c2edc8cdd --- /dev/null +++ b/javax/swing/text/html/TableView.java @@ -0,0 +1,137 @@ +/* TableView.java -- A table view for HTML tables + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.swing.text.html; + +import javax.swing.text.Document; +import javax.swing.text.Element; +import javax.swing.text.View; +import javax.swing.text.ViewFactory; + +/** + * A conrete implementation of TableView that renders HTML tables. + * + * @author Roman Kennke (kennke@aicas.com) + */ +class TableView + extends javax.swing.text.TableView +{ + /** + * Represents a single table row. + */ + public class RowView extends TableRow + { + /** + * Creates a new instance of the <code>RowView</code>. + * + * @param el the element for which to create a row view + */ + public RowView(Element el) + { + super(el); + } + + /** + * Get the associated style sheet from the document. + * + * @return the associated style sheet. + */ + protected StyleSheet getStyleSheet() + { + Document d = getElement().getDocument(); + if (d instanceof HTMLDocument) + return ((HTMLDocument) d).getStyleSheet(); + else + return null; + } + } + + /** + * Creates a new HTML table view for the specified element. + * + * @param el the element for the table view + */ + public TableView(Element el) + { + super(el); + } + + /** + * Get the associated style sheet from the document. + * + * @return the associated style sheet. + */ + protected StyleSheet getStyleSheet() + { + Document d = getElement().getDocument(); + if (d instanceof HTMLDocument) + return ((HTMLDocument) d).getStyleSheet(); + else + return null; + } + + /** + * Creates a view for a table row. + * + * @param el the element that represents the table row + * @return a view for rendering the table row + * (and instance of {@link RowView}). + */ + protected TableRow createTableRow(Element el) + { + return new RowView(el); + } + + /** + * Loads the children of the Table. This completely bypasses the ViewFactory + * and creates instances of TableRow instead. + * + * @param vf ignored + */ + protected void loadChildren(ViewFactory vf) + { + Element el = getElement(); + int numChildren = el.getElementCount(); + View[] rows = new View[numChildren]; + for (int i = 0; i < numChildren; ++i) + { + rows[i] = createTableRow(el.getElement(i)); + } + replace(0, getViewCount(), rows); + } +} diff --git a/lib/Makefile.am b/lib/Makefile.am index 0b0d3650f..f0e962346 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -7,7 +7,7 @@ sinclude $(JAVA_DEPEND) propertydirs := $(shell cd $(top_srcdir)/resource && $(FIND) gnu java javax org META-INF -type d ! -name CVS -print) propertyfiles := $(shell cd $(top_srcdir)/resource && $(FIND) gnu java javax org -name \*\.properties -print) -metafiles := $(shell cd $(top_srcdir)/resource && $(FIND) META-INF -name CVS -prune -o -type f -print) +metafiles := $(shell cd $(top_srcdir)/resource && $(FIND) META-INF -name CVS -prune -o -name \*\.in -prune -o -type f -print) iconfiles := $(shell cd $(top_srcdir) && $(FIND) gnu/javax/swing/plaf/gtk/icons -name *.png -type f -print) compile_classpath = $(vm_classes):$(top_srcdir):$(top_srcdir)/external/w3c_dom:$(top_srcdir)/external/sax:$(top_srcdir)/external/relaxngDatatype:$(top_srcdir)/external/jsr166:.:$(USER_CLASSLIB):$(PATH_TO_ESCHER) @@ -167,9 +167,10 @@ compile-classes: classes $(JAVA_SRCS) Makefile EXTRA_DIST = standard.omit.in mkcollections.pl.in Makefile.gcj split-for-gcj.sh CLEANFILES = compile-classes resources classes \ - glibj.zip classes.1 classes.2 \ + glibj.zip classes.1 classes.2 Makefile.deps \ $(top_builddir)/gnu/java/locale/LocaleData.java \ $(JAVA_DEPEND) +DISTCLEANFILES = standard.omit clean-local: -rm -rf gnu @@ -180,8 +181,6 @@ clean-local: -rm -rf sun -rm -rf META-INF -rm -rf lists - -rm -f Makefile.deps - -rm -f standard.omit dist-hook: mkdir -p $(distdir) diff --git a/lib/copy-vmresources.sh.in b/lib/copy-vmresources.sh.in index 39b3292e7..dbda9de20 100644 --- a/lib/copy-vmresources.sh.in +++ b/lib/copy-vmresources.sh.in @@ -13,7 +13,7 @@ for p in ${vmdirs}; do for u in ${dirs}; do mkdir -p ${destMetaDir}/${u}; done; - files=`find . -name "CVS" -prune -o -type f -print`; + files=`find . -name "CVS" -prune -o -name "*.in" -prune -o -type f -print`; for u in ${files}; do cp ${u} ${destMetaDir}/${u}; done diff --git a/native/jni/gconf-peer/GConfNativePeer.c b/native/jni/gconf-peer/GConfNativePeer.c index 55989f059..bc8f78067 100644 --- a/native/jni/gconf-peer/GConfNativePeer.c +++ b/native/jni/gconf-peer/GConfNativePeer.c @@ -78,24 +78,24 @@ static void init_gconf_client (void); /** * Throws a new runtime exception after a failure, with the given message. */ -static void throw_exception (JNIEnv *env, const char *msg); +static void throw_exception (JNIEnv * env, const char *msg); /** * Throws the given exception after a failure, with the given message. */ static void -throw_exception_by_name (JNIEnv *env, const char *name, const char *msg); +throw_exception_by_name (JNIEnv * env, const char *name, const char *msg); /** * Return a reference to a java.util.ArrayList class. */ -static gboolean set_jlist_class (JNIEnv *env); +static gboolean set_jlist_class (JNIEnv * env); /** * Builds a new reference to a new java.util.ArrayList instace. * The instance should be freed by the caller after use. */ -static jclass get_jlist_reference (JNIEnv *env, jclass jlist_class); +static jclass get_jlist_reference (JNIEnv * env, jclass jlist_class); /* ***** END: PRIVATE FUNCTIONS DELCARATION ***** */ @@ -108,16 +108,17 @@ static jclass get_jlist_reference (JNIEnv *env, jclass jlist_class); */ JNIEXPORT void JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_init_1class - (JNIEnv *env, jclass clazz) + (JNIEnv *env, jclass clazz) { - if (reference_count == 0) { - Java_gnu_java_util_prefs_gconf_GConfNativePeer_init_1id_1cache - (env, clazz); - return; - } - - reference_count++; -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_init_1class */ + if (reference_count == 0) + { + Java_gnu_java_util_prefs_gconf_GConfNativePeer_init_1id_1cache + (env, clazz); + return; + } + + reference_count++; +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -126,27 +127,29 @@ JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_init_1class */ JNIEXPORT void JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_init_1id_1cache - (JNIEnv *env, jclass clazz __attribute__ ((unused))) + (JNIEnv *env, jclass clazz __attribute__ ((unused))) { - reference_count++; + reference_count++; - init_gconf_client (); - - /* if client is null, there is probably an out or memory */ - if (client == NULL) { - /* release the string and throw a runtime exception */ - throw_exception (env, - "Unable to initialize GConfClient in native code\n"); - return; - } - - /* ***** java.util.ArrayList ***** */ - if (set_jlist_class (env) == FALSE) { - throw_exception (env, - "Unable to get valid reference to java.util.List in native code\n"); - return; - } -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_init_1id_1cache */ + init_gconf_client (); + + /* if client is null, there is probably an out of memory */ + if (client == NULL) + { + /* release the string and throw a runtime exception */ + throw_exception (env, + "Unable to initialize GConfClient in native code\n"); + return; + } + + /* ***** java.util.ArrayList ***** */ + if (set_jlist_class (env) == FALSE) + { + throw_exception (env, + "Unable to get valid reference to java.util.List in native code\n"); + return; + } +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -155,58 +158,63 @@ JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_init_1id_1cache */ JNIEXPORT jobject JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1gconf_1client_1all_1keys - (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) + (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) { - const char *dir = NULL; - GError *err = NULL; - GSList *entries = NULL; - GSList *tmp; - - /* java.util.ArrayList */ - jobject jlist = NULL; - - dir = JCL_jstring_to_cstring(env, node); - if (dir == NULL) { - return NULL; - } - - entries = gconf_client_all_entries (client, dir, &err); - if (err != NULL) { - throw_exception_by_name (env, "java/util/prefs/BackingStoreException", - err->message); - g_error_free (err); - err = NULL; - - JCL_free_cstring(env, node, dir); - return NULL; - } - - jlist = get_jlist_reference (env, jlist_class); - if (jlist == NULL) { - throw_exception_by_name (env, "java/util/prefs/BackingStoreException", - "Unable to get java.util.List reference in native code\n"); - JCL_free_cstring(env, node, dir); - g_slist_foreach (entries, (GFunc) gconf_entry_free, NULL); - g_slist_free (entries); - return NULL; - } - - tmp = entries; - while (tmp != NULL) { - const char *_val = gconf_entry_get_key(tmp->data); - _val = strrchr (_val, '/'); ++_val; - (*env)->CallBooleanMethod(env, jlist, jlist_add_id, - (*env)->NewStringUTF(env, _val)); - tmp = g_slist_next (tmp); - } - - /* clean up things */ - JCL_free_cstring(env, node, dir); - g_slist_foreach (entries, (GFunc) gconf_entry_free, NULL); - g_slist_free (entries); - - return jlist; -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1gconf_1client_1all_1keys */ + const char *dir = NULL; + GError *err = NULL; + GSList *entries = NULL; + GSList *tmp; + + /* java.util.ArrayList */ + jobject jlist = NULL; + + dir = JCL_jstring_to_cstring (env, node); + if (dir == NULL) + { + return NULL; + } + + entries = gconf_client_all_entries (client, dir, &err); + if (err != NULL) + { + throw_exception_by_name (env, "java/util/prefs/BackingStoreException", + err->message); + g_error_free (err); + err = NULL; + + JCL_free_cstring (env, node, dir); + return NULL; + } + + jlist = get_jlist_reference (env, jlist_class); + if (jlist == NULL) + { + throw_exception_by_name (env, "java/util/prefs/BackingStoreException", + "Unable to get java.util.List reference in native code\n"); + JCL_free_cstring (env, node, dir); + g_slist_foreach (entries, (GFunc) gconf_entry_free, NULL); + g_slist_free (entries); + return NULL; + } + + tmp = entries; + while (tmp != NULL) + { + const char *_val = gconf_entry_get_key (tmp->data); + _val = strrchr (_val, '/'); + ++_val; + (*env)->CallBooleanMethod (env, jlist, jlist_add_id, + (*env)->NewStringUTF (env, _val)); + tmp = g_slist_next (tmp); + } + + /* clean up things */ + JCL_free_cstring (env, node, dir); + g_slist_foreach (entries, (GFunc) gconf_entry_free, NULL); + g_slist_free (entries); + + return jlist; +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -215,57 +223,62 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1gconf_1client_1all */ JNIEXPORT jobject JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1gconf_1client_1all_1nodes - (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) + (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) { - const char *dir = NULL; - GError *err = NULL; - GSList *entries = NULL; - GSList *tmp; - - /* java.util.ArrayList */ - jobject jlist = NULL; - - dir = JCL_jstring_to_cstring(env, node); - if (dir == NULL) { - return NULL; - } - - entries = gconf_client_all_dirs (client, dir, &err); - if (err != NULL) { - throw_exception_by_name (env, "java/util/prefs/BackingStoreException", - err->message); - g_error_free (err); - err = NULL; - JCL_free_cstring(env, node, dir); - return NULL; - } - - jlist = get_jlist_reference (env, jlist_class); - if (jlist == NULL) { - throw_exception_by_name (env, "java/util/prefs/BackingStoreException", - "Unable to get java.util.List reference in native code\n"); - JCL_free_cstring(env, node, dir); - g_slist_foreach (entries, (GFunc) gconf_entry_free, NULL); - g_slist_free (entries); - return NULL; - } - - tmp = entries; - while (tmp != NULL) { - const char *_val = tmp->data; - _val = strrchr (_val, '/'); ++_val; - (*env)->CallBooleanMethod(env, jlist, jlist_add_id, - (*env)->NewStringUTF(env, _val)); - tmp = g_slist_next (tmp); - } - - /* clean up things */ - JCL_free_cstring(env, node, dir); - g_slist_foreach (entries, (GFunc) gconf_entry_free, NULL); - g_slist_free (entries); - - return jlist; -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1gconf_1client_1all_1nodes */ + const char *dir = NULL; + GError *err = NULL; + GSList *entries = NULL; + GSList *tmp; + + /* java.util.ArrayList */ + jobject jlist = NULL; + + dir = JCL_jstring_to_cstring (env, node); + if (dir == NULL) + { + return NULL; + } + + entries = gconf_client_all_dirs (client, dir, &err); + if (err != NULL) + { + throw_exception_by_name (env, "java/util/prefs/BackingStoreException", + err->message); + g_error_free (err); + err = NULL; + JCL_free_cstring (env, node, dir); + return NULL; + } + + jlist = get_jlist_reference (env, jlist_class); + if (jlist == NULL) + { + throw_exception_by_name (env, "java/util/prefs/BackingStoreException", + "Unable to get java.util.List reference in native code\n"); + JCL_free_cstring (env, node, dir); + g_slist_foreach (entries, (GFunc) gconf_entry_free, NULL); + g_slist_free (entries); + return NULL; + } + + tmp = entries; + while (tmp != NULL) + { + const char *_val = tmp->data; + _val = strrchr (_val, '/'); + ++_val; + (*env)->CallBooleanMethod (env, jlist, jlist_add_id, + (*env)->NewStringUTF (env, _val)); + tmp = g_slist_next (tmp); + } + + /* clean up things */ + JCL_free_cstring (env, node, dir); + g_slist_foreach (entries, (GFunc) gconf_entry_free, NULL); + g_slist_free (entries); + + return jlist; +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -274,18 +287,19 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1gconf_1client_1all */ JNIEXPORT void JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1suggest_1sync - (JNIEnv *env, jclass clazz __attribute__ ((unused))) + (JNIEnv *env, jclass clazz __attribute__ ((unused))) { - GError *err = NULL; - - gconf_client_suggest_sync (client, &err); - if (err != NULL) { - throw_exception_by_name (env, "java/util/prefs/BackingStoreException", - err->message); - g_error_free (err); - err = NULL; - } -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1suggest_1sync */ + GError *err = NULL; + + gconf_client_suggest_sync (client, &err); + if (err != NULL) + { + throw_exception_by_name (env, "java/util/prefs/BackingStoreException", + err->message); + g_error_free (err); + err = NULL; + } +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -294,22 +308,30 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1suggest_1sync */ JNIEXPORT jboolean JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1unset - (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring key) + (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring key) { - const char *_key = NULL; - gboolean result = JNI_FALSE; - - _key = JCL_jstring_to_cstring(env, key); - if (_key == NULL) { - return JNI_FALSE; - } - - result = gconf_client_unset (client, _key, NULL); - - JCL_free_cstring(env, key, _key); + const char *_key = NULL; + gboolean result = JNI_FALSE; + GError *err = NULL; + + _key = JCL_jstring_to_cstring (env, key); + if (_key == NULL) + { + return JNI_FALSE; + } + + result = gconf_client_unset (client, _key, &err); + if (err != NULL) + { + result = JNI_FALSE; + g_error_free (err); + err = NULL; + } + + JCL_free_cstring (env, key, _key); - return result; -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1unset */ + return result; +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -318,25 +340,36 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1unset */ JNIEXPORT jstring JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1get_1string - (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring key) + (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring key) { - const char *_key = NULL; - const char *_value = NULL; - jstring result = NULL; - - _key = JCL_jstring_to_cstring(env, key); - if (_key == NULL) { - return NULL; - } - - _value = gconf_client_get_string (client, _key, NULL); - JCL_free_cstring(env, key, _key); - - result = (*env)->NewStringUTF (env, _value); - g_free ((gpointer) _value); - - return result; -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1get_1string */ + const char *_key = NULL; + const char *_value = NULL; + GError *err = NULL; + jstring result = NULL; + + _key = JCL_jstring_to_cstring (env, key); + if (_key == NULL) + { + return NULL; + } + + _value = gconf_client_get_string (client, _key, &err); + JCL_free_cstring (env, key, _key); + if (err != NULL) + { + /* just in case */ + if (_value != NULL) g_free ((gpointer) _value); + g_error_free (err); + err = NULL; + + return NULL; + } + + result = (*env)->NewStringUTF (env, _value); + g_free ((gpointer) _value); + + return result; +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -345,28 +378,36 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1get_1string */ JNIEXPORT jboolean JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1set_1string - (JNIEnv *env, jclass clazz __attribute__ ((unused)), - jstring key, jstring value) + (JNIEnv *env, jclass clazz __attribute__ ((unused)), + jstring key, jstring value) { - const char *_key = NULL; - const char *_value = NULL; - - gboolean result = JNI_FALSE; - - /* load an UTF string from the virtual machine. */ - _key = JCL_jstring_to_cstring (env, key); - _value = JCL_jstring_to_cstring (env, value); - if (_key == NULL && _value == NULL) { - return JNI_FALSE; - } - - result = gconf_client_set_string (client, _key, _value, NULL); - - JCL_free_cstring (env, key, _key); - JCL_free_cstring (env, value, _value); - - return (jboolean) result; -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1set_1string */ + const char *_key = NULL; + const char *_value = NULL; + GError *err = NULL; + + gboolean result = JNI_FALSE; + + /* load an UTF string from the virtual machine. */ + _key = JCL_jstring_to_cstring (env, key); + _value = JCL_jstring_to_cstring (env, value); + if (_key == NULL && _value == NULL) + { + return JNI_FALSE; + } + + result = gconf_client_set_string (client, _key, _value, &err); + if (err != NULL) + { + g_error_free (err); + err = NULL; + result = JNI_FALSE; + } + + JCL_free_cstring (env, key, _key); + JCL_free_cstring (env, value, _value); + + return (jboolean) result; +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -375,18 +416,18 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1set_1string */ JNIEXPORT void JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1remove_1dir - (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) + (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) { - const char *dir = NULL; - - dir = JCL_jstring_to_cstring (env, node); - if (dir == NULL) - return; - - gconf_client_remove_dir (client, dir, NULL); - - JCL_free_cstring (env, node, dir); -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1remove_1dir */ + const char *dir = NULL; + + dir = JCL_jstring_to_cstring (env, node); + if (dir == NULL) + return; + + gconf_client_remove_dir (client, dir, NULL); + + JCL_free_cstring (env, node, dir); +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -395,19 +436,19 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1remove_1dir */ JNIEXPORT void JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1add_1dir - (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) + (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) { - const char *dir = NULL; + const char *dir = NULL; - dir = JCL_jstring_to_cstring (env, node); - if (dir == NULL) - return; - - /* ignore errors */ - gconf_client_add_dir (client, dir, GCONF_CLIENT_PRELOAD_ONELEVEL, NULL); + dir = JCL_jstring_to_cstring (env, node); + if (dir == NULL) + return; - JCL_free_cstring (env, node, dir); -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1add_1dir */ + /* ignore errors */ + gconf_client_add_dir (client, dir, GCONF_CLIENT_PRELOAD_ONELEVEL, NULL); + + JCL_free_cstring (env, node, dir); +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -416,22 +457,25 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1add_1dir */ JNIEXPORT jboolean JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1dir_1exists - (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) -{ - const char *dir = NULL; - jboolean value = JNI_FALSE; - - dir = JCL_jstring_to_cstring (env, node); - if (dir == NULL) - return value; - - /* we ignore errors here */ - value = gconf_client_dir_exists (client, dir, NULL); - - JCL_free_cstring (env, node, dir); + (JNIEnv *env, jclass clazz __attribute__ ((unused)), jstring node) +{ + const char *dir = NULL; + GError *err = NULL; + jboolean value = JNI_FALSE; + dir = JCL_jstring_to_cstring (env, node); + if (dir == NULL) return value; -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1dir_1exists */ + + /* on error return false */ + value = gconf_client_dir_exists (client, dir, &err); + if (err != NULL) + value = JNI_FALSE; + + JCL_free_cstring (env, node, dir); + + return value; +} /* * Class: gnu_java_util_prefs_gconf_GConfNativePeer @@ -440,23 +484,24 @@ Java_gnu_java_util_prefs_gconf_GConfNativePeer_gconf_1client_1dir_1exists */ JNIEXPORT void JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_finalize_1class - (JNIEnv *env, jclass clazz __attribute__ ((unused))) + (JNIEnv *env, jclass clazz __attribute__ ((unused))) { - if (reference_count == 0) { - /* last reference, free all resources and return */ - g_object_unref (G_OBJECT (client)); - - (*env)->DeleteGlobalRef (env, jlist_class); - - jlist_class = NULL; - jlist_init_id = NULL; - jlist_add_id = NULL; - - return; - } - - reference_count--; -} /* Java_gnu_java_util_prefs_gconf_GConfNativePeer_finalize_1class */ + if (reference_count == 0) + { + /* last reference, free all resources and return */ + g_object_unref (G_OBJECT (client)); + + (*env)->DeleteGlobalRef (env, jlist_class); + + jlist_class = NULL; + jlist_init_id = NULL; + jlist_add_id = NULL; + + return; + } + + reference_count--; +} /* ***** END: NATIVE FUNCTIONS ***** */ @@ -464,55 +509,59 @@ JNICALL Java_gnu_java_util_prefs_gconf_GConfNativePeer_finalize_1class static void throw_exception (JNIEnv *env, const char *msg) { - throw_exception_by_name (env, "java/lang/RuntimeException", msg); -} /* throw_exception */ + throw_exception_by_name (env, "java/lang/RuntimeException", msg); +} static void throw_exception_by_name (JNIEnv *env, const char *name, const char *msg) -{ - JCL_ThrowException(env, name, msg); -} /* throw_exception */ +{ + JCL_ThrowException (env, name, msg); +} static void init_gconf_client (void) -{ - client = gconf_client_get_default (); - g_type_init(); -} /* init_gconf_client */ +{ + client = gconf_client_get_default (); + g_type_init (); +} static gboolean set_jlist_class (JNIEnv *env) { - jclass local_jlist_class = NULL; - - /* gets a reference to the ArrayList class */ - local_jlist_class = JCL_FindClass (env, "java/util/ArrayList"); - if (local_jlist_class == NULL) { - return FALSE; - } - - jlist_class = (*env)->NewGlobalRef(env, local_jlist_class); - (*env)->DeleteLocalRef(env, local_jlist_class); - if (jlist_class == NULL) { - return FALSE; - } - - /* and initialize it */ - jlist_init_id = (*env)->GetMethodID (env, jlist_class, "<init>", "()V"); - if (jlist_init_id == NULL) { - return FALSE; - } - - jlist_add_id = (*env)->GetMethodID (env, jlist_class, "add", - "(Ljava/lang/Object;)Z"); - if (jlist_add_id == NULL) { - return FALSE; - } - - return TRUE; -} /* set_jlist_class */ + jclass local_jlist_class = NULL; + + /* gets a reference to the ArrayList class */ + local_jlist_class = JCL_FindClass (env, "java/util/ArrayList"); + if (local_jlist_class == NULL) + { + return FALSE; + } + + jlist_class = (*env)->NewGlobalRef (env, local_jlist_class); + (*env)->DeleteLocalRef (env, local_jlist_class); + if (jlist_class == NULL) + { + return FALSE; + } + + /* and initialize it */ + jlist_init_id = (*env)->GetMethodID (env, jlist_class, "<init>", "()V"); + if (jlist_init_id == NULL) + { + return FALSE; + } + + jlist_add_id = (*env)->GetMethodID (env, jlist_class, "add", + "(Ljava/lang/Object;)Z"); + if (jlist_add_id == NULL) + { + return FALSE; + } + + return TRUE; +} static jobject get_jlist_reference (JNIEnv *env, jclass jlist_class) { - return (*env)->NewObject(env, jlist_class, jlist_init_id); -} /* get_jlist_reference */ + return (*env)->NewObject (env, jlist_class, jlist_init_id); +} /* ***** END: PRIVATE FUNCTIONS IMPLEMENTATION ***** */ diff --git a/native/plugin/Makefile.am b/native/plugin/Makefile.am index d357e88ca..59c4cb3f3 100644 --- a/native/plugin/Makefile.am +++ b/native/plugin/Makefile.am @@ -1,4 +1,4 @@ -lib_LTLIBRARIES = libgcjwebplugin.la +nativeexeclib_LTLIBRARIES = libgcjwebplugin.la libgcjwebplugin_la_SOURCES = gcjwebplugin.cc @@ -10,7 +10,7 @@ libgcjwebplugin_la_LDFLAGS = -avoid-version \ $(GLIB_LIBS) $(GTK_LIBS) \ -lstdc++ -install-plugin: $(lib_LTLIBRARIES) +install-plugin: $(nativeexeclib_LTLIBRARIES) $(INSTALL) -d -m0755 $(DESTDIR)$(PLUGIN_DIR) $(INSTALL) .libs/libgcjwebplugin.so $(DESTDIR)$(PLUGIN_DIR) diff --git a/resource/META-INF/services/java.util.prefs.PreferencesFactory.in b/resource/META-INF/services/java.util.prefs.PreferencesFactory.in new file mode 100644 index 000000000..b9465ce54 --- /dev/null +++ b/resource/META-INF/services/java.util.prefs.PreferencesFactory.in @@ -0,0 +1 @@ +@DEFAULT_PREFS_PEER@ diff --git a/resource/META-INF/services/javax.sound.sampled.spi.AudioFileReader b/resource/META-INF/services/javax.sound.sampled.spi.AudioFileReader new file mode 100644 index 000000000..b1a18ace3 --- /dev/null +++ b/resource/META-INF/services/javax.sound.sampled.spi.AudioFileReader @@ -0,0 +1 @@ +gnu.javax.sound.sampled.WAV.WAVReader diff --git a/tools/.cvsignore b/tools/.cvsignore index d2e24c413..8dce53527 100644 --- a/tools/.cvsignore +++ b/tools/.cvsignore @@ -8,3 +8,6 @@ appletviewer gappletviewer gjarsigner gkeytool +gjar +gnative2ascii +gserialver diff --git a/vm/reference/gnu/java/lang/management/VMGarbageCollectorMXBeanImpl.java b/vm/reference/gnu/java/lang/management/VMGarbageCollectorMXBeanImpl.java new file mode 100644 index 000000000..2a202849a --- /dev/null +++ b/vm/reference/gnu/java/lang/management/VMGarbageCollectorMXBeanImpl.java @@ -0,0 +1,80 @@ +/* VMGarbageCollectorMXBeanImpl.java - VM interface for a GC bean + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.java.lang.management; + +/** + * Provides access to information about the garbage collectors + * of the virtual machine. Garbage collectors are responsible + * for removing unreferenced objects from memory. A garbage + * collector is a type of memory manager, so this interface + * is combined with that of generic memory managers. An instance + * of this bean for each garbage collector is obtained by calling + * {@link ManagementFactory#getGarbageCollectorMXBeans()}. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +final class VMGarbageCollectorMXBeanImpl +{ + + /** + * Returns the number of collections the garbage collector + * represented by this bean has made. -1 is returned if the + * collection count is undefined. + * + * @param name the name of the garbage collector. + * @return the number of collections made, or -1 if this is + * undefined. + */ + static native long getCollectionCount(String name); + + /** + * Returns the accumulated number of milliseconds this garbage + * collector has spent freeing the memory used by unreferenced + * objects. -1 is returned if the collection time is undefined. + * Note that the accumulated time may not change, even when the + * collection count increases, if the time taken is sufficiently + * short; this depends on the resolution of the timer used. + * + * @param name the name of the garbage collector. + * @return the accumulated number of milliseconds spent collecting, + * or -1 if this is undefined. + */ + static native long getCollectionTime(String name); + +} diff --git a/vm/reference/gnu/java/lang/management/VMMemoryManagerMXBeanImpl.java b/vm/reference/gnu/java/lang/management/VMMemoryManagerMXBeanImpl.java new file mode 100644 index 000000000..0a4204a6d --- /dev/null +++ b/vm/reference/gnu/java/lang/management/VMMemoryManagerMXBeanImpl.java @@ -0,0 +1,95 @@ +/* VMMemoryManagerMXBeanImpl.java - VM interface for a memory manager bean + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.java.lang.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryPoolMXBean; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Provides access to information about the memory managers + * of the virtual machine. An instance of this bean for each + * memory manager is obtained by calling + * {@link ManagementFactory#getMemoryManagerMXBeans()}. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +final class VMMemoryManagerMXBeanImpl +{ + + /** + * Returns an array containing the names of the memory pools + * this memory manager manages. + * + * @param name the name of the memory manager. + * @return an array containing the name of each memory pool + * this manager is responsible for. + */ + static String[] getMemoryPoolNames(String name) + { + List managedPools = new ArrayList(); + Iterator beans = ManagementFactory.getMemoryPoolMXBeans().iterator(); + while (beans.hasNext()) + { + MemoryPoolMXBean bean = (MemoryPoolMXBean) beans.next(); + String[] managers = bean.getMemoryManagerNames(); + for (int a = 0; a < managers.length; ++a) + if (managers[a].equals(name)) + { + managedPools.add(bean.getName()); + break; + } + } + return (String[]) managedPools.toArray(new String[managedPools.size()]); + } + + /** + * Returns true if this memory manager is still valid. A memory + * manager becomes invalid when it is removed by the virtual machine + * and no longer used. + * + * @param name the name of the memory manager. + * @return true if this memory manager is valid. + */ + static native boolean isValid(String name); + +} diff --git a/vm/reference/gnu/java/lang/management/VMMemoryPoolMXBeanImpl.java b/vm/reference/gnu/java/lang/management/VMMemoryPoolMXBeanImpl.java new file mode 100644 index 000000000..e32e8f0ac --- /dev/null +++ b/vm/reference/gnu/java/lang/management/VMMemoryPoolMXBeanImpl.java @@ -0,0 +1,186 @@ +/* MemoryPoolMXBeanImpl.java - VM interface for memory pool beans + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.java.lang.management; + +import java.lang.management.MemoryUsage; + +/** + * Provides access to information on the memory resources or + * pools used by the current invocation of the virtual machine. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +final class VMMemoryPoolMXBeanImpl +{ + + /** + * Returns memory usage statistics for the specified pool + * just after a best-effort attempt to free memory. This + * is valid only for certain garbage collectors. + * + * @param name the name of the pool to obtain statistics on. + * @return a {@link java.lang.management.MemoryUsage} object + * containing the statistics or <code>null</code> + * if this pool does not support such statistics. + */ + static native MemoryUsage getCollectionUsage(String name); + + /** + * Returns the collection usage threshold for the specified pool. + * This is only called if this functionality is supported + * by the virtual machine (i.e. the appropriate property, + * <code>gnu.java.lang.management.CollectionUsageThresholdSupport</code>, + * is defined). The value is initially zero. + * + * @param name the name of the pool to obtain statistics on. + * @return the collection usage threshold. + */ + static native long getCollectionUsageThreshold(String name); + + /** + * Returns the number of times the collection usage threshold + * has been met or exceeded by the specified pool. + * This is only called if this functionality is supported + * by the virtual machine (i.e. the appropriate property, + * <code>gnu.java.lang.management.CollectionUsageThresholdSupport</code>, + * is defined). + * + * @param name the name of the pool to obtain statistics on. + * @return the collection usage threshold count. + */ + static native long getCollectionUsageThresholdCount(String name); + + /** + * Returns an array of names of memory managers which manage + * the specified pool. + * + * @param name the name of the pool to obtain statistics on. + * @return a list of memory managers for the pool. + */ + static native String[] getMemoryManagerNames(String name); + + /** + * Returns the peak usage level of the specified pool. + * This is only called if the pool is valid. + * + * @param name the name of the pool to obtain statistics on. + * @return a {@link java.lang.management.MemoryUsage} object + * containing the statistics. + */ + static native MemoryUsage getPeakUsage(String name); + + /** + * Returns the current usage level of the specified pool. + * This is only called if the pool is valid. + * + * @param name the name of the pool to obtain statistics on. + * @return a {@link java.lang.management.MemoryUsage} object + * containing the statistics. + */ + static native MemoryUsage getUsage(String name); + + /** + * Returns the usage threshold for the specified pool. + * This is only called if this functionality is supported + * by the virtual machine (i.e. the appropriate property, + * <code>gnu.java.lang.management.UsageThresholdSupport</code>, + * is defined). The value is initially defined by the + * virtual machine. + * + * @param name the name of the pool to obtain statistics on. + * @return the usage threshold. + */ + static native long getUsageThreshold(String name); + + /** + * Returns the number of times the usage threshold + * has been met or exceeded by the specified pool. + * This is only called if this functionality is supported + * by the virtual machine (i.e. the appropriate property, + * <code>gnu.java.lang.management.UsageThresholdSupport</code>, + * is defined). + * + * @param name the name of the pool to obtain statistics on. + * @return the usage threshold count. + */ + static native long getUsageThresholdCount(String name); + + /** + * Returns true if the specified pool is still valid i.e. + * it is still in use by the virtual machine. + * + * @param name the name of the pool to check the validity of. + * @return true if the pool is valid. + */ + static native boolean isValid(String name); + + /** + * Resets the peak usage level to the current usage level for + * the specified pool. + * + * @param name the name of the pool to reset the peak usage of. + */ + static native void resetPeakUsage(String name); + + /** + * Sets the collection usage threshold for the specified + * pool to the supplied value. + * This is only called if this functionality is supported + * by the virtual machine (i.e. the appropriate property, + * <code>gnu.java.lang.management.CollectionUsageThresholdSupport</code>, + * is defined). + * + * @param name the name of the pool to set the threshold of. + * @param threshold the new threshold level. + */ + static native void setCollectionUsageThreshold(String name, long threshold); + + /** + * Sets the usage threshold for the specified pool to the supplied value. + * This is only called if this functionality is supported + * by the virtual machine (i.e. the appropriate property, + * <code>gnu.java.lang.management.UsageThresholdSupport</code>, + * is defined). + * + * @param name the name of the pool to set the threshold of. + * @param threshold the new threshold level. + */ + static native void setUsageThreshold(String name, long threshold); + +} diff --git a/vm/reference/java/lang/management/VMManagementFactory.java b/vm/reference/java/lang/management/VMManagementFactory.java new file mode 100644 index 000000000..f10497014 --- /dev/null +++ b/vm/reference/java/lang/management/VMManagementFactory.java @@ -0,0 +1,75 @@ +/* VMManagementFactory.java - VM interface for obtaining system beans. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.lang.management; + +/** + * Provides lists of resources required by the + * {@link java.lang.management.ManagementFactory} for + * creating beans. + * + * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @since 1.5 + */ +final class VMManagementFactory +{ + + /** + * Return a list of the names of the currently available + * memory pools within the virtual machine. + * + * @return a list of memory pool names. + */ + static native String[] getMemoryPoolNames(); + + /** + * Return a list of the names of the currently available + * memory managers within the virtual machine. This should + * not include the garbage collectors listed below. + * + * @return a list of memory manager names. + */ + static native String[] getMemoryManagerNames(); + + /** + * Return a list of the names of the currently available + * garbage collectors within the virtual machine. + * + * @return a list of garbage collector names. + */ + static native String[] getGarbageCollectorNames(); +} |