--- a/.hgtags Tue Aug 05 13:06:42 2008 -0700
+++ b/.hgtags Tue Aug 05 13:15:22 2008 -0700
@@ -5,3 +5,4 @@ 02e4c5348592a8d7fc2cba28bc5f8e35c0e17277
02e4c5348592a8d7fc2cba28bc5f8e35c0e17277 jdk7-b28
e21f4266466cd1306b176aaa08b2cd8337a9be3d jdk7-b29
b6d6877c1155621a175dccd12dc14c54f938fb8b jdk7-b30
+b7474b739d13bacd9972f88ac91f6350b7b0be12 jdk7-b31
--- a/make/com/sun/java/pack/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/com/sun/java/pack/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -97,9 +97,6 @@ ifeq ($(PLATFORM), windows)
/D "J2SE_FTYPE=0x1L"
RES = $(OBJDIR)/$(PGRM).res
-
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
else
LDOUTPUT = -o #Have a space
LDDFLAGS += -lc
--- a/make/com/sun/security/auth/module/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/com/sun/security/auth/module/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -55,9 +55,6 @@ LIBRARY = jaas_nt
EXTRA_LIBS += netapi32.lib user32.lib mpr.lib
endif #fdlibm
# code generates errors when compiled at warning level 3 and warnings are fatal
- ifeq ($(ARCH_DATA_MODEL), 64)
- COMPILER_WARNINGS_FATAL=false
- endif # ARCH_DATA_MODEL
endif # windows
ifeq ($(PLATFORM), solaris)
--- a/make/common/Defs-linux.gmk Tue Aug 05 13:06:42 2008 -0700
+++ b/make/common/Defs-linux.gmk Tue Aug 05 13:15:22 2008 -0700
@@ -149,10 +149,9 @@ PIC_CODE_LARGE = -fPIC
PIC_CODE_LARGE = -fPIC
PIC_CODE_SMALL = -fpic
GLOBAL_KPIC = $(PIC_CODE_LARGE)
+CFLAGS_COMMON += $(GLOBAL_KPIC) $(GCC_WARNINGS)
ifeq ($(ARCH), amd64)
- CFLAGS_COMMON += $(GLOBAL_KPIC) $(GCC_WARNINGS) -pipe
-else
- CFLAGS_COMMON += $(GLOBAL_KPIC) $(GCC_WARNINGS)
+ CFLAGS_COMMON += -pipe
endif
# Linux 64bit machines use Dwarf2, which can be HUGE, have fastdebug use -g1
--- a/make/common/Defs-solaris.gmk Tue Aug 05 13:06:42 2008 -0700
+++ b/make/common/Defs-solaris.gmk Tue Aug 05 13:15:22 2008 -0700
@@ -40,6 +40,9 @@
# LDLIBS (set $(EXTRA_LIBS) instead)
# LDLIBS_COMMON (set $(EXTRA_LIBS) instead)
# LINTFLAGS (set $(OTHER_LINTFLAGS) instead)
+#
+# Note: CPPFLAGS are used in C and C++ compiles.
+#
# Get shared JDK settings
include $(JDK_MAKE_SHARED_DIR)/Defs.gmk
@@ -112,6 +115,10 @@ endif
# Required with many of the source files.
# -mt Assume multi-threaded (important)
#
+# The more unusual options to the Sun C compiler:
+# +w Print more warnings
+# +w2 Maximum warnings
+#
#
# Debug flag for C and C++ compiler
@@ -140,15 +147,34 @@ ifeq ($(FASTDEBUG), true)
CXXFLAGS_DEBUG_OPTION = -g0 $(CC_FASTDEBUG_OPT)
endif
-CFLAGS_COMMON = -v -mt -L$(OBJDIR) -xc99=%none
+CFLAGS_COMMON = -L$(OBJDIR)
+
+# Do not allow C99 language features like declarations in code etc.
+CFLAGS_COMMON += -xc99=%none
+
+# Allow C++ comments in C code
CFLAGS_COMMON += -xCC
-CFLAGS_COMMON += -errshort=tags
+
+# Show error message tags on errors
+CFLAGS_COMMON += -errshort=tags
+CXXFLAGS_COMMON += -errtags=yes
+
+# Optimization flags
CFLAGS_OPT = $(POPT)
+
+# Debug version flags
CFLAGS_DBG = $(CFLAGS_DEBUG_OPTION)
-CFLAGS_COMMON += -Xa $(CFLAGS_REQUIRED)
+
+# Required C compiler flags
+CFLAGS_COMMON += -Xa $(CFLAGS_REQUIRED)
+
+# Maximum warnings all the time
+CXXFLAGS_COMMON += +w
+CFLAGS_COMMON += -v
# Assume MT behavior all the time (important)
-CXXFLAGS_COMMON = -mt
+CXXFLAGS_COMMON += -mt
+CFLAGS_COMMON += -mt
# Assume no C++ exceptions are used
CXXFLAGS_COMMON += -features=no%except -DCC_NOEX
@@ -237,8 +263,8 @@ LINTFLAGS_COMMON += $(LINT_XARCH_OPTION)
# OTHER_CFLAGS += -DPERTURBALOT
#
-CPPFLAGS_COMMON = -D$(ARCH_FAMILY) -D__solaris__ -D_REENTRANT
-CPPFLAGS_OPT =
+CPPFLAGS_COMMON = -D__solaris__ -D$(ARCH_FAMILY)
+CPPFLAGS_OPT = -DNDEBUG
CPPFLAGS_DBG = -DDEBUG
ifeq ($(ARCH_FAMILY), i586)
--- a/make/common/Defs-windows.gmk Tue Aug 05 13:06:42 2008 -0700
+++ b/make/common/Defs-windows.gmk Tue Aug 05 13:15:22 2008 -0700
@@ -283,7 +283,7 @@ ifeq ($(ARCH), amd64)
ifeq ($(ARCH), amd64)
CPPFLAGS_COMMON += -D_AMD64_ -Damd64
else
- CPPFLAGS_COMMON += -DWIN32 -D_X86_ -Dx86
+ CPPFLAGS_COMMON += -D_X86_ -Dx86
endif
CPPFLAGS_COMMON += -DWIN32_LEAN_AND_MEAN
@@ -291,6 +291,13 @@ CPPFLAGS_COMMON += -DWIN32_LEAN_AND_MEAN
# Output options (use specific filenames to avoid parallel compile errors)
#
CFLAGS_COMMON += -Fd$(OBJDIR)/$(basename $(@F)).pdb -Fm$(OBJDIR)/$(basename $(@F)).map
+
+#
+# Use -wdNNNN to disable warning NNNN.
+# C4800 is a warning about bool performance casts (can't make go away)
+#
+COMPILER_WARNINGS_TO_IGNORE = 4800
+CFLAGS_COMMON += $(COMPILER_WARNINGS_TO_IGNORE:%=-wd%)
#
# Add warnings and extra on 64bit issues
@@ -298,11 +305,11 @@ ifeq ($(ARCH_DATA_MODEL), 64)
ifeq ($(ARCH_DATA_MODEL), 64)
CFLAGS_COMMON += -Wp64
endif
+
+#
+# Treat compiler warnings as errors, if requested
+#
CFLAGS_COMMON += -W$(COMPILER_WARNING_LEVEL)
-
-#
-# Treat compiler warnings as errors, if requested
-#
ifeq ($(COMPILER_WARNINGS_FATAL),true)
CFLAGS_COMMON += -WX
endif
@@ -352,17 +359,9 @@ else
# BUILD_WIN_SA=1
# on the make command.
ifdef BUILD_WIN_SA
- ifeq ($(ARCH), amd64)
- INCLUDE_SA = true
- else
- INCLUDE_SA = true
- endif
+ INCLUDE_SA = true
else
- ifeq ($(ARCH), amd64)
- INCLUDE_SA = false
- else
- INCLUDE_SA = false
- endif
+ INCLUDE_SA = false
endif
endif
@@ -404,7 +403,6 @@ else
else
JDK_UPDATE_VER := 0
endif
-JDK_VER = $(JDK_MINOR_VERSION),$(JDK_MICRO_VERSION),$(JDK_UPDATE_VER),$(COOKED_BUILD_NUMBER)
RC_FLAGS = /l 0x409 /r
@@ -414,15 +412,23 @@ else
RC_FLAGS += $(MS_RC_DEBUG_OPTION)
endif
-ifndef COPYRIGHT_YEAR
- COPYRIGHT_YEAR = 2007
-endif
+# Values for the RC variables defined in RC_FLAGS
+JDK_RC_BUILD_ID = $(FULL_VERSION)
+JDK_RC_COMPANY = $(COMPANY_NAME)
+JDK_RC_COMPONENT = $(PRODUCT_NAME) $(JDK_RC_PLATFORM_NAME) binary
+JDK_RC_VER = \
+ $(JDK_MINOR_VERSION).$(JDK_MICRO_VERSION).$(JDK_UPDATE_VER).$(COOKED_BUILD_NUMBER)
+JDK_RC_COPYRIGHT = Copyright \xA9 $(COPYRIGHT_YEAR)
+JDK_RC_NAME = \
+ $(PRODUCT_NAME) $(JDK_RC_PLATFORM_NAME) $(JDK_MINOR_VERSION) $(JDK_UPDATE_META_TAG)
+JDK_RC_FVER = \
+ $(JDK_MINOR_VERSION),$(JDK_MICRO_VERSION),$(JDK_UPDATE_VER),$(COOKED_BUILD_NUMBER)
# J2SE name required here
-RC_FLAGS += -d "J2SE_BUILD_ID=$(FULL_VERSION)" \
- -d "J2SE_COMPANY=$(COMPANY_NAME)" \
- -d "J2SE_COMPONENT=$(PRODUCT_NAME) Platform SE binary" \
- -d "J2SE_VER=$(JDK_MINOR_VERSION).$(JDK_MICRO_VERSION).$(JDK_UPDATE_VER).$(COOKED_BUILD_NUMBER)" \
- -d "J2SE_COPYRIGHT=Copyright \xA9 $(COPYRIGHT_YEAR)" \
- -d "J2SE_NAME=$(PRODUCT_NAME) Platform SE $(JDK_MINOR_VERSION) $(JDK_UPDATE_META_TAG)" \
- -d "J2SE_FVER=$(JDK_VER)"
+RC_FLAGS += -d "J2SE_BUILD_ID=$(JDK_RC_BUILD_ID)" \
+ -d "J2SE_COMPANY=$(JDK_RC_COMPANY)" \
+ -d "J2SE_COMPONENT=$(JDK_RC_COMPONENT)" \
+ -d "J2SE_VER=$(JDK_RC_VER)" \
+ -d "J2SE_COPYRIGHT=$(JDK_RC_COPYRIGHT)" \
+ -d "J2SE_NAME=$(JDK_RC_NAME)" \
+ -d "J2SE_FVER=$(JDK_RC_FVER)"
--- a/make/common/Defs.gmk Tue Aug 05 13:06:42 2008 -0700
+++ b/make/common/Defs.gmk Tue Aug 05 13:15:22 2008 -0700
@@ -703,7 +703,7 @@ ifdef ALT_COPYRIGHT_YEAR
ifdef ALT_COPYRIGHT_YEAR
COPYRIGHT_YEAR = $(ALT_COPYRIGHT_YEAR)
else
- COPYRIGHT_YEAR = $(shell $(DATE) '+%Y')
+ COPYRIGHT_YEAR := $(shell $(DATE) '+%Y')
endif
# Install of imported file (JDK_IMPORT_PATH, or some other external location)
--- a/make/common/shared/Compiler-gcc.gmk Tue Aug 05 13:06:42 2008 -0700
+++ b/make/common/shared/Compiler-gcc.gmk Tue Aug 05 13:15:22 2008 -0700
@@ -73,23 +73,18 @@ ifeq ($(PLATFORM), linux)
REQUIRED_CC_VER = 4.0
REQUIRED_GCC_VER = 4.0.*
else
- ifeq ($(ARCH_DATA_MODEL), 32)
- # i586
REQUIRED_CC_VER = 3.2
- REQUIRED_GCC_VER = 3.2.1*
- REQUIRED_GCC_VER_INT = 3.2.1-7a
- else
- ifeq ($(ARCH), amd64)
- # amd64
- REQUIRED_CC_VER = 3.2
- REQUIRED_GCC_VER = 3.2.*
- endif
- ifeq ($(ARCH), ia64)
- # ia64
- REQUIRED_CC_VER = 3.2
- REQUIRED_GCC_VER = 2.9[56789].*
- endif
- endif
+ ifeq ($(ARCH_DATA_MODEL), 32)
+ REQUIRED_GCC_VER = 3.2.1*
+ REQUIRED_GCC_VER_INT = 3.2.1-7a
+ else
+ ifeq ($(ARCH), amd64)
+ REQUIRED_GCC_VER = 3.2.*
+ endif
+ ifeq ($(ARCH), ia64)
+ REQUIRED_GCC_VER = 2.9[56789].*
+ endif
+ endif
endif
# Option used to create a shared library
SHARED_LIBRARY_FLAG = -shared -mimpure-text
--- a/make/common/shared/Defs-java.gmk Tue Aug 05 13:06:42 2008 -0700
+++ b/make/common/shared/Defs-java.gmk Tue Aug 05 13:15:22 2008 -0700
@@ -107,7 +107,10 @@ ifeq ($(DEBUG_CLASSFILES),true)
ifeq ($(DEBUG_CLASSFILES),true)
JAVACFLAGS += -g
endif
-ifeq ($(COMPILER_WARNINGS_FATAL), true)
+ifeq ($(JAVAC_MAX_WARNINGS), true)
+ JAVACFLAGS += -Xlint:all
+endif
+ifeq ($(JAVAC_WARNINGS_FATAL), true)
JAVACFLAGS += -Werror
endif
@@ -180,7 +183,10 @@ endif
# The javac options supplied to the boot javac is limited. This compiler
# should only be used to build the 'make/tools' sources, which are not
# class files that end up in the classes directory.
-ifeq ($(COMPILER_WARNINGS_FATAL), true)
+ifeq ($(JAVAC_MAX_WARNINGS), true)
+ BOOT_JAVACFLAGS += -Xlint:all
+endif
+ifeq ($(JAVAC_WARNINGS_FATAL), true)
BOOT_JAVACFLAGS += -Werror
endif
BOOT_JAVACFLAGS += -encoding ascii
--- a/make/common/shared/Defs.gmk Tue Aug 05 13:06:42 2008 -0700
+++ b/make/common/shared/Defs.gmk Tue Aug 05 13:15:22 2008 -0700
@@ -188,16 +188,18 @@ endif
endif
# Default names
-LAUNCHER_NAME = java
-PRODUCT_NAME = Java(TM)
-PRODUCT_SUFFIX = SE Runtime Environment
-COMPANY_NAME = Sun Microsystems, Inc.
-
ifdef OPENJDK
LAUNCHER_NAME = openjdk
PRODUCT_NAME = OpenJDK
PRODUCT_SUFFIX = Runtime Environment
- COMPANY_NAME =
+ JDK_RC_PLATFORM_NAME = Platform
+ COMPANY_NAME = N/A
+else
+ LAUNCHER_NAME = java
+ PRODUCT_NAME = Java(TM)
+ PRODUCT_SUFFIX = SE Runtime Environment
+ JDK_RC_PLATFORM_NAME = Platform SE
+ COMPANY_NAME = Sun Microsystems, Inc.
endif
RUNTIME_NAME = $(PRODUCT_NAME) $(PRODUCT_SUFFIX)
--- a/make/common/shared/Platform.gmk Tue Aug 05 13:06:42 2008 -0700
+++ b/make/common/shared/Platform.gmk Tue Aug 05 13:15:22 2008 -0700
@@ -373,34 +373,40 @@ ifeq ($(PLATFORM), windows)
REQUIRED_DXSDK_VER = 0x0700
OS_VENDOR = Microsoft
# How much RAM does this machine have:
- ifeq ($(USING_CYGWIN),true)
- # CYGWIN has the 'free' utility
- _MB_OF_MEMORY := \
- $(shell free -m | grep Mem: | awk '{print $$2;}' )
- else
- # Windows 2000 has the mem utility, but two memory areas
- # extended memory is what is beyond 1024M
- _B_OF_EXT_MEMORY := \
- $(shell mem 2> $(DEV_NULL) | grep 'total contiguous extended memory' | awk '{print $$1;}')
- ifeq ($(_B_OF_EXT_MEMORY),)
- _B_OF_MEMORY := \
- $(shell mem 2> $(DEV_NULL) | grep 'total conventional memory' | awk '{print $$1;}')
- else
- _B_OF_MEMORY := \
- $(shell expr 1048576 '+' $(_B_OF_EXT_MEMORY) 2> $(DEV_NULL))
- endif
- ifeq ($(_B_OF_MEMORY),)
- # Windows 2003 has the systeminfo utility use it if mem doesn't work
+ ifeq ($(JDK_HAS_MEM_INFO),)
+ ifeq ($(USING_CYGWIN),true)
+ # CYGWIN has the 'free' utility
_MB_OF_MEMORY := \
- $(shell systeminfo 2> $(DEV_NULL) | grep 'Total Physical Memory:' | awk '{print $$4;}' | sed -e 's@,@@')
- else
- _MB_OF_MEMORY := $(shell expr $(_B_OF_MEMORY) '/' 1024 2> $(DEV_NULL))
- endif
- endif
- ifeq ($(shell expr $(_MB_OF_MEMORY) '+' 0 2> $(DEV_NULL)), $(_MB_OF_MEMORY))
- MB_OF_MEMORY := $(_MB_OF_MEMORY)
- else
- MB_OF_MEMORY := 512
+ $(shell free -m | grep Mem: | awk '{print $$2;}' )
+ else
+ # Windows 2000 has the mem utility, but two memory areas
+ # extended memory is what is beyond 1024M
+ _B_OF_EXT_MEMORY := \
+ $(shell mem 2> $(DEV_NULL) | \
+ grep 'total contiguous extended memory' | awk '{print $$1;}')
+ ifeq ($(_B_OF_EXT_MEMORY),)
+ _B_OF_MEMORY := \
+ $(shell mem 2> $(DEV_NULL) | \
+ grep 'total conventional memory' | awk '{print $$1;}')
+ else
+ _B_OF_MEMORY := \
+ $(shell expr 1048576 '+' $(_B_OF_EXT_MEMORY) 2> $(DEV_NULL))
+ endif
+ ifeq ($(_B_OF_MEMORY),)
+ # Windows 2003 has the systeminfo utility use it if mem doesn't work
+ _MB_OF_MEMORY := \
+ $(shell systeminfo 2> $(DEV_NULL) | \
+ grep 'Total Physical Memory:' | \
+ awk '{print $$4;}' | sed -e 's@,@@')
+ else
+ _MB_OF_MEMORY := $(shell expr $(_B_OF_MEMORY) '/' 1024 2> $(DEV_NULL))
+ endif
+ endif
+ ifeq ($(shell expr $(_MB_OF_MEMORY) '+' 0 2> $(DEV_NULL)), $(_MB_OF_MEMORY))
+ MB_OF_MEMORY := $(_MB_OF_MEMORY)
+ else
+ MB_OF_MEMORY := 512
+ endif
endif
endif
@@ -446,30 +452,38 @@ endif
# system swapping during the build.
# If we don't know, assume 512. Subtract 128 from MB for VM MAX.
# Don't set VM max over 1024-128=896.
-ifneq ($(MB_OF_MEMORY),)
- LOW_MEMORY_MACHINE := $(shell \
- if [ $(MB_OF_MEMORY) -le 512 ] ; then \
- echo "true"; \
- else \
- echo "false"; \
- fi)
- MAX_VM_MEMORY := $(shell \
- if [ $(MB_OF_MEMORY) -le 1024 ] ; then \
- expr $(MB_OF_MEMORY) '-' 128 2> $(DEV_NULL) ; \
- else \
- echo "896"; \
- fi)
- MIN_VM_MEMORY := $(shell \
- if [ $(MAX_VM_MEMORY) -le 128 ] ; then \
- expr $(MAX_VM_MEMORY) '-' 8 2> $(DEV_NULL) ; \
- else \
- echo "128"; \
- fi)
-else
- MB_OF_MEMORY := unknown
- LOW_MEMORY_MACHINE := true
- MAX_VM_MEMORY := 384
- MIN_VM_MEMORY := 128
+ifeq ($(JDK_HAS_MEM_INFO),)
+ JDK_HAS_MEM_INFO=true
+ export JDK_HAS_MEM_INFO
+ ifneq ($(MB_OF_MEMORY),)
+ LOW_MEMORY_MACHINE := $(shell \
+ if [ $(MB_OF_MEMORY) -le 512 ] ; then \
+ echo "true"; \
+ else \
+ echo "false"; \
+ fi)
+ MAX_VM_MEMORY := $(shell \
+ if [ $(MB_OF_MEMORY) -le 1024 ] ; then \
+ expr $(MB_OF_MEMORY) '-' 128 2> $(DEV_NULL) ; \
+ else \
+ echo "896"; \
+ fi)
+ MIN_VM_MEMORY := $(shell \
+ if [ $(MAX_VM_MEMORY) -le 128 ] ; then \
+ expr $(MAX_VM_MEMORY) '-' 8 2> $(DEV_NULL) ; \
+ else \
+ echo "128"; \
+ fi)
+ else
+ MB_OF_MEMORY := unknown
+ LOW_MEMORY_MACHINE := true
+ MAX_VM_MEMORY := 384
+ MIN_VM_MEMORY := 128
+ endif
+ export MB_OF_MEMORY
+ export LOW_MEMORY_MACHINE
+ export MAX_VM_MEMORY
+ export MIN_VM_MEMORY
endif
# If blanks in the username, use the first 4 words and pack them together
--- a/make/java/fdlibm/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/fdlibm/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -46,8 +46,6 @@ ifeq ($(PLATFORM),windows)
_OPT = $(CC_NO_OPT)
OTHER_CFLAGS =
CPPFLAGS_DBG += -DLOGGING
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
endif
#
--- a/make/java/hpi/windows/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/hpi/windows/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -37,8 +37,6 @@ include $(BUILDDIR)/common/Defs.gmk
# windows compiler flags
ifeq ($(PLATFORM),windows)
CPPFLAGS_DBG += -DLOGGING
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
endif
FILES_c = \
--- a/make/java/java/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/java/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -37,8 +37,6 @@ include $(BUILDDIR)/common/Defs.gmk
# windows compiler flags
ifeq ($(PLATFORM),windows)
OTHER_CFLAGS =
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
# build directly into BINDIR...
LIB_LOCATION = $(BINDIR)
# Exported functions
--- a/make/java/java_crw_demo/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/java_crw_demo/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -48,11 +48,6 @@ OTHER_INCLUDES = -I$(SRCDIR)
OTHER_INCLUDES = -I$(SRCDIR)
#
-# This removes all asserts in the optimized version
-#
-CPPFLAGS_OPT += -DNDEBUG
-
-#
# Library to compile.
#
include $(BUILDDIR)/common/Library.gmk
--- a/make/java/java_hprof_demo/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/java_hprof_demo/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -92,11 +92,6 @@ INIT += $(LIBDIR)/jvm.hprof.txt
INIT += $(LIBDIR)/jvm.hprof.txt
#
-# This removes all asserts in the optimized version
-#
-CPPFLAGS_OPT += -DNDEBUG
-
-#
# This puts logging code in
#
CPPFLAGS_DBG += -DHPROF_LOGGING
--- a/make/java/jli/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/jli/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -126,9 +126,6 @@ ifeq ($(PLATFORM), windows)
-export:JLI_ManifestIterate \
-export:JLI_SetTraceLauncher
- # Files from zlib built here do not compile with warning level 3
- # if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
endif
OTHER_INCLUDES += -I$(LAUNCHER_SHARE_SRC)
--- a/make/java/module/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/module/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -58,7 +58,7 @@ SYSTEM_EXTENSION_DIR = $(LIBDIR)/module/
#
# Resources
#
-REPOSITORY_METADATA_XML = $(PKGDIR)/RepositoryMetadata.xml
+REPOSITORY_METADATA_XML = $(PKGDIR)/repository-metadata-schema.xml
LOCALE_SET_DEFINITION = jdk
NEW_RESOURCE_BUNDLES_PROPERTIES = sun/module/tools/resources/messenger.properties
@@ -68,7 +68,7 @@ NEW_RESOURCE_BUNDLES_PROPERTIES = sun/mo
#
include $(BUILDDIR)/common/Rules.gmk
-all: classes repository_metadata_xml
+all: classes repository_metadata_schema_xml
build: properties visibilitypolicy importoverridepolicy repositoryprops systemextensiondir
@@ -102,9 +102,9 @@ clean clobber:: .delete.classlist
$(RM) -r $(CLASSBINDIR)/java/module
$(RM) $(PROPS_BUILD) $(VISIBILITY_POLICY_BUILD) $(IMPORT_OVERRIDE_POLICY_BUILD) $(REPOSITORY_PROPS_BUILD)
-repository_metadata_xml: $(CLASSBINDIR)/$(REPOSITORY_METADATA_XML)
+repository_metadata_schema_xml: $(CLASSBINDIR)/$(REPOSITORY_METADATA_XML)
$(CLASSBINDIR)/%.xml: $(SHARE_SRC)/classes/%.xml
$(install-file)
-.PHONY: repository_metadata_xml
+.PHONY: repository_metadata_schema_xml
--- a/make/java/net/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/net/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -94,8 +94,6 @@ include $(BUILDDIR)/common/Library.gmk
ifeq ($(PLATFORM), windows)
OTHER_LDLIBS = ws2_32.lib $(JVMLIB)
- # Will not compile at warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
else
OTHER_LDLIBS = $(LIBSOCKET) -lnsl -ldl $(JVMLIB)
endif
--- a/make/java/nio/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/nio/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -134,7 +134,6 @@ ifeq ($(PLATFORM),windows)
$(OBJDIR)/../../../java.lang/java/$(OBJDIRNAME)/FileDescriptor_md.obj
endif
ifeq ($(PLATFORM), linux)
-COMPILER_WARNINGS_FATAL=true
OTHER_LDLIBS += -L$(LIBDIR)/$(LIBARCH) -ljava -lnet -lpthread -ldl
endif
ifeq ($(PLATFORM), solaris)
--- a/make/java/npt/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/npt/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -53,11 +53,6 @@ OTHER_INCLUDES = -I$(SRCDIR) -I$(PSRCDIR
OTHER_INCLUDES = -I$(SRCDIR) -I$(PSRCDIR)
#
-# This removes all asserts in the optimized version
-#
-CPPFLAGS_OPT += -DNDEBUG
-
-#
# Library to compile.
#
include $(BUILDDIR)/common/Library.gmk
--- a/make/java/verify/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/verify/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -43,8 +43,6 @@ ifeq ($(PLATFORM), windows)
#
JAVALIB =
EXTRA_LIBS =
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
endif
#
--- a/make/java/zip/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/java/zip/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -49,9 +49,6 @@ FILES_export = \
ifneq ($(PLATFORM), windows)
OTHER_CFLAGS += -DUSE_MMAP
-else
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
endif
#
--- a/make/jpda/back/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/jpda/back/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -51,11 +51,6 @@ ifneq ($(PLATFORM), windows)
ifneq ($(PLATFORM), windows)
OTHER_LDLIBS += -ldl
endif # PLATFORM
-
-#
-# This turns off all assert() checking in the optimized library
-#
-CPPFLAGS_OPT += -DNDEBUG
#
# This controls the ability to do logging in the library.
--- a/make/jpda/transport/shmem/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/jpda/transport/shmem/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -35,13 +35,6 @@ FILES_m = mapfile-vers
FILES_m = mapfile-vers
include $(BUILDDIR)/common/Defs.gmk
-
-# 64-bit windows does not build at -W3 if warnings are fatal
-ifeq ($(PLATFORM), windows)
- ifeq ($(ARCH_DATA_MODEL), 64)
- COMPILER_WARNINGS_FATAL=false
- endif
-endif
FILES_c = \
SharedMemoryTransport.c \
--- a/make/jpda/transport/socket/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/jpda/transport/socket/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -35,11 +35,6 @@ FILES_m = mapfile-vers
FILES_m = mapfile-vers
include $(BUILDDIR)/common/Defs.gmk
-
-ifeq ($(PLATFORM), windows)
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
-endif
ifeq ($(PLATFORM), linux)
OTHER_LDLIBS += -lnsl $(LIBSOCKET) -lpthread
--- a/make/sun/cmm/kcms/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/sun/cmm/kcms/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -47,8 +47,6 @@ ifeq ($(PLATFORM), windows)
ifeq ($(PLATFORM), windows)
# Override the default version info with our own resource file (see 5043594)
VERSIONINFO_RESOURCE = $(CLOSED_SRC)/share/native/sun/java2d/cmm/kcms/cmm.rc
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
endif
# Rules
--- a/make/sun/font/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/sun/font/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -77,9 +77,6 @@ FILES_export = \
ifeq ($(PLATFORM), windows)
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
-
LDLIBS += user32.lib gdi32.lib $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib
OTHER_CFLAGS += -DCC_NOEX
--- a/make/sun/font/t2k/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/sun/font/t2k/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -64,9 +64,6 @@ FILES_export = \
ifeq ($(PLATFORM), windows)
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
-
# t2k imports several shared methods from fontmanager.dll
LDLIBS += user32.lib $(OBJDIR)/../../../sun.font/fontmanager/$(OBJDIRNAME)/fontmanager.lib
--- a/make/sun/jdbc/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/sun/jdbc/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -69,11 +69,6 @@ ifneq ($(PLATFORM), windows)
INIT += $(ODBC_FAKE_LIBRARIES)
endif
-ifeq ($(PLATFORM),windows)
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
-endif
-
#
# Rules
#
--- a/make/sun/jpeg/Makefile Tue Aug 05 13:06:42 2008 -0700
+++ b/make/sun/jpeg/Makefile Tue Aug 05 13:15:22 2008 -0700
@@ -73,10 +73,5 @@ include $(BUILDDIR)/common/Library.gmk
#
vpath %.c $(SHARE_SRC)/native/$(PKGDIR)/image/jpeg
-ifeq ($(PLATFORM), windows)
- # Files built here do not compile with warning level 3 if warnings are fatal
- COMPILER_WARNINGS_FATAL=false
-endif # PLATFORM
-
CLASSES.export += java.io.InputStream
--- a/src/share/back/eventFilter.c Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/back/eventFilter.c Tue Aug 05 13:15:22 2008 -0700
@@ -492,14 +492,17 @@ eventFilterRestricted_passesFilter(JNIEn
char *sourceName = 0;
jvmtiError error = JVMTI_FUNC_PTR(gdata->jvmti,GetSourceFileName)
(gdata->jvmti, clazz, &sourceName);
- if (error == JVMTI_ERROR_NONE) {
- if (sourceName == 0 || !patternStringMatch(sourceName, desiredNamePattern)) {
- /* We have no match */
- jvmtiDeallocate(sourceName);
- return JNI_FALSE;
- }
+ if (error == JVMTI_ERROR_NONE &&
+ sourceName != 0 &&
+ patternStringMatch(sourceName, desiredNamePattern)) {
+ // got a hit - report the event
+ jvmtiDeallocate(sourceName);
+ break;
}
+ // We have no match, we have no source file name,
+ // or we got a JVM TI error. Don't report the event.
jvmtiDeallocate(sourceName);
+ return JNI_FALSE;
}
break;
}
--- a/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java Tue Aug 05 13:15:22 2008 -0700
@@ -84,8 +84,13 @@ import com.sun.jmx.mbeanserver.Repositor
import com.sun.jmx.mbeanserver.Repository;
import com.sun.jmx.mbeanserver.NamedObject;
import com.sun.jmx.mbeanserver.Introspector;
+import com.sun.jmx.mbeanserver.MBeanInjector;
+import com.sun.jmx.mbeanserver.NotifySupport;
+import com.sun.jmx.mbeanserver.Repository.RegistrationContext;
import com.sun.jmx.mbeanserver.Util;
import com.sun.jmx.remote.util.EnvHelp;
+import javax.management.DynamicWrapperMBean;
+import javax.management.NotificationBroadcasterSupport;
/**
* This is the default class for MBean manipulation on the agent side. It
@@ -433,36 +438,26 @@ public class DefaultMBeanServerIntercept
if (instance instanceof MBeanRegistration)
preDeregisterInvoke((MBeanRegistration) instance);
- repository.remove(name);
- // may throw InstanceNotFoundException
-
- /**
- * Checks if the unregistered MBean is a ClassLoader
- * If so, it removes the MBean from the default loader repository.
- */
-
- Object resource = getResource(instance);
- if (resource instanceof ClassLoader
- && resource != server.getClass().getClassLoader()) {
- final ModifiableClassLoaderRepository clr =
- instantiator.getClassLoaderRepository();
- if (clr != null) clr.removeClassLoader(name);
- }
-
- // ---------------------
- // Send deletion event
- // ---------------------
- if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
- MBEANSERVER_LOGGER.logp(Level.FINER,
- DefaultMBeanServerInterceptor.class.getName(),
- "unregisterMBean", "Send delete notification of object " +
- name.getCanonicalName());
- }
- sendNotification(MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
- name);
+ final Object resource = getResource(instance);
+
+ // Unregisters the MBean from the repository.
+ // Returns the resource context that was used.
+ // The returned context does nothing for regular MBeans.
+ // For ClassLoader MBeans and JMXNamespace (and JMXDomain)
+ // MBeans - the context makes it possible to unregister these
+ // objects from the appropriate framework artifacts, such as
+ // the CLR or the dispatcher, from within the repository lock.
+ // In case of success, we also need to call context.done() at the
+ // end of this method.
+ //
+ final ResourceContext context =
+ unregisterFromRepository(resource, instance, name);
+
if (instance instanceof MBeanRegistration)
postDeregisterInvoke((MBeanRegistration) instance);
+
+ context.done();
}
public ObjectInstance getObjectInstance(ObjectName name)
@@ -939,15 +934,22 @@ public class DefaultMBeanServerIntercept
}
ObjectName logicalName = name;
-
- if (mbean instanceof MBeanRegistration) {
- MBeanRegistration reg = (MBeanRegistration) mbean;
- logicalName = preRegisterInvoke(reg, name, server);
+ logicalName = preRegister(mbean, server, name);
+
+ // preRegister returned successfully, so from this point on we
+ // must call postRegister(false) if there is any problem.
+ boolean registered = false;
+ boolean registerFailed = false;
+ ResourceContext context = null;
+
+ try {
+ mbean = injectResources(mbean, server, logicalName);
+
if (mbean instanceof DynamicMBean2) {
try {
((DynamicMBean2) mbean).preRegister2(server, logicalName);
+ registerFailed = true; // until we succeed
} catch (Exception e) {
- postRegisterInvoke(reg, false, false);
if (e instanceof RuntimeException)
throw (RuntimeException) e;
if (e instanceof InstanceAlreadyExistsException)
@@ -960,86 +962,102 @@ public class DefaultMBeanServerIntercept
logicalName =
ObjectName.getInstance(nonDefaultDomain(logicalName));
}
- }
-
- checkMBeanPermission(classname, null, logicalName, "registerMBean");
-
- final ObjectInstance result;
- if (logicalName!=null) {
- result = new ObjectInstance(logicalName, classname);
- internal_addObject(mbean, logicalName);
- } else {
- if (mbean instanceof MBeanRegistration)
- postRegisterInvoke((MBeanRegistration) mbean, false, true);
- final RuntimeException wrapped =
- new IllegalArgumentException("No object name specified");
- throw new RuntimeOperationsException(wrapped,
- "Exception occurred trying to register the MBean");
- }
-
- if (mbean instanceof MBeanRegistration)
- postRegisterInvoke((MBeanRegistration) mbean, true, false);
-
- /**
- * Checks if the newly registered MBean is a ClassLoader
- * If so, tell the ClassLoaderRepository (CLR) about it. We do
- * this even if the object is a PrivateClassLoader. In that
- * case, the CLR remembers the loader for use when it is
- * explicitly named (e.g. as the loader in createMBean) but
- * does not add it to the list that is consulted by
- * ClassLoaderRepository.loadClass.
- */
- final Object resource = getResource(mbean);
- if (resource instanceof ClassLoader) {
- final ModifiableClassLoaderRepository clr =
- instantiator.getClassLoaderRepository();
- if (clr == null) {
+
+ checkMBeanPermission(classname, null, logicalName, "registerMBean");
+
+ if (logicalName == null) {
final RuntimeException wrapped =
- new IllegalArgumentException(
- "Dynamic addition of class loaders is not supported");
+ new IllegalArgumentException("No object name specified");
throw new RuntimeOperationsException(wrapped,
- "Exception occurred trying to register the MBean as a class loader");
- }
- clr.addClassLoader(logicalName, (ClassLoader) resource);
- }
-
- return result;
- }
-
- private static ObjectName preRegisterInvoke(MBeanRegistration moi,
- ObjectName name,
- MBeanServer mbs)
- throws InstanceAlreadyExistsException, MBeanRegistrationException {
-
- final ObjectName newName;
-
+ "Exception occurred trying to register the MBean");
+ }
+
+ final Object resource = getResource(mbean);
+
+ // Register the MBean with the repository.
+ // Returns the resource context that was used.
+ // The returned context does nothing for regular MBeans.
+ // For ClassLoader MBeans and JMXNamespace (and JMXDomain)
+ // MBeans - the context makes it possible to register these
+ // objects with the appropriate framework artifacts, such as
+ // the CLR or the dispatcher, from within the repository lock.
+ // In case of success, we also need to call context.done() at the
+ // end of this method.
+ //
+ context = registerWithRepository(resource, mbean, logicalName);
+
+ registerFailed = false;
+ registered = true;
+ } finally {
+ postRegister(mbean, registered, registerFailed);
+ }
+
+ context.done();
+ return new ObjectInstance(logicalName, classname);
+ }
+
+ private static void throwMBeanRegistrationException(Throwable t, String where)
+ throws MBeanRegistrationException {
try {
- newName = moi.preRegister(mbs, name);
+ throw t;
} catch (RuntimeException e) {
- throw new RuntimeMBeanException(e,
- "RuntimeException thrown in preRegister method");
+ throw new RuntimeMBeanException(
+ e, "RuntimeException thrown " + where);
} catch (Error er) {
- throw new RuntimeErrorException(er,
- "Error thrown in preRegister method");
+ throw new RuntimeErrorException(er, "Error thrown " + where);
} catch (MBeanRegistrationException r) {
throw r;
} catch (Exception ex) {
- throw new MBeanRegistrationException(ex,
- "Exception thrown in preRegister method");
+ throw new MBeanRegistrationException(ex, "Exception thrown " + where);
+ } catch (Throwable t1) {
+ throw new RuntimeException(t); // neither Error nor Exception??
+ }
+ }
+
+ private static ObjectName preRegister(
+ DynamicMBean mbean, MBeanServer mbs, ObjectName name)
+ throws InstanceAlreadyExistsException, MBeanRegistrationException {
+
+ ObjectName newName = null;
+
+ try {
+ if (mbean instanceof MBeanRegistration)
+ newName = ((MBeanRegistration) mbean).preRegister(mbs, name);
+ } catch (Throwable t) {
+ throwMBeanRegistrationException(t, "in preRegister method");
}
if (newName != null) return newName;
else return name;
}
- private static void postRegisterInvoke(MBeanRegistration moi,
- boolean registrationDone,
- boolean registerFailed) {
-
- if (registerFailed && moi instanceof DynamicMBean2)
- ((DynamicMBean2) moi).registerFailed();
+ private static DynamicMBean injectResources(
+ DynamicMBean mbean, MBeanServer mbs, ObjectName name)
+ throws MBeanRegistrationException {
try {
- moi.postRegister(registrationDone);
+ Object resource = getResource(mbean);
+ MBeanInjector.inject(resource, mbs, name);
+ if (MBeanInjector.injectsSendNotification(resource)) {
+ NotificationBroadcasterSupport nbs =
+ new NotificationBroadcasterSupport();
+ MBeanInjector.injectSendNotification(resource, nbs);
+ mbean = NotifySupport.wrap(mbean, nbs);
+ }
+ return mbean;
+ } catch (Throwable t) {
+ throwMBeanRegistrationException(t, "injecting @Resources");
+ return null; // not reached
+ }
+ }
+
+ private static void postRegister(
+ DynamicMBean mbean, boolean registrationDone, boolean registerFailed) {
+
+ if (registerFailed && mbean instanceof DynamicMBean2)
+ ((DynamicMBean2) mbean).registerFailed();
+ try {
+ if (mbean instanceof MBeanRegistration)
+ ((MBeanRegistration) mbean).postRegister(registrationDone);
} catch (RuntimeException e) {
throw new RuntimeMBeanException(e,
"RuntimeException thrown in postRegister method");
@@ -1053,17 +1071,8 @@ public class DefaultMBeanServerIntercept
throws MBeanRegistrationException {
try {
moi.preDeregister();
- } catch (RuntimeException e) {
- throw new RuntimeMBeanException(e,
- "RuntimeException thrown in preDeregister method");
- } catch (Error er) {
- throw new RuntimeErrorException(er,
- "Error thrown in preDeregister method");
- } catch (MBeanRegistrationException t) {
- throw t;
- } catch (Exception ex) {
- throw new MBeanRegistrationException(ex,
- "Exception thrown in preDeregister method");
+ } catch (Throwable t) {
+ throwMBeanRegistrationException(t, "in preDeregister method");
}
}
@@ -1104,10 +1113,17 @@ public class DefaultMBeanServerIntercept
}
private static Object getResource(DynamicMBean mbean) {
- if (mbean instanceof DynamicMBean2)
- return ((DynamicMBean2) mbean).getResource();
+ if (mbean instanceof DynamicWrapperMBean)
+ return ((DynamicWrapperMBean) mbean).getWrappedObject();
else
return mbean;
+ }
+
+ private static ClassLoader getResourceLoader(DynamicMBean mbean) {
+ if (mbean instanceof DynamicWrapperMBean)
+ return ((DynamicWrapperMBean) mbean).getWrappedClassLoader();
+ else
+ return mbean.getClass().getClassLoader();
}
private ObjectName nonDefaultDomain(ObjectName name) {
@@ -1123,14 +1139,7 @@ public class DefaultMBeanServerIntercept
if one is supplied where it shouldn't be). */
final String completeName = domain + name;
- try {
- return new ObjectName(completeName);
- } catch (MalformedObjectNameException e) {
- final String msg =
- "Unexpected default domain problem: " + completeName + ": " +
- e;
- throw EnvHelp.initCause(new IllegalArgumentException(msg), e);
- }
+ return Util.newObjectName(completeName);
}
public String getDefaultDomain() {
@@ -1211,7 +1220,7 @@ public class DefaultMBeanServerIntercept
}
NotificationListener listenerWrapper =
- getListenerWrapper(listener, name, broadcaster, true);
+ getListenerWrapper(listener, name, instance, true);
broadcaster.addNotificationListener(listenerWrapper, filter, handback);
}
@@ -1335,7 +1344,6 @@ public class DefaultMBeanServerIntercept
DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, null, name,
"removeNotificationListener");
- Object resource = getResource(instance);
/* We could simplify the code by assigning broadcaster after
assigning listenerWrapper, but that would change the error
@@ -1348,7 +1356,7 @@ public class DefaultMBeanServerIntercept
getNotificationBroadcaster(name, instance, reqClass);
NotificationListener listenerWrapper =
- getListenerWrapper(listener, name, resource, false);
+ getListenerWrapper(listener, name, instance, false);
if (listenerWrapper == null)
throw new ListenerNotFoundException("Unknown listener");
@@ -1366,8 +1374,10 @@ public class DefaultMBeanServerIntercept
private static <T extends NotificationBroadcaster>
T getNotificationBroadcaster(ObjectName name, Object instance,
Class<T> reqClass) {
- if (instance instanceof DynamicMBean2)
- instance = ((DynamicMBean2) instance).getResource();
+ if (reqClass.isInstance(instance))
+ return reqClass.cast(instance);
+ if (instance instanceof DynamicWrapperMBean)
+ instance = ((DynamicWrapperMBean) instance).getWrappedObject();
if (reqClass.isInstance(instance))
return reqClass.cast(instance);
final RuntimeException exc =
@@ -1415,24 +1425,31 @@ public class DefaultMBeanServerIntercept
checkMBeanPermission(instance, null, name, "isInstanceOf");
try {
- if (instance instanceof DynamicMBean2) {
- Object resource = ((DynamicMBean2) instance).getResource();
- ClassLoader loader = resource.getClass().getClassLoader();
- Class<?> c = Class.forName(className, false, loader);
- return c.isInstance(resource);
- }
-
- final String cn = getClassName(instance);
- if (cn.equals(className))
+ Object resource = getResource(instance);
+
+ final String resourceClassName =
+ (resource instanceof DynamicMBean) ?
+ getClassName((DynamicMBean) resource) :
+ resource.getClass().getName();
+
+ if (resourceClassName.equals(className))
return true;
- final ClassLoader cl = instance.getClass().getClassLoader();
+ final ClassLoader cl = getResourceLoader(instance);
final Class<?> classNameClass = Class.forName(className, false, cl);
- if (classNameClass.isInstance(instance))
+ if (classNameClass.isInstance(resource))
return true;
- final Class<?> instanceClass = Class.forName(cn, false, cl);
- return classNameClass.isAssignableFrom(instanceClass);
+ // Ensure that isInstanceOf(NotificationEmitter) is true when
+ // the MBean is a NotificationEmitter by virtue of a @Resource
+ // annotation specifying a SendNotification resource.
+ // This is a hack.
+ if (instance instanceof NotificationBroadcaster &&
+ classNameClass.isAssignableFrom(NotificationEmitter.class))
+ return true;
+
+ final Class<?> resourceClass = Class.forName(resourceClassName, false, cl);
+ return classNameClass.isAssignableFrom(resourceClass);
} catch (Exception x) {
/* Could be SecurityException or ClassNotFoundException */
if (MBEANSERVER_LOGGER.isLoggable(Level.FINEST)) {
@@ -1457,7 +1474,7 @@ public class DefaultMBeanServerIntercept
DynamicMBean instance = getMBean(mbeanName);
checkMBeanPermission(instance, null, mbeanName, "getClassLoaderFor");
- return getResource(instance).getClass().getClassLoader();
+ return getResourceLoader(instance);
}
/**
@@ -1486,40 +1503,6 @@ public class DefaultMBeanServerIntercept
" is not a classloader");
return (ClassLoader) resource;
- }
-
- /**
- * Adds a MBean in the repository
- */
- private void internal_addObject(DynamicMBean object, ObjectName logicalName)
- throws InstanceAlreadyExistsException {
-
- // ------------------------------
- // ------------------------------
-
- // Let the repository do the work.
-
- try {
- repository.addMBean(object, logicalName);
- } catch (InstanceAlreadyExistsException e) {
- if (object instanceof MBeanRegistration) {
- postRegisterInvoke((MBeanRegistration) object, false, true);
- }
- throw e;
- }
-
- // ---------------------
- // Send create event
- // ---------------------
- if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
- MBEANSERVER_LOGGER.logp(Level.FINER,
- DefaultMBeanServerInterceptor.class.getName(),
- "addObject", "Send create notification of object " +
- logicalName.getCanonicalName());
- }
-
- sendNotification(MBeanServerNotification.REGISTRATION_NOTIFICATION,
- logicalName ) ;
}
/**
@@ -1712,9 +1695,10 @@ public class DefaultMBeanServerIntercept
*/
private NotificationListener getListenerWrapper(NotificationListener l,
ObjectName name,
- Object mbean,
+ DynamicMBean mbean,
boolean create) {
- ListenerWrapper wrapper = new ListenerWrapper(l, name, mbean);
+ Object resource = getResource(mbean);
+ ListenerWrapper wrapper = new ListenerWrapper(l, name, resource);
synchronized (listenerWrappers) {
WeakReference<ListenerWrapper> ref = listenerWrappers.get(wrapper);
if (ref != null) {
@@ -1758,6 +1742,7 @@ public class DefaultMBeanServerIntercept
listener.handleNotification(notification, handback);
}
+ @Override
public boolean equals(Object o) {
if (!(o instanceof ListenerWrapper))
return false;
@@ -1774,6 +1759,7 @@ public class DefaultMBeanServerIntercept
*/
}
+ @Override
public int hashCode() {
return (System.identityHashCode(listener) ^
System.identityHashCode(mbean));
@@ -1851,4 +1837,213 @@ public class DefaultMBeanServerIntercept
}
}
+ // ------------------------------------------------------------------
+ //
+ // Dealing with registration of special MBeans in the repository.
+ //
+ // ------------------------------------------------------------------
+
+ /**
+ * A RegistrationContext that makes it possible to perform additional
+ * post registration actions (or post unregistration actions) outside
+ * of the repository lock, once postRegister (or postDeregister) has
+ * been called.
+ * The method {@code done()} will be called in registerMBean or
+ * unregisterMBean, at the end.
+ */
+ private static interface ResourceContext extends RegistrationContext {
+ public void done();
+ /** An empty ResourceContext which does nothing **/
+ public static final ResourceContext NONE = new ResourceContext() {
+ public void done() {}
+ public void registering() {}
+ public void unregistered() {}
+ };
+ }
+
+ /**
+ * Adds a MBean in the repository,
+ * sends MBeanServerNotification.REGISTRATION_NOTIFICATION,
+ * returns ResourceContext for special resources such as ClassLoaders
+ * or JMXNamespaces. For regular MBean this method returns
+ * ResourceContext.NONE.
+ * @return a ResourceContext for special resources such as ClassLoaders
+ * or JMXNamespaces.
+ */
+ private ResourceContext registerWithRepository(
+ final Object resource,
+ final DynamicMBean object,
+ final ObjectName logicalName)
+ throws InstanceAlreadyExistsException,
+ MBeanRegistrationException {
+
+ // Creates a registration context, if needed.
+ //
+ final ResourceContext context =
+ makeResourceContextFor(resource, logicalName);
+
+
+ repository.addMBean(object, logicalName, context);
+ // May throw InstanceAlreadyExistsException
+
+ // ---------------------
+ // Send create event
+ // ---------------------
+ if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
+ MBEANSERVER_LOGGER.logp(Level.FINER,
+ DefaultMBeanServerInterceptor.class.getName(),
+ "addObject", "Send create notification of object " +
+ logicalName.getCanonicalName());
+ }
+
+ sendNotification(
+ MBeanServerNotification.REGISTRATION_NOTIFICATION,
+ logicalName);
+
+ return context;
+ }
+
+ /**
+ * Removes a MBean in the repository,
+ * sends MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
+ * returns ResourceContext for special resources such as ClassLoaders
+ * or JMXNamespaces, or null. For regular MBean this method returns
+ * ResourceContext.NONE.
+ *
+ * @return a ResourceContext for special resources such as ClassLoaders
+ * or JMXNamespaces.
+ */
+ private ResourceContext unregisterFromRepository(
+ final Object resource,
+ final DynamicMBean object,
+ final ObjectName logicalName)
+ throws InstanceNotFoundException {
+
+ // Creates a registration context, if needed.
+ //
+ final ResourceContext context =
+ makeResourceContextFor(resource, logicalName);
+
+
+ repository.remove(logicalName, context);
+
+ // ---------------------
+ // Send deletion event
+ // ---------------------
+ if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
+ MBEANSERVER_LOGGER.logp(Level.FINER,
+ DefaultMBeanServerInterceptor.class.getName(),
+ "unregisterMBean", "Send delete notification of object " +
+ logicalName.getCanonicalName());
+ }
+
+ sendNotification(MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
+ logicalName);
+ return context;
+ }
+
+ /**
+ * Registers a ClassLoader with the CLR.
+ * This method is called by the ResourceContext from within the
+ * repository lock.
+ * @param loader The ClassLoader.
+ * @param logicalName The ClassLoader MBean ObjectName.
+ */
+ private void addClassLoader(ClassLoader loader,
+ final ObjectName logicalName) {
+ /**
+ * Called when the newly registered MBean is a ClassLoader
+ * If so, tell the ClassLoaderRepository (CLR) about it. We do
+ * this even if the loader is a PrivateClassLoader. In that
+ * case, the CLR remembers the loader for use when it is
+ * explicitly named (e.g. as the loader in createMBean) but
+ * does not add it to the list that is consulted by
+ * ClassLoaderRepository.loadClass.
+ */
+ final ModifiableClassLoaderRepository clr =
+ instantiator.getClassLoaderRepository();
+ if (clr == null) {
+ final RuntimeException wrapped =
+ new IllegalArgumentException(
+ "Dynamic addition of class loaders" +
+ " is not supported");
+ throw new RuntimeOperationsException(wrapped,
+ "Exception occurred trying to register" +
+ " the MBean as a class loader");
+ }
+ clr.addClassLoader(logicalName, loader);
+ }
+
+ /**
+ * Unregisters a ClassLoader from the CLR.
+ * This method is called by the ResourceContext from within the
+ * repository lock.
+ * @param loader The ClassLoader.
+ * @param logicalName The ClassLoader MBean ObjectName.
+ */
+ private void removeClassLoader(ClassLoader loader,
+ final ObjectName logicalName) {
+ /**
+ * Removes the MBean from the default loader repository.
+ */
+ if (loader != server.getClass().getClassLoader()) {
+ final ModifiableClassLoaderRepository clr =
+ instantiator.getClassLoaderRepository();
+ if (clr != null) {
+ clr.removeClassLoader(logicalName);
+ }
+ }
+ }
+
+ /**
+ * Creates a ResourceContext for a ClassLoader MBean.
+ * The resource context makes it possible to add the ClassLoader to
+ * (ResourceContext.registering) or resp. remove the ClassLoader from
+ * (ResourceContext.unregistered) the CLR
+ * when the associated MBean is added to or resp. removed from the
+ * repository.
+ *
+ * @param loader The ClassLoader MBean being registered or
+ * unregistered.
+ * @param logicalName The name of the ClassLoader MBean.
+ * @return a ResourceContext that takes in charge the addition or removal
+ * of the loader to or from the CLR.
+ */
+ private ResourceContext createClassLoaderContext(
+ final ClassLoader loader,
+ final ObjectName logicalName) {
+ return new ResourceContext() {
+
+ public void registering() {
+ addClassLoader(loader, logicalName);
+ }
+
+ public void unregistered() {
+ removeClassLoader(loader, logicalName);
+ }
+
+ public void done() {
+ }
+ };
+ }
+
+ /**
+ * Creates a ResourceContext for the given resource.
+ * If the resource does not need a ResourceContext, returns
+ * ResourceContext.NONE.
+ * At this time, only JMXNamespaces and ClassLoaders need a
+ * ResourceContext.
+ *
+ * @param resource The resource being registered or unregistered.
+ * @param logicalName The name of the associated MBean.
+ * @return
+ */
+ private ResourceContext makeResourceContextFor(Object resource,
+ ObjectName logicalName) {
+ if (resource instanceof ClassLoader) {
+ return createClassLoaderContext((ClassLoader) resource,
+ logicalName);
+ }
+ return ResourceContext.NONE;
+ }
}
--- a/src/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java Tue Aug 05 13:15:22 2008 -0700
@@ -686,7 +686,7 @@ public class DefaultMXBeanMappingFactory
final String msg =
"Cannot convert SortedSet with non-null comparator: " +
comparator;
- throw new OpenDataException(msg);
+ throw openDataException(msg, new IllegalArgumentException(msg));
}
}
final Object[] openArray = (Object[])
@@ -800,7 +800,7 @@ public class DefaultMXBeanMappingFactory
final String msg =
"Cannot convert SortedMap with non-null comparator: " +
comparator;
- throw new OpenDataException(msg);
+ throw openDataException(msg, new IllegalArgumentException(msg));
}
}
final TabularType tabularType = (TabularType) getOpenType();
--- a/src/share/classes/com/sun/jmx/mbeanserver/DynamicMBean2.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/DynamicMBean2.java Tue Aug 05 13:15:22 2008 -0700
@@ -25,7 +25,7 @@
package com.sun.jmx.mbeanserver;
-import javax.management.DynamicMBean;
+import javax.management.DynamicWrapperMBean;
import javax.management.MBeanServer;
import javax.management.ObjectName;
@@ -35,17 +35,7 @@ import javax.management.ObjectName;
*
* @since 1.6
*/
-public interface DynamicMBean2 extends DynamicMBean {
- /**
- * The resource corresponding to this MBean. This is the object whose
- * class name should be reflected by the MBean's
- * getMBeanInfo().getClassName() for example. For a "plain"
- * DynamicMBean it will be "this". For an MBean that wraps another
- * object, like javax.management.StandardMBean, it will be the wrapped
- * object.
- */
- public Object getResource();
-
+public interface DynamicMBean2 extends DynamicWrapperMBean {
/**
* The name of this MBean's class, as used by permission checks.
* This is typically equal to getResource().getClass().getName().
--- a/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java Tue Aug 05 13:15:22 2008 -0700
@@ -25,23 +25,39 @@
package com.sun.jmx.mbeanserver;
+import com.sun.jmx.remote.util.EnvHelp;
+import java.beans.BeanInfo;
+import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
+import java.util.logging.Level;
+import javax.management.AttributeNotFoundException;
+import javax.management.Description;
import javax.management.Descriptor;
+import javax.management.DescriptorFields;
import javax.management.DescriptorKey;
import javax.management.DynamicMBean;
import javax.management.ImmutableDescriptor;
+import javax.management.MBean;
import javax.management.MBeanInfo;
+import javax.management.MXBean;
import javax.management.NotCompliantMBeanException;
-
+import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.MXBeanMappingFactory;
+
+import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER;
+import com.sun.jmx.mbeanserver.Util;
import com.sun.jmx.remote.util.EnvHelp;
import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
@@ -133,8 +149,12 @@ public class Introspector {
}
}
- public static void checkCompliance(Class mbeanClass)
- throws NotCompliantMBeanException {
+ public static void checkCompliance(Class<?> mbeanClass)
+ throws NotCompliantMBeanException {
+
+ // Check that @Resource is used correctly (if it used).
+ MBeanInjector.validate(mbeanClass);
+
// Is DynamicMBean?
//
if (DynamicMBean.class.isAssignableFrom(mbeanClass))
@@ -157,21 +177,39 @@ public class Introspector {
} catch (NotCompliantMBeanException e) {
mxbeanException = e;
}
+ // Is @MBean or @MXBean class?
+ // In fact we find @MBean or @MXBean as a hacky variant of
+ // getStandardMBeanInterface or getMXBeanInterface. If we get here
+ // then nothing worked.
final String msg =
"MBean class " + mbeanClass.getName() + " does not implement " +
- "DynamicMBean, neither follows the Standard MBean conventions (" +
- mbeanException.toString() + ") nor the MXBean conventions (" +
- mxbeanException.toString() + ")";
+ "DynamicMBean; does not follow the Standard MBean conventions (" +
+ mbeanException.toString() + "); does not follow the MXBean conventions (" +
+ mxbeanException.toString() + "); and does not have or inherit the @" +
+ MBean.class.getSimpleName() + " or @" + MXBean.class.getSimpleName() +
+ " annotation";
throw new NotCompliantMBeanException(msg);
}
+ /**
+ * <p>Make a DynamicMBean out of the existing MBean object. The object
+ * may already be a DynamicMBean, or it may be a Standard MBean or
+ * MXBean, possibly defined using {@code @MBean} or {@code @MXBean}.</p>
+ * @param mbean the object to convert to a DynamicMBean.
+ * @param <T> a type parameter defined for implementation convenience
+ * (which would have to be removed if this method were part of the public
+ * API).
+ * @return the converted DynamicMBean.
+ * @throws NotCompliantMBeanException if {@code mbean} is not a compliant
+ * MBean object, including the case where it is null.
+ */
public static <T> DynamicMBean makeDynamicMBean(T mbean)
throws NotCompliantMBeanException {
if (mbean == null)
throw new NotCompliantMBeanException("Null MBean object");
if (mbean instanceof DynamicMBean)
return (DynamicMBean) mbean;
- final Class mbeanClass = mbean.getClass();
+ final Class<?> mbeanClass = mbean.getClass();
Class<? super T> c = null;
try {
c = Util.cast(getStandardMBeanInterface(mbeanClass));
@@ -270,7 +308,7 @@ public class Introspector {
* Return <code>null</code> if the MBean is a DynamicMBean,
* or if no MBean interface is found.
*/
- public static Class getMBeanInterface(Class baseClass) {
+ public static Class<?> getMBeanInterface(Class<?> baseClass) {
// Check if the given class implements the MBean interface
// or the Dynamic MBean interface
if (isDynamic(baseClass)) return null;
@@ -291,10 +329,12 @@ public class Introspector {
* @throws NotCompliantMBeanException The specified class is
* not a JMX compliant Standard MBean.
*/
- public static Class getStandardMBeanInterface(Class baseClass)
- throws NotCompliantMBeanException {
- Class current = baseClass;
- Class mbeanInterface = null;
+ public static <T> Class<? super T> getStandardMBeanInterface(Class<T> baseClass)
+ throws NotCompliantMBeanException {
+ if (baseClass.isAnnotationPresent(MBean.class))
+ return baseClass;
+ Class<? super T> current = baseClass;
+ Class<? super T> mbeanInterface = null;
while (current != null) {
mbeanInterface =
findMBeanInterface(current, current.getName());
@@ -321,8 +361,10 @@ public class Introspector {
* @throws NotCompliantMBeanException The specified class is
* not a JMX compliant MXBean.
*/
- public static Class getMXBeanInterface(Class baseClass)
+ public static <T> Class<? super T> getMXBeanInterface(Class<T> baseClass)
throws NotCompliantMBeanException {
+ if (hasMXBeanAnnotation(baseClass))
+ return baseClass;
try {
return MXBeanSupport.findMXBeanInterface(baseClass);
} catch (Exception e) {
@@ -345,22 +387,69 @@ public class Introspector {
* ------------------------------------------
*/
+ static boolean hasMXBeanAnnotation(Class<?> c) {
+ MXBean m = c.getAnnotation(MXBean.class);
+ return (m != null && m.value());
+ }
/**
* Try to find the MBean interface corresponding to the class aName
* - i.e. <i>aName</i>MBean, from within aClass and its superclasses.
**/
- private static Class findMBeanInterface(Class aClass, String aName) {
- Class current = aClass;
+ private static <T> Class<? super T> findMBeanInterface(
+ Class<T> aClass, String aName) {
+ Class<? super T> current = aClass;
while (current != null) {
- final Class[] interfaces = current.getInterfaces();
+ final Class<?>[] interfaces = current.getInterfaces();
final int len = interfaces.length;
for (int i=0;i<len;i++) {
- final Class inter =
- implementsMBean(interfaces[i], aName);
+ Class<? super T> inter = Util.cast(interfaces[i]);
+ inter = implementsMBean(inter, aName);
if (inter != null) return inter;
}
current = current.getSuperclass();
+ }
+ return null;
+ }
+
+ public static String descriptionForElement(AnnotatedElement elmt) {
+ if (elmt == null)
+ return null;
+ Description d = elmt.getAnnotation(Description.class);
+ if (d == null)
+ return null;
+ return d.value();
+ }
+
+ public static String descriptionForParameter(
+ Annotation[] parameterAnnotations) {
+ for (Annotation a : parameterAnnotations) {
+ if (a instanceof Description)
+ return ((Description) a).value();
+ }
+ return null;
+ }
+
+ public static String nameForParameter(
+ Annotation[] parameterAnnotations) {
+ for (Annotation a : parameterAnnotations) {
+ Class<? extends Annotation> ac = a.annotationType();
+ // You'd really have to go out of your way to have more than
+ // one @Name annotation, so we don't check for that.
+ if (ac.getSimpleName().equals("Name")) {
+ try {
+ Method value = ac.getMethod("value");
+ if (value.getReturnType() == String.class &&
+ value.getParameterTypes().length == 0) {
+ return (String) value.invoke(a);
+ }
+ } catch (Exception e) {
+ MBEANSERVER_LOGGER.log(
+ Level.WARNING,
+ "Unexpected exception getting @" + ac.getName(),
+ e);
+ }
+ }
}
return null;
}
@@ -372,47 +461,80 @@ public class Introspector {
return descriptorForAnnotations(annots);
}
+ public static Descriptor descriptorForAnnotation(Annotation annot) {
+ return descriptorForAnnotations(new Annotation[] {annot});
+ }
+
public static Descriptor descriptorForAnnotations(Annotation[] annots) {
if (annots.length == 0)
return ImmutableDescriptor.EMPTY_DESCRIPTOR;
Map<String, Object> descriptorMap = new HashMap<String, Object>();
for (Annotation a : annots) {
- Class<? extends Annotation> c = a.annotationType();
- Method[] elements = c.getMethods();
- for (Method element : elements) {
- DescriptorKey key = element.getAnnotation(DescriptorKey.class);
- if (key != null) {
- String name = key.value();
- Object value;
- try {
- value = element.invoke(a);
- } catch (RuntimeException e) {
- // we don't expect this - except for possibly
- // security exceptions?
- // RuntimeExceptions shouldn't be "UndeclaredThrowable".
- // anyway...
- //
- throw e;
- } catch (Exception e) {
- // we don't expect this
- throw new UndeclaredThrowableException(e);
- }
- value = annotationToField(value);
- Object oldValue = descriptorMap.put(name, value);
- if (oldValue != null && !equals(oldValue, value)) {
- final String msg =
- "Inconsistent values for descriptor field " + name +
- " from annotations: " + value + " :: " + oldValue;
- throw new IllegalArgumentException(msg);
- }
- }
- }
+ if (a instanceof DescriptorFields)
+ addDescriptorFieldsToMap(descriptorMap, (DescriptorFields) a);
+ addAnnotationFieldsToMap(descriptorMap, a);
}
if (descriptorMap.isEmpty())
return ImmutableDescriptor.EMPTY_DESCRIPTOR;
else
return new ImmutableDescriptor(descriptorMap);
+ }
+
+ private static void addDescriptorFieldsToMap(
+ Map<String, Object> descriptorMap, DescriptorFields df) {
+ for (String field : df.value()) {
+ int eq = field.indexOf('=');
+ if (eq < 0) {
+ throw new IllegalArgumentException(
+ "@DescriptorFields string must contain '=': " +
+ field);
+ }
+ String name = field.substring(0, eq);
+ String value = field.substring(eq + 1);
+ addToMap(descriptorMap, name, value);
+ }
+ }
+
+ private static void addAnnotationFieldsToMap(
+ Map<String, Object> descriptorMap, Annotation a) {
+ Class<? extends Annotation> c = a.annotationType();
+ Method[] elements = c.getMethods();
+ for (Method element : elements) {
+ DescriptorKey key = element.getAnnotation(DescriptorKey.class);
+ if (key != null) {
+ String name = key.value();
+ Object value;
+ try {
+ value = element.invoke(a);
+ } catch (RuntimeException e) {
+ // we don't expect this - except for possibly
+ // security exceptions?
+ // RuntimeExceptions shouldn't be "UndeclaredThrowable".
+ // anyway...
+ throw e;
+ } catch (Exception e) {
+ // we don't expect this
+ throw new UndeclaredThrowableException(e);
+ }
+ if (!key.omitIfDefault() ||
+ !equals(value, element.getDefaultValue())) {
+ value = annotationToField(value);
+ addToMap(descriptorMap, name, value);
+ }
+ }
+ }
+ }
+
+ private static void addToMap(
+ Map<String, Object> descriptorMap, String name, Object value) {
+ Object oldValue = descriptorMap.put(name, value);
+ if (oldValue != null && !equals(oldValue, value)) {
+ final String msg =
+ "Inconsistent values for descriptor field " + name +
+ " from annotations: " + value + " :: " + oldValue;
+ throw new IllegalArgumentException(msg);
+ }
}
/**
@@ -473,8 +595,13 @@ public class Introspector {
// The only other possibility is that the value is another
// annotation, or that the language has evolved since this code
// was written. We don't allow for either of those currently.
+ // If it is indeed another annotation, then x will be a proxy
+ // with an unhelpful name like $Proxy2. So we extract the
+ // proxy's interface to use that in the exception message.
+ if (Proxy.isProxyClass(c))
+ c = c.getInterfaces()[0]; // array "can't be empty"
throw new IllegalArgumentException("Illegal type for annotation " +
- "element: " + x.getClass().getName());
+ "element using @DescriptorKey: " + c.getName());
}
// This must be consistent with the check for duplicate field values in
@@ -490,15 +617,15 @@ public class Introspector {
* @param c The interface to be tested
* @param clName The name of the class implementing this interface
*/
- private static Class implementsMBean(Class c, String clName) {
+ private static <T> Class<? super T> implementsMBean(Class<T> c, String clName) {
String clMBeanName = clName + "MBean";
if (c.getName().equals(clMBeanName)) {
return c;
}
- Class[] interfaces = c.getInterfaces();
+ Class<?>[] interfaces = c.getInterfaces();
for (int i = 0;i < interfaces.length; i++) {
if (interfaces[i].getName().equals(clMBeanName))
- return interfaces[i];
+ return Util.cast(interfaces[i]);
}
return null;
--- a/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java Tue Aug 05 13:15:22 2008 -0700
@@ -33,6 +33,10 @@ import java.util.List;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import javax.management.MBean;
+import javax.management.MXBean;
+import javax.management.ManagedAttribute;
+import javax.management.ManagedOperation;
import javax.management.NotCompliantMBeanException;
/**
@@ -125,18 +129,26 @@ class MBeanAnalyzer<M> {
for (Method m : methods) {
final String name = m.getName();
final int nParams = m.getParameterTypes().length;
+ final boolean managedOp = m.isAnnotationPresent(ManagedOperation.class);
+ final boolean managedAttr = m.isAnnotationPresent(ManagedAttribute.class);
+ if (managedOp && managedAttr) {
+ throw new NotCompliantMBeanException("Method " + name +
+ " has both @ManagedOperation and @ManagedAttribute");
+ }
final M cm = introspector.mFrom(m);
String attrName = "";
- if (name.startsWith("get"))
- attrName = name.substring(3);
- else if (name.startsWith("is")
- && m.getReturnType() == boolean.class)
- attrName = name.substring(2);
+ if (!managedOp) {
+ if (name.startsWith("get"))
+ attrName = name.substring(3);
+ else if (name.startsWith("is")
+ && m.getReturnType() == boolean.class)
+ attrName = name.substring(2);
+ }
if (attrName.length() != 0 && nParams == 0
- && m.getReturnType() != void.class) {
+ && m.getReturnType() != void.class && !managedOp) {
// It's a getter
// Check we don't have both isX and getX
AttrMethods<M> am = attrMap.get(attrName);
@@ -153,7 +165,7 @@ class MBeanAnalyzer<M> {
attrMap.put(attrName, am);
} else if (name.startsWith("set") && name.length() > 3
&& nParams == 1 &&
- m.getReturnType() == void.class) {
+ m.getReturnType() == void.class && !managedOp) {
// It's a setter
attrName = name.substring(3);
AttrMethods<M> am = attrMap.get(attrName);
@@ -166,6 +178,9 @@ class MBeanAnalyzer<M> {
}
am.setter = cm;
attrMap.put(attrName, am);
+ } else if (managedAttr) {
+ throw new NotCompliantMBeanException("Method " + name +
+ " has @ManagedAttribute but is not a valid getter or setter");
} else {
// It's an operation
List<M> cms = opMap.get(name);
--- a/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java Tue Aug 05 13:15:22 2008 -0700
@@ -36,20 +36,28 @@ import java.lang.reflect.Type;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
+import java.util.Map;
import java.util.WeakHashMap;
+import javax.management.Description;
import javax.management.Descriptor;
import javax.management.ImmutableDescriptor;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
+import javax.management.MBean;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
+import javax.management.MXBean;
+import javax.management.ManagedAttribute;
+import javax.management.ManagedOperation;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationBroadcaster;
+import javax.management.NotificationInfo;
+import javax.management.NotificationInfos;
import javax.management.ReflectionException;
/**
@@ -153,6 +161,25 @@ abstract class MBeanIntrospector<M> {
abstract MBeanAttributeInfo getMBeanAttributeInfo(String attributeName,
M getter, M setter) throws IntrospectionException;
+ final String getAttributeDescription(
+ String attributeName, String defaultDescription,
+ Method getter, Method setter) throws IntrospectionException {
+ String g = Introspector.descriptionForElement(getter);
+ String s = Introspector.descriptionForElement(setter);
+ if (g == null) {
+ if (s == null)
+ return defaultDescription;
+ else
+ return s;
+ } else if (s == null || g.equals(s)) {
+ return g;
+ } else {
+ throw new IntrospectionException(
+ "Inconsistent @Description on getter and setter for " +
+ "attribute " + attributeName);
+ }
+ }
+
/**
* Construct an MBeanOperationInfo for the given operation based on
* the M it was derived from.
@@ -184,8 +211,12 @@ abstract class MBeanIntrospector<M> {
}
void checkCompliance(Class<?> mbeanType) throws NotCompliantMBeanException {
- if (!mbeanType.isInterface()) {
- throw new NotCompliantMBeanException("Not an interface: " +
+ if (!mbeanType.isInterface() &&
+ !mbeanType.isAnnotationPresent(MBean.class) &&
+ !Introspector.hasMXBeanAnnotation(mbeanType)) {
+ throw new NotCompliantMBeanException("Not an interface and " +
+ "does not have @" + MBean.class.getSimpleName() +
+ " or @" + MXBean.class.getSimpleName() + " annotation: " +
mbeanType.getName());
}
}
@@ -194,7 +225,12 @@ abstract class MBeanIntrospector<M> {
* Get the methods to be analyzed to build the MBean interface.
*/
List<Method> getMethods(final Class<?> mbeanType) throws Exception {
- return Arrays.asList(mbeanType.getMethods());
+ if (mbeanType.isInterface())
+ return Arrays.asList(mbeanType.getMethods());
+
+ final List<Method> methods = newList();
+ getAnnotatedMethods(mbeanType, methods);
+ return methods;
}
final PerInterface<M> getPerInterface(Class<?> mbeanInterface)
@@ -232,8 +268,11 @@ abstract class MBeanIntrospector<M> {
MBeanAnalyzer<M> analyzer) throws IntrospectionException {
final MBeanInfoMaker maker = new MBeanInfoMaker();
analyzer.visit(maker);
- final String description =
+ final String defaultDescription =
"Information on the management interface of the MBean";
+ String description = Introspector.descriptionForElement(mbeanInterface);
+ if (description == null)
+ description = defaultDescription;
return maker.makeMBeanInfo(mbeanInterface, description);
}
@@ -407,7 +446,15 @@ abstract class MBeanIntrospector<M> {
throws NotCompliantMBeanException {
MBeanInfo mbi =
getClassMBeanInfo(resource.getClass(), perInterface);
- MBeanNotificationInfo[] notifs = findNotifications(resource);
+ MBeanNotificationInfo[] notifs;
+ try {
+ notifs = findNotifications(resource);
+ } catch (RuntimeException e) {
+ NotCompliantMBeanException x =
+ new NotCompliantMBeanException(e.getMessage());
+ x.initCause(e);
+ throw x;
+ }
Descriptor d = getSpecificMBeanDescriptor();
boolean anyNotifs = (notifs != null && notifs.length > 0);
if (!anyNotifs && ImmutableDescriptor.EMPTY_DESCRIPTOR.equals(d))
@@ -460,13 +507,43 @@ abstract class MBeanIntrospector<M> {
}
}
+ /*
+ * Add to "methods" every public method that has the @ManagedAttribute
+ * or @ManagedOperation annotation, in the given class or any of
+ * its superclasses or superinterfaces.
+ *
+ * We always add superclass or superinterface methods first, so that
+ * the stable sort used by eliminateCovariantMethods will put the
+ * method from the most-derived class last. This means that we will
+ * see the version of the @ManagedAttribute (or ...Operation) annotation
+ * from that method, which might have a different description or whatever.
+ */
+ private static void getAnnotatedMethods(Class<?> c, List<Method> methods)
+ throws Exception {
+ Class<?> sup = c.getSuperclass();
+ if (sup != null)
+ getAnnotatedMethods(sup, methods);
+ Class<?>[] intfs = c.getInterfaces();
+ for (Class<?> intf : intfs)
+ getAnnotatedMethods(intf, methods);
+ for (Method m : c.getMethods()) {
+ // We are careful not to add m if it is inherited from a parent
+ // class or interface, because duplicate methods lead to nasty
+ // behaviour in eliminateCovariantMethods.
+ if (m.getDeclaringClass() == c &&
+ (m.isAnnotationPresent(ManagedAttribute.class) ||
+ m.isAnnotationPresent(ManagedOperation.class)))
+ methods.add(m);
+ }
+ }
+
static MBeanNotificationInfo[] findNotifications(Object moi) {
if (!(moi instanceof NotificationBroadcaster))
return null;
MBeanNotificationInfo[] mbn =
((NotificationBroadcaster) moi).getNotificationInfo();
if (mbn == null || mbn.length == 0)
- return null;
+ return findNotificationsFromAnnotations(moi.getClass());
MBeanNotificationInfo[] result =
new MBeanNotificationInfo[mbn.length];
for (int i = 0; i < mbn.length; i++) {
@@ -478,11 +555,81 @@ abstract class MBeanIntrospector<M> {
return result;
}
+ private static MBeanNotificationInfo[] findNotificationsFromAnnotations(
+ Class<?> mbeanClass) {
+ Class<?> c = getAnnotatedNotificationInfoClass(mbeanClass);
+ if (c == null)
+ return null;
+ NotificationInfo ni = c.getAnnotation(NotificationInfo.class);
+ NotificationInfos nis = c.getAnnotation(NotificationInfos.class);
+ List<NotificationInfo> list = newList();
+ if (ni != null)
+ list.add(ni);
+ if (nis != null)
+ list.addAll(Arrays.asList(nis.value()));
+ if (list.isEmpty())
+ return null;
+ List<MBeanNotificationInfo> mbnis = newList();
+ for (NotificationInfo x : list) {
+ // The Descriptor includes any fields explicitly specified by
+ // x.descriptorFields(), plus any fields from the contained
+ // @Description annotation.
+ Descriptor d = new ImmutableDescriptor(x.descriptorFields());
+ d = ImmutableDescriptor.union(
+ d, Introspector.descriptorForAnnotation(x.description()));
+ MBeanNotificationInfo mbni = new MBeanNotificationInfo(
+ x.types(), x.notificationClass().getName(),
+ x.description().value(), d);
+ mbnis.add(mbni);
+ }
+ return mbnis.toArray(new MBeanNotificationInfo[mbnis.size()]);
+ }
+
+ private static final Map<Class<?>, WeakReference<Class<?>>>
+ annotatedNotificationInfoClasses = newWeakHashMap();
+
+ private static Class<?> getAnnotatedNotificationInfoClass(Class<?> baseClass) {
+ synchronized (annotatedNotificationInfoClasses) {
+ WeakReference<Class<?>> wr =
+ annotatedNotificationInfoClasses.get(baseClass);
+ if (wr != null)
+ return wr.get();
+ Class<?> c = null;
+ if (baseClass.isAnnotationPresent(NotificationInfo.class) ||
+ baseClass.isAnnotationPresent(NotificationInfos.class)) {
+ c = baseClass;
+ } else {
+ Class<?>[] intfs = baseClass.getInterfaces();
+ for (Class<?> intf : intfs) {
+ Class<?> c1 = getAnnotatedNotificationInfoClass(intf);
+ if (c1 != null) {
+ if (c != null) {
+ throw new IllegalArgumentException(
+ "Class " + baseClass.getName() + " inherits " +
+ "@NotificationInfo(s) from both " +
+ c.getName() + " and " + c1.getName());
+ }
+ c = c1;
+ }
+ }
+ }
+ // Record the result of the search. If no @NotificationInfo(s)
+ // were found, c is null, and we store a WeakReference(null).
+ // This prevents us from having to search again and fail again.
+ annotatedNotificationInfoClasses.put(baseClass,
+ new WeakReference<Class<?>>(c));
+ return c;
+ }
+ }
+
private static MBeanConstructorInfo[] findConstructors(Class<?> c) {
Constructor[] cons = c.getConstructors();
MBeanConstructorInfo[] mbc = new MBeanConstructorInfo[cons.length];
for (int i = 0; i < cons.length; i++) {
- final String descr = "Public constructor of the MBean";
+ String descr = "Public constructor of the MBean";
+ Description d = cons[i].getAnnotation(Description.class);
+ if (d != null)
+ descr = d.value();
mbc[i] = new MBeanConstructorInfo(descr, cons[i]);
}
return mbc;
--- a/src/share/classes/com/sun/jmx/mbeanserver/MBeanSupport.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/MBeanSupport.java Tue Aug 05 13:15:22 2008 -0700
@@ -263,8 +263,12 @@ public abstract class MBeanSupport<M>
return resource.getClass().getName();
}
- public final Object getResource() {
+ public final Object getWrappedObject() {
return resource;
+ }
+
+ public final ClassLoader getWrappedClassLoader() {
+ return resource.getClass().getClassLoader();
}
public final Class<?> getMBeanInterface() {
--- a/src/share/classes/com/sun/jmx/mbeanserver/MXBeanIntrospector.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/MXBeanIntrospector.java Tue Aug 05 13:15:22 2008 -0700
@@ -35,6 +35,7 @@ import java.lang.reflect.Type;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.WeakHashMap;
+import javax.management.Description;
import javax.management.Descriptor;
import javax.management.ImmutableDescriptor;
import javax.management.IntrospectionException;
@@ -43,6 +44,7 @@ import javax.management.MBeanException;
import javax.management.MBeanException;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
+import javax.management.ManagedOperation;
import javax.management.NotCompliantMBeanException;
import javax.management.openmbean.MXBeanMappingFactory;
import javax.management.openmbean.OpenMBeanAttributeInfoSupport;
@@ -180,7 +182,10 @@ class MXBeanIntrospector extends MBeanIn
final boolean isWritable = (setter != null);
final boolean isIs = isReadable && getName(getter).startsWith("is");
- final String description = attributeName;
+ final String description = getAttributeDescription(
+ attributeName, attributeName,
+ getter == null ? null : getter.getMethod(),
+ setter == null ? null : setter.getMethod());
final OpenType<?> openType;
final Type originalType;
@@ -229,13 +234,17 @@ class MXBeanIntrospector extends MBeanIn
MBeanOperationInfo getMBeanOperationInfo(String operationName,
ConvertingMethod operation) {
final Method method = operation.getMethod();
- final String description = operationName;
+ String description = operationName;
/* Ideally this would be an empty string, but
- OMBOperationInfo constructor forbids that. Also, we
- could consult an annotation to get a useful
- description. */
-
- final int impact = MBeanOperationInfo.UNKNOWN;
+ OMBOperationInfo constructor forbids that. */
+ Description d = method.getAnnotation(Description.class);
+ if (d != null)
+ description = d.value();
+
+ int impact = MBeanOperationInfo.UNKNOWN;
+ ManagedOperation annot = method.getAnnotation(ManagedOperation.class);
+ if (annot != null)
+ impact = annot.impact().getCode();
final OpenType<?> returnType = operation.getOpenReturnType();
final Type originalReturnType = operation.getGenericReturnType();
@@ -247,8 +256,15 @@ class MXBeanIntrospector extends MBeanIn
boolean openParameterTypes = true;
Annotation[][] annots = method.getParameterAnnotations();
for (int i = 0; i < paramTypes.length; i++) {
- final String paramName = "p" + i;
- final String paramDescription = paramName;
+ String paramName = Introspector.nameForParameter(annots[i]);
+ if (paramName == null)
+ paramName = "p" + i;
+
+ String paramDescription =
+ Introspector.descriptionForParameter(annots[i]);
+ if (paramDescription == null)
+ paramDescription = paramName;
+
final OpenType<?> openType = paramTypes[i];
final Type originalType = originalParamTypes[i];
Descriptor descriptor =
--- a/src/share/classes/com/sun/jmx/mbeanserver/MXBeanSupport.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/MXBeanSupport.java Tue Aug 05 13:15:22 2008 -0700
@@ -161,7 +161,7 @@ public class MXBeanSupport extends MBean
synchronized (lock) {
this.mxbeanLookup = MXBeanLookup.Plain.lookupFor(server);
- this.mxbeanLookup.addReference(name, getResource());
+ this.mxbeanLookup.addReference(name, getWrappedObject());
this.objectName = name;
}
}
@@ -170,7 +170,7 @@ public class MXBeanSupport extends MBean
public void unregister() {
synchronized (lock) {
if (mxbeanLookup != null) {
- if (mxbeanLookup.removeReference(objectName, getResource()))
+ if (mxbeanLookup.removeReference(objectName, getWrappedObject()))
objectName = null;
}
// XXX: need to revisit the whole register/unregister logic in
--- a/src/share/classes/com/sun/jmx/mbeanserver/Repository.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/Repository.java Tue Aug 05 13:15:22 2008 -0700
@@ -29,6 +29,7 @@ import static com.sun.jmx.defaults.JmxPr
import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -39,7 +40,6 @@ import javax.management.DynamicMBean;
import javax.management.DynamicMBean;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
-import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.RuntimeOperationsException;
@@ -51,6 +51,27 @@ import javax.management.RuntimeOperation
* @since 1.5
*/
public class Repository {
+
+ /**
+ * An interface that allows the caller to get some control
+ * over the registration.
+ * @see #addMBean
+ * @see #remove
+ */
+ public interface RegistrationContext {
+ /**
+ * Called by {@link #addMBean}.
+ * Can throw a RuntimeOperationsException to cancel the
+ * registration.
+ */
+ public void registering();
+
+ /**
+ * Called by {@link #remove}.
+ * Any exception thrown by this method will be ignored.
+ */
+ public void unregistered();
+ }
// Private fields -------------------------------------------->
@@ -115,7 +136,6 @@ public class Repository {
/**
* Builds a new ObjectNamePattern object from an ObjectName pattern
* constituents.
- * @param domain pattern.getDomain().
* @param propertyListPattern pattern.isPropertyListPattern().
* @param propertyValuePattern pattern.isPropertyValuePattern().
* @param canonicalProps pattern.getCanonicalKeyPropertyListString().
@@ -216,16 +236,6 @@ public class Repository {
}
}
- private void addNewDomMoi(final DynamicMBean object, final String dom,
- final ObjectName name) {
- final Map<String,NamedObject> moiTb =
- new HashMap<String,NamedObject>();
- moiTb.put(name.getCanonicalKeyPropertyListString(),
- new NamedObject(name, object));
- domainTb.put(dom, moiTb);
- nbElements++;
- }
-
/** Match a string against a shell-style pattern. The only pattern
characters recognised are <code>?</code>, standing for any one
character, and <code>*</code>, standing for any string of
@@ -306,6 +316,50 @@ public class Repository {
}
}
+ private void addNewDomMoi(final DynamicMBean object,
+ final String dom,
+ final ObjectName name,
+ final RegistrationContext context) {
+ final Map<String,NamedObject> moiTb =
+ new HashMap<String,NamedObject>();
+ final String key = name.getCanonicalKeyPropertyListString();
+ addMoiToTb(object,name,key,moiTb,context);
+ domainTb.put(dom, moiTb);
+ nbElements++;
+ }
+
+ private void registering(RegistrationContext context) {
+ if (context == null) return;
+ try {
+ context.registering();
+ } catch (RuntimeOperationsException x) {
+ throw x;
+ } catch (RuntimeException x) {
+ throw new RuntimeOperationsException(x);
+ }
+ }
+
+ private void unregistering(RegistrationContext context, ObjectName name) {
+ if (context == null) return;
+ try {
+ context.unregistered();
+ } catch (Exception x) {
+ // shouldn't come here...
+ MBEANSERVER_LOGGER.log(Level.FINE,
+ "Unexpected exception while unregistering "+name,
+ x);
+ }
+ }
+
+ private void addMoiToTb(final DynamicMBean object,
+ final ObjectName name,
+ final String key,
+ final Map<String,NamedObject> moiTb,
+ final RegistrationContext context) {
+ registering(context);
+ moiTb.put(key,new NamedObject(name, object));
+ }
+
/**
* Retrieves the named object contained in repository
* from the given objectname.
@@ -355,12 +409,12 @@ public class Repository {
domainTb = new HashMap<String,Map<String,NamedObject>>(5);
if (domain != null && domain.length() != 0)
- this.domain = domain;
+ this.domain = domain.intern(); // we use == domain later on...
else
this.domain = ServiceName.DOMAIN;
- // Creates an new hastable for the default domain
- domainTb.put(this.domain.intern(), new HashMap<String,NamedObject>());
+ // Creates a new hashtable for the default domain
+ domainTb.put(this.domain, new HashMap<String,NamedObject>());
}
/**
@@ -395,10 +449,21 @@ public class Repository {
/**
* Stores an MBean associated with its object name in the repository.
*
- * @param object MBean to be stored in the repository.
- * @param name MBean object name.
- */
- public void addMBean(final DynamicMBean object, ObjectName name)
+ * @param object MBean to be stored in the repository.
+ * @param name MBean object name.
+ * @param context A registration context. If non null, the repository
+ * will call {@link RegistrationContext#registering()
+ * context.registering()} from within the repository
+ * lock, when it has determined that the {@code object}
+ * can be stored in the repository with that {@code name}.
+ * If {@link RegistrationContext#registering()
+ * context.registering()} throws an exception, the
+ * operation is abandonned, the MBean is not added to the
+ * repository, and a {@link RuntimeOperationsException}
+ * is thrown.
+ */
+ public void addMBean(final DynamicMBean object, ObjectName name,
+ final RegistrationContext context)
throws InstanceAlreadyExistsException {
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
@@ -431,7 +496,7 @@ public class Repository {
lock.writeLock().lock();
try {
- // Domain cannot be JMImplementation if entry does not exists
+ // Domain cannot be JMImplementation if entry does not exist
if ( !to_default_domain &&
dom.equals("JMImplementation") &&
domainTb.containsKey("JMImplementation")) {
@@ -440,21 +505,21 @@ public class Repository {
"Repository: domain name cannot be JMImplementation"));
}
- // If domain not already exists, add it to the hash table
+ // If domain does not already exist, add it to the hash table
final Map<String,NamedObject> moiTb = domainTb.get(dom);
if (moiTb == null) {
- addNewDomMoi(object, dom, name);
+ addNewDomMoi(object, dom, name, context);
return;
- }
-
- // Add instance if not already present
- String cstr = name.getCanonicalKeyPropertyListString();
- NamedObject elmt= moiTb.get(cstr);
- if (elmt != null) {
- throw new InstanceAlreadyExistsException(name.toString());
} else {
- nbElements++;
- moiTb.put(cstr, new NamedObject(name, object));
+ // Add instance if not already present
+ String cstr = name.getCanonicalKeyPropertyListString();
+ NamedObject elmt= moiTb.get(cstr);
+ if (elmt != null) {
+ throw new InstanceAlreadyExistsException(name.toString());
+ } else {
+ nbElements++;
+ addMoiToTb(object,name,cstr,moiTb,context);
+ }
}
} finally {
@@ -533,7 +598,7 @@ public class Repository {
// ":*", ":[key=value],*" : names in defaultDomain
// "domain:*", "domain:[key=value],*" : names in the specified domain
- // Surely one of the most frequent case ... query on the whole world
+ // Surely one of the most frequent cases ... query on the whole world
ObjectName name;
if (pattern == null ||
pattern.getCanonicalName().length() == 0 ||
@@ -546,8 +611,7 @@ public class Repository {
// If pattern is not a pattern, retrieve this mbean !
if (!name.isPattern()) {
- final NamedObject no;
- no = retrieveNamedObject(name);
+ final NamedObject no = retrieveNamedObject(name);
if (no != null) result.add(no);
return result;
}
@@ -577,12 +641,22 @@ public class Repository {
return result;
}
+ if (!name.isDomainPattern()) {
+ final Map<String,NamedObject> moiTb = domainTb.get(name.getDomain());
+ if (moiTb == null) return Collections.emptySet();
+ if (allNames)
+ result.addAll(moiTb.values());
+ else
+ addAllMatching(moiTb, result, namePattern);
+ return result;
+ }
+
// Pattern matching in the domain name (*, ?)
char[] dom2Match = name.getDomain().toCharArray();
- for (String domain : domainTb.keySet()) {
- char[] theDom = domain.toCharArray();
+ for (String dom : domainTb.keySet()) {
+ char[] theDom = dom.toCharArray();
if (wildmatch(theDom, dom2Match)) {
- final Map<String,NamedObject> moiTb = domainTb.get(domain);
+ final Map<String,NamedObject> moiTb = domainTb.get(dom);
if (allNames)
result.addAll(moiTb.values());
else
@@ -599,11 +673,21 @@ public class Repository {
* Removes an MBean from the repository.
*
* @param name name of the MBean to remove.
+ * @param context A registration context. If non null, the repository
+ * will call {@link RegistrationContext#unregistered()
+ * context.unregistered()} from within the repository
+ * lock, just after the mbean associated with
+ * {@code name} is removed from the repository.
+ * If {@link RegistrationContext#unregistered()
+ * context.unregistered()} is not expected to throw any
+ * exception. If it does, the exception is logged
+ * and swallowed.
*
* @exception InstanceNotFoundException The MBean does not exist in
* the repository.
*/
- public void remove(final ObjectName name)
+ public void remove(final ObjectName name,
+ final RegistrationContext context)
throws InstanceNotFoundException {
// Debugging stuff
@@ -645,6 +729,9 @@ public class Repository {
if (dom == domain)
domainTb.put(domain, new HashMap<String,NamedObject>());
}
+
+ unregistering(context,name);
+
} finally {
lock.writeLock().unlock();
}
--- a/src/share/classes/com/sun/jmx/mbeanserver/StandardMBeanIntrospector.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/StandardMBeanIntrospector.java Tue Aug 05 13:15:22 2008 -0700
@@ -35,6 +35,7 @@ import javax.management.MBeanAttributeIn
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanOperationInfo;
+import javax.management.ManagedOperation;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationBroadcasterSupport;
@@ -118,22 +119,32 @@ class StandardMBeanIntrospector extends
@Override
MBeanAttributeInfo getMBeanAttributeInfo(String attributeName,
- Method getter, Method setter) {
-
- final String description = "Attribute exposed for management";
- try {
- return new MBeanAttributeInfo(attributeName, description,
- getter, setter);
- } catch (IntrospectionException e) {
- throw new RuntimeException(e); // should not happen
- }
+ Method getter, Method setter) throws IntrospectionException {
+
+ String description = getAttributeDescription(
+ attributeName, "Attribute exposed for management",
+ getter, setter);
+ return new MBeanAttributeInfo(attributeName, description,
+ getter, setter);
}
@Override
MBeanOperationInfo getMBeanOperationInfo(String operationName,
Method operation) {
- final String description = "Operation exposed for management";
- return new MBeanOperationInfo(description, operation);
+ final String defaultDescription = "Operation exposed for management";
+ String description = Introspector.descriptionForElement(operation);
+ if (description == null)
+ description = defaultDescription;
+
+ int impact = MBeanOperationInfo.UNKNOWN;
+ ManagedOperation annot = operation.getAnnotation(ManagedOperation.class);
+ if (annot != null)
+ impact = annot.impact().getCode();
+
+ MBeanOperationInfo mboi = new MBeanOperationInfo(description, operation);
+ return new MBeanOperationInfo(
+ mboi.getName(), mboi.getDescription(), mboi.getSignature(),
+ mboi.getReturnType(), impact, mboi.getDescriptor());
}
@Override
--- a/src/share/classes/com/sun/jmx/mbeanserver/StandardMBeanSupport.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/StandardMBeanSupport.java Tue Aug 05 13:15:22 2008 -0700
@@ -41,26 +41,24 @@ public class StandardMBeanSupport extend
public class StandardMBeanSupport extends MBeanSupport<Method> {
/**
- <p>Construct a Standard MBean that wraps the given resource using the
- given Standard MBean interface.</p>
-
- @param resource the underlying resource for the new MBean.
-
- @param mbeanInterface the interface to be used to determine
- the MBean's management interface.
-
- @param <T> a type parameter that allows the compiler to check
- that {@code resource} implements {@code mbeanInterface},
- provided that {@code mbeanInterface} is a class constant like
- {@code SomeMBean.class}.
-
- @throws IllegalArgumentException if {@code resource} is null or
- if it does not implement the class {@code mbeanInterface} or if
- that class is not a valid Standard MBean interface.
- */
- public <T> StandardMBeanSupport(T resource, Class<T> mbeanInterface)
+ * <p>Construct a Standard MBean that wraps the given resource using the
+ * given Standard MBean interface.</p>
+ *
+ * @param resource the underlying resource for the new MBean.
+ * @param mbeanInterfaceType the class or interface to be used to determine
+ * the MBean's management interface. An interface if this is a
+ * classic Standard MBean; a class if this is a {@code @ManagedResource}.
+ * @param <T> a type parameter that allows the compiler to check
+ * that {@code resource} implements {@code mbeanInterfaceType},
+ * provided that {@code mbeanInterfaceType} is a class constant like
+ * {@code SomeMBean.class}.
+ * @throws IllegalArgumentException if {@code resource} is null or
+ * if it does not implement the class {@code mbeanInterfaceType} or if
+ * that class is not a valid Standard MBean interface.
+ */
+ public <T> StandardMBeanSupport(T resource, Class<T> mbeanInterfaceType)
throws NotCompliantMBeanException {
- super(resource, mbeanInterface, (MXBeanMappingFactory) null);
+ super(resource, mbeanInterfaceType, (MXBeanMappingFactory) null);
}
@Override
@@ -86,13 +84,14 @@ public class StandardMBeanSupport extend
@Override
public MBeanInfo getMBeanInfo() {
MBeanInfo mbi = super.getMBeanInfo();
- Class<?> resourceClass = getResource().getClass();
- if (StandardMBeanIntrospector.isDefinitelyImmutableInfo(resourceClass))
+ Class<?> resourceClass = getWrappedObject().getClass();
+ if (!getMBeanInterface().isInterface() ||
+ StandardMBeanIntrospector.isDefinitelyImmutableInfo(resourceClass))
return mbi;
return new MBeanInfo(mbi.getClassName(), mbi.getDescription(),
mbi.getAttributes(), mbi.getConstructors(),
mbi.getOperations(),
- MBeanIntrospector.findNotifications(getResource()),
+ MBeanIntrospector.findNotifications(getWrappedObject()),
mbi.getDescriptor());
}
}
--- a/src/share/classes/com/sun/jmx/mbeanserver/Util.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/jmx/mbeanserver/Util.java Tue Aug 05 13:15:22 2008 -0700
@@ -38,6 +38,7 @@ import java.util.Set;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
+import java.util.WeakHashMap;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
@@ -69,6 +70,10 @@ public class Util {
static <K, V> Map<K, V> newInsertionOrderMap() {
return new LinkedHashMap<K, V>();
+ }
+
+ static <K, V> WeakHashMap<K, V> newWeakHashMap() {
+ return new WeakHashMap<K, V>();
}
static <E> Set<E> newSet() {
--- a/src/share/classes/com/sun/tools/jdi/EventSetImpl.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/tools/jdi/EventSetImpl.java Tue Aug 05 13:15:22 2008 -0700
@@ -208,8 +208,9 @@ public class EventSetImpl extends ArrayL
}
public String toString() {
- return eventName() + "@" + location().toString() +
- " in thread " + thread().name();
+ return eventName() + "@" +
+ ((location() == null) ? " null" : location().toString()) +
+ " in thread " + thread().name();
}
}
--- a/src/share/classes/com/sun/tools/jdi/MonitorInfoImpl.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/tools/jdi/MonitorInfoImpl.java Tue Aug 05 13:15:22 2008 -0700
@@ -40,11 +40,12 @@ public class MonitorInfoImpl extends Mir
int stack_depth;
MonitorInfoImpl(VirtualMachine vm, ObjectReference mon,
- ThreadReference thread, int dpth) {
+ ThreadReferenceImpl thread, int dpth) {
super(vm);
this.monitor = mon;
this.thread = thread;
this.stack_depth = dpth;
+ thread.addListener(this);
}
--- a/src/share/classes/com/sun/tools/jdi/ThreadReferenceImpl.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/tools/jdi/ThreadReferenceImpl.java Tue Aug 05 13:15:22 2008 -0700
@@ -35,12 +35,34 @@ public class ThreadReferenceImpl extends
static final int SUSPEND_STATUS_SUSPENDED = 0x1;
static final int SUSPEND_STATUS_BREAK = 0x2;
+ private int suspendedZombieCount = 0;
+
+ /*
+ * Some objects can only be created while a thread is suspended and are valid
+ * only while the thread remains suspended. Examples are StackFrameImpl
+ * and MonitorInfoImpl. When the thread resumes, these objects have to be
+ * marked as invalid so that their methods can throw
+ * InvalidStackFrameException if they are called. To do this, such objects
+ * register themselves as listeners of the associated thread. When the
+ * thread is resumed, its listeners are notified and mark themselves
+ * invalid.
+ * Also, note that ThreadReferenceImpl itself caches some info that
+ * is valid only as long as the thread is suspended. When the thread
+ * is resumed, that cache must be purged.
+ * Lastly, note that ThreadReferenceImpl and its super, ObjectReferenceImpl
+ * cache some info that is only valid as long as the entire VM is suspended.
+ * If _any_ thread is resumed, this cache must be purged. To handle this,
+ * both ThreadReferenceImpl and ObjectReferenceImpl register themselves as
+ * VMListeners so that they get notified when all threads are suspended and
+ * when any thread is resumed.
+ */
+
+ // This is cached for the life of the thread
private ThreadGroupReference threadGroup;
- private int suspendedZombieCount = 0;
-
- // This is cached only while the VM is suspended
- private static class Cache extends ObjectReferenceImpl.Cache {
- String name = null;
+
+ // This is cached only while this one thread is suspended. Each time
+ // the thread is resumed, we clear this and start with a fresh one.
+ private static class LocalCache {
JDWP.ThreadReference.Status status = null;
List<StackFrame> frames = null;
int framesStart = -1;
@@ -52,6 +74,17 @@ public class ThreadReferenceImpl extends
boolean triedCurrentContended = false;
}
+ private LocalCache localCache;
+
+ private void resetLocalCache() {
+ localCache = new LocalCache();
+ }
+
+ // This is cached only while all threads in the VM are suspended
+ // Yes, someone could change the name of a thread while it is suspended.
+ private static class Cache extends ObjectReferenceImpl.Cache {
+ String name = null;
+ }
protected ObjectReferenceImpl.Cache newCache() {
return new Cache();
}
@@ -59,8 +92,10 @@ public class ThreadReferenceImpl extends
// Listeners - synchronized on vm.state()
private List<WeakReference<ThreadListener>> listeners = new ArrayList<WeakReference<ThreadListener>>();
+
ThreadReferenceImpl(VirtualMachine aVm, long aRef) {
super(aVm,aRef);
+ resetLocalCache();
vm.state().addListener(this);
}
@@ -72,10 +107,24 @@ public class ThreadReferenceImpl extends
* VMListener implementation
*/
public boolean vmNotSuspended(VMAction action) {
- synchronized (vm.state()) {
- processThreadAction(new ThreadAction(this,
- ThreadAction.THREAD_RESUMABLE));
- }
+ if (action.resumingThread() == null) {
+ // all threads are being resumed
+ synchronized (vm.state()) {
+ processThreadAction(new ThreadAction(this,
+ ThreadAction.THREAD_RESUMABLE));
+ }
+
+ }
+
+ /*
+ * Othewise, only one thread is being resumed:
+ * if it is us,
+ * we have already done our processThreadAction to notify our
+ * listeners when we processed the resume.
+ * if it is not us,
+ * we don't want to notify our listeners
+ * because we are not being resumed.
+ */
return super.vmNotSuspended(action);
}
@@ -191,23 +240,19 @@ public class ThreadReferenceImpl extends
}
private JDWP.ThreadReference.Status jdwpStatus() {
- JDWP.ThreadReference.Status status = null;
- try {
- Cache local = (Cache)getCache();
-
- if (local != null) {
- status = local.status;
- }
- if (status == null) {
- status = JDWP.ThreadReference.Status.process(vm, this);
- if (local != null) {
- local.status = status;
- }
- }
- } catch (JDWPException exc) {
- throw exc.toJDIException();
- }
- return status;
+ JDWP.ThreadReference.Status myStatus = localCache.status;
+ try {
+ if (myStatus == null) {
+ myStatus = JDWP.ThreadReference.Status.process(vm, this);
+ if ((myStatus.suspendStatus & SUSPEND_STATUS_SUSPENDED) != 0) {
+ // thread is suspended, we can cache the status.
+ localCache.status = myStatus;
+ }
+ }
+ } catch (JDWPException exc) {
+ throw exc.toJDIException();
+ }
+ return myStatus;
}
public int status() {
@@ -245,8 +290,7 @@ public class ThreadReferenceImpl extends
public ThreadGroupReference threadGroup() {
/*
- * Thread group can't change, so it's cached more conventionally
- * than other things in this class.
+ * Thread group can't change, so it's cached once and for all.
*/
if (threadGroup == null) {
try {
@@ -260,19 +304,10 @@ public class ThreadReferenceImpl extends
}
public int frameCount() throws IncompatibleThreadStateException {
- int frameCount = -1;
- try {
- Cache local = (Cache)getCache();
-
- if (local != null) {
- frameCount = local.frameCount;
- }
- if (frameCount == -1) {
- frameCount = JDWP.ThreadReference.FrameCount
+ try {
+ if (localCache.frameCount == -1) {
+ localCache.frameCount = JDWP.ThreadReference.FrameCount
.process(vm, this).frameCount;
- if (local != null) {
- local.frameCount = frameCount;
- }
}
} catch (JDWPException exc) {
switch (exc.errorCode()) {
@@ -283,7 +318,7 @@ public class ThreadReferenceImpl extends
throw exc.toJDIException();
}
}
- return frameCount;
+ return localCache.frameCount;
}
public List<StackFrame> frames() throws IncompatibleThreadStateException {
@@ -297,23 +332,25 @@ public class ThreadReferenceImpl extends
/**
* Is the requested subrange within what has been retrieved?
- * local is known to be non-null
- */
- private boolean isSubrange(Cache local,
- int start, int length, List frames) {
- if (start < local.framesStart) {
+ * local is known to be non-null. Should only be called from
+ * a sync method.
+ */
+ private boolean isSubrange(LocalCache localCache,
+ int start, int length) {
+ if (start < localCache.framesStart) {
return false;
}
if (length == -1) {
- return (local.framesLength == -1);
- }
- if (local.framesLength == -1) {
- if ((start + length) > (local.framesStart + frames.size())) {
+ return (localCache.framesLength == -1);
+ }
+ if (localCache.framesLength == -1) {
+ if ((start + length) > (localCache.framesStart +
+ localCache.frames.size())) {
throw new IndexOutOfBoundsException();
}
return true;
}
- return ((start + length) <= (local.framesStart + local.framesLength));
+ return ((start + length) <= (localCache.framesStart + localCache.framesLength));
}
public List<StackFrame> frames(int start, int length)
@@ -329,51 +366,42 @@ public class ThreadReferenceImpl extends
* Private version of frames() allows "-1" to specify all
* remaining frames.
*/
- private List<StackFrame> privateFrames(int start, int length)
+ synchronized private List<StackFrame> privateFrames(int start, int length)
throws IncompatibleThreadStateException {
- List<StackFrame> frames = null;
- try {
- Cache local = (Cache)getCache();
-
- if (local != null) {
- frames = local.frames;
- }
- if (frames == null || !isSubrange(local, start, length, frames)) {
+
+ // Lock must be held while creating stack frames so if that two threads
+ // do this at the same time, one won't clobber the subset created by the other.
+
+ try {
+ if (localCache.frames == null || !isSubrange(localCache, start, length)) {
JDWP.ThreadReference.Frames.Frame[] jdwpFrames
= JDWP.ThreadReference.Frames.
- process(vm, this, start, length).frames;
+ process(vm, this, start, length).frames;
int count = jdwpFrames.length;
- frames = new ArrayList<StackFrame>(count);
-
- // Lock must be held while creating stack frames.
- // so that a resume will not resume a partially
- // created stack.
- synchronized (vm.state()) {
- for (int i = 0; i<count; i++) {
- if (jdwpFrames[i].location == null) {
- throw new InternalException("Invalid frame location");
- }
- StackFrame frame = new StackFrameImpl(vm, this,
- jdwpFrames[i].frameID,
- jdwpFrames[i].location);
- // Add to the frame list
- frames.add(frame);
+ localCache.frames = new ArrayList<StackFrame>(count);
+
+ for (int i = 0; i<count; i++) {
+ if (jdwpFrames[i].location == null) {
+ throw new InternalException("Invalid frame location");
}
- }
- if (local != null) {
- local.frames = frames;
- local.framesStart = start;
- local.framesLength = length;
- }
+ StackFrame frame = new StackFrameImpl(vm, this,
+ jdwpFrames[i].frameID,
+ jdwpFrames[i].location);
+ // Add to the frame list
+ localCache.frames.add(frame);
+ }
+ localCache.framesStart = start;
+ localCache.framesLength = length;
+ return Collections.unmodifiableList(localCache.frames);
} else {
- int fromIndex = start - local.framesStart;
+ int fromIndex = start - localCache.framesStart;
int toIndex;
if (length == -1) {
- toIndex = frames.size() - fromIndex;
+ toIndex = localCache.frames.size() - fromIndex;
} else {
toIndex = fromIndex + length;
}
- frames = frames.subList(fromIndex, toIndex);
+ return Collections.unmodifiableList(localCache.frames.subList(fromIndex, toIndex));
}
} catch (JDWPException exc) {
switch (exc.errorCode()) {
@@ -384,28 +412,18 @@ public class ThreadReferenceImpl extends
throw exc.toJDIException();
}
}
- return Collections.unmodifiableList(frames);
}
public List<ObjectReference> ownedMonitors() throws IncompatibleThreadStateException {
- List<ObjectReference> monitors = null;
- try {
- Cache local = (Cache)getCache();
-
- if (local != null) {
- monitors = local.ownedMonitors;
- }
- if (monitors == null) {
- monitors = Arrays.asList(
+ try {
+ if (localCache.ownedMonitors == null) {
+ localCache.ownedMonitors = Arrays.asList(
(ObjectReference[])JDWP.ThreadReference.OwnedMonitors.
process(vm, this).owned);
- if (local != null) {
- local.ownedMonitors = monitors;
- if ((vm.traceFlags & vm.TRACE_OBJREFS) != 0) {
- vm.printTrace(description() +
- " temporarily caching owned monitors"+
- " (count = " + monitors.size() + ")");
- }
+ if ((vm.traceFlags & vm.TRACE_OBJREFS) != 0) {
+ vm.printTrace(description() +
+ " temporarily caching owned monitors"+
+ " (count = " + localCache.ownedMonitors.size() + ")");
}
}
} catch (JDWPException exc) {
@@ -417,29 +435,22 @@ public class ThreadReferenceImpl extends
throw exc.toJDIException();
}
}
- return monitors;
+ return localCache.ownedMonitors;
}
public ObjectReference currentContendedMonitor()
throws IncompatibleThreadStateException {
- ObjectReference monitor = null;
- try {
- Cache local = (Cache)getCache();
-
- if (local != null && local.triedCurrentContended) {
- monitor = local.contendedMonitor;
- } else {
- monitor = JDWP.ThreadReference.CurrentContendedMonitor.
+ try {
+ if (localCache.contendedMonitor == null &&
+ !localCache.triedCurrentContended) {
+ localCache.contendedMonitor = JDWP.ThreadReference.CurrentContendedMonitor.
process(vm, this).monitor;
- if (local != null) {
- local.triedCurrentContended = true;
- local.contendedMonitor = monitor;
- if ((monitor != null) &&
- ((vm.traceFlags & vm.TRACE_OBJREFS) != 0)) {
- vm.printTrace(description() +
- " temporarily caching contended monitor"+
- " (id = " + monitor.uniqueID() + ")");
- }
+ localCache.triedCurrentContended = true;
+ if ((localCache.contendedMonitor != null) &&
+ ((vm.traceFlags & vm.TRACE_OBJREFS) != 0)) {
+ vm.printTrace(description() +
+ " temporarily caching contended monitor"+
+ " (id = " + localCache.contendedMonitor.uniqueID() + ")");
}
}
} catch (JDWPException exc) {
@@ -450,40 +461,31 @@ public class ThreadReferenceImpl extends
throw exc.toJDIException();
}
}
- return monitor;
+ return localCache.contendedMonitor;
}
public List<MonitorInfo> ownedMonitorsAndFrames() throws IncompatibleThreadStateException {
- List<MonitorInfo> monitors = null;
- try {
- Cache local = (Cache)getCache();
-
- if (local != null) {
- monitors = local.ownedMonitorsInfo;
- }
- if (monitors == null) {
+ try {
+ if (localCache.ownedMonitorsInfo == null) {
JDWP.ThreadReference.OwnedMonitorsStackDepthInfo.monitor[] minfo;
minfo = JDWP.ThreadReference.OwnedMonitorsStackDepthInfo.process(vm, this).owned;
- monitors = new ArrayList<MonitorInfo>(minfo.length);
+ localCache.ownedMonitorsInfo = new ArrayList<MonitorInfo>(minfo.length);
for (int i=0; i < minfo.length; i++) {
JDWP.ThreadReference.OwnedMonitorsStackDepthInfo.monitor mi =
minfo[i];
MonitorInfo mon = new MonitorInfoImpl(vm, minfo[i].monitor, this, minfo[i].stack_depth);
- monitors.add(mon);
- }
-
- if (local != null) {
- local.ownedMonitorsInfo = monitors;
- if ((vm.traceFlags & vm.TRACE_OBJREFS) != 0) {
- vm.printTrace(description() +
- " temporarily caching owned monitors"+
- " (count = " + monitors.size() + ")");
+ localCache.ownedMonitorsInfo.add(mon);
+ }
+
+ if ((vm.traceFlags & vm.TRACE_OBJREFS) != 0) {
+ vm.printTrace(description() +
+ " temporarily caching owned monitors"+
+ " (count = " + localCache.ownedMonitorsInfo.size() + ")");
}
}
- }
} catch (JDWPException exc) {
switch (exc.errorCode()) {
case JDWP.Error.THREAD_NOT_SUSPENDED:
@@ -493,7 +495,7 @@ public class ThreadReferenceImpl extends
throw exc.toJDIException();
}
}
- return monitors;
+ return localCache.ownedMonitorsInfo;
}
public void popFrames(StackFrame frame) throws IncompatibleThreadStateException {
@@ -511,7 +513,7 @@ public class ThreadReferenceImpl extends
}
public void forceEarlyReturn(Value returnValue) throws InvalidTypeException,
- ClassNotLoadedException,
+ ClassNotLoadedException,
IncompatibleThreadStateException {
if (!vm.canForceEarlyReturn()) {
throw new UnsupportedOperationException(
@@ -604,6 +606,9 @@ public class ThreadReferenceImpl extends
iter.remove();
}
}
+
+ // Discard our local cache
+ resetLocalCache();
}
}
}
--- a/src/share/classes/com/sun/tools/jdi/VMAction.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/tools/jdi/VMAction.java Tue Aug 05 13:15:22 2008 -0700
@@ -38,10 +38,18 @@ class VMAction extends EventObject {
static final int VM_NOT_SUSPENDED = 2;
int id;
+ ThreadReference resumingThread;
VMAction(VirtualMachine vm, int id) {
+ this(vm, null, id);
+ }
+
+ // For id = VM_NOT_SUSPENDED, if resumingThread != null, then it is
+ // the only thread that is being resumed.
+ VMAction(VirtualMachine vm, ThreadReference resumingThread, int id) {
super(vm);
this.id = id;
+ this.resumingThread = resumingThread;
}
VirtualMachine vm() {
return (VirtualMachine)getSource();
@@ -49,4 +57,8 @@ class VMAction extends EventObject {
int id() {
return id;
}
+
+ ThreadReference resumingThread() {
+ return resumingThread;
+ }
}
--- a/src/share/classes/com/sun/tools/jdi/VMState.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/tools/jdi/VMState.java Tue Aug 05 13:15:22 2008 -0700
@@ -116,16 +116,25 @@ class VMState {
}
/**
+ * All threads are resuming
+ */
+ void thaw() {
+ thaw(null);
+ }
+
+ /**
* Tell listeners to invalidate suspend-sensitive caches.
- */
- synchronized void thaw() {
+ * If resumingThread != null, then only that thread is being
+ * resumed.
+ */
+ synchronized void thaw(ThreadReference resumingThread) {
if (cache != null) {
if ((vm.traceFlags & vm.TRACE_OBJREFS) != 0) {
vm.printTrace("Clearing VM suspended cache");
}
disableCache();
}
- processVMAction(new VMAction(vm, VMAction.VM_NOT_SUSPENDED));
+ processVMAction(new VMAction(vm, resumingThread, VMAction.VM_NOT_SUSPENDED));
}
private synchronized void processVMAction(VMAction action) {
--- a/src/share/classes/com/sun/tools/jdi/VirtualMachineImpl.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/com/sun/tools/jdi/VirtualMachineImpl.java Tue Aug 05 13:15:22 2008 -0700
@@ -146,8 +146,9 @@ class VirtualMachineImpl extends MirrorI
public boolean threadResumable(ThreadAction action) {
/*
* If any thread is resumed, the VM is considered not suspended.
- */
- state.thaw();
+ * Just one thread is being resumed so pass it to thaw.
+ */
+ state.thaw(action.thread());
return true;
}
--- a/src/share/classes/java/lang/ClassLoader.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/lang/ClassLoader.java Tue Aug 05 13:15:22 2008 -0700
@@ -260,13 +260,13 @@ public abstract class ClassLoader {
* <p>If this class loader is the
* {@linkplain java.module.Module#getClassLoader module class loader}
* of a {@link Module} instance, this method returns that
- * {@code Module} object. Otherwise, it returns null.
+ * {@code Module} object. Otherwise, it returns {@code null}.
*
* @return the {@code Module} instance associated with
* this {@code ClassLoader}, or {@code null}.
- * @throws IllegalStateException if a {@code Module} instance is
- * associated with this {@code ClassLoader} but the
- * {@code Module} instance has not been fully initialized.
+ * @throws IllegalStateException if the {@code Module} instance
+ * associated with this {@code ClassLoader} has not
+ * been <i>fully initialized</i>.
* @since 1.7
*/
public Module getModule() {
--- a/src/share/classes/java/module/ImportOverridePolicy.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/ImportOverridePolicy.java Tue Aug 05 13:15:22 2008 -0700
@@ -29,10 +29,19 @@ import java.util.Map;
import java.util.Map;
/**
- * This interface represents an import override policy in the JAM
- * module system. An import override policy allows deployers to
- * control the resolution of a module instance in the JAM module system
- * by narrowing the version constraints in the import dependencies.
+ * This interface represents an import override policy in the JAM module
+ * system. The import override policy controls the
+ * <a href="ModuleSystem.html#Resolution">resolution</a> of
+ * all initializing module instances in the module system by narrowing
+ * the version constraints in the import dependencies of the module
+ * instances.
+ * <p>
+ * The system's import override policy can be
+ * obtained by invoking the {@link Modules#getImportOverridePolicy()
+ * <tt>getImportOverridePolicy</tt>} method of the {@code Modules} class.
+ * Similarly, the system's import override policy can be set
+ * by invoking the {@link Modules#setImportOverridePolicy(ImportOverridePolicy)
+ * <tt>setImportOverridePolicy</tt>} method of the {@code Modules} class.
* <p>
* @see java.module.ImportDependency
* @see java.module.ModuleDefinition
@@ -43,23 +52,35 @@ public interface ImportOverridePolicy {
public interface ImportOverridePolicy {
/**
- * Returns a map of import dependencies and overridden version constraints
- * for the specified module definition.
+ * Returns a map from {@link ImportDependency} objects to
+ * {@link VersionConstraint} objects for an initializing module
+ * instance of the specified module definition.
* <p>
- * The returned map must contain the same set of import dependencies as
- * in the given {@code map}. For each import dependency in the returned
- * map, the overridden version constraint must be within the boundary of
- * the original version constraint of the import dependency
- * that is returned from the specified module definition's
- * {@link ModuleDefinition#getImportDependencies() getImportDependencies}
- * method.
+ * The given {@code constraints} is constructed from the initializing
+ * module instance's
+ * {@linkplain ModuleDefinition#getImportDependencies imports}.
+ * Implementations of this method should construct a map containing
+ * the elements in the given {@code constraints}, override the
+ * appropriate version constraints of the import dependencies
+ * in the map, and return the map as the result.
+ * <p>
+ * The set of import dependencies in the returned map must be equal
+ * to the set of imports of the initializing module instance.
+ * For each import dependency in the returned map, the corresponding
+ * version constraint <i>R</i> may be {@code null} if the import
+ * dependency is
+ * {@linkplain ImportDependency#isOptional() optional}
+ * and should be ignored by the module system during
+ * <a href="ModuleSystem.html#Resolution">resolution</a>. Otherwise,
+ * <i>R</i> must be within the boundary of the declared version constraint
+ * in the initializing module instance's imports.
*
- * @param importer the importing module definition.
- * @param map an unmodifiable map of import dependencies and
- * overridden version constraints.
- * @return the map of import dependencies and overridden version
- * constraints.
+ * @param moduleDef the module definition.
+ * @param constraints an unmodifiable map from {@link ImportDependency}
+ * objects to overridden {@link VersionConstraint} objects.
+ * @return a map from {@link ImportDependency} objects to
+ * overridden {@link VersionConstraint} objects.
*/
- public abstract Map<ImportDependency, VersionConstraint> narrow(ModuleDefinition importer,
- Map<ImportDependency, VersionConstraint> map);
+ public abstract Map<ImportDependency, VersionConstraint> narrow(ModuleDefinition moduleDef,
+ Map<ImportDependency, VersionConstraint> constraints);
}
--- a/src/share/classes/java/module/ImportPolicy.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/ImportPolicy.java Tue Aug 05 13:15:22 2008 -0700
@@ -29,10 +29,11 @@ import java.util.Map;
import java.util.Map;
/**
- * This interface represents the import policy of a module definition
- * in the JAM module system. The import policy is used to
- * determine the version constraints that should be used to resolve
- * the import dependencies in a module during initialization.
+ * This interface represents the import policy of a module instance
+ * in the JAM module system. The import policy controls the
+ * <a href="ModuleSystem.html#Resolution">resolution</a> of
+ * an initializing module instance by narrowing the version constraints
+ * in the import dependencies of the module instance.
* <p>
* @see java.module.ImportDependency
* @see java.module.ImportOverridePolicy
@@ -46,46 +47,49 @@ public interface ImportPolicy {
public interface ImportPolicy {
/**
- * Returns a map of import dependencies and the associated version
- * constraints that should used when initializing this module instance.
+ * Returns a map from {@link ImportDependency} objects to
+ * {@link VersionConstraint} objects for a module instance of
+ * the specified module definition.
* <p>
- * The list of import dependencies that is returned from the
- * {@code getImportDependencies()} method of the
- * {@code ModuleDefinition} object only reflects the import dependencies
- * with the original version constraints that were specified
- * in the module definition at build time. However, it is possible that
- * deployers might have used the system's import override policy to narrow
- * these version constraints at deployment time to control the actual
- * resolution.
+ * The given {@code constraints} consists of the same set
+ * of import dependencies as the initializing module instance's
+ * {@linkplain ModuleDefinition#getImportDependencies imports}.
+ * For each import dependency in the given {@code constraints},
+ * the corresponding version constraint <i>V</i> represents
+ * the version constraint under consideration by
+ * the module system for
+ * <a href="ModuleSystem.html#Resolution">resolving</a> the
+ * import dependency;
+ * <i>V</i> may be {@code null} if the import dependency is
+ * {@linkplain ImportDependency#isOptional() optional}
+ * and should be ignored by the module system.
* <p>
- * Some implementations may use the map of import dependencies and
- * overridden version constraints to determine if the version constraint of
- * an import has been overridden. The map is passed in one of the
- * parameters of this method.
+ * Implementations of this method should construct a map containing the
+ * elements in the given {@code constraints}, override the appropriate
+ * version constraints of the import dependencies in the
+ * map, and return the map as the result. Implementations of this method
+ * may also use the given {@code defaultImportPolicy} object to determine
+ * the result of the default resolution in the module system.
* <p>
- * Some implementations may use the default import policy instance for
- * determining the map of import dependencies and default version
- * constraints for resolving, and it is passed in one of the parameters of
- * this method.
- * <p>
- * Implementations must return a map of import dependencies and
- * version constraints after resolving the imports. If an import cannot
- * be resolved and the import dependency is mandatory (i.e. non-optional),
- * {@code UnsatisfiedDependencyException} must be thrown. If an import
- * cannot be resolved and the import dependency is optional, {@code null}
- * must be used to represent the version constraint of the missing import
- * in the map.
+ * The set of import dependencies in the returned map must be equal to the
+ * set of imports of the initializing module instance.
+ * For each import dependency in the returned map, the corresponding
+ * version constraint <i>R</i> may be {@code null} if the import
+ * dependency is optional and should be ignored by the module system during
+ * resolution. Otherwise, <i>R</i> must be within the boundary of the
+ * declared version constraint in the initializing module instance's
+ * imports.
*
- * @param moduleDef the module definition of this module instance.
- * @param constraints an unmodifiable map of import dependencies and
- * overridden version constraints.
+ * @param moduleDef the module definition.
+ * @param constraints an unmodifiable map from {@link ImportDependency}
+ * objects to overridden {@link VersionConstraint} objects.
* @param defaultImportPolicy the default import policy for this module
* instance.
+ * @return a map from {@link ImportDependency} objects to
+ * overridden {@link VersionConstraint} objects.
* @throws UnsatisfiedDependencyException if an import dependency cannot
* be satisfied.
* @throws ModuleInitializationException if there is other error.
- * @return a map of import dependencies and overridden version constraints
- * for preparing this module instance in the resolving process.
*/
public Map<ImportDependency, VersionConstraint> getImports(ModuleDefinition moduleDef,
Map<ImportDependency,VersionConstraint> constraints, ImportPolicy defaultImportPolicy)
--- a/src/share/classes/java/module/Module.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/Module.java Tue Aug 05 13:15:22 2008 -0700
@@ -97,8 +97,6 @@ public abstract class Module {
* @throws SecurityException if a security manager exists and its
* {@code checkPermission} method denies access to the class loader
* for this {@code Module}.
- * @throws IllegalStateException if the class loader has not yet been
- * created during module initialization.
*/
public abstract ClassLoader getClassLoader();
@@ -106,9 +104,6 @@ public abstract class Module {
* Returns an unmodifiable list of imported module instances.
*
* @return an unmodifiable list of imported module instances.
- * @throws IllegalStateException if the list of imported
- * module instances has not yet been created during module
- * initialization.
*/
public abstract List<Module> getImportedModules();
@@ -175,9 +170,6 @@ public abstract class Module {
builder.append(getModuleDefinition().getName());
builder.append(" v");
builder.append(getModuleDefinition().getVersion());
- builder.append(" (");
- builder.append(getModuleDefinition().getRepository().getName());
- builder.append(" repository)");
return builder.toString();
}
--- a/src/share/classes/java/module/ModuleDefinition.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/ModuleDefinition.java Tue Aug 05 13:15:22 2008 -0700
@@ -111,10 +111,22 @@ public abstract class ModuleDefinition {
public abstract class ModuleDefinition {
/**
- * Constructor used by subclasses.
+ * Creates a {@code ModuleDefinition} instance.
+ * <p>
+ * If a security manager is present, this method calls the security
+ * manager's {@code checkPermission} method with
+ * {@code ModuleSystemPermission("createModuleDefinition")} permission to
+ * ensure it's ok to create a module definition.
+ *
+ * @throws SecurityException if a security manager exists and its
+ * {@code checkPermission} method denies access to create a new
+ * module definition.
*/
protected ModuleDefinition() {
- // empty
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ sm.checkPermission(new ModuleSystemPermission("createModuleDefinition"));
+ }
}
/**
@@ -187,6 +199,23 @@ public abstract class ModuleDefinition {
* @return the {@code ModuleSystem} object.
*/
public abstract ModuleSystem getModuleSystem();
+
+ /**
+ * Returns the module archive information that is associated with this
+ * {@code ModuleDefinition}.
+ * <p>
+ * If a security manager is present, this method calls the security
+ * manager's {@code checkPermission} method with a
+ * {@code ModuleSystemPermission("getModuleArchiveInfo")}
+ * permission to ensure it's ok to access the module archive
+ * info of this {@code ModuleDefinition}.
+ *
+ * @return the {@code ModuleArchiveInfo} object.
+ * @throws SecurityException if a security manager exists and
+ * its {@code checkPermission} method denies access
+ * to the module archive info of this {@code ModuleDefinition}.
+ */
+ public abstract ModuleArchiveInfo getModuleArchiveInfo();
/**
* Returns the name of the main class in this {@code ModuleDefinition}.
@@ -380,7 +409,7 @@ public abstract class ModuleDefinition {
* <p>
* If a security manager is present, this method calls the security
* manager's {@code checkPermission} method with a
- * {@code ModuleSystemPermission("accessModuleContent")}
+ * {@code ModuleSystemPermission("getModuleContent")}
* permission to ensure it's ok to access the content of this
* {@code ModuleDefinition}.
*
@@ -432,9 +461,6 @@ public abstract class ModuleDefinition {
builder.append(getName());
builder.append(" v");
builder.append(getVersion());
- builder.append(" (");
- builder.append(getRepository().getName());
- builder.append(" repository)");
return builder.toString();
}
}
--- a/src/share/classes/java/module/ModuleInitializer.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/ModuleInitializer.java Tue Aug 05 13:15:22 2008 -0700
@@ -27,11 +27,16 @@ package java.module;
/**
* This interface represents a module initializer of a module instance
- * specifically in the JAM module system. The
- * {@link #initialize(Module) initialize} method is invoked when
- * the module system initializes a module instance; the
- * {@link #release(Module) release} method is invoked when that module
- * instance is released from the module system.
+ * specifically in the JAM module system.
+ * <p>
+ * The
+ * {@link #initialize(ModuleDefinition) initialize} method is invoked when
+ * the module system initializes the module instance; the module system must
+ * cause the module initialization to fail if this method
+ * throws any exception. The
+ * {@link #release() release} method is invoked when the module system
+ * releases the module instance; the module system must
+ * ignore any exception being thrown in this method.
* <p>
* @see java.module.Module
* @see java.module.ModuleDefinition
@@ -43,69 +48,34 @@ public interface ModuleInitializer {
public interface ModuleInitializer {
/**
- * This method is invoked when a module instance is initializing in the
- * module system. It is invoked after the module instance has been shallow
- * validated successfully, but before the module instance becomes ready.
+ * This method is invoked when a module instance is being initialized in the
+ * module system.
* <p>
- * If this method throws any exception during execution, it will cause the
- * module instance's initialization to fail.
- * <p>
- * Note that when this method is invoked, it is possible that some of the
- * imported modules are still in the middle of the initialization, and
- * there are two potential issues:
- * <p>
- * 1. The exported classes from an imported module are not guaranteed
- * to be accessible from this method.<p>
- * 2. If an imported module have a module initializer, its
- * {@link #initialize(Module) initialize} method may not yet been invoked.
- * <p>
- * Implementations of this method should avoid accessing classes from the
- * imported modules, and should make no assumption that the imported
- * modules have been fully intitalized. Otherwise, the result is
- * undeterministic.
- * <p>
- * Note that the module instance passed as the argument of this method has
- * not been fully initialized.
+ * The imported module instances of the
+ * initializing module instance may not be <i>fully initialized</i> when this
+ * method is invoked; the exported classes from the imported
+ * module instances of the initializing module instance may not be
+ * accessible from this method.
*
- * @param module the {@code Module} instance to be initialized.
+ * @param moduleDef the {@code ModuleDefinition} associated with the
+ * initializing module instance.
* @throws ModuleInitializationException if this {@code ModuleInitializer}
* fails to initialize.
*/
- public void initialize(Module module) throws ModuleInitializationException;
+ public void initialize(ModuleDefinition moduleDef) throws ModuleInitializationException;
/**
- * This method is invoked when a module instance is released from the
- * module system. It is invoked in the following situations:
+ * This method is invoked when a module instance is being released from the
+ * module system. There is no guarantee that this method is ever
+ * invoked when the virtual machine exits.
* <p>
- * 1. The {@link #initialize(Module) initialize} method has been
- * invoked successfully, but this module instance still gets into error
- * state because one or more of its imported modules get into error
- * state, or<p>
- * 2. After the {@link ModuleSystem#releaseModule(ModuleDefinition) releaseModule}
- * method of the {@code ModuleSystem} is invoked.
+ * The module instance may not be <i>fully initialized</i> when
+ * this method is invoked.
* <p>
- * In the first situation, the module instance passed as the argument of
- * this method is in error state. The only methods in {@code Module} that
- * the implementation of this method could invoke reliably are
- * {@code Module}'s
- * {@link Module#getModuleDefinition() <tt>getModuleDefinition</tt>},
- * {@link Module#hashCode() <tt>hashCode</tt>}, and
- * {@link Module#toString() <tt>toString</tt>} methods.
- * Otherwise, the result is undeterministric.
- * <p>
- * Note that after this method is invoked, the module classloader of this
- * module instance might still be accessible from other modules. If the
- * implementation of this method attempt to reset some states or
- * shutdown some functionalities in this module instance, this could be
- * problematic for the importing modules if they continue to access this
- * module instance after this module instance has been released.
- * <p>
- * Also, when the virtual machine exits, there is no guarantee that this
- * method is ever invoked even if the
- * {@link #initialize(Module) initialize} method has been invoked
- * successfully.
- *
- * @param module the {@code Module} instance to be released.
+ * The imported module instances of the module instance may
+ * not be fully initialized when this method is invoked;
+ * the exported classes from the imported module instances of
+ * the module instance may not be accessible from this method.
*/
- public void release(Module module);
+ public void release();
}
--- a/src/share/classes/java/module/ModuleSystemPermission.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/ModuleSystemPermission.java Tue Aug 05 13:15:22 2008 -0700
@@ -52,6 +52,32 @@ at the permission allows, and associated
* load their rogue modules and classes into the system.</td>
* </tr>
* <tr>
+ * <td>createModuleDefinition</td>
+ * <td>Creation of a module definition.</td>
+ * <td>This is an extremely dangerous permission to grant. Malicious
+ * applications that can instantiate their own module definitions could
+ * then load their rogue modules and classes into the system through an
+ * existing module system.</td>
+ * </tr>
+ * <tr>
+ * <td>createRepository</td>
+ * <td>Creation of a repository.</td>
+ * <td>This is an extremely dangerous permission to grant. Malicious
+ * applications that can instantiate their own repositories could then
+ * load their rogue modules and classes into the system.</td>
+ * </tr>
+ * <tr>
+ * <td>disableModuleDefinition</td>
+ * <td>Disables a module definition in a module system via calls to
+ * the {@code ModuleSystem}'s
+ * {@link ModuleSystem#disableModuleDefinition(ModuleDefinition)
+ * <tt>disableModuleDefinition</tt>} method.</td>
+ * <td>This is an extremely dangerous permission to grant. Malicious
+ * applications could allow an attacker to perform denial-of-service
+ * attacks by disabling a module definition, and the module system will
+ * not create any new module instances from the module definition.</td>
+ * </tr>
+ * <tr>
* <td>releaseModule</td>
* <td>Releases an existing module instance from a module system via calls to
* the {@code ModuleSystem}'s
@@ -59,20 +85,8 @@ at the permission allows, and associated
* <tt>releaseModule</tt>} method.</td>
* <td>This is a dangerous permission to grant. Malicious applications could
* allow an attacker to release an existing module instance, so the
- * runtime characteristics of the Java virtual machine is changed
- * unexpectedly and it could cause the system to misbehave.</td>
- * </tr>
- * <tr>
- * <td>disableModuleDefinition</td>
- * <td>Disables a module definition in a module system via calls to
- * the {@code ModuleSystem}'s
- * {@link ModuleSystem#disableModuleDefinition(ModuleDefinition)
- * <tt>disableModuleDefinition</tt>} method.</td>
- * <td>This is an extremely dangerous permission to grant. Malicious
- * applications could allow an attacker to perform denial-of-service
- * attack by disabling a module definition, and the module system will be
- * disallowed from creating any new module instance from that disabled
- * module definition.</td>
+ * runtime characteristics of the Java virtual machine are changed
+ * unexpectedly and could cause the system to misbehave.</td>
* </tr>
* <tr>
* <td>installModuleArchive</td>
@@ -98,13 +112,6 @@ at the permission allows, and associated
* repository.</td>
* </tr>
* <tr>
- * <td>createRepository</td>
- * <td>Creation of a repository.</td>
- * <td>This is an extremely dangerous permission to grant. Malicious
- * applications that can instantiate their own repositories could then
- * load their rogue modules and classes into the system.</td>
- * </tr>
- * <tr>
* <td>shutdownRepository</td>
* <td>Shutdown a repository via calls
* to the {@code Repository}'s {@link Repository#shutdown()
@@ -117,27 +124,59 @@ at the permission allows, and associated
* <td>Reloads module definitions in a repository via calls
* to the {@code Repository}'s {@link Repository#reload()
* <tt>reload</tt>} method.</td>
- * <td>This allows an attacker to invalidate the lifetime of the outstanding
- * module instances instantiated from the module definitions in the
- * repository.</td>
- * </tr>
- * <tr>
- * <td>accessModuleContent</td>
- * <td>Accesses the content of the module definition via calls
- * to the {@code ModuleDefinition}'s {@link ModuleDefinition#getModuleContent()
+ * <td>This allows an attacker to reload the module definitions
+ * in the repository, so the runtime characteristics of the
+ * Java virtual machine are changed unexpectedly and could
+ * cause the system to misbehave.</td>
+ * </tr>
+ * <tr>
+ * <td>getModuleArchiveInfo</td>
+ * <td>Gets the module archive info of the module definition via calls
+ * to the {@code ModuleDefinition}'s
+ * {@link ModuleDefinition#getModuleArchiveInfo()
+ * <tt>getModuleArchiveInfo</tt>} method.</td>
+ * <td>This allows an attacker to access the module archive info of
+ * the module definition, which may has sensitive information.</td>
+ * </tr>
+ * <tr>
+ * <td>getModuleContent</td>
+ * <td>Gets the content of the module definition via calls
+ * to the {@code ModuleDefinition}'s
+ * {@link ModuleDefinition#getModuleContent()
* <tt>getModuleContent</tt>} method.</td>
- * <td>This allows an attacker to have access to the actual content of the
- * module definition, which may contain sensitive information internally.</td>
+ * <td>This allows an attacker to access the content of the
+ * module definition, which may contain sensitive information.</td>
+ * </tr>
+ * <tr>
+ * <td>getVisibilityPolicy</td>
+ * <td>Gets the system's visibility policy
+ * via calls to the {@code Modules}'s
+ * {@link Modules#getVisibilityPolicy()
+ * <tt>getVisibilityPolicy</tt>} method.</td>
+ * .</td>
+ * <td>This allows an attacker to determine which module definitions
+ * are visible.</td>
* </tr>
* <tr>
* <td>setImportOverridePolicy</td>
- * <td>Changes the default import override policy in the JAM module system via calls
- * to the {@code Modules}'s
+ * <td>Changes the system's import override policy in the JAM module system
+ * via calls to the {@code Modules}'s
* {@link Modules#setImportOverridePolicy(ImportOverridePolicy)
* <tt>setImportOverridePolicy</tt>} method.</td>
* .</td>
- * <td>This allows an attacker to choose specific versions of imported
- * modules when a module instance is initialized.</td>
+ * <td>This allows an attacker to install a malicious import override
+ * policy to control the resolution of module instances in the JAM
+ * module system.</td>
+ * </tr>
+ * <tr>
+ * <td>getImportOverridePolicy</td>
+ * <td>Gets the system's import override policy in the JAM module system
+ * via calls to the {@code Modules}'s
+ * {@link Modules#getImportOverridePolicy()
+ * <tt>getImportOverridePolicy</tt>} method.</td>
+ * .</td>
+ * <td>This allows an attacker to determine the resolution result of module
+ * instances in the JAM module system.</td>
* </tr>
* <tr>
* <td>addModuleSystemListener</td>
@@ -145,8 +184,7 @@ at the permission allows, and associated
* calls to the {@code ModuleSystem}'s
* {@link ModuleSystem#addModuleSystemListener(ModuleSystemListener)
* <tt>addModuleSystemListener</tt>} method.</td>
- * <td>This allows an attacker to monitor the module system events in the
- * module systems.</td>
+ * <td>This allows an attacker to monitor the events in the module systems.</td>
* </tr>
* <tr>
* <td>removeModuleSystemListener</td>
@@ -154,8 +192,8 @@ at the permission allows, and associated
* via calls to the {@code ModuleSystem}'s
* {@link ModuleSystem#removeModuleSystemListener(ModuleSystemListener)
* <tt>removeModuleSystemListener</tt>} method.</td>
- * <td>This allows an attacker to remove a system-provided module system
- * listener from the module systems.</td>
+ * <td>This allows an attacker to remove a system-provided event listener from
+ * the module systems.</td>
* </tr>
* <tr>
* <td>addRepositoryListener</td>
@@ -163,8 +201,7 @@ at the permission allows, and associated
* via calls to the {@code Repository}'s
* {@link Repository#addRepositoryListener(RepositoryListener)
* <tt>addRepositoryListener</tt>} method.</td>
- * <td>This allows an attacker to monitor the repository events in the
- * repositories.</td>
+ * <td>This allows an attacker to monitor the events in the repositories.</td>
* </tr>
* <tr>
* <td>removeRepositoryListener</td>
@@ -172,7 +209,7 @@ at the permission allows, and associated
* via calls to the {@code Repository}'s
* {@link Repository#removeRepositoryListener(RepositoryListener)
* <tt>removeRepositoryListener</tt>} method.</td>
- * <td>This allows an attacker to remove a system-provided repository
+ * <td>This allows an attacker to remove a system-provided event
* listener from the repositories.</td>
* </tr>
* </table>
--- a/src/share/classes/java/module/Modules.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/Modules.java Tue Aug 05 13:15:22 2008 -0700
@@ -27,10 +27,15 @@ package java.module;
import java.io.File;
import java.io.IOException;
+import java.nio.ByteBuffer;
import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.List;
import java.util.Map;
+import java.util.WeakHashMap;
import sun.module.core.JamModuleDefinition;
+import sun.module.core.ModuleSystemImpl;
import sun.module.config.DefaultImportOverridePolicy;
import sun.module.config.DefaultVisibilityPolicy;
import sun.module.config.ModuleSystemConfig;
@@ -56,96 +61,41 @@ import sun.module.repository.URLReposito
* <h3> ModuleDefinition</h3>
* The JAM module system provides a concrete {@link ModuleDefinition}
* implementation for JAM modules. Applications can obtain the
- * {@code ModuleDefinition} objects by calling the
- * {@link #newModuleDefinition(byte[], ModuleContent,Repository,boolean)
- * <tt>newModuleDefinition</tt>} factory method.
+ * {@code ModuleDefinition} objects by calling one of the
+ * {@link #newModuleDefinition(java.nio.ByteBuffer,ModuleContent,Repository,boolean)
+ * <tt>newModuleDefinition</tt>} factory methods.
* <p>
* <h3> Repository</h3>
* The JAM module system provides two concrete repository implementations:
- * <i>Local repository</i> and <i>URL repository</i>. Both repository
- * implementations must support the JAM file format as described in the JAM
- * Module System Specification. Both repository implementations must also
- * validate the integrity of a JAM file when the file is installed.
- * <p>
- * <A NAME="SelectionPolicy"></A><h5>Selection policy for JAM modules</h5>
- *
- * Local repository and URL repository have both platform-neutral and
- * <a href="package-summary.html#PlatformSpecificModules">platform-specific modules</a>
- * installed. Implementations of these repositories must use the following
- * policy to select the set of JAM modules appropriate for the platform and
- * architecture of the system:
- * <ul>
- * <li><p>JAM module with platform binding which does not match
- * the platform and architecture of the system is ignored.
- * </p></li>
- *
- * <li><p>JAM module with platform binding which matches
- * the system's platform and architecture is preferred
- * over the JAM module of the same name and version with no
- * platform binding.</p></li>
- * </ul>
- *
- * <h4>Local Repository</h4>
+ * <i>Local repository</i> and <i>URL repository</i>. Both repositories
+ * support the JAM file format as described in the JAM Module System
+ * Specification.
+ *
+ * <h4>Local repository</h4>
* <i>Local repository</i> supports loading JAM modules from a directory on
* a file system. Different repository instances in the same or different
- * Java virtual machines can process the
- * JAM modules from the same directory for sharing purposes. Hence, the
- * directory is also called <i>repository interchange directory</i>.
- * <p>
- * A local repository must follow the policy below to
- * process JAM modules in the repository interchange directory, when the
+ * Java virtual machines can process the JAM modules from the same directory
+ * for sharing purposes. Hence, the directory is called
+ * <i>repository interchange directory</i>.
+ * <p>
+ * Each local repository processes JAM modules in the repository interchange
+ * directory as follows, when the
* {@link Repository#initialize() <tt>initialize</tt>} or
* {@link Repository#reload() <tt>reload</tt>} method is called:
* <ul>
- * <li><p>A local repository must process JAM file which
- * has {@code .jam} extension and follows the naming convention
- * defined in Section 3.1 of the JAM Module System Specification.
- * A local repository must ignore JAM file which
- * has {@code .jam} extension but does not follow the naming
- * convention.
- * A local repository must ignore JAM file which
- * has {@code .jam.pack.gz}, {@code .jar}, {@code .zip} or other
- * filename extensions.
- *
- * <li><p>A local repository must support a
- * "hidden" (in the UNIX sense) repository interchange directory.
- * </p></li>
- *
- * <li><p>A local repository must ignore subdirectories
- * under the repository interchange directory.
- * </p></li>
- *
- * <li><p>Local repository implementations may enumerate the JAM files in
- * any order.</p></li>
- *
- * <li><p>Local repository implementations must ignore the duplicates
- * if there is more than one JAM file containing the same JAM module.
+ * <li><p>Only JAM files in the directory which have {@code .jam} extension
+ * and follow the naming convention
+ * defined in Section 3.1 of the JAM Module System Specification
+ * are recognized. Other files in the directory are ignored.
+ *
+ * <li><p>Subdirectories are ignored.</p></li>
+ *
+ * <li><p>JAM files in the directory may be enumerated in any order.</p></li>
+ *
+ * <li><p>Duplicates are ignored if there is more than one JAM
+ * file containing the same JAM module.
* </p></li>
* </ul>
- * <p>
- * A local repository must follow the
- * <a href="#SelectionPolicy">selection policy</a> to determine a
- * selected set of JAM modules, from the set of JAM modules available
- * in the repository interchange directory. Local repository
- * implementations must only create {@code ModuleDefinition}s for the
- * selected set of JAM modules.
- * <p>
- * Local repository implementations must support the
- * {@link Repository#reload() <tt>reload</tt>} operation. During reload,
- * a local repository must compare the set of JAM
- * modules in the repository interchange directory against
- * the set of JAM modules which was last recognized by the local
- * repository.
- * See
- * {@link Repository#reload()} for more details.
- * <p>
- * Local repository implementations must become
- * {@linkplain Repository#isReadOnly() read-only}
- * if the repository interchange directory is read-only as determined
- * when the repository is initialized and reloaded.
- * Local repository implementations must support the
- * {@link Repository#install(URI) <tt>install</tt>} and
- * {@link Repository#uninstall(ModuleArchiveInfo) <tt>uninstall</tt>} operations.
* <p>
* Instances of this {@code Repository} can be constructed using one of the
* {@link #newLocalRepository(String, File, Map, Repository)
@@ -166,32 +116,30 @@ import sun.module.repository.URLReposito
* // Search org.foo.xml version 1.0.0 from the repository instance.
* ModuleDefinition moduleDef = repo.find("org.foo.xml", VersionConstraint.valueOf("1.0.0"));</pre>
*
- * <h4>URL Repository</h4>
- * <i>URL repository</i> supports loading JAM modules
- * from a codebase URL. URL repository is typically used to
- * download JAM modules from server, but it can also be used with a
- * file-based URL.
- * <p>
- * URL repository must have a <i>repository metadata file</i>
- * (i.e. repository-metadata.xml) which describes the JAM modules in
+ * <h4>URL repository</h4>
+ * <i>URL repository</i> supports loading JAM modules from a codebase URL.
+ * URL repository is typically used to load JAM modules from a server, but
+ * it can also be used to load JAM modules from a file URL.
+ * <p>
+ * Each URL repository has a <i>repository metadata file</i>
+ * (i.e. {@code repository-metadata.xml}) which describes the JAM modules in
* the repository. The <i>repository metadata file</i> must exist
* directly under the codebase URL, and it must conform to the
- * <a href="RepositoryMetadata.xml">repository metadata schema</a>.
+ * <a href="repository-metadata-schema.xml">repository metadata schema</a>.
* <pre>
* {codebase}/repository-metadata.xml</pre>
*
* A JAM module in the URL repository is identified by placing an entry
- * in the <i>repository metadata file</i>. Each entry has a
- * module name, module version, path (relative path to a location
- * where the module is stored under the codebase URL), and platform
- * binding. URL repository implementations must ignore the duplicates
- * if there is more than one entry for the JAM module with the
+ * in the <i>repository metadata file</i>. Each entry has a module name,
+ * module version, path (relative path to a location where the module is
+ * stored under the codebase URL), and platform binding. Duplicates must
+ * be ignored if there is more than one entry for the JAM module with the
* same name, version, and platform binding.
* For a given JAM module in the URL repository, its module
* metadata file {@code MODULE.METADATA} must exist under the path, and
* its module archive (i.e. either {@code .jam} file,
* {@code .jam.pack.gz} file, or both} must also exist under the path.
- * <h5>Platform-neutral JAM module</h5>
+ * <h5>Portable JAM module</h5>
* <pre>
* {codebase}/{path}/MODULE.METADATA
* {codebase}/{path}/<module-name>-<module-version>.jam
@@ -203,59 +151,18 @@ import sun.module.repository.URLReposito
* {codebase}/{path}/<module-name>-<module-version>[<platform>-<arch>].jam
* {codebase}/{path}/<module-name>-<module-version>[<platform>-<arch>].jam.pack.gz</pre>
*
- * URL repository implementations must follow the
- * <a href="#SelectionPolicy">selection policy</a> to determine a
- * selected set of JAM modules, from the set of JAM modules available
- * in the repository as described in the repository metadata file.
- * URL repository implementations must only create
- * {@code ModuleDefinition}s for the selected set of JAM modules.
- * <p>
- * For each JAM module in the selected set,
- * <ul>
- * <li><p>URL repository implementations must either download the
- * {@code .jam} file or {@code .jam.pack.gz} file for the given
- * JAM module. URL repository implementations must prefer
- * the {@code .jam.pack.gz} file over the {@code .jam} file
- * if the codebase URL is not file-based.</p></li>
- *
- * <li><p>URL repository implementations must ignore the JAM module
- * if the module's name, version, and platform binding specified
- * in the repository metadata file do not match the information
- * in the module metadata file
- * (i.e. {@code MODULE.METADATA file}).</p></li>
- *
- * <li><p>A URL repository implementation must throw exception in
- * methods of {@link ModuleContent} in the
- * {@link ModuleDefinition}s the URL repository creates, if
- * the module metadata file (i.e. {@code MODULE.METADATA
- * file}) is not bit-wise equal to the module metadata file
- * inside the {@code .jam} file or {@code .jam.pack.gz} file
- * which the URL repository has downloaded.
- * </p></li>
- * </ul>
- * URL repository is {@linkplain Repository#isReadOnly() read-only}
- * if the codebase is a non-file-based URL or it is a file-based URL
- * which represents a read-only directory on the file system.
- * URL repository implementations must support the
- * {@link Repository#install(java.net.URI) <tt>install</tt>} and
- * {@link Repository#uninstall(ModuleArchiveInfo) <tt>uninstall</tt>}
- * operations for JAM files.
- * <p>
- * A URL repository must support the
- * {@linkplain Repository#reload() reload}
- * operation; it must compare the timestamp of the
- * <i>repository metadata file</i> against the timestamp of the same file
- * which was last downloaded. If the timestamps are different, a URL
- * repository must do the following:
- * <ol>
- * <li><p>Download the repository metadata file and determine
- * the set of JAM modules based on the selection policy.</p></li>
- * <li><p>Remove all existing module archives and module definitions
- * from the repository.</p></li>
- * <li><p>Add new module archives and module definitions to the
- * repository.</p></li>
- * </ol>
- * See {@link Repository#reload()} for more details.
+ * URL repository must ignore a JAM module if the name, version, and
+ * platform binding in its module metadata file
+ * (i.e. {@code MODULE.METADATA} file) does not match the information
+ * in its entry in the repository metadata file.
+ * URL repository must block instantiation of module instance from
+ * a module definition if its module metadata file
+ * is not bit-wise equal to the content of
+ * {@code META-INF/MODULE.METADATA} in the {@code .jam} file or
+ * {@code .jam.pack.gz} file.
+ * URL repository must prefer {@code .jam.pack.gz} file over {@code .jam}
+ * file for remote URL; it must prefer {@code .jam} file
+ * over {@code .jam.pack.gz} for file URL.
* <p>
* Instance of this {@code Repository} can be constructed using one of the
* {@link #newURLRepository(String, URL, Map, Repository)
@@ -278,6 +185,66 @@ import sun.module.repository.URLReposito
* // Search org.foo.xml version 1.3.0 from the repository instance.
* ModuleDefinition moduleDef = repo.find("org.foo.xml", VersionConstraint.valueOf("1.3.0"));</pre>
*
+ *
+ * <h4>Creating module definitions from JAM modules</h4>
+ *
+ * <i>Local repository</i> and <i>URL repository</i> may have portable and
+ * <a href="package-summary.html#PlatformSpecificModules">platform specific</a>
+ * modules installed for a given module's name and version. When a repository
+ * creates a module definition for a given module name and
+ * version during {@code initialize} or {@code reload},
+ * it must ignore all JAM modules that are
+ * incompatible with the system's platform and architecture. It must prefer
+ * a platform specific JAM module compatibile with the system rather than a
+ * portable JAM module for a given module's name and version.
+ * </ul>
+ *
+ * <h4>List</h4>
+ * <i>Local repository</i> supports the
+ * {@link Repository#list() <tt>list</tt>} operation by listing all JAM modules
+ * in the repository interchange directory.
+ * <i>URL repository</i> supports the operation by listing all JAM modules
+ * described in the repository metadata file.
+ *
+ * <h4>Install</h4><i>Local repository</i> and <i>URL repository</i> support the
+ * {@link Repository#install(URI) <tt>install</tt>} operation with JAM file.
+ * Both repositories must block the installation if the JAM file is invalid. If the
+ * repository has no existing module definition for a given module name and
+ * version when the JAM module is installed, the repository must create one
+ * from the newly installed JAM mdoule.
+ *
+ * <h4>Uninstall</h4><i>Local repository</i> and <i>URL repository</i> support the
+ * {@link Repository#uninstall(ModuleArchiveInfo) <tt>uninstall</tt>}
+ * operation for a given JAM module. If the repository has an
+ * existing module definition created from the JAM module, it removes
+ * the module definition if the uninstallation succeeds.
+ *
+ * <h4>Reload</h4><i>Local repository</i> supports the
+ * {@link Repository#reload() <tt>reload</tt>} operation by comparing
+ * the set of JAM modules in the repository interchange directory against
+ * the set of JAM modules last known to the repository. The repository
+ * removes an existing JAM module if the corresponding JAM file is
+ * missing from the directory. The repository replaces an existing JAM
+ * module if the corresponding JAM file in the directory has a different
+ * timestamp than the last known value. The repository adds a new JAM module
+ * if the corresponding JAM file is new in the directory.
+ * <p>
+ * <i>URL repository</i> supports the reload operation by comparing the
+ * timestamp of the <i>repository metadata file</i> against the timestamp
+ * last known to the repository. If the timestamps are different,
+ * the repository removes all existing JAM modules, and loads all new
+ * JAM modules from the codebase based on the repository metadata file.
+ * <p>
+ * See
+ * {@link Repository#reload()} for more details.
+ *
+ * <h4>Read only</h4>
+ * <i>Local repository</i> is {@linkplain Repository#isReadOnly() read-only}
+ * if the repository interchange directory is read-only.
+ * <i>URL repository</i> is read-only if the codebase is a non-file
+ * URL, or the codebase is a file URL that represents a read-only
+ * directory on the file system.
+ *
* <h3> Module dependency and package dependency</h3>
* The JAM module system provides a concrete implementation for
* {@link ModuleDependency} and another concrete implementation for
@@ -312,7 +279,21 @@ import sun.module.repository.URLReposito
*/
public class Modules {
- static {
+ private static WeakHashMap<ThreadGroup, ModuleSystem> moduleSystemMap = new WeakHashMap<ThreadGroup, ModuleSystem>();
+
+ // System's import override policy
+ private static ImportOverridePolicy importOverridePolicy;
+
+ // System's visibility policy
+ private static VisibilityPolicy visibilityPolicy;
+
+
+ static
+ {
+ // Construct a JAM module system instance for the main thread group
+ // as early as possible.
+ getModuleSystem();
+
// Load the import override policy and the visibililty policy as early
// as possible. This is to avoid potential deadlock when setting up
// the extension module loader that may cause these polcies to be
@@ -322,30 +303,39 @@ public class Modules {
getVisibilityPolicy();
}
- // ModuleSystem implementation for JAM module system.
- private static ModuleSystem defaultImpl = null;
-
- // Default import override policy
- private static ImportOverridePolicy importOverridePolicy;
-
- // Default visibility policy
- private static VisibilityPolicy visibilityPolicy;
-
// private constructor to prevent instantiation and subclassing
private Modules() {
// empty
}
/**
- * Returns the JAM module system.
- *
- * @return the JAM module system.
+ * Returns a JAM module system instance.
+ * <p>
+ * Each JAM module system instance must create all new threads in a
+ * {@link java.lang.ThreadGroup}. If a security manager is present,
+ * this method returns a JAM module system instance which uses the
+ * {@linkplain java.lang.SecurityManager#getThreadGroup()
+ * thread group of the system's security manager}; otherwise,
+ * this method returns a JAM module system instance which uses the
+ * thread group of the current thread.
+ *
+ * @return an instance of the JAM module system.
*/
public static synchronized ModuleSystem getModuleSystem() {
- if (defaultImpl == null) {
- defaultImpl = sun.module.core.ModuleSystemImpl.INSTANCE;
- }
- return defaultImpl;
+ SecurityManager sm = System.getSecurityManager();
+ final ThreadGroup group = (sm != null) ? sm.getThreadGroup() :
+ Thread.currentThread().getThreadGroup();
+
+ ModuleSystem ms = moduleSystemMap.get(group);
+ if (ms == null) {
+ ms = AccessController.doPrivileged(new PrivilegedAction<ModuleSystem>() {
+ public ModuleSystem run() {
+ return new ModuleSystemImpl(group);
+ }
+ });
+ moduleSystemMap.put(group, ms);
+ }
+ return ms;
}
/**
@@ -551,14 +541,43 @@ public class Modules {
/**
* Returns the system's import override policy for module definitions.
- * <p>
- * The default class of the override policy can be changed using the
- * {@code java.module.import.override.policy.classname} system property.
- *
- * @return the system's default import override policy for module definitions.
+ * This value should not be cached, as it may be changed by a call to
+ * {@code setImportOverridePolicy}.
+ * <p>
+ * If the system has no import override policy installed, this method returns
+ * an instance of the default {@code ImportOverridePolicy} implementation.
+ * <p>
+ * The default {@code ImportOverridePolicy} implementation can be changed
+ * by setting the value of the "import.override.policy.classname" property
+ * (in the Java module properties file) to the fully qualified name of
+ * the desired {@code ImportOverridePolicy} implementation. The Java module
+ * properties file is located in the file named
+ * {@code <JAVA_HOME>/lib/module/module.properties}. {@code <JAVA_HOME>}
+ * refers to the value of the {@code java.home} system property, and
+ * specifies the directory where the JRE is installed.
+ * <p>
+ * The default {@code ImportOverridePolicy} implementation can also be
+ * changed by setting the value of the
+ * {@code java.module.import.override.policy.classname} system property to the
+ * fully qualified name of the desired {@code ImportOverridePolicy}
+ * implementation.
+ * <p>
+ * If a security manager is present, this method calls the security
+ * manager's {@code checkPermission} method with a
+ * {@code ModuleSystemPermission("getImportOverridePolicy")}
+ * permission to ensure it's ok to get the system's import
+ * override policy.
+ *
+ * @return the system's import override policy for module definitions.
+ * @throws SecurityException if a security manager exists and its
+ * {@code checkPermission} method denies access to get the
+ * system's import override policy.
*/
public synchronized static ImportOverridePolicy getImportOverridePolicy() {
-
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ sm.checkPermission(new ModuleSystemPermission("getImportOverridePolicy"));
+ }
if (importOverridePolicy == null) {
try {
String clazzName = java.security.AccessController.doPrivileged(
@@ -607,13 +626,13 @@ public class Modules {
* If a security manager is present, this method calls the security
* manager's {@code checkPermission} method with a
* {@code ModuleSystemPermission("setImportOverridePolicy")}
- * permission to ensure it's ok to set the system's default import
+ * permission to ensure it's ok to set the system's import
* override policy.
*
* @param policy the import override policy for module definitions.
* @throws SecurityException if a security manager exists and its
* {@code checkPermission} method denies access to set the
- * system's default import override policy.
+ * system's import override policy.
*/
public synchronized static void setImportOverridePolicy(ImportOverridePolicy policy) {
if (policy == null)
@@ -627,16 +646,42 @@ public class Modules {
}
/**
- * Returns the system's default visibility policy for module definitions
- * in the repositories.
- * <p>
- * The default class of the visibility policy can be overridden using the
- * {@code java.module.visibility.policy.classname} system property.
- *
- * @return the system's default visibility policy for module definitions.
+ * Returns the system's visibility policy for module definitions in the
+ * repositories.
+ * <p>
+ * If the system has no visibility policy installed, this method returns
+ * an instance of the default {@code VisibilityPolicy} implementation.
+ * <p>
+ * The default {@code VisibilityPolicy} implementation can be changed
+ * by setting the value of the "visibility.policy.classname" property
+ * (in the Java module properties file) to the fully qualified name of
+ * the desired {@code VisibilityPolicy} implementation. The Java module
+ * properties file is located in the file named
+ * {@code <JAVA_HOME>/lib/module/module.properties}. {@code <JAVA_HOME>}
+ * refers to the value of the {@code java.home} system property, and
+ * specifies the directory where the JRE is installed.
+ * <p>
+ * The default {@code VisibilityPolicy} implementation can also be
+ * changed by setting the value of the
+ * {@code java.module.visibility.policy.classname} system property to the
+ * fully qualified name of the desired {@code VisibilityPolicy}
+ * implementation.
+ * <p>
+ * If a security manager is present, this method calls the security
+ * manager's {@code checkPermission} method with a
+ * {@code ModuleSystemPermission("getVisibilityPolicy")}
+ * permission to ensure it's ok to get the system's visibility policy.
+ *
+ * @return the system's visibility policy for module definitions.
+ * @throws SecurityException if a security manager exists and its
+ * {@code checkPermission} method denies access to get the
+ * system's visibility policy.
*/
synchronized static VisibilityPolicy getVisibilityPolicy() {
-
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ sm.checkPermission(new ModuleSystemPermission("getVisibilityPolicy"));
+ }
if (visibilityPolicy == null) {
try {
String clazzName = java.security.AccessController.doPrivileged(
@@ -681,37 +726,101 @@ public class Modules {
/**
* Returns a new {@code ModuleDefinition} instance for a JAM module.
- *
- * <p>This method will typically be called by repository implementations
+ * Equivalent to:
+ * <pre>
+ * newModuleDefinition(metadata, content, moduleArchiveInfo, repository, moduleReleasable, getModuleSystem());</pre>
+ *
+ * The content of the byte buffer is copied.
+ * This method will typically be called by repository implementations
* and not by applications.
- *
- * @param metadata an array of bytes which is the content of the
+ * <p>
+ * If a security manager is present, this method calls the security
+ * manager's {@code checkPermission} method with
+ * {@code ModuleSystemPermission("createModuleDefinition")} permission to
+ * ensure it's ok to create a module definition.
+ *
+ * @param metadata a byte buffer which contains the content of the
* module metadata file
* @param content the {@code ModuleContent} to be used to access the
* contents of the module definition
- * @param repository the {@code Repository} in which the module definition
- * is associated with
+ * @param mai the module archive information with which the
+ * mdoule definition is associated
+ * @param repository the {@code Repository} with which the module definition
+ * is associated
* @param moduleReleasable true if the module instance instantiated from
* this {@code ModuleDefinition} is releasable from its module
* system
+ * @throws SecurityException if a security manager exists and its
+ * {@code checkPermission} method denies access to create a new
+ * module definition.
* @throws ModuleFormatException if the content of module metadata file
* is not recognized or is not well formed.
* @return a new {@code ModuleDefinition}.
*/
- public static ModuleDefinition newModuleDefinition(byte[] metadata,
- ModuleContent content, Repository repository, boolean moduleReleasable)
+ public static ModuleDefinition newModuleDefinition(ByteBuffer metadata,
+ ModuleContent content, ModuleArchiveInfo mai,
+ Repository repository, boolean moduleReleasable)
+ throws ModuleFormatException {
+ return newModuleDefinition(metadata, content, mai, repository, moduleReleasable, getModuleSystem());
+ }
+
+ /**
+ * Returns a new {@code ModuleDefinition} instance for a JAM module.
+ * <p>
+ * The content of the byte buffer is copied.
+ * This method will typically be called by repository implementations
+ * and not by applications.
+ * <p>
+ * If a security manager is present, this method calls the security
+ * manager's {@code checkPermission} method with
+ * {@code ModuleSystemPermission("createModuleDefinition")} permission to
+ * ensure it's ok to create a module definition.
+ *
+ * @param metadata a byte buffer which contains the content of the
+ * module metadata file
+ * @param content the {@code ModuleContent} to be used to access the
+ * contents of the module definition
+ * @param mai the module archive information with which the
+ * mdoule definition is associated
+ * @param repository the {@code Repository} with which the module definition
+ * is associated
+ * @param moduleReleasable true if the module instance instantiated from
+ * this {@code ModuleDefinition} is releasable from its module
+ * system
+ * @param moduleSystem the {@code ModuleSystem} instance to be associated with
+ * the module definition.
+ * @throws SecurityException if a security manager exists and its
+ * {@code checkPermission} method denies access to create a new
+ * module definition.
+ * @throws ModuleFormatException if the content of module metadata file
+ * is not recognized or is not well formed.
+ * @return a new {@code ModuleDefinition}.
+ */
+ public static ModuleDefinition newModuleDefinition(ByteBuffer metadata,
+ ModuleContent content, ModuleArchiveInfo mai,
+ Repository repository, boolean moduleReleasable,
+ ModuleSystem moduleSystem)
throws ModuleFormatException {
if (metadata == null) {
- throw new NullPointerException("metadata must not be null.");
+ throw new NullPointerException("metadataByteBuffer must not be null.");
}
if (content == null) {
throw new NullPointerException("content must not be null.");
}
+ if (mai == null) {
+ throw new NullPointerException("mai must not be null.");
+ }
if (repository == null) {
throw new NullPointerException("repository must not be null.");
}
- return new JamModuleDefinition
- (getModuleSystem(),
- null, null, metadata, null, content, repository, moduleReleasable);
+ if (moduleSystem == null) {
+ throw new NullPointerException("moduleSystem must not be null.");
+ }
+
+ byte[] metadataBytes = new byte[metadata.remaining()];
+ metadata.get(metadataBytes); // get bytes out of byte buffer.
+
+ return new JamModuleDefinition(moduleSystem,
+ null, null, metadataBytes, content, mai, repository, moduleReleasable);
}
}
--- a/src/share/classes/java/module/Repository.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/Repository.java Tue Aug 05 13:15:22 2008 -0700
@@ -242,13 +242,36 @@ public abstract class Repository {
}
/**
- * Returns the system's default visibility policy for module definitions
- * in the repositories.
- * <p>
- * The default class of the visibility policy can be overridden using the
- * {@code java.module.visibility.policy.classname} system property.
- *
- * @return the system's default visibility policy for module definitions.
+ * Returns the system's visibility policy for module definitions in the
+ * repositories.
+ * <p>
+ * If the system has no visibility policy installed, this method returns
+ * an instance of the default {@code VisibilityPolicy} implementation.
+ * <p>
+ * The default {@code VisibilityPolicy} implementation can be changed
+ * by setting the value of the "visibility.policy.classname" property
+ * (in the Java module properties file) to the fully qualified name of
+ * the desired {@code VisibilityPolicy} implementation. The Java module
+ * properties file is located in the file named
+ * {@code <JAVA_HOME>/lib/module/module.properties}. {@code <JAVA_HOME>}
+ * refers to the value of the {@code java.home} system property, and
+ * specifies the directory where the JRE is installed.
+ * <p>
+ * The default {@code VisibilityPolicy} implementation can also be
+ * changed by setting the value of the
+ * {@code java.module.visibility.policy.classname} system property to the
+ * fully qualified name of the desired {@code VisibilityPolicy}
+ * implementation.
+ * <p>
+ * If a security manager is present, this method calls the security
+ * manager's {@code checkPermission} method with a
+ * {@code ModuleSystemPermission("getVisibilityPolicy")}
+ * permission to ensure it's ok to get the system's visibility policy.
+ *
+ * @return the system's visibility policy for module definitions.
+ * @throws SecurityException if a security manager exists and its
+ * {@code checkPermission} method denies access to get the
+ * system's visibility policy.
*/
public static VisibilityPolicy getVisibilityPolicy() {
return Modules.getVisibilityPolicy();
--- a/src/share/classes/java/module/VisibilityPolicy.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/VisibilityPolicy.java Tue Aug 05 13:15:22 2008 -0700
@@ -28,7 +28,7 @@ package java.module;
/**
* This interface represents the visibility policy for the module definitions.
* <p>
- * The visibility policy is used to determine whether a module definition in a
+ * The visibility policy determines whether a module definition in a
* repository is visible to the application at runtime, when the
* {@link Repository#find(Query) <tt>find(Query)</tt>} method of the
* {@code Repository} instance is invoked. The system's visibility policy can be
--- a/src/share/classes/java/module/annotation/ImportPolicyClass.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/annotation/ImportPolicyClass.java Tue Aug 05 13:15:22 2008 -0700
@@ -32,9 +32,9 @@ import java.lang.annotation.RetentionPol
/**
* Indicates the import policy class of a module definition. The class must
- * implement {@link java.module.ImportPolicy}. The class must be declared
- * {@code public}, and must have a public constructor which takes no argument.
- * This metadata annotation is applied to a Java module. For example,
+ * implement {@link java.module.ImportPolicy}. The class must be concrete,
+ * and must have a zero-argument public constructor. This metadata annotation
+ * is applied to a Java module. For example,
* <blockquote><pre>
* //
* // com/wombat/xyz/module-info.java
--- a/src/share/classes/java/module/annotation/ModuleInitializerClass.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/annotation/ModuleInitializerClass.java Tue Aug 05 13:15:22 2008 -0700
@@ -33,8 +33,8 @@ import java.lang.annotation.RetentionPol
/**
* Indicates the class of the initializer of a module definition. The class
* must implement {@link java.module.ModuleInitializer}. The class must be
- * declared {@code public}, and must have a public constructor which takes no
- * argument. This metadata annotation is applied to a Java module. For example,
+ * conrete, and must have a zero-argument public constructor. This metadata
+ * annotation is applied to a Java module. For example,
* <blockquote><pre>
* //
* // com/wombat/xyz/module-info.java
--- a/src/share/classes/java/module/package-info.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/module/package-info.java Tue Aug 05 13:15:22 2008 -0700
@@ -191,16 +191,17 @@
* implementation and the default module system within the Java Module System.
* <p>
* <h3> JAM modules</h3>
- * Modules in the JAM module system are called JAM modules. The distribution
+ * Modules in the JAM module system are called JAM modules. JAM modules are
+ * <i>portable</i> by default and can run under any platform. The distribution
* format of a JAM module is also called JAM. Each JAM file
* is self-contained by definition, and it does not reference any resource
* externally. See the JAM Module System Specification for more details.
* <p>
* <A NAME="PlatformSpecificModules"></A><h4> Platform-specific modules</h4>
- * JAM modules are <i>platform-neutral</i> by default. A JAM module is
- * <i>platform-specific</i> if it has
+ * JAM modules with
* {@link java.module.annotation.PlatformBinding platform binding}
- * for a specific platform and architecture.
+ * are <i>platform specific</i>. They can only run under the specific
+ * platform and architecture.
* <p>
* <h4> Resource modules</h4>
* Resources of different locales can be placed in different
--- a/src/share/classes/java/nio/channels/SelectionKey.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/nio/channels/SelectionKey.java Tue Aug 05 13:15:22 2008 -0700
@@ -191,7 +191,7 @@ public abstract class SelectionKey {
* @throws IllegalArgumentException
* If a bit in the set does not correspond to an operation that
* is supported by this key's channel, that is, if
- * <tt>set & ~(channel().validOps()) != 0</tt>
+ * <tt>(ops & ~channel().validOps()) != 0</tt>
*
* @throws CancelledKeyException
* If this key has been cancelled
--- a/src/share/classes/java/util/ServiceLoader.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/java/util/ServiceLoader.java Tue Aug 05 13:15:22 2008 -0700
@@ -110,7 +110,7 @@ import sun.module.repository.RepositoryC
* <p>
* A <i>service provider module</i> is a JAM module which contains one or more
* provider classes for one or more services. A service provider module may
- * have more than one provider classes for the same service. A service
+ * have more than one provider class for the same service. A service
* provider module may have the same provider class for more than one service.
* A service provider is identified by placing a
* {@code ModuleServiceProviderTable} attribute in the metadata
@@ -741,7 +741,7 @@ public final class ServiceLoader<S>
boolean rc = false;
if (providerMod != null) {
List<Module> reexports = new ArrayList<Module>();
- ModuleUtils.expandReexports(providerMod, reexports, true);
+ ModuleUtils.expandReexports(providerMod, reexports);
rc = reexports.contains(serviceMod);
}
return rc;
@@ -962,28 +962,28 @@ public final class ServiceLoader<S>
}
/**
- * <span style="color: rgb(204, 0, 0);"><B>[UPDATED]</B></span>
+ * <span style="color: rgb(204, 0, 0);"><B>[REVISED]</B></span>
* Creates a new service loader for the given service type and class
* loader.
* <p>
* <span style="color: rgb(204, 0, 0);">
* The service loader first uses the class loader to search for providers
- * for the given service type; the service loader then uses the following
- * repository in the Java Module System to search for service provider
- * modules for the given service type if the service type is from a
- * module module:
+ * for the given service type; the service loader then uses the
+ * following repositories in the Java Module System to search for service
+ * provider modules for the given service type if the service type is from a
+ * module:
* <p>
- * <ul>
- * <li> {@linkplain java.module.Repository#getApplicationRepository Application repository}
+ * <ol>
+ * <li> Use the {@linkplain java.module.Repository#getApplicationRepository application repository}
* if the class loader or an ancestor of the class loader is the system class loader.</li>
*
- * <li> {@linkplain java.module.Repository#getSystemRepository System repository}
+ * <li> Otherwise, use the {@linkplain java.module.Repository#getSystemRepository system repository}
* if the class loader or an ancestor of the class loader is the extension class loader.</li>
*
- * <li> The repository associated with the module which the class loader
- * belongs if the class loader is a
+ * <li> Otherwise, use the repository associated with the module
+ * which the class loader belongs if the class loader is a
* {@linkplain java.module.Module#getClassLoader module class loader}.</li>
- * </ul>
+ * </ol>
* </span>
*
* @param service
@@ -1101,7 +1101,7 @@ public final class ServiceLoader<S>
}
/**
- * <span style="color: rgb(204, 0, 0);"><B>[UPDATED]</B></span>
+ * <span style="color: rgb(204, 0, 0);"><B>[REVISED]</B></span>
* Creates a new service loader for the given service type, using the
* <span style="color: rgb(204, 0, 0);">
* the extension class loader, and using the
--- a/src/share/classes/javax/management/BinaryRelQueryExp.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/BinaryRelQueryExp.java Tue Aug 05 13:15:22 2008 -0700
@@ -192,6 +192,7 @@ class BinaryRelQueryExp extends QueryEva
return "(" + exp1 + ") " + relOpString() + " (" + exp2 + ")";
}
+ @Override
String toQueryString() {
return exp1 + " " + relOpString() + " " + exp2;
}
--- a/src/share/classes/javax/management/Descriptor.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/Descriptor.java Tue Aug 05 13:15:22 2008 -0700
@@ -38,6 +38,7 @@ import java.util.ResourceBundle;
import java.util.ResourceBundle;
import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.MXBeanMappingFactory;
import javax.management.openmbean.OpenMBeanAttributeInfoSupport;
import javax.management.openmbean.OpenMBeanOperationInfoSupport;
import javax.management.openmbean.OpenMBeanParameterInfoSupport;
@@ -117,21 +118,19 @@ import javax.management.openmbean.OpenTy
* deprecation, for example {@code "1.3 Replaced by the Capacity
* attribute"}.</td>
*
- * <tr><td>descriptionResource<br>BundleBaseName</td><td>String</td><td>Any</td>
+ * <tr id="descriptionResourceBundleBaseName">
+ * <td>descriptionResource<br>BundleBaseName</td><td>String</td><td>Any</td>
*
* <td>The base name for the {@link ResourceBundle} in which the key given in
* the {@code descriptionResourceKey} field can be found, for example
- * {@code "com.example.myapp.MBeanResources"}. The meaning of this
- * field is defined by this specification but the field is not set or
- * used by the JMX API itself.</td>
- *
- * <tr><td>descriptionResourceKey</td><td>String</td><td>Any</td>
+ * {@code "com.example.myapp.MBeanResources"}.</td>
+ *
+ * <tr id="descriptionResourceKey">
+ * <td>descriptionResourceKey</td><td>String</td><td>Any</td>
*
* <td>A resource key for the description of this element. In
* conjunction with the {@code descriptionResourceBundleBaseName},
- * this can be used to find a localized version of the description.
- * The meaning of this field is defined by this specification but the
- * field is not set or used by the JMX API itself.</td>
+ * this can be used to find a localized version of the description.</td>
*
* <tr><td>enabled</td><td>String</td>
* <td>MBeanAttributeInfo<br>MBeanNotificationInfo<br>MBeanOperationInfo</td>
@@ -216,6 +215,14 @@ import javax.management.openmbean.OpenTy
* StandardMBean} class will have this field in its MBeanInfo
* Descriptor.</td>
*
+ * <tr><td id="mxbeanMappingFactoryClass"><i>mxbeanMappingFactoryClass</i>
+ * </td><td>String</td>
+ * <td>MBeanInfo</td>
+ *
+ * <td>The name of the {@link MXBeanMappingFactory} class that was used for this
+ * MXBean, if it was not the {@linkplain MXBeanMappingFactory#DEFAULT default}
+ * one.</td>
+ *
* <tr><td><a name="openType"><i>openType</i></a><td>{@link OpenType}</td>
* <td>MBeanAttributeInfo<br>MBeanOperationInfo<br>MBeanParameterInfo</td>
*
--- a/src/share/classes/javax/management/DescriptorKey.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/DescriptorKey.java Tue Aug 05 13:15:22 2008 -0700
@@ -32,6 +32,11 @@ import java.lang.annotation.*;
* to a field in a {@link Descriptor}. This can be the Descriptor for
* an MBean, or for an attribute, operation, or constructor in an
* MBean, or for a parameter of an operation or constructor.</p>
+ *
+ * <p>(The {@link DescriptorFields @DescriptorFields} annotation
+ * provides another way to add fields to a {@code Descriptor}. See
+ * the documentation for that annotation for a comparison of the
+ * two possibilities.)</p>
*
* <p>Consider this annotation for example:</p>
*
@@ -57,7 +62,7 @@ import java.lang.annotation.*;
* <p>When a Standard MBean is made from the {@code CacheControlMBean},
* the usual rules mean that it will have an attribute called
* {@code CacheSize} of type {@code long}. The {@code @Units}
- * attribute, given the above definition, will ensure that the
+ * annotation, given the above definition, will ensure that the
* {@link MBeanAttributeInfo} for this attribute will have a
* {@code Descriptor} that has a field called {@code units} with
* corresponding value {@code bytes}.</p>
@@ -125,12 +130,13 @@ import java.lang.annotation.*;
* the method in the child interface are considered.
*
* <p>The Descriptor fields contributed in this way by different
- * annotations on the same program element must be consistent. That
- * is, two different annotations, or two members of the same
- * annotation, must not define a different value for the same
- * Descriptor field. Fields from annotations on a getter method must
- * also be consistent with fields from annotations on the
- * corresponding setter method.</p>
+ * annotations on the same program element must be consistent with
+ * each other and with any fields contributed by a {@link
+ * DescriptorFields @DescriptorFields} annotation. That is, two
+ * different annotations, or two members of the same annotation, must
+ * not define a different value for the same Descriptor field. Fields
+ * from annotations on a getter method must also be consistent with
+ * fields from annotations on the corresponding setter method.</p>
*
* <p>The Descriptor resulting from these annotations will be merged
* with any Descriptor fields provided by the implementation, such as
@@ -169,4 +175,36 @@ import java.lang.annotation.*;
@Target(ElementType.METHOD)
public @interface DescriptorKey {
String value();
+
+ /**
+ * <p>Do not include this field in the Descriptor if the annotation
+ * element has its default value. For example, suppose {@code @Units} is
+ * defined like this:</p>
+ *
+ * <pre>
+ * @Documented
+ * @Target(ElementType.METHOD)
+ * @Retention(RetentionPolicy.RUNTIME)
+ * public @interface Units {
+ * @DescriptorKey("units")
+ * String value();
+ *
+ * <b>@DescriptorKey(value = "descriptionResourceKey",
+ * omitIfDefault = true)</b>
+ * String resourceKey() default "";
+ *
+ * <b>@DescriptorKey(value = "descriptionResourceBundleBaseName",
+ * omitIfDefault = true)</b>
+ * String resourceBundleBaseName() default "";
+ * }
+ * </pre>
+ *
+ * <p>Then consider a usage such as {@code @Units("bytes")} or
+ * {@code @Units(value = "bytes", resourceKey = "")}, where the
+ * {@code resourceKey} and {@code resourceBundleBaseNames} elements
+ * have their default values. In this case the Descriptor resulting
+ * from these annotations will not include a {@code descriptionResourceKey}
+ * or {@code descriptionResourceBundleBaseName} field.</p>
+ */
+ boolean omitIfDefault() default false;
}
--- a/src/share/classes/javax/management/JMX.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/JMX.java Tue Aug 05 13:15:22 2008 -0700
@@ -26,6 +26,7 @@ package javax.management;
package javax.management;
import com.sun.jmx.mbeanserver.Introspector;
+import com.sun.jmx.mbeanserver.MBeanInjector;
import com.sun.jmx.remote.util.ClassLogger;
import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
@@ -130,6 +131,7 @@ public class JMX {
* </pre>
*
* @see javax.management.JMX.ProxyOptions
+ * @see javax.management.StandardMBean.Options
*/
public static class MBeanOptions implements Serializable, Cloneable {
private static final long serialVersionUID = -6380842449318177843L;
@@ -739,4 +741,28 @@ public class JMX {
// exactly the string "MXBean" since that would mean there
// was no package name, which is pretty unlikely in practice.
}
+
+ /**
+ * <p>Test if an MBean can emit notifications. An MBean can emit
+ * notifications if either it implements {@link NotificationBroadcaster}
+ * (perhaps through its child interface {@link NotificationEmitter}), or
+ * it uses <a href="MBeanRegistration.html#injection">resource
+ * injection</a> to obtain an instance of {@link SendNotification}
+ * through which it can send notifications.</p>
+ *
+ * @param mbean an MBean object.
+ * @return true if the given object is a valid MBean that can emit
+ * notifications; false if the object is a valid MBean but that
+ * cannot emit notifications.
+ * @throws NotCompliantMBeanException if the given object is not
+ * a valid MBean.
+ */
+ public static boolean isNotificationSource(Object mbean)
+ throws NotCompliantMBeanException {
+ if (mbean instanceof NotificationBroadcaster)
+ return true;
+ Object resource = (mbean instanceof DynamicWrapperMBean) ?
+ ((DynamicWrapperMBean) mbean).getWrappedObject() : mbean;
+ return (MBeanInjector.injectsSendNotification(resource));
+ }
}
--- a/src/share/classes/javax/management/MBeanOperationInfo.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/MBeanOperationInfo.java Tue Aug 05 13:15:22 2008 -0700
@@ -46,25 +46,30 @@ public class MBeanOperationInfo extends
new MBeanOperationInfo[0];
/**
- * Indicates that the operation is read-like,
- * it basically returns information.
+ * Indicates that the operation is read-like:
+ * it returns information but does not change any state.
+ * @see Impact#INFO
*/
public static final int INFO = 0;
/**
- * Indicates that the operation is a write-like,
- * and would modify the MBean in some way, typically by writing some value
- * or changing a configuration.
+ * Indicates that the operation is write-like: it has an effect but does
+ * not return any information from the MBean.
+ * @see Impact#ACTION
*/
public static final int ACTION = 1;
/**
- * Indicates that the operation is both read-like and write-like.
+ * Indicates that the operation is both read-like and write-like:
+ * it has an effect, and it also returns information from the MBean.
+ * @see Impact#ACTION_INFO
*/
public static final int ACTION_INFO = 2;
/**
- * Indicates that the operation has an "unknown" nature.
+ * Indicates that the impact of the operation is unknown or cannot be
+ * expressed using one of the other values.
+ * @see Impact#UNKNOWN
*/
public static final int UNKNOWN = 3;
@@ -120,8 +125,9 @@ public class MBeanOperationInfo extends
* describing the parameters(arguments) of the method. This may be
* null with the same effect as a zero-length array.
* @param type The type of the method's return value.
- * @param impact The impact of the method, one of <CODE>INFO,
- * ACTION, ACTION_INFO, UNKNOWN</CODE>.
+ * @param impact The impact of the method, one of
+ * {@link #INFO}, {@link #ACTION}, {@link #ACTION_INFO},
+ * {@link #UNKNOWN}.
*/
public MBeanOperationInfo(String name,
String description,
@@ -140,8 +146,9 @@ public class MBeanOperationInfo extends
* describing the parameters(arguments) of the method. This may be
* null with the same effect as a zero-length array.
* @param type The type of the method's return value.
- * @param impact The impact of the method, one of <CODE>INFO,
- * ACTION, ACTION_INFO, UNKNOWN</CODE>.
+ * @param impact The impact of the method, one of
+ * {@link #INFO}, {@link #ACTION}, {@link #ACTION_INFO},
+ * {@link #UNKNOWN}.
* @param descriptor The descriptor for the operation. This may be null
* which is equivalent to an empty descriptor.
*
@@ -319,9 +326,14 @@ public class MBeanOperationInfo extends
for (int i = 0; i < classes.length; i++) {
Descriptor d = Introspector.descriptorForAnnotations(annots[i]);
- final String pn = "p" + (i + 1);
- params[i] =
- new MBeanParameterInfo(pn, classes[i].getName(), "", d);
+ String description = Introspector.descriptionForParameter(annots[i]);
+ if (description == null)
+ description = "";
+ String name = Introspector.nameForParameter(annots[i]);
+ if (name == null)
+ name = "p" + (i + 1);
+ params[i] = new MBeanParameterInfo(
+ name, classes[i].getName(), description, d);
}
return params;
--- a/src/share/classes/javax/management/MBeanRegistration.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/MBeanRegistration.java Tue Aug 05 13:15:22 2008 -0700
@@ -27,9 +27,101 @@ package javax.management;
/**
- * Can be implemented by an MBean in order to
+ * <p>Can be implemented by an MBean in order to
* carry out operations before and after being registered or unregistered from
- * the MBean server.
+ * the MBean Server. An MBean can also implement this interface in order
+ * to get a reference to the MBean Server and/or its name within that
+ * MBean Server.</p>
+ *
+ * <h4 id="injection">Resource injection</h4>
+ *
+ * <p>As an alternative to implementing {@code MBeanRegistration}, if all that
+ * is needed is the MBean Server or ObjectName then an MBean can use
+ * <em>resource injection</em>.</p>
+ *
+ * <p>If a field in the MBean object has type {@link ObjectName} and has
+ * the {@link javax.annotation.Resource @Resource} annotation,
+ * then the {@code ObjectName} under which the MBean is registered is
+ * assigned to that field during registration. Likewise, if a field has type
+ * {@link MBeanServer} and the <code>@Resource</code> annotation, then it will
+ * be set to the {@code MBeanServer} in which the MBean is registered.</p>
+ *
+ * <p>For example:</p>
+ *
+ * <pre>
+ * public Configuration implements ConfigurationMBean {
+ * @Resource
+ * private volatile MBeanServer mbeanServer;
+ * @Resource
+ * private volatile ObjectName objectName;
+ * ...
+ * void unregisterSelf() throws Exception {
+ * mbeanServer.unregisterMBean(objectName);
+ * }
+ * }
+ * </pre>
+ *
+ * <p>Resource injection can also be used on fields of type
+ * {@link SendNotification} to simplify notification sending. Such a field
+ * will get a reference to an object of type {@code SendNotification} when
+ * the MBean is registered, and it can use this reference to send notifications.
+ * For example:</p>
+ *
+ * <pre>
+ * public Configuration implements ConfigurationMBean {
+ * @Resource
+ * private volatile SendNotification sender;
+ * ...
+ * private void updated() {
+ * Notification n = new Notification(...);
+ * sender.sendNotification(n);
+ * }
+ * }
+ * </pre>
+ *
+ * <p>A field to be injected must not be static. It is recommended that
+ * such fields be declared {@code volatile}.</p>
+ *
+ * <p>It is also possible to use the <code>@Resource</code> annotation on
+ * methods. Such a method must have a {@code void} return type and a single
+ * argument of the appropriate type, for example {@code ObjectName}.</p>
+ *
+ * <p>Any number of fields and methods may have the <code>@Resource</code>
+ * annotation. All fields and methods with type {@code ObjectName}
+ * (for example) will receive the same {@code ObjectName} value.</p>
+ *
+ * <p>Resource injection is available for all types of MBeans, not just
+ * Standard MBeans.</p>
+ *
+ * <p>If an MBean implements the {@link DynamicWrapperMBean} interface then
+ * resource injection happens on the object returned by that interface's
+ * {@link DynamicWrapperMBean#getWrappedObject() getWrappedObject()} method
+ * rather than on the MBean object itself.
+ *
+ * <p>Resource injection happens after the {@link #preRegister preRegister}
+ * method is called (if any), and before the MBean is actually registered
+ * in the MBean Server. If a <code>@Resource</code> method throws
+ * an exception, the effect is the same as if {@code preRegister} had
+ * thrown the exception. In particular it will prevent the MBean from being
+ * registered.</p>
+ *
+ * <p>Resource injection can be used on a field or method where the type
+ * is a parent of the injected type, if the injected type is explicitly
+ * specified in the <code>@Resource</code> annotation. For example:</p>
+ *
+ * <pre>
+ * @Resource(type = MBeanServer.class)
+ * private volatile MBeanServerConnection mbsc;
+ * </pre>
+ *
+ * <p>Formally, suppose <em>R</em> is the type in the <code>@Resource</code>
+ * annotation and <em>T</em> is the type of the method parameter or field.
+ * Then one of <em>R</em> and <em>T</em> must be a subtype of the other
+ * (or they must be the same type). Injection happens if this subtype
+ * is {@code MBeanServer}, {@code ObjectName}, or {@code SendNotification}.
+ * Otherwise the <code>@Resource</code> annotation is ignored.</p>
+ *
+ * <p>Resource injection in MBeans is new in version 2.0 of the JMX API.</p>
*
* @since 1.5
*/
@@ -38,12 +130,12 @@ public interface MBeanRegistration {
/**
* Allows the MBean to perform any operations it needs before
- * being registered in the MBean server. If the name of the MBean
+ * being registered in the MBean Server. If the name of the MBean
* is not specified, the MBean can provide a name for its
* registration. If any exception is raised, the MBean will not be
- * registered in the MBean server.
+ * registered in the MBean Server.
*
- * @param server The MBean server in which the MBean will be registered.
+ * @param server The MBean Server in which the MBean will be registered.
*
* @param name The object name of the MBean. This name is null if
* the name parameter to one of the <code>createMBean</code> or
@@ -57,7 +149,7 @@ public interface MBeanRegistration {
* the returned value.
*
* @exception java.lang.Exception This exception will be caught by
- * the MBean server and re-thrown as an {@link
+ * the MBean Server and re-thrown as an {@link
* MBeanRegistrationException}.
*/
public ObjectName preRegister(MBeanServer server,
--- a/src/share/classes/javax/management/MBeanServer.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/MBeanServer.java Tue Aug 05 13:15:22 2008 -0700
@@ -61,7 +61,7 @@ import javax.management.loading.ClassLoa
* <CODE>ObjectName</CODE> is: <BR>
* <CODE>JMImplementation:type=MBeanServerDelegate</CODE>.</p>
*
- * <p>An object obtained from the {@link
+ * <p id="security">An object obtained from the {@link
* MBeanServerFactory#createMBeanServer(String) createMBeanServer} or
* {@link MBeanServerFactory#newMBeanServer(String) newMBeanServer}
* methods of the {@link MBeanServerFactory} class applies security
@@ -661,13 +661,16 @@ public interface MBeanServer extends MBe
ReflectionException;
/**
- * <p>Return the {@link java.lang.ClassLoader} that was used for
- * loading the class of the named MBean.</p>
+ * <p>Return the {@link java.lang.ClassLoader} that was used for loading
+ * the class of the named MBean. If the MBean implements the {@link
+ * DynamicWrapperMBean} interface, then the returned value is the
+ * result of the {@link DynamicWrapperMBean#getWrappedClassLoader()}
+ * method.</p>
*
* @param mbeanName The ObjectName of the MBean.
*
* @return The ClassLoader used for that MBean. If <var>l</var>
- * is the MBean's actual ClassLoader, and <var>r</var> is the
+ * is the value specified by the rules above, and <var>r</var> is the
* returned value, then either:
*
* <ul>
--- a/src/share/classes/javax/management/MBeanServerConnection.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/MBeanServerConnection.java Tue Aug 05 13:15:22 2008 -0700
@@ -839,6 +839,12 @@ public interface MBeanServerConnection {
*
* <p>Otherwise, the result is false.</p>
*
+ * <p>If the MBean implements the {@link DynamicWrapperMBean}
+ * interface, then in the above rules X is the result of the MBean's {@link
+ * DynamicWrapperMBean#getWrappedObject() getWrappedObject()} method and L
+ * is the result of its {@link DynamicWrapperMBean#getWrappedClassLoader()
+ * getWrappedClassLoader()} method.
+ *
* @param name The <CODE>ObjectName</CODE> of the MBean.
* @param className The name of the class.
*
--- a/src/share/classes/javax/management/MXBean.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/MXBean.java Tue Aug 05 13:15:22 2008 -0700
@@ -27,6 +27,7 @@ package javax.management;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@@ -57,11 +58,13 @@ import javax.management.openmbean.Tabula
import javax.management.openmbean.TabularType;
/**
- <p>Annotation to mark an interface explicitly as being an MXBean
- interface, or as not being an MXBean interface. By default, an
+ <p>Annotation to mark a class or interface explicitly as being an MXBean,
+ or as not being an MXBean. By default, an
interface is an MXBean interface if its name ends with {@code
- MXBean}, as in {@code SomethingMXBean}. The following interfaces
- are MXBean interfaces:</p>
+ MXBean}, as in {@code SomethingMXBean}. A class is never an MXBean by
+ default.</p>
+
+ <p>The following interfaces are MXBean interfaces:</p>
<pre>
public interface WhatsitMXBean {}
@@ -81,6 +84,11 @@ import javax.management.openmbean.Tabula
@MXBean(false)
public interface MisleadingMXBean {}
</pre>
+
+ <p>A class can be annotated with {@code @MXBean} to indicate that it
+ is an MXBean. In this case, its methods should have <code>@{@link
+ ManagedAttribute}</code> or <code>@{@link ManagedOperation}</code>
+ annotations, as described for <code>@{@link MBean}</code>.</p>
<h3 id="MXBean-spec">MXBean specification</h3>
@@ -1246,9 +1254,24 @@ public interface Node {
@since 1.6
*/
+/*
+ * This annotation is @Inherited because if an MXBean is defined as a
+ * class using annotations, then its subclasses are also MXBeans.
+ * For example:
+ * @MXBean
+ * public class Super {
+ * @ManagedAttribute
+ * public String getName() {...}
+ * }
+ * public class Sub extends Super {}
+ * Here Sub is an MXBean.
+ *
+ * The @Inherited annotation has no effect when applied to an interface.
+ */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
+@Inherited
public @interface MXBean {
/**
True if the annotated interface is an MXBean interface.
--- a/src/share/classes/javax/management/NotQueryExp.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/NotQueryExp.java Tue Aug 05 13:15:22 2008 -0700
@@ -91,6 +91,7 @@ class NotQueryExp extends QueryEval impl
return "not (" + exp + ")";
}
+ @Override
String toQueryString() {
return "not (" + Query.toString(exp) + ")";
}
--- a/src/share/classes/javax/management/NotificationBroadcasterSupport.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/NotificationBroadcasterSupport.java Tue Aug 05 13:15:22 2008 -0700
@@ -58,7 +58,8 @@ import com.sun.jmx.remote.util.ClassLogg
*
* @since 1.5
*/
-public class NotificationBroadcasterSupport implements NotificationEmitter {
+public class NotificationBroadcasterSupport
+ implements NotificationEmitter, SendNotification {
/**
* Constructs a NotificationBroadcasterSupport where each listener is invoked by the
* thread sending the notification. This constructor is equivalent to
--- a/src/share/classes/javax/management/StandardEmitterMBean.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/StandardEmitterMBean.java Tue Aug 05 13:15:22 2008 -0700
@@ -24,6 +24,9 @@
*/
package javax.management;
+
+import com.sun.jmx.mbeanserver.MBeanInjector;
+import static javax.management.JMX.MBeanOptions;
/**
* <p>An MBean whose management interface is determined by reflection
@@ -62,7 +65,7 @@ package javax.management;
* @since 1.6
*/
public class StandardEmitterMBean extends StandardMBean
- implements NotificationEmitter {
+ implements NotificationEmitter, SendNotification {
private final NotificationEmitter emitter;
private final MBeanNotificationInfo[] notificationInfo;
@@ -76,9 +79,10 @@ public class StandardEmitterMBean extend
* for {@code implementation} and {@code emitter} to be the same object.</p>
*
* <p>If {@code emitter} is an instance of {@code
- * NotificationBroadcasterSupport} then the MBean's {@link #sendNotification
- * sendNotification} method will call {@code emitter.}{@link
- * NotificationBroadcasterSupport#sendNotification sendNotification}.</p>
+ * SendNotification} (for example, a {@link NotificationBroadcasterSupport}),
+ * then the MBean's {@link #sendNotification
+ * sendNotification} method will call {@code emitter.}{@link
+ * SendNotification#sendNotification sendNotification}.</p>
*
* <p>The array returned by {@link #getNotificationInfo()} on the
* new MBean is a copy of the array returned by
@@ -90,20 +94,18 @@ public class StandardEmitterMBean extend
*
* @param implementation the implementation of the MBean interface.
* @param mbeanInterface a Standard MBean interface.
- * @param emitter the object that will handle notifications.
+ * @param emitter the object that will handle notifications. If null,
+ * a new {@code NotificationEmitter} will be constructed that also
+ * implements {@link SendNotification}.
*
* @throws IllegalArgumentException if the {@code mbeanInterface}
* does not follow JMX design patterns for Management Interfaces, or
* if the given {@code implementation} does not implement the
- * specified interface, or if {@code emitter} is null.
+ * specified interface.
*/
public <T> StandardEmitterMBean(T implementation, Class<T> mbeanInterface,
NotificationEmitter emitter) {
- super(implementation, mbeanInterface, false);
- if (emitter == null)
- throw new IllegalArgumentException("Null emitter");
- this.emitter = emitter;
- this.notificationInfo = emitter.getNotificationInfo();
+ this(implementation, mbeanInterface, false, emitter);
}
/**
@@ -118,9 +120,10 @@ public class StandardEmitterMBean extend
* same object.</p>
*
* <p>If {@code emitter} is an instance of {@code
- * NotificationBroadcasterSupport} then the MBean's {@link #sendNotification
- * sendNotification} method will call {@code emitter.}{@link
- * NotificationBroadcasterSupport#sendNotification sendNotification}.</p>
+ * SendNotification} (for example, a {@link NotificationBroadcasterSupport}),
+ * then the MBean's {@link #sendNotification
+ * sendNotification} method will call {@code emitter.}{@link
+ * SendNotification#sendNotification sendNotification}.</p>
*
* <p>The array returned by {@link #getNotificationInfo()} on the
* new MBean is a copy of the array returned by
@@ -134,21 +137,69 @@ public class StandardEmitterMBean extend
* @param mbeanInterface a Standard MBean interface.
* @param isMXBean If true, the {@code mbeanInterface} parameter
* names an MXBean interface and the resultant MBean is an MXBean.
- * @param emitter the object that will handle notifications.
+ * @param emitter the object that will handle notifications. If null,
+ * a new {@code NotificationEmitter} will be constructed that also
+ * implements {@link SendNotification}.
*
* @throws IllegalArgumentException if the {@code mbeanInterface}
* does not follow JMX design patterns for Management Interfaces, or
* if the given {@code implementation} does not implement the
- * specified interface, or if {@code emitter} is null.
+ * specified interface.
*/
public <T> StandardEmitterMBean(T implementation, Class<T> mbeanInterface,
boolean isMXBean,
NotificationEmitter emitter) {
- super(implementation, mbeanInterface, isMXBean);
+ this(implementation, mbeanInterface,
+ isMXBean ? MBeanOptions.MXBEAN : null, emitter);
+ }
+
+ /**
+ * <p>Make an MBean whose management interface is specified by {@code
+ * mbeanInterface}, with the given implementation and options, and where
+ * notifications are handled by the given {@code NotificationEmitter}.
+ * Options select whether to make a Standard MBean or an MXBean, and
+ * whether the result of {@link #getWrappedObject()} is the {@code
+ * StandardEmitterMBean} object or the given implementation. The resultant
+ * MBean implements the {@code NotificationEmitter} interface by forwarding
+ * its methods to {@code emitter}. It is legal and useful for {@code
+ * implementation} and {@code emitter} to be the same object.</p>
+ *
+ * <p>If {@code emitter} is an instance of {@code
+ * SendNotification} (for example, a {@link NotificationBroadcasterSupport}),
+ * then the MBean's {@link #sendNotification
+ * sendNotification} method will call {@code emitter.}{@link
+ * SendNotification#sendNotification sendNotification}.</p>
+ *
+ * <p>The array returned by {@link #getNotificationInfo()} on the
+ * new MBean is a copy of the array returned by
+ * {@code emitter.}{@link NotificationBroadcaster#getNotificationInfo
+ * getNotificationInfo()} at the time of construction. If the array
+ * returned by {@code emitter.getNotificationInfo()} later changes,
+ * that will have no effect on this object's
+ * {@code getNotificationInfo()}.</p>
+ *
+ * @param implementation the implementation of the MBean interface.
+ * @param mbeanInterface a Standard MBean interface.
+ * @param options MBeanOptions that control the operation of the resulting
+ * MBean.
+ * @param emitter the object that will handle notifications. If null,
+ * a new {@code NotificationEmitter} will be constructed that also
+ * implements {@link SendNotification}.
+ *
+ * @throws IllegalArgumentException if the {@code mbeanInterface}
+ * does not follow JMX design patterns for Management Interfaces, or
+ * if the given {@code implementation} does not implement the
+ * specified interface.
+ */
+ public <T> StandardEmitterMBean(T implementation, Class<T> mbeanInterface,
+ MBeanOptions options,
+ NotificationEmitter emitter) {
+ super(implementation, mbeanInterface, options);
if (emitter == null)
- throw new IllegalArgumentException("Null emitter");
+ emitter = defaultEmitter();
this.emitter = emitter;
this.notificationInfo = emitter.getNotificationInfo();
+ injectEmitter();
}
/**
@@ -159,9 +210,10 @@ public class StandardEmitterMBean extend
* by forwarding its methods to {@code emitter}.</p>
*
* <p>If {@code emitter} is an instance of {@code
- * NotificationBroadcasterSupport} then the MBean's {@link #sendNotification
- * sendNotification} method will call {@code emitter.}{@link
- * NotificationBroadcasterSupport#sendNotification sendNotification}.</p>
+ * SendNotification} (for example, a {@link NotificationBroadcasterSupport}),
+ * then the MBean's {@link #sendNotification
+ * sendNotification} method will call {@code emitter.}{@link
+ * SendNotification#sendNotification sendNotification}.</p>
*
* <p>The array returned by {@link #getNotificationInfo()} on the
* new MBean is a copy of the array returned by
@@ -175,20 +227,17 @@ public class StandardEmitterMBean extend
* the given {@code mbeanInterface}.</p>
*
* @param mbeanInterface a StandardMBean interface.
- * @param emitter the object that will handle notifications.
- *
- * @throws IllegalArgumentException if the {@code mbeanInterface}
- * does not follow JMX design patterns for Management Interfaces, or
- * if {@code this} does not implement the specified interface, or
- * if {@code emitter} is null.
+ * @param emitter the object that will handle notifications. If null,
+ * a new {@code NotificationEmitter} will be constructed that also
+ * implements {@link SendNotification}.
+ *
+ * @throws IllegalArgumentException if the {@code mbeanInterface}
+ * does not follow JMX design patterns for Management Interfaces, or
+ * if {@code this} does not implement the specified interface.
*/
protected StandardEmitterMBean(Class<?> mbeanInterface,
NotificationEmitter emitter) {
- super(mbeanInterface, false);
- if (emitter == null)
- throw new IllegalArgumentException("Null emitter");
- this.emitter = emitter;
- this.notificationInfo = emitter.getNotificationInfo();
+ this(mbeanInterface, false, emitter);
}
/**
@@ -200,9 +249,10 @@ public class StandardEmitterMBean extend
* forwarding its methods to {@code emitter}.</p>
*
* <p>If {@code emitter} is an instance of {@code
- * NotificationBroadcasterSupport} then the MBean's {@link #sendNotification
- * sendNotification} method will call {@code emitter.}{@link
- * NotificationBroadcasterSupport#sendNotification sendNotification}.</p>
+ * SendNotification} (for example, a {@link NotificationBroadcasterSupport}),
+ * then the MBean's {@link #sendNotification
+ * sendNotification} method will call {@code emitter.}{@link
+ * SendNotification#sendNotification sendNotification}.</p>
*
* <p>The array returned by {@link #getNotificationInfo()} on the
* new MBean is a copy of the array returned by
@@ -218,20 +268,86 @@ public class StandardEmitterMBean extend
* @param mbeanInterface a StandardMBean interface.
* @param isMXBean If true, the {@code mbeanInterface} parameter
* names an MXBean interface and the resultant MBean is an MXBean.
- * @param emitter the object that will handle notifications.
- *
- * @throws IllegalArgumentException if the {@code mbeanInterface}
- * does not follow JMX design patterns for Management Interfaces, or
- * if {@code this} does not implement the specified interface, or
- * if {@code emitter} is null.
+ * @param emitter the object that will handle notifications. If null,
+ * a new {@code NotificationEmitter} will be constructed that also
+ * implements {@link SendNotification}.
+ *
+ * @throws IllegalArgumentException if the {@code mbeanInterface}
+ * does not follow JMX design patterns for Management Interfaces, or
+ * if {@code this} does not implement the specified interface.
*/
protected StandardEmitterMBean(Class<?> mbeanInterface, boolean isMXBean,
NotificationEmitter emitter) {
- super(mbeanInterface, isMXBean);
+ this(mbeanInterface, isMXBean ? MBeanOptions.MXBEAN : null, emitter);
+ }
+
+ /**
+ * <p>Make an MBean whose management interface is specified by {@code
+ * mbeanInterface}, with the given options, and where notifications are
+ * handled by the given {@code NotificationEmitter}. This constructor can
+ * be used to make either Standard MBeans or MXBeans. The resultant MBean
+ * implements the {@code NotificationEmitter} interface by forwarding its
+ * methods to {@code emitter}.</p>
+ *
+ * <p>If {@code emitter} is an instance of {@code
+ * SendNotification} (for example, a {@link NotificationBroadcasterSupport}),
+ * then the MBean's {@link #sendNotification
+ * sendNotification} method will call {@code emitter.}{@link
+ * SendNotification#sendNotification sendNotification}.</p>
+ *
+ * <p>The array returned by {@link #getNotificationInfo()} on the
+ * new MBean is a copy of the array returned by
+ * {@code emitter.}{@link NotificationBroadcaster#getNotificationInfo
+ * getNotificationInfo()} at the time of construction. If the array
+ * returned by {@code emitter.getNotificationInfo()} later changes,
+ * that will have no effect on this object's
+ * {@code getNotificationInfo()}.</p>
+ *
+ * <p>This constructor must be called from a subclass that implements
+ * the given {@code mbeanInterface}.</p>
+ *
+ * @param mbeanInterface a StandardMBean interface.
+ * @param options MBeanOptions that control the operation of the resulting
+ * MBean.
+ * @param emitter the object that will handle notifications. If null,
+ * a new {@code NotificationEmitter} will be constructed that also
+ * implements {@link SendNotification}.
+ *
+ * @throws IllegalArgumentException if the {@code mbeanInterface}
+ * does not follow JMX design patterns for Management Interfaces, or
+ * if {@code this} does not implement the specified interface.
+ */
+ protected StandardEmitterMBean(Class<?> mbeanInterface, MBeanOptions options,
+ NotificationEmitter emitter) {
+ super(mbeanInterface, options);
if (emitter == null)
- throw new IllegalArgumentException("Null emitter");
+ emitter = defaultEmitter();
this.emitter = emitter;
this.notificationInfo = emitter.getNotificationInfo();
+ injectEmitter();
+ }
+
+ private NotificationEmitter defaultEmitter() {
+ MBeanNotificationInfo[] mbnis = getNotificationInfo();
+ // Will be null unless getNotificationInfo() is overridden,
+ // since the notificationInfo field has not been set at this point.
+ if (mbnis == null)
+ mbnis = getMBeanInfo().getNotifications();
+ return new NotificationBroadcasterSupport(mbnis);
+ }
+
+ private void injectEmitter() {
+ if (emitter instanceof SendNotification) {
+ try {
+ Object resource = getImplementation();
+ SendNotification send = (SendNotification) emitter;
+ MBeanInjector.injectSendNotification(resource, send);
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
}
public void removeNotificationListener(NotificationListener listener)
@@ -259,10 +375,10 @@ public class StandardEmitterMBean extend
/**
* <p>Sends a notification.</p>
*
- * <p>If the {@code emitter} parameter to the constructor was an
- * instance of {@code NotificationBroadcasterSupport} then this
- * method will call {@code emitter.}{@link
- * NotificationBroadcasterSupport#sendNotification
+ * <p>If the {@code emitter} parameter to the constructor was
+ * an instance of {@link SendNotification}, such as {@link
+ * NotificationBroadcasterSupport}, then this method will call {@code
+ * emitter.}{@link SendNotification#sendNotification
* sendNotification}.</p>
*
* @param n the notification to send.
@@ -271,13 +387,12 @@ public class StandardEmitterMBean extend
* constructor was not a {@code NotificationBroadcasterSupport}.
*/
public void sendNotification(Notification n) {
- if (emitter instanceof NotificationBroadcasterSupport)
- ((NotificationBroadcasterSupport) emitter).sendNotification(n);
+ if (emitter instanceof SendNotification)
+ ((SendNotification) emitter).sendNotification(n);
else {
final String msg =
"Cannot sendNotification when emitter is not an " +
- "instance of NotificationBroadcasterSupport: " +
- emitter.getClass().getName();
+ "instance of SendNotification: " + emitter.getClass().getName();
throw new ClassCastException(msg);
}
}
@@ -292,6 +407,7 @@ public class StandardEmitterMBean extend
* @param info The default MBeanInfo derived by reflection.
* @return the MBeanNotificationInfo[] for the new MBeanInfo.
*/
+ @Override
MBeanNotificationInfo[] getNotifications(MBeanInfo info) {
return getNotificationInfo();
}
--- a/src/share/classes/javax/management/StandardMBean.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/StandardMBean.java Tue Aug 05 13:15:22 2008 -0700
@@ -27,6 +27,7 @@ package javax.management;
import com.sun.jmx.mbeanserver.DescriptorCache;
import com.sun.jmx.mbeanserver.Introspector;
+import com.sun.jmx.mbeanserver.MBeanInjector;
import com.sun.jmx.mbeanserver.MBeanSupport;
import com.sun.jmx.mbeanserver.MXBeanSupport;
import com.sun.jmx.mbeanserver.StandardMBeanSupport;
@@ -125,7 +126,78 @@ import static javax.management.JMX.MBean
*
* @since 1.5
*/
-public class StandardMBean implements DynamicMBean, MBeanRegistration {
+public class StandardMBean implements DynamicWrapperMBean, MBeanRegistration {
+
+ /**
+ * <p>Options controlling the behavior of {@code StandardMBean} instances.</p>
+ */
+ public static class Options extends JMX.MBeanOptions {
+ private static final long serialVersionUID = 5107355471177517164L;
+
+ private boolean wrappedVisible;
+
+ /**
+ * <p>Construct an {@code Options} object where all options have
+ * their default values.</p>
+ */
+ public Options() {}
+
+ @Override
+ public Options clone() {
+ return (Options) super.clone();
+ }
+
+ /**
+ * <p>Defines whether the {@link StandardMBean#getWrappedObject()
+ * getWrappedObject} method returns the wrapped object.</p>
+ *
+ * <p>If this option is true, then {@code getWrappedObject()} will return
+ * the same object as {@link StandardMBean#getImplementation()
+ * getImplementation}. Otherwise, it will return the
+ * StandardMBean instance itself. The setting of this option
+ * affects the behavior of {@link MBeanServer#getClassLoaderFor
+ * MBeanServer.getClassLoaderFor} and {@link MBeanServer#isInstanceOf
+ * MBeanServer.isInstanceOf}. The default value is false for
+ * compatibility reasons, but true is a better value for most new code.</p>
+ *
+ * @return true if this StandardMBean's {@link
+ * StandardMBean#getWrappedObject getWrappedObject} returns the wrapped
+ * object.
+ */
+ public boolean isWrappedObjectVisible() {
+ return this.wrappedVisible;
+ }
+
+ /**
+ * <p>Set the {@link #isWrappedObjectVisible WrappedObjectVisible} option
+ * to the given value.</p>
+ * @param visible the new value.
+ */
+ public void setWrappedObjectVisible(boolean visible) {
+ this.wrappedVisible = visible;
+ }
+
+ // Canonical objects for each of (MXBean,!MXBean) x (WVisible,!WVisible)
+ private static final Options[] CANONICALS = {
+ new Options(), new Options(), new Options(), new Options(),
+ };
+ static {
+ CANONICALS[1].setMXBeanMappingFactory(MXBeanMappingFactory.DEFAULT);
+ CANONICALS[2].setWrappedObjectVisible(true);
+ CANONICALS[3].setMXBeanMappingFactory(MXBeanMappingFactory.DEFAULT);
+ CANONICALS[3].setWrappedObjectVisible(true);
+ }
+ @Override
+ MBeanOptions[] canonicals() {
+ return CANONICALS;
+ }
+
+ @Override
+ boolean same(MBeanOptions opts) {
+ return (super.same(opts) && opts instanceof Options &&
+ ((Options) opts).wrappedVisible == wrappedVisible);
+ }
+ }
private final static DescriptorCache descriptors =
DescriptorCache.getInstance(JMX.proof);
@@ -347,7 +419,7 @@ public class StandardMBean implements Dy
* the management interface associated with the given
* implementation.
* @param options MBeanOptions that control the operation of the resulting
- * MBean, as documented in the {@link MBeanOptions} class.
+ * MBean.
* @param <T> Allows the compiler to check
* that {@code implementation} does indeed implement the class
* described by {@code mbeanInterface}. The compiler can only
@@ -381,7 +453,7 @@ public class StandardMBean implements Dy
* @param mbeanInterface The Management Interface exported by this
* MBean.
* @param options MBeanOptions that control the operation of the resulting
- * MBean, as documented in the {@link MBeanOptions} class.
+ * MBean.
*
* @exception IllegalArgumentException if the <var>mbeanInterface</var>
* does not follow JMX design patterns for Management Interfaces, or
@@ -441,7 +513,67 @@ public class StandardMBean implements Dy
* @see #setImplementation
**/
public Object getImplementation() {
- return mbean.getResource();
+ return mbean.getWrappedObject();
+ }
+
+ /**
+ * <p>Get the wrapped implementation object or return this object.</p>
+ *
+ * <p>For compatibility reasons, this method only returns the wrapped
+ * implementation object if the {@link Options#isWrappedObjectVisible
+ * WrappedObjectVisible} option was specified when this StandardMBean
+ * was created. Otherwise it returns {@code this}.</p>
+ *
+ * <p>If you want the MBeanServer's {@link MBeanServer#getClassLoaderFor
+ * getClassLoaderFor} and {@link MBeanServer#isInstanceOf
+ * isInstanceOf} methods to refer to the wrapped implementation and
+ * not this StandardMBean object, then you must set the
+ * {@code WrappedObjectVisible} option, for example using:</p>
+ *
+ * <pre>
+ * StandardMBean.Options opts = new StandardMBean.Options();
+ * opts.setWrappedObjectVisible(true);
+ * StandardMBean mbean = new StandardMBean(impl, MyMBean.class, opts);
+ * </pre>
+ *
+ * @return The wrapped implementation object, or this StandardMBean
+ * instance.
+ */
+ public Object getWrappedObject() {
+ if (options instanceof Options &&
+ ((Options) options).isWrappedObjectVisible())
+ return getImplementation();
+ else
+ return this;
+ }
+
+ /**
+ * <p>Get the ClassLoader of the wrapped implementation object or of this
+ * object.</p>
+ *
+ * <p>For compatibility reasons, this method only returns the ClassLoader
+ * of the wrapped implementation object if the {@link
+ * Options#isWrappedObjectVisible WrappedObjectVisible} option was
+ * specified when this StandardMBean was created. Otherwise it returns
+ * {@code this.getClass().getClassLoader()}.</p>
+ *
+ * <p>If you want the MBeanServer's {@link MBeanServer#getClassLoaderFor
+ * getClassLoaderFor} and {@link MBeanServer#isInstanceOf
+ * isInstanceOf} methods to refer to the wrapped implementation and
+ * not this StandardMBean object, then you must set the
+ * {@code WrappedObjectVisible} option, for example using:</p>
+ *
+ * <pre>
+ * StandardMBean.Options opts = new StandardMBean.Options();
+ * opts.setWrappedObjectVisible(true);
+ * StandardMBean mbean = new StandardMBean(impl, MyMBean.class, opts);
+ * </pre>
+ *
+ * @return The ClassLoader of the wrapped Cimplementation object, or of
+ * this StandardMBean instance.
+ */
+ public ClassLoader getWrappedClassLoader() {
+ return getWrappedObject().getClass().getClassLoader();
}
/**
@@ -457,7 +589,7 @@ public class StandardMBean implements Dy
* @return The class of the implementation of this Standard MBean (or MXBean).
**/
public Class<?> getImplementationClass() {
- return mbean.getResource().getClass();
+ return mbean.getWrappedObject().getClass();
}
/**
@@ -559,7 +691,7 @@ public class StandardMBean implements Dy
MBeanSupport msupport = mbean;
final MBeanInfo bi = msupport.getMBeanInfo();
- final Object impl = msupport.getResource();
+ final Object impl = msupport.getWrappedObject();
final boolean immutableInfo = immutableInfo(this.getClass());
@@ -1184,6 +1316,7 @@ public class StandardMBean implements Dy
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
mbean.register(server, name);
+ MBeanInjector.inject(mbean.getWrappedObject(), server, name);
return name;
}
--- a/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java Tue Aug 05 13:15:22 2008 -0700
@@ -23,7 +23,7 @@
* have any questions.
*/
/*
- * @author IBM Corp.
+ * @(#)author IBM Corp.
*
* Copyright IBM Corp. 1999-2000. All rights reserved.
*/
@@ -55,6 +55,7 @@ import javax.management.AttributeList;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.Descriptor;
+import javax.management.DynamicWrapperMBean;
import javax.management.InstanceNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
@@ -115,7 +116,7 @@ import sun.reflect.misc.ReflectUtil;
*/
public class RequiredModelMBean
- implements ModelMBean, MBeanRegistration, NotificationEmitter {
+ implements ModelMBean, MBeanRegistration, NotificationEmitter, DynamicWrapperMBean {
/*************************************/
/* attributes */
@@ -132,6 +133,9 @@ public class RequiredModelMBean
/* handle, name, or reference for instance on which the actual invoke
* and operations will be executed */
private Object managedResource = null;
+
+ /* true if getWrappedObject returns the wrapped resource */
+ private boolean visible;
/* records the registering in MBeanServer */
private boolean registered = false;
@@ -318,9 +322,13 @@ public class RequiredModelMBean
*
* @param mr Object that is the managed resource
* @param mr_type The type of reference for the managed resource.
- * <br>Can be: "ObjectReference", "Handle", "IOR", "EJBHandle",
- * or "RMIReference".
- * <br>In this implementation only "ObjectReference" is supported.
+ * <br>Can be: "ObjectReference", "VisibleObjectReference",
+ * "Handle", "IOR", "EJBHandle", or "RMIReference".
+ * <br>In this implementation only "ObjectReference" and
+ * "VisibleObjectReference" are supported. The two
+ * types are equivalent except for the behavior of the
+ * {@link #getWrappedObject()} and {@link #getWrappedClassLoader()}
+ * methods.
*
* @exception MBeanException The initializer of the object has
* thrown an exception.
@@ -340,10 +348,11 @@ public class RequiredModelMBean
"setManagedResource(Object,String)","Entry");
}
+ visible = "visibleObjectReference".equalsIgnoreCase(mr_type);
+
// check that the mr_type is supported by this JMXAgent
// only "objectReference" is supported
- if ((mr_type == null) ||
- (! mr_type.equalsIgnoreCase("objectReference"))) {
+ if (!"objectReference".equalsIgnoreCase(mr_type) && !visible) {
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
@@ -366,6 +375,51 @@ public class RequiredModelMBean
RequiredModelMBean.class.getName(),
"setManagedResource(Object, String)", "Exit");
}
+ }
+
+ /**
+ * <p>Get the managed resource for this Model MBean. For compatibility
+ * reasons, the managed resource is only returned if the resource type
+ * specified to {@link #setManagedResource setManagedResource} was {@code
+ * "visibleObjectReference"}. Otherwise, {@code this} is returned.</p>
+ *
+ * @return The value that was specified to {@link #setManagedResource
+ * setManagedResource}, if the resource type is {@code
+ * "visibleObjectReference"}. Otherwise, {@code this}.
+ */
+ public Object getWrappedObject() {
+ if (visible)
+ return managedResource;
+ else
+ return this;
+ }
+
+ /**
+ * <p>Get the ClassLoader of the managed resource for this Model MBean. For
+ * compatibility reasons, the ClassLoader of the managed resource is only
+ * returned if the resource type specified to {@link #setManagedResource
+ * setManagedResource} was {@code "visibleObjectReference"}. Otherwise,
+ * {@code this.getClass().getClassLoader()} is returned.</p>
+ *
+ * @return The ClassLoader of the value that was specified to
+ * {@link #setManagedResource setManagedResource}, if the resource
+ * type is {@code "visibleObjectReference"}. Otherwise, {@code
+ * this.getClass().getClassLoader()}.
+ */
+ public ClassLoader getWrappedClassLoader() {
+ return getWrappedObject().getClass().getClassLoader();
+ }
+
+ private static boolean isTrue(Descriptor d, String field) {
+ if (d == null)
+ return false;
+ Object x = d.getFieldValue(field);
+ if (x instanceof Boolean)
+ return (Boolean) x;
+ if (!(x instanceof String))
+ return false;
+ String s = (String) x;
+ return ("true".equalsIgnoreCase(s) || "T".equalsIgnoreCase(s));
}
/**
--- a/src/share/classes/javax/management/monitor/package.html Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/monitor/package.html Tue Aug 05 13:15:22 2008 -0700
@@ -38,14 +38,17 @@ have any questions.
so within the access control context of the
{@link javax.management.monitor.Monitor#start} caller.</p>
- <p>The value being monitored can be a simple value contained within a
- complex type. For example, the {@link java.lang.management.MemoryMXBean
- MemoryMXBean} defined in <tt>java.lang.management</tt> has an attribute
- <tt>HeapMemoryUsage</tt> of type {@link java.lang.management.MemoryUsage
- MemoryUsage}. To monitor the amount of <i>used</i> memory, described by
- the <tt>used</tt> property of <tt>MemoryUsage</tt>, you could monitor
- "<tt>HeapMemoryUsage.used</tt>". That string would be the argument to
- {@link javax.management.monitor.MonitorMBean#setObservedAttribute(String)
+ <p id="complex">The value being monitored can be a simple value
+ contained within a complex type. For example, the {@link
+ java.lang.management.MemoryMXBean MemoryMXBean} defined in
+ <tt>java.lang.management</tt> has an attribute
+ <tt>HeapMemoryUsage</tt> of type {@link
+ java.lang.management.MemoryUsage MemoryUsage}. To monitor the
+ amount of <i>used</i> memory, described by the <tt>used</tt>
+ property of <tt>MemoryUsage</tt>, you could monitor
+ "<tt>HeapMemoryUsage.used</tt>". That string would be the
+ argument to {@link
+ javax.management.monitor.MonitorMBean#setObservedAttribute(String)
setObservedAttribute}.</p>
<p>The rules used to interpret an <tt>ObservedAttribute</tt> like
--- a/src/share/classes/javax/management/package.html Tue Aug 05 13:06:42 2008 -0700
+++ b/src/share/classes/javax/management/package.html Tue Aug 05 13:15:22 2008 -0700
@@ -56,41 +56,41 @@ have any questions.
resource. It has a <em>management interface</em> consisting
of:</p>
- <ul>
- <li>named and typed attributes that can be read and/or
- written</li>
-
- <li>named and typed operations that can be invoked</li>
-
- <li>typed notifications that can be emitted by the MBean.</li>
- </ul>
-
- <p>For example, an MBean representing an application's
- configuration could have attributes representing the different
- configuration items. Reading the <code>CacheSize</code>
- attribute would return the current value of that item.
- Writing it would update the item, potentially changing the
- behavior of the running application. An operation such as
- <code>save</code> could store the current configuration
- persistently. A notification such as
- <code>ConfigurationChangedNotification</code> could be sent
- every time the configuration is changed.</p>
-
- <p>In the standard usage of the JMX API, MBeans are implemented
- as Java objects. However, as explained below, these objects are
- not usually referenced directly.</p>
-
-
- <h3>Standard MBeans</h3>
-
- <p>To make MBean implementation simple, the JMX API includes the
- notion of <em>Standard MBeans</em>. A Standard MBean is one
- whose attributes and operations are deduced from a Java
- interface using certain naming patterns, similar to those used
- by JavaBeans<sup><font size="-1">TM</font></sup>. For
- example, consider an interface like this:</p>
-
- <pre>
+ <ul>
+ <li>named and typed attributes that can be read and/or
+ written</li>
+
+ <li>named and typed operations that can be invoked</li>
+
+ <li>typed notifications that can be emitted by the MBean.</li>
+ </ul>
+
+ <p>For example, an MBean representing an application's
+ configuration could have attributes representing the different
+ configuration items. Reading the <code>CacheSize</code>
+ attribute would return the current value of that item.
+ Writing it would update the item, potentially changing the
+ behavior of the running application. An operation such as
+ <code>save</code> could store the current configuration
+ persistently. A notification such as
+ <code>ConfigurationChangedNotification</code> could be sent
+ every time the configuration is changed.</p>
+
+ <p>In the standard usage of the JMX API, MBeans are implemented
+ as Java objects. However, as explained below, these objects are
+ not usually referenced directly.</p>
+
+
+ <h3>Standard MBeans</h3>
+
+ <p>To make MBean implementation simple, the JMX API includes the
+ notion of <em>Standard MBeans</em>. A Standard MBean is one
+ whose attributes and operations are deduced from a Java
+ interface using certain naming patterns, similar to those used
+ by JavaBeans<sup><font size="-1">TM</font></sup>. For
+ example, consider an interface like this:</p>
+
+ <pre>
public interface ConfigurationMBean {
public int getCacheSize();
public void setCacheSize(int size);
@@ -128,107 +128,148 @@ have any questions.
class.</p>
- <h3>MXBeans</h3>
-
- <p>An <em>MXBean</em> is a variant of Standard MBean where complex
- types are mapped to a standard set of types defined in the
- {@link javax.management.openmbean} package. MXBeans are appropriate
- if you would otherwise need to reference application-specific
- classes in your MBean interface. They are described in detail
- in the specification for {@link javax.management.MXBean MXBean}.
-
-
- <h3>Dynamic MBeans</h3>
-
- <p>A <em>Dynamic MBean</em> is an MBean that defines its
- management interface at run-time. For example, a configuration
- MBean could determine the names and types of the attributes it
- exposes by parsing an XML file.</p>
-
- <p>Any Java object of a class that implements the {@link
- javax.management.DynamicMBean DynamicMBean} interface is a
- Dynamic MBean.</p>
-
-
- <h3>Open MBeans</h3>
-
- <p>An <em>Open MBean</em> is a kind of Dynamic MBean where the
- types of attributes and of operation parameters and return
- values are built using a small set of predefined Java classes.
- Open MBeans facilitate operation with remote management programs
- that do not necessarily have access to application-specific
- types, including non-Java programs. Open MBeans are defined by
- the package <a href="openmbean/package-summary.html"><code>
- javax.management.openmbean</code></a>.</p>
-
-
- <h3>Model MBeans</h3>
-
- <p>A <em>Model MBean</em> is a kind of Dynamic MBean that acts
- as a bridge between the management interface and the
- underlying managed resource. Both the management interface and
- the managed resource are specified as Java objects. The same
- Model MBean implementation can be reused many times with
- different management interfaces and managed resources, and it can
- provide common functionality such as persistence and caching.
- Model MBeans are defined by the package
- <a href="modelmbean/package-summary.html"><code>
- javax.management.modelmbean</code></a>.</p>
-
-
- <h2>MBean Server</h2>
-
- <p>To be useful, an MBean must be registered in an <em>MBean
- Server</em>. An MBean Server is a repository of MBeans.
- Usually the only access to the MBeans is through the MBean
- Server. In other words, code no longer accesses the Java
- object implementing the MBean directly, but instead accesses
- the MBean by name through the MBean Server. Each MBean has a
- unique name within the MBean Server, defined by the {@link
- javax.management.ObjectName ObjectName} class.</p>
-
- <p>An MBean Server is an object implementing the interface
- {@link javax.management.MBeanServer MBeanServer}.
- The most convenient MBean Server to use is the
- <em>Platform MBean Server</em>. This is a
- single MBean Server that can be shared by different managed
- components running within the same Java Virtual Machine. The
- Platform MBean Server is accessed with the method {@link
- java.lang.management.ManagementFactory#getPlatformMBeanServer()}.</p>
-
- <p>Application code can also create a new MBean Server, or
- access already-created MBean Servers, using the {@link
- javax.management.MBeanServerFactory MBeanServerFactory} class.</p>
-
-
- <h3>Creating MBeans in the MBean Server</h3>
-
- <p>There are two ways to create an MBean. One is to construct a
- Java object that will be the MBean, then use the {@link
- javax.management.MBeanServer#registerMBean registerMBean}
- method to register it in the MBean Server. The other is to
- create and register the MBean in a single operation using one
- of the {@link javax.management.MBeanServer#createMBean(String,
- javax.management.ObjectName) createMBean} methods.</p>
-
- <p>The <code>registerMBean</code> method is simpler for local
- use, but cannot be used remotely. The
- <code>createMBean</code> method can be used remotely, but
- sometimes requires attention to class loading issues.</p>
-
- <p>An MBean can perform actions when it is registered in or
- unregistered from an MBean Server if it implements the {@link
- javax.management.MBeanRegistration MBeanRegistration}
- interface.</p>
-
-
- <h3>Accessing MBeans in the MBean Server</h3>
-
- <p>Given an <code>ObjectName</code> <code>name</code> and an
- <code>MBeanServer</code> <code>mbs</code>, you can access
- attributes and operations as in this example:</p>
-
- <pre>
+ <h3 id="stdannot">Defining Standard MBeans with annotations</h3>
+
+ <p>As an alternative to creating an interface such as
+ <code>ConfigurationMBean</code> and a class that implements it,
+ you can write just the class, and use annotations to pick out the
+ public methods that will make up the management interface. For
+ example, the following class has the same management interface
+ as a <code>Configuration</code> class that implements the
+ <code>ConfigurationMBean</code> interface above.</p>
+
+ <pre>
+ {@link javax.management.MBean @MBean}
+ public class Configuration {
+ {@link javax.management.ManagedAttribute @ManagedAttribute}
+ public int getCacheSize() {...}
+ @ManagedAttribute
+ public void setCacheSize(int size) {...}
+
+ @ManagedAttribute
+ public long getLastChangedTime() {...}
+
+ {@link javax.management.ManagedOperation @ManagedOperation}
+ public void save() {...}
+ ...
+ }
+ </pre>
+
+ <p>This approach simplifies development, but it does have two
+ potential drawbacks. First, if you run the Javadoc tool on
+ this class, the documentation of the management interface may
+ be mixed in with the documentation of non-management methods
+ in the class. Second, you cannot make a proxy
+ as described <a href="#proxy">below</a> if you do not have an
+ interface like <code>ConfigurationMBean</code>.</p>
+
+
+ <h3>MXBeans</h3>
+
+ <p>An <em>MXBean</em> is a variant of Standard MBean where complex
+ types are mapped to a standard set of types defined in the
+ {@link javax.management.openmbean} package. MXBeans are appropriate
+ if you would otherwise need to reference application-specific
+ classes in your MBean interface. They are described in detail
+ in the specification for {@link javax.management.MXBean MXBean}.</p>
+
+ <p>You can define MXBeans using annotations as described
+ in the <a href="#stdannot">previous section</a>, but
+ using the <code>@MXBean</code> annotation instead of
+ <code>@MBean</code>.</p>
+
+
+ <h3>Dynamic MBeans</h3>
+
+ <p>A <em>Dynamic MBean</em> is an MBean that defines its
+ management interface at run-time. For example, a configuration
+ MBean could determine the names and types of the attributes it
+ exposes by parsing an XML file.</p>
+
+ <p>Any Java object of a class that implements the {@link
+