This commit is contained in:
J. Duke 2017-07-05 17:32:09 +02:00
commit baba3e9383
221 changed files with 7188 additions and 3416 deletions

View File

@ -99,3 +99,4 @@ a12a9e78df8a9d534da0b4a244ed68f0de0bd58e jdk7-b118
f1591eed71f64f6eba79fb7426f5616cc4dfea73 jdk7-b122 f1591eed71f64f6eba79fb7426f5616cc4dfea73 jdk7-b122
ed6950da30cf1e8904b4bdb034d471647942271f jdk7-b123 ed6950da30cf1e8904b4bdb034d471647942271f jdk7-b123
024a6755895bf91b5a3c98984c89ee018efbf538 jdk7-b124 024a6755895bf91b5a3c98984c89ee018efbf538 jdk7-b124
5c4df7e992775c102f08e9f1c0a124b324641b70 jdk7-b125

View File

@ -140,3 +140,4 @@ f5603a6e50422046ebc0d2f1671d55cb8f1bf1e9 jdk7-b120
9669f9b284108a9ee0a0ccbe215c37a130c9dcf5 hs20-b04 9669f9b284108a9ee0a0ccbe215c37a130c9dcf5 hs20-b04
0a8e0d4345b37b71ec49dda08ee03b68c4f1b592 jdk7-b124 0a8e0d4345b37b71ec49dda08ee03b68c4f1b592 jdk7-b124
0a8e0d4345b37b71ec49dda08ee03b68c4f1b592 hs20-b05 0a8e0d4345b37b71ec49dda08ee03b68c4f1b592 hs20-b05
e24ab3fa6aafad3efabbe7dba9918c5f461a20b1 jdk7-b125

View File

@ -99,3 +99,4 @@ a661d8587b5d8986aacae086f5df66af9e1a96b1 jdk7-b121
ac311eb325bfc763698219252bf3cee9e091f3af jdk7-b122 ac311eb325bfc763698219252bf3cee9e091f3af jdk7-b122
869190935eedee7750d955019ab2a1b80f0a13a8 jdk7-b123 869190935eedee7750d955019ab2a1b80f0a13a8 jdk7-b123
1c72adc9d5f331cb882cf5354ba0dcb118a60b23 jdk7-b124 1c72adc9d5f331cb882cf5354ba0dcb118a60b23 jdk7-b124
0a56bdd709d01c1663047e55201d19152ffd3d69 jdk7-b125

View File

@ -155,7 +155,7 @@ ifdef LANGTOOLS_DIST
"-Xbootclasspath/p:$(JAVAC_JAR)" \ "-Xbootclasspath/p:$(JAVAC_JAR)" \
-jar $(JAVAC_JAR) $(JAVACFLAGS) -jar $(JAVAC_JAR) $(JAVACFLAGS)
JAVAH_CMD = $(BOOT_JAVA_CMD) \ JAVAH_CMD = $(BOOT_JAVA_CMD) \
"-Xbootclasspath/p:$(JAVAH_JAR)$(CLASSPATH_SEPARATOR)$(JAVADOC_JAR)$(CLASSPATH_SEPARATOR)$(JAVAC_JAR)" \ "-Xbootclasspath/p:$(JAVAH_JAR)$(CLASSPATH_SEPARATOR)$(JAVAC_JAR)" \
-jar $(JAVAH_JAR) $(JAVAHFLAGS) -jar $(JAVAH_JAR) $(JAVAHFLAGS)
JAVADOC_CMD = $(BOOT_JAVA_CMD) \ JAVADOC_CMD = $(BOOT_JAVA_CMD) \
"-Xbootclasspath/p:$(JAVADOC_JAR)$(CLASSPATH_SEPARATOR)$(JAVAC_JAR)$(CLASSPATH_SEPARATOR)$(DOCLETS_JAR)" \ "-Xbootclasspath/p:$(JAVADOC_JAR)$(CLASSPATH_SEPARATOR)$(JAVAC_JAR)$(CLASSPATH_SEPARATOR)$(DOCLETS_JAR)" \

View File

@ -42,7 +42,15 @@ ifneq ($(PLATFORM), windows)
ifndef OPENJDK ifndef OPENJDK
ifeq ($(PLATFORM), solaris) ifeq ($(PLATFORM), solaris)
ifneq ($(ARCH), amd64) ifneq ($(ARCH), amd64)
DGA_SUBDIR = jdga # Solaris 11 does not have support for new compilation of DGA code.
OS_VERSION = $(shell uname -r)
OS_MAJOR_VERSION := $(call MajorVersion,$(OS_VERSION))
OS_MINOR_VERSION := $(call MinorVersion,$(OS_VERSION))
ifeq ($(shell $(EXPR) $(OS_MAJOR_VERSION) == 5), 1)
ifeq ($(shell $(EXPR) $(OS_MINOR_VERSION) \<= 10), 1)
DGA_SUBDIR = jdga
endif
endif
endif endif
endif endif
endif endif

View File

@ -175,6 +175,10 @@ endif
include $(BUILDDIR)/common/Mapfile-vers.gmk include $(BUILDDIR)/common/Mapfile-vers.gmk
include $(BUILDDIR)/common/Library.gmk include $(BUILDDIR)/common/Library.gmk
COMPILEFONTCONFIG_FLAGS =
ifdef ALT_COMPILEFONTCONFIG_FLAGS
COMPILEFONTCONFIG_FLAGS += $(ALT_COMPILEFONTCONFIG_FLAGS)
endif
build: fontconfigs build: fontconfigs
@ -406,7 +410,7 @@ COMPILEFONTCONFIG_JARFILE = $(BUILDTOOLJARDIR)/compilefontconfig.jar
$(LIBDIR)/%.bfc: $(FONTCONFIGS_SRC)/$(FONTCONFIGS_SRC_PREFIX)%.properties \ $(LIBDIR)/%.bfc: $(FONTCONFIGS_SRC)/$(FONTCONFIGS_SRC_PREFIX)%.properties \
$(COMPILEFONTCONFIG_JARFILE) $(COMPILEFONTCONFIG_JARFILE)
$(prep-target) $(prep-target)
$(BOOT_JAVA_CMD) -jar $(COMPILEFONTCONFIG_JARFILE) $< $@ $(BOOT_JAVA_CMD) -jar $(COMPILEFONTCONFIG_JARFILE) $(COMPILEFONTCONFIG_FLAGS) $< $@
$(install-module-file) $(install-module-file)
$(call chmod-file, 444) $(call chmod-file, 444)
@$(java-vm-cleanup) @$(java-vm-cleanup)

View File

@ -224,7 +224,7 @@ $(OBJDIR)/DllUtil.obj:: ../../../src/windows/native/sun/windows/DllUtil.h
$(OBJDIR)/DrawLine.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_DrawLine.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/java2d/j2d_md.h $(OBJDIR)/DrawLine.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_DrawLine.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/java2d/j2d_md.h
$(OBJDIR)/DrawParallelogram.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_DrawParallelogram.h $(CLASSHDRDIR)/sun_java2d_loops_FillParallelogram.h ../../../src/share/javavm/export/classfile_constants.h ../../../src/share/javavm/export/jni.h ../../../src/share/javavm/export/jvm.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/common/jlong.h ../../../src/share/native/common/jni_util.h ../../../src/share/native/sun/awt/debug/debug_assert.h ../../../src/share/native/sun/awt/debug/debug_mem.h ../../../src/share/native/sun/awt/debug/debug_trace.h ../../../src/share/native/sun/awt/debug/debug_util.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/loops/LoopMacros.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/share/native/sun/java2d/Trace.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/javavm/export/jvm_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/common/jlong_md.h ../../../src/windows/native/sun/java2d/j2d_md.h $(OBJDIR)/DrawParallelogram.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_DrawParallelogram.h ../../../src/share/javavm/export/classfile_constants.h ../../../src/share/javavm/export/jni.h ../../../src/share/javavm/export/jvm.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/common/jlong.h ../../../src/share/native/common/jni_util.h ../../../src/share/native/sun/awt/debug/debug_assert.h ../../../src/share/native/sun/awt/debug/debug_mem.h ../../../src/share/native/sun/awt/debug/debug_trace.h ../../../src/share/native/sun/awt/debug/debug_util.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/loops/ParallelogramUtils.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/share/native/sun/java2d/Trace.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/javavm/export/jvm_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/common/jlong_md.h ../../../src/windows/native/sun/java2d/j2d_md.h
$(OBJDIR)/DrawPath.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_DrawPath.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/common/jlong.h ../../../src/share/native/common/jni_util.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/DrawPath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/loops/ProcessPath.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/common/jlong_md.h ../../../src/windows/native/sun/java2d/j2d_md.h $(OBJDIR)/DrawPath.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_DrawPath.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/common/jlong.h ../../../src/share/native/common/jni_util.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/DrawPath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/loops/ProcessPath.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/common/jlong_md.h ../../../src/windows/native/sun/java2d/j2d_md.h
@ -232,7 +232,7 @@ $(OBJDIR)/DrawPolygons.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDR
$(OBJDIR)/DrawRect.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_DrawRect.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/java2d/j2d_md.h $(OBJDIR)/DrawRect.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_DrawRect.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/java2d/j2d_md.h
$(OBJDIR)/FillParallelogram.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_FillParallelogram.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/java2d/j2d_md.h $(OBJDIR)/FillParallelogram.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_FillParallelogram.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/ParallelogramUtils.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/java2d/j2d_md.h
$(OBJDIR)/FillPath.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_FillPath.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/common/jlong.h ../../../src/share/native/common/jni_util.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/DrawPath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/loops/ProcessPath.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/common/jlong_md.h ../../../src/windows/native/sun/java2d/j2d_md.h $(OBJDIR)/FillPath.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_FillPath.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/common/jlong.h ../../../src/share/native/common/jni_util.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/DrawPath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/LineUtils.h ../../../src/share/native/sun/java2d/loops/ProcessPath.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/common/jlong_md.h ../../../src/windows/native/sun/java2d/j2d_md.h
@ -284,7 +284,7 @@ $(OBJDIR)/IntRgbx.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h ../../../src/sh
$(OBJDIR)/MaskBlit.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_MaskBlit.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/pipe/Region.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/awt/utility/rect.h ../../../src/windows/native/sun/java2d/j2d_md.h $(OBJDIR)/MaskBlit.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_MaskBlit.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/pipe/Region.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/awt/utility/rect.h ../../../src/windows/native/sun/java2d/j2d_md.h
$(OBJDIR)/MaskFill.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_MaskFill.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/java2d/j2d_md.h $(OBJDIR)/MaskFill.obj:: $(CLASSHDRDIR)/java_awt_AlphaComposite.h $(CLASSHDRDIR)/sun_java2d_loops_MaskFill.h ../../../src/share/javavm/export/jni.h ../../../src/share/native/common/gdefs.h ../../../src/share/native/sun/java2d/loops/AlphaMath.h ../../../src/share/native/sun/java2d/loops/GlyphImageRef.h ../../../src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.h ../../../src/share/native/sun/java2d/loops/ParallelogramUtils.h ../../../src/share/native/sun/java2d/pipe/SpanIterator.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/native/common/gdefs_md.h ../../../src/windows/native/sun/java2d/j2d_md.h
$(OBJDIR)/MouseInfo.obj:: $(CLASSHDRDIR)/java_awt_AWTEvent.h $(CLASSHDRDIR)/java_awt_Component.h $(CLASSHDRDIR)/java_awt_Dimension.h $(CLASSHDRDIR)/java_awt_Event.h $(CLASSHDRDIR)/java_awt_event_FocusEvent.h $(CLASSHDRDIR)/java_awt_event_KeyEvent.h $(CLASSHDRDIR)/java_awt_event_MouseEvent.h $(CLASSHDRDIR)/java_awt_event_WindowEvent.h $(CLASSHDRDIR)/java_awt_Font.h $(CLASSHDRDIR)/sun_awt_FontDescriptor.h $(CLASSHDRDIR)/sun_awt_PlatformFont.h $(CLASSHDRDIR)/sun_awt_windows_WComponentPeer.h $(CLASSHDRDIR)/sun_awt_windows_WFontMetrics.h $(CLASSHDRDIR)/sun_awt_windows_WObjectPeer.h $(CLASSHDRDIR)/sun_awt_windows_WToolkit.h ../../../src/share/javavm/export/classfile_constants.h ../../../src/share/javavm/export/jni.h ../../../src/share/javavm/export/jvm.h ../../../src/share/native/common/jlong.h ../../../src/share/native/common/jni_util.h ../../../src/share/native/sun/awt/debug/debug_assert.h ../../../src/share/native/sun/awt/debug/debug_mem.h ../../../src/share/native/sun/awt/debug/debug_trace.h ../../../src/share/native/sun/awt/debug/debug_util.h ../../../src/share/native/sun/awt/image/cvutils/img_globals.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/share/native/sun/java2d/Trace.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/javavm/export/jvm_md.h ../../../src/windows/native/common/jlong_md.h ../../../src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.h ../../../src/windows/native/sun/windows/alloc.h ../../../src/windows/native/sun/windows/awt.h ../../../src/windows/native/sun/windows/awtmsg.h ../../../src/windows/native/sun/windows/awt_Brush.h ../../../src/windows/native/sun/windows/awt_Component.h ../../../src/windows/native/sun/windows/awt_Debug.h ../../../src/windows/native/sun/windows/awt_Font.h ../../../src/windows/native/sun/windows/awt_GDIObject.h ../../../src/windows/native/sun/windows/awt_Object.h ../../../src/windows/native/sun/windows/awt_Palette.h ../../../src/windows/native/sun/windows/awt_Pen.h ../../../src/windows/native/sun/windows/awt_Toolkit.h ../../../src/windows/native/sun/windows/awt_Win32GraphicsDevice.h ../../../src/windows/native/sun/windows/colordata.h ../../../src/windows/native/sun/windows/Devices.h ../../../src/windows/native/sun/windows/GDIHashtable.h ../../../src/windows/native/sun/windows/Hashtable.h ../../../src/windows/native/sun/windows/ObjectList.h ../../../src/windows/native/sun/windows/stdhdrs.h $(OBJDIR)/MouseInfo.obj:: $(CLASSHDRDIR)/java_awt_AWTEvent.h $(CLASSHDRDIR)/java_awt_Component.h $(CLASSHDRDIR)/java_awt_Dimension.h $(CLASSHDRDIR)/java_awt_Event.h $(CLASSHDRDIR)/java_awt_event_FocusEvent.h $(CLASSHDRDIR)/java_awt_event_KeyEvent.h $(CLASSHDRDIR)/java_awt_event_MouseEvent.h $(CLASSHDRDIR)/java_awt_event_WindowEvent.h $(CLASSHDRDIR)/java_awt_Font.h $(CLASSHDRDIR)/sun_awt_FontDescriptor.h $(CLASSHDRDIR)/sun_awt_PlatformFont.h $(CLASSHDRDIR)/sun_awt_windows_WComponentPeer.h $(CLASSHDRDIR)/sun_awt_windows_WFontMetrics.h $(CLASSHDRDIR)/sun_awt_windows_WObjectPeer.h $(CLASSHDRDIR)/sun_awt_windows_WToolkit.h ../../../src/share/javavm/export/classfile_constants.h ../../../src/share/javavm/export/jni.h ../../../src/share/javavm/export/jvm.h ../../../src/share/native/common/jlong.h ../../../src/share/native/common/jni_util.h ../../../src/share/native/sun/awt/debug/debug_assert.h ../../../src/share/native/sun/awt/debug/debug_mem.h ../../../src/share/native/sun/awt/debug/debug_trace.h ../../../src/share/native/sun/awt/debug/debug_util.h ../../../src/share/native/sun/awt/image/cvutils/img_globals.h ../../../src/share/native/sun/java2d/SurfaceData.h ../../../src/share/native/sun/java2d/Trace.h ../../../src/windows/javavm/export/jni_md.h ../../../src/windows/javavm/export/jvm_md.h ../../../src/windows/native/common/jlong_md.h ../../../src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.h ../../../src/windows/native/sun/windows/alloc.h ../../../src/windows/native/sun/windows/awt.h ../../../src/windows/native/sun/windows/awtmsg.h ../../../src/windows/native/sun/windows/awt_Brush.h ../../../src/windows/native/sun/windows/awt_Component.h ../../../src/windows/native/sun/windows/awt_Debug.h ../../../src/windows/native/sun/windows/awt_Font.h ../../../src/windows/native/sun/windows/awt_GDIObject.h ../../../src/windows/native/sun/windows/awt_Object.h ../../../src/windows/native/sun/windows/awt_Palette.h ../../../src/windows/native/sun/windows/awt_Pen.h ../../../src/windows/native/sun/windows/awt_Toolkit.h ../../../src/windows/native/sun/windows/awt_Win32GraphicsDevice.h ../../../src/windows/native/sun/windows/colordata.h ../../../src/windows/native/sun/windows/Devices.h ../../../src/windows/native/sun/windows/GDIHashtable.h ../../../src/windows/native/sun/windows/Hashtable.h ../../../src/windows/native/sun/windows/ObjectList.h ../../../src/windows/native/sun/windows/stdhdrs.h

View File

@ -118,6 +118,8 @@ SUNWprivate_1.1 {
Java_sun_java2d_loops_GraphicsPrimitiveMgr_registerNativeLoops; Java_sun_java2d_loops_GraphicsPrimitiveMgr_registerNativeLoops;
Java_sun_java2d_loops_MaskBlit_MaskBlit; Java_sun_java2d_loops_MaskBlit_MaskBlit;
Java_sun_java2d_loops_MaskFill_MaskFill; Java_sun_java2d_loops_MaskFill_MaskFill;
Java_sun_java2d_loops_MaskFill_FillAAPgram;
Java_sun_java2d_loops_MaskFill_DrawAAPgram;
Java_sun_java2d_loops_TransformHelper_Transform; Java_sun_java2d_loops_TransformHelper_Transform;
Java_sun_java2d_pipe_Region_initIDs; Java_sun_java2d_pipe_Region_initIDs;
Java_sun_java2d_pipe_SpanClipRenderer_initIDs; Java_sun_java2d_pipe_SpanClipRenderer_initIDs;

View File

@ -115,6 +115,8 @@ SUNWprivate_1.1 {
Java_sun_java2d_loops_GraphicsPrimitiveMgr_registerNativeLoops; Java_sun_java2d_loops_GraphicsPrimitiveMgr_registerNativeLoops;
Java_sun_java2d_loops_MaskBlit_MaskBlit; Java_sun_java2d_loops_MaskBlit_MaskBlit;
Java_sun_java2d_loops_MaskFill_MaskFill; Java_sun_java2d_loops_MaskFill_MaskFill;
Java_sun_java2d_loops_MaskFill_FillAAPgram;
Java_sun_java2d_loops_MaskFill_DrawAAPgram;
Java_sun_java2d_pipe_BufferedRenderPipe_fillSpans; Java_sun_java2d_pipe_BufferedRenderPipe_fillSpans;
Java_sun_java2d_pipe_SpanClipRenderer_initIDs; Java_sun_java2d_pipe_SpanClipRenderer_initIDs;
sun_awt_image_GifImageDecoder_initIDs; sun_awt_image_GifImageDecoder_initIDs;

View File

@ -222,6 +222,7 @@ class Zoneinfo {
boolean continued = false; boolean continued = false;
Zone zone = null; Zone zone = null;
String l; String l;
lineNum = 0;
try { try {
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {

View File

@ -158,8 +158,9 @@ static jboolean IsWildCardEnabled();
* Running Java code in primordial thread caused many problems. We will * Running Java code in primordial thread caused many problems. We will
* create a new thread to invoke JVM. See 6316197 for more information. * create a new thread to invoke JVM. See 6316197 for more information.
*/ */
static jlong threadStackSize = 0; /* stack size of the new thread */ static jlong threadStackSize = 0; /* stack size of the new thread */
static jlong heapSize = 0; /* heap size */ static jlong maxHeapSize = 0; /* max heap size */
static jlong initialHeapSize = 0; /* inital heap size */
int JNICALL JavaMain(void * args); /* entry point */ int JNICALL JavaMain(void * args); /* entry point */
@ -381,7 +382,7 @@ JavaMain(void * _args)
if (showSettings != NULL) { if (showSettings != NULL) {
ShowSettings(env, showSettings); ShowSettings(env, showSettings);
CHECK_EXCEPTION_LEAVE(0); CHECK_EXCEPTION_LEAVE(1);
} }
/* If the user specified neither a class name nor a JAR file */ /* If the user specified neither a class name nor a JAR file */
if (printXUsage || printUsage || (jarfile == 0 && classname == 0)) { if (printXUsage || printUsage || (jarfile == 0 && classname == 0)) {
@ -689,7 +690,14 @@ AddOption(char *str, void *info)
if (JLI_StrCCmp(str, "-Xmx") == 0) { if (JLI_StrCCmp(str, "-Xmx") == 0) {
jlong tmp; jlong tmp;
if (parse_size(str + 4, &tmp)) { if (parse_size(str + 4, &tmp)) {
heapSize = tmp; maxHeapSize = tmp;
}
}
if (JLI_StrCCmp(str, "-Xms") == 0) {
jlong tmp;
if (parse_size(str + 4, &tmp)) {
initialHeapSize = tmp;
} }
} }
} }
@ -1506,12 +1514,13 @@ ShowSettings(JNIEnv *env, char *optString)
jstring joptString; jstring joptString;
NULL_CHECK(cls = FindBootStrapClass(env, "sun/launcher/LauncherHelper")); NULL_CHECK(cls = FindBootStrapClass(env, "sun/launcher/LauncherHelper"));
NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls, NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
"showSettings", "(ZLjava/lang/String;JJZ)V")); "showSettings", "(ZLjava/lang/String;JJJZ)V"));
joptString = (*env)->NewStringUTF(env, optString); joptString = (*env)->NewStringUTF(env, optString);
(*env)->CallStaticVoidMethod(env, cls, showSettingsID, (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
JNI_TRUE, JNI_TRUE,
joptString, joptString,
(jlong)heapSize, (jlong)initialHeapSize,
(jlong)maxHeapSize,
(jlong)threadStackSize, (jlong)threadStackSize,
ServerClassMachine()); ServerClassMachine());
} }

View File

@ -29,13 +29,14 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Adaptive coding. * Adaptive coding.
* See the section "Adaptive Encodings" in the Pack200 spec. * See the section "Adaptive Encodings" in the Pack200 spec.
* @author John Rose * @author John Rose
*/ */
class AdaptiveCoding implements Constants, CodingMethod { class AdaptiveCoding implements CodingMethod {
CodingMethod headCoding; CodingMethod headCoding;
int headLength; int headLength;
CodingMethod tailCoding; CodingMethod tailCoding;
@ -147,7 +148,6 @@ class AdaptiveCoding implements Constants, CodingMethod {
} }
if (KX == KX_MAX) return Integer.MAX_VALUE; if (KX == KX_MAX) return Integer.MAX_VALUE;
KX += 1; KX += 1;
int unit2 = 1 << (KX * KX_LG2BASE);
int mask2 = KB_MAX << (KX * KX_LG2BASE); int mask2 = KB_MAX << (KX * KX_LG2BASE);
K1 |= (mask & ~mask2); K1 |= (mask & ~mask2);
K1 += unit; K1 += unit;
@ -250,7 +250,7 @@ class AdaptiveCoding implements Constants, CodingMethod {
return m.toString(); return m.toString();
} }
public String toString() { public String toString() {
StringBuffer res = new StringBuffer(20); StringBuilder res = new StringBuilder(20);
AdaptiveCoding run = this; AdaptiveCoding run = this;
res.append("run("); res.append("run(");
for (;;) { for (;;) {

View File

@ -36,6 +36,7 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Represents an attribute in a class-file. * Represents an attribute in a class-file.
@ -44,7 +45,7 @@ import java.util.Map;
* attribute layouts. * attribute layouts.
* @author John Rose * @author John Rose
*/ */
class Attribute implements Comparable, Constants { class Attribute implements Comparable {
// Attribute instance fields. // Attribute instance fields.
Layout def; // the name and format of this attr Layout def; // the name and format of this attr
@ -103,7 +104,6 @@ class Attribute implements Comparable, Constants {
return this.def.compareTo(that.def); return this.def.compareTo(that.def);
} }
private static final byte[] noBytes = {};
private static final Map<List<Attribute>, List<Attribute>> canonLists = new HashMap<>(); private static final Map<List<Attribute>, List<Attribute>> canonLists = new HashMap<>();
private static final Map<Layout, Attribute> attributes = new HashMap<>(); private static final Map<Layout, Attribute> attributes = new HashMap<>();
private static final Map<Layout, Attribute> standardDefs = new HashMap<>(); private static final Map<Layout, Attribute> standardDefs = new HashMap<>();
@ -112,7 +112,7 @@ class Attribute implements Comparable, Constants {
// are used by trimToSize, in order to reduce footprint // are used by trimToSize, in order to reduce footprint
// of some common cases. (Note that Code attributes are // of some common cases. (Note that Code attributes are
// always zero size.) // always zero size.)
public static List getCanonList(List<Attribute> al) { public static List<Attribute> getCanonList(List<Attribute> al) {
synchronized (canonLists) { synchronized (canonLists) {
List<Attribute> cl = canonLists.get(al); List<Attribute> cl = canonLists.get(al);
if (cl == null) { if (cl == null) {
@ -465,7 +465,9 @@ class Attribute implements Comparable, Constants {
return ConstantPool.getUtf8Entry(name()); return ConstantPool.getUtf8Entry(name());
} }
public boolean isEmpty() { return layout == ""; } public boolean isEmpty() {
return layout.isEmpty();
}
public Layout(int ctype, String name, String layout) { public Layout(int ctype, String name, String layout) {
this.ctype = ctype; this.ctype = ctype;
@ -479,19 +481,19 @@ class Attribute implements Comparable, Constants {
} else { } else {
String[] bodies = splitBodies(layout); String[] bodies = splitBodies(layout);
// Make the callables now, so they can be linked immediately. // Make the callables now, so they can be linked immediately.
Element[] elems = new Element[bodies.length]; Element[] lelems = new Element[bodies.length];
this.elems = elems; this.elems = lelems;
for (int i = 0; i < elems.length; i++) { for (int i = 0; i < lelems.length; i++) {
Element ce = this.new Element(); Element ce = this.new Element();
ce.kind = EK_CBLE; ce.kind = EK_CBLE;
ce.removeBand(); ce.removeBand();
ce.bandIndex = NO_BAND_INDEX; ce.bandIndex = NO_BAND_INDEX;
ce.layout = bodies[i]; ce.layout = bodies[i];
elems[i] = ce; lelems[i] = ce;
} }
// Next fill them in. // Next fill them in.
for (int i = 0; i < elems.length; i++) { for (int i = 0; i < lelems.length; i++) {
Element ce = elems[i]; Element ce = lelems[i];
ce.body = tokenizeLayout(this, i, bodies[i]); ce.body = tokenizeLayout(this, i, bodies[i]);
} }
//System.out.println(Arrays.asList(elems)); //System.out.println(Arrays.asList(elems));
@ -525,11 +527,12 @@ class Attribute implements Comparable, Constants {
} }
public boolean equals(Object x) { public boolean equals(Object x) {
return x instanceof Layout && equals((Layout)x); return ( x != null) && ( x.getClass() == Layout.class ) &&
equals((Layout)x);
} }
public boolean equals(Layout that) { public boolean equals(Layout that) {
return this.name == that.name return this.name.equals(that.name)
&& this.layout == that.layout && this.layout.equals(that.layout)
&& this.ctype == that.ctype; && this.ctype == that.ctype;
} }
public int hashCode() { public int hashCode() {
@ -589,14 +592,14 @@ class Attribute implements Comparable, Constants {
return str; return str;
} }
private String stringForDebug() { private String stringForDebug() {
Element[] body = this.body; Element[] lbody = this.body;
switch (kind) { switch (kind) {
case EK_CALL: case EK_CALL:
body = null; lbody = null;
break; break;
case EK_CASE: case EK_CASE:
if (flagTest(EF_BACK)) if (flagTest(EF_BACK))
body = null; lbody = null;
break; break;
} }
return layout return layout
@ -604,7 +607,7 @@ class Attribute implements Comparable, Constants {
+ "<"+ (flags==0?"":""+flags)+kind+len + "<"+ (flags==0?"":""+flags)+kind+len
+ (refKind==0?"":""+refKind) + ">" + (refKind==0?"":""+refKind) + ">"
+ (value==0?"":"("+value+")") + (value==0?"":"("+value+")")
+ (body==null?"": ""+Arrays.asList(body)); + (lbody==null?"": ""+Arrays.asList(lbody));
} }
} }
@ -613,16 +616,19 @@ class Attribute implements Comparable, Constants {
} }
static private final Element[] noElems = {}; static private final Element[] noElems = {};
public Element[] getCallables() { public Element[] getCallables() {
if (hasCallables()) if (hasCallables()) {
return elems; Element[] nelems = Arrays.copyOf(elems, elems.length);
else return nelems;
} else
return noElems; // no callables at all return noElems; // no callables at all
} }
public Element[] getEntryPoint() { public Element[] getEntryPoint() {
if (hasCallables()) if (hasCallables())
return elems[0].body; // body of first callable return elems[0].body; // body of first callable
else else {
return elems; // no callables; whole body Element[] nelems = Arrays.copyOf(elems, elems.length);
return nelems; // no callables; whole body
}
} }
/** Return a sequence of tokens from the given attribute bytes. /** Return a sequence of tokens from the given attribute bytes.
@ -674,7 +680,7 @@ class Attribute implements Comparable, Constants {
} }
} }
void visitRefs(Holder holder, int mode, final Collection refs) { void visitRefs(Holder holder, int mode, final Collection<Entry> refs) {
if (mode == VRM_CLASSIC) { if (mode == VRM_CLASSIC) {
refs.add(getNameRef()); refs.add(getNameRef());
} }
@ -720,7 +726,7 @@ class Attribute implements Comparable, Constants {
*/ */
static public static public
String normalizeLayoutString(String layout) { String normalizeLayoutString(String layout) {
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
for (int i = 0, len = layout.length(); i < len; ) { for (int i = 0, len = layout.length(); i < len; ) {
char ch = layout.charAt(i++); char ch = layout.charAt(i++);
if (ch <= ' ') { if (ch <= ' ') {
@ -832,14 +838,14 @@ class Attribute implements Comparable, Constants {
*/ */
static //private static //private
Layout.Element[] tokenizeLayout(Layout self, int curCble, String layout) { Layout.Element[] tokenizeLayout(Layout self, int curCble, String layout) {
ArrayList<Layout.Element> col = new ArrayList<>(layout.length()); List<Layout.Element> col = new ArrayList<>(layout.length());
tokenizeLayout(self, curCble, layout, col); tokenizeLayout(self, curCble, layout, col);
Layout.Element[] res = new Layout.Element[col.size()]; Layout.Element[] res = new Layout.Element[col.size()];
col.toArray(res); col.toArray(res);
return res; return res;
} }
static //private static //private
void tokenizeLayout(Layout self, int curCble, String layout, ArrayList<Layout.Element> col) { void tokenizeLayout(Layout self, int curCble, String layout, List<Layout.Element> col) {
boolean prevBCI = false; boolean prevBCI = false;
for (int len = layout.length(), i = 0; i < len; ) { for (int len = layout.length(), i = 0; i < len; ) {
int start = i; int start = i;
@ -897,7 +903,7 @@ class Attribute implements Comparable, Constants {
case 'T': // union: 'T' any_int union_case* '(' ')' '[' body ']' case 'T': // union: 'T' any_int union_case* '(' ')' '[' body ']'
kind = EK_UN; kind = EK_UN;
i = tokenizeSInt(e, layout, i); i = tokenizeSInt(e, layout, i);
ArrayList<Layout.Element> cases = new ArrayList<>(); List<Layout.Element> cases = new ArrayList<>();
for (;;) { for (;;) {
// Keep parsing cases until we hit the default case. // Keep parsing cases until we hit the default case.
if (layout.charAt(i++) != '(') if (layout.charAt(i++) != '(')
@ -1051,7 +1057,7 @@ class Attribute implements Comparable, Constants {
} }
static //private static //private
String[] splitBodies(String layout) { String[] splitBodies(String layout) {
ArrayList<String> bodies = new ArrayList<>(); List<String> bodies = new ArrayList<>();
// Parse several independent layout bodies: "[foo][bar]...[baz]" // Parse several independent layout bodies: "[foo][bar]...[baz]"
for (int i = 0; i < layout.length(); i++) { for (int i = 0; i < layout.length(); i++) {
if (layout.charAt(i++) != '[') if (layout.charAt(i++) != '[')
@ -1156,7 +1162,7 @@ class Attribute implements Comparable, Constants {
String expandCaseDashNotation(String layout) { String expandCaseDashNotation(String layout) {
int dash = findCaseDash(layout, 0); int dash = findCaseDash(layout, 0);
if (dash < 0) return layout; // no dashes (the common case) if (dash < 0) return layout; // no dashes (the common case)
StringBuffer result = new StringBuffer(layout.length() * 3); StringBuilder result = new StringBuilder(layout.length() * 3);
int sofar = 0; // how far have we processed the layout? int sofar = 0; // how far have we processed the layout?
for (;;) { for (;;) {
// for each dash, collect everything up to the dash // for each dash, collect everything up to the dash

View File

@ -44,16 +44,17 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.jar.Pack200; import java.util.jar.Pack200;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Define the structure and ordering of "bands" in a packed file. * Define the structure and ordering of "bands" in a packed file.
* @author John Rose * @author John Rose
*/ */
abstract abstract
class BandStructure implements Constants { class BandStructure {
static final int MAX_EFFORT = 9; static final int MAX_EFFORT = 9;
static final int MIN_EFFORT = 1; static final int MIN_EFFORT = 1;
static final int DEFAULT_EFFORT = 5; static final int DEFAULT_EFFORT = 5;
@ -251,18 +252,18 @@ class BandStructure implements Constants {
null null
}; };
final private static HashMap basicCodingIndexes; final private static Map<Coding, Integer> basicCodingIndexes;
static { static {
assert(basicCodings[_meta_default] == null); assert(basicCodings[_meta_default] == null);
assert(basicCodings[_meta_canon_min] != null); assert(basicCodings[_meta_canon_min] != null);
assert(basicCodings[_meta_canon_max] != null); assert(basicCodings[_meta_canon_max] != null);
HashMap map = new HashMap(); Map<Coding, Integer> map = new HashMap<>();
for (int i = 0; i < basicCodings.length; i++) { for (int i = 0; i < basicCodings.length; i++) {
Coding c = basicCodings[i]; Coding c = basicCodings[i];
if (c == null) continue; if (c == null) continue;
assert(i >= _meta_canon_min); assert(i >= _meta_canon_min);
assert(i <= _meta_canon_max); assert(i <= _meta_canon_max);
map.put(c, new Integer(i)); map.put(c, i);
} }
basicCodingIndexes = map; basicCodingIndexes = map;
} }
@ -270,12 +271,12 @@ class BandStructure implements Constants {
return i < basicCodings.length ? basicCodings[i] : null; return i < basicCodings.length ? basicCodings[i] : null;
} }
public static int indexOf(Coding c) { public static int indexOf(Coding c) {
Integer i = (Integer) basicCodingIndexes.get(c); Integer i = basicCodingIndexes.get(c);
if (i == null) return 0; if (i == null) return 0;
return i.intValue(); return i.intValue();
} }
public static Coding[] getBasicCodings() { public static Coding[] getBasicCodings() {
return (Coding[]) basicCodings.clone(); return basicCodings.clone();
} }
protected byte[] bandHeaderBytes; // used for input only protected byte[] bandHeaderBytes; // used for input only
@ -687,7 +688,6 @@ class BandStructure implements Constants {
} }
bandCoding.writeArrayTo(out, values, 0, length); bandCoding.writeArrayTo(out, values, 0, length);
if (out == outputCounter) { if (out == outputCounter) {
long len1 = outputCounter.getCount();
assert(outputSize == outputCounter.getCount() - len0) assert(outputSize == outputCounter.getCount() - len0)
: (outputSize+" != "+outputCounter.getCount()+"-"+len0); : (outputSize+" != "+outputCounter.getCount()+"-"+len0);
} }
@ -1050,8 +1050,8 @@ class BandStructure implements Constants {
// Bootstrap support for CPRefBands. These are needed to record // Bootstrap support for CPRefBands. These are needed to record
// intended CP indexes, before the CP has been created. // intended CP indexes, before the CP has been created.
private ArrayList allKQBands = new ArrayList(); private final List<CPRefBand> allKQBands = new ArrayList<>();
private ArrayList needPredefIndex = new ArrayList(); private List<Object[]> needPredefIndex = new ArrayList<>();
int encodeRef(Entry e, Index ix) { int encodeRef(Entry e, Index ix) {
@ -1078,9 +1078,9 @@ class BandStructure implements Constants {
&& this instanceof PackageWriter) { && this instanceof PackageWriter) {
// Twist the random state based on my first file. // Twist the random state based on my first file.
// This sends each segment off in a different direction. // This sends each segment off in a different direction.
List classes = ((PackageWriter)this).pkg.classes; List<Package.Class> classes = ((PackageWriter)this).pkg.classes;
if (!classes.isEmpty()) { if (!classes.isEmpty()) {
Package.Class cls = (Package.Class) classes.get(0); Package.Class cls = classes.get(0);
codingChooser.addStressSeed(cls.getName().hashCode()); codingChooser.addStressSeed(cls.getName().hashCode());
} }
} }
@ -1619,8 +1619,7 @@ class BandStructure implements Constants {
/** Given CP indexes, distribute tag-specific indexes to bands. */ /** Given CP indexes, distribute tag-specific indexes to bands. */
protected void setBandIndexes() { protected void setBandIndexes() {
// Handle prior calls to setBandIndex: // Handle prior calls to setBandIndex:
for (Iterator i = needPredefIndex.iterator(); i.hasNext(); ) { for (Object[] need : needPredefIndex) {
Object[] need = (Object[]) i.next();
CPRefBand b = (CPRefBand) need[0]; CPRefBand b = (CPRefBand) need[0];
Byte which = (Byte) need[1]; Byte which = (Byte) need[1];
b.setIndex(getCPIndex(which.byteValue())); b.setIndex(getCPIndex(which.byteValue()));
@ -1633,7 +1632,7 @@ class BandStructure implements Constants {
} }
protected void setBandIndex(CPRefBand b, byte which) { protected void setBandIndex(CPRefBand b, byte which) {
Object[] need = { b, new Byte(which) }; Object[] need = { b, Byte.valueOf(which) };
if (which == CONSTANT_Literal) { if (which == CONSTANT_Literal) {
// I.e., attribute layouts KQ (no null) or KQN (null ok). // I.e., attribute layouts KQ (no null) or KQN (null ok).
allKQBands.add(b); allKQBands.add(b);
@ -1645,7 +1644,7 @@ class BandStructure implements Constants {
} }
} }
protected void setConstantValueIndex(com.sun.java.util.jar.pack.Package.Class.Field f) { protected void setConstantValueIndex(Field f) {
Index ix = null; Index ix = null;
if (f != null) { if (f != null) {
byte tag = f.getLiteralTag(); byte tag = f.getLiteralTag();
@ -1655,8 +1654,7 @@ class BandStructure implements Constants {
assert(ix != null); assert(ix != null);
} }
// Typically, allKQBands is the singleton of field_ConstantValue_KQ. // Typically, allKQBands is the singleton of field_ConstantValue_KQ.
for (Iterator i = allKQBands.iterator(); i.hasNext(); ) { for (CPRefBand xxx_KQ : allKQBands) {
CPRefBand xxx_KQ = (CPRefBand) i.next();
xxx_KQ.setIndex(ix); xxx_KQ.setIndex(ix);
} }
} }
@ -1688,7 +1686,7 @@ class BandStructure implements Constants {
protected int attrClassFileVersionMask; protected int attrClassFileVersionMask;
// Mapping from Attribute.Layout to Band[] (layout element bands). // Mapping from Attribute.Layout to Band[] (layout element bands).
protected HashMap attrBandTable = new HashMap(); protected Map<Attribute.Layout, Band[]> attrBandTable = new HashMap<>();
// Well-known attributes: // Well-known attributes:
protected final Attribute.Layout attrCodeEmpty; protected final Attribute.Layout attrCodeEmpty;
@ -1697,15 +1695,18 @@ class BandStructure implements Constants {
protected final Attribute.Layout attrConstantValue; protected final Attribute.Layout attrConstantValue;
// Mapping from Attribute.Layout to Integer (inverse of attrDefs) // Mapping from Attribute.Layout to Integer (inverse of attrDefs)
HashMap attrIndexTable = new HashMap(); Map<Attribute.Layout, Integer> attrIndexTable = new HashMap<>();
// Mapping from attribute index (<32 are flag bits) to attributes. // Mapping from attribute index (<32 are flag bits) to attributes.
protected ArrayList[] attrDefs = new ArrayList[ATTR_CONTEXT_LIMIT]; protected List<List<Attribute.Layout>> attrDefs =
new FixedList<>(ATTR_CONTEXT_LIMIT);
{ {
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
assert(attrIndexLimit[i] == 0); assert(attrIndexLimit[i] == 0);
attrIndexLimit[i] = 32; // just for the sake of predefs. attrIndexLimit[i] = 32; // just for the sake of predefs.
attrDefs[i] = new ArrayList(Collections.nCopies(attrIndexLimit[i], null)); attrDefs.set(i, new ArrayList<>(Collections.nCopies(
attrIndexLimit[i], (Attribute.Layout)null)));
} }
// Add predefined attribute definitions: // Add predefined attribute definitions:
@ -1867,9 +1868,10 @@ class BandStructure implements Constants {
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
assert(attrIndexLimit[i] == 0); // decide on it now! assert(attrIndexLimit[i] == 0); // decide on it now!
attrIndexLimit[i] = (haveFlagsHi(i)? 63: 32); attrIndexLimit[i] = (haveFlagsHi(i)? 63: 32);
assert(attrDefs[i].size() == 32); // all predef indexes are <32 List<Attribute.Layout> defList = attrDefs.get(i);
int addMore = attrIndexLimit[i] - attrDefs[i].size(); assert(defList.size() == 32); // all predef indexes are <32
attrDefs[i].addAll(Collections.nCopies(addMore, null)); int addMore = attrIndexLimit[i] - defList.size();
defList.addAll(Collections.nCopies(addMore, (Attribute.Layout) null));
} }
} }
@ -1890,13 +1892,13 @@ class BandStructure implements Constants {
return testBit(archiveOptions, mask); return testBit(archiveOptions, mask);
} }
protected ArrayList getPredefinedAttrs(int ctype) { protected List getPredefinedAttrs(int ctype) {
assert(attrIndexLimit[ctype] != 0); assert(attrIndexLimit[ctype] != 0);
ArrayList res = new ArrayList(attrIndexLimit[ctype]); List<Attribute.Layout> res = new ArrayList<>(attrIndexLimit[ctype]);
// Remove nulls and non-predefs. // Remove nulls and non-predefs.
for (int ai = 0; ai < attrIndexLimit[ctype]; ai++) { for (int ai = 0; ai < attrIndexLimit[ctype]; ai++) {
if (testBit(attrDefSeen[ctype], 1L<<ai)) continue; if (testBit(attrDefSeen[ctype], 1L<<ai)) continue;
Attribute.Layout def = (Attribute.Layout) attrDefs[ctype].get(ai); Attribute.Layout def = attrDefs.get(ctype).get(ai);
if (def == null) continue; // unused flag bit if (def == null) continue; // unused flag bit
assert(isPredefinedAttr(ctype, ai)); assert(isPredefinedAttr(ctype, ai));
res.add(def); res.add(def);
@ -1910,7 +1912,7 @@ class BandStructure implements Constants {
if (ai >= attrIndexLimit[ctype]) return false; if (ai >= attrIndexLimit[ctype]) return false;
// If the bit is set, it was explicitly def'd. // If the bit is set, it was explicitly def'd.
if (testBit(attrDefSeen[ctype], 1L<<ai)) return false; if (testBit(attrDefSeen[ctype], 1L<<ai)) return false;
return (attrDefs[ctype].get(ai) != null); return (attrDefs.get(ctype).get(ai) != null);
} }
protected void adjustSpecialAttrMasks() { protected void adjustSpecialAttrMasks() {
@ -2050,8 +2052,8 @@ class BandStructure implements Constants {
System.out.println("Removing predefined "+ATTR_CONTEXT_NAME[ctype]+ System.out.println("Removing predefined "+ATTR_CONTEXT_NAME[ctype]+
" attribute on bit "+index); " attribute on bit "+index);
} }
List defList = attrDefs[ctype]; List<Attribute.Layout> defList = attrDefs.get(ctype);
Attribute.Layout def = (Attribute.Layout) defList.get(index); Attribute.Layout def = defList.get(index);
assert(def != null); assert(def != null);
defList.set(index, null); defList.set(index, null);
attrIndexTable.put(def, null); attrIndexTable.put(def, null);
@ -2059,7 +2061,7 @@ class BandStructure implements Constants {
assert(index < 64); assert(index < 64);
attrDefSeen[ctype] &= ~(1L<<index); attrDefSeen[ctype] &= ~(1L<<index);
attrFlagMask[ctype] &= ~(1L<<index); attrFlagMask[ctype] &= ~(1L<<index);
Band[] ab = (Band[]) attrBandTable.get(def); Band[] ab = attrBandTable.get(def);
for (int j = 0; j < ab.length; j++) { for (int j = 0; j < ab.length; j++) {
ab[j].doneWithUnusedBand(); ab[j].doneWithUnusedBand();
} }
@ -2085,9 +2087,8 @@ class BandStructure implements Constants {
long defSeen = attrDefSeen[ctype]; long defSeen = attrDefSeen[ctype];
// Note: attrDefSeen is always a subset of attrFlagMask. // Note: attrDefSeen is always a subset of attrFlagMask.
assert((defSeen & ~attrFlagMask[ctype]) == 0); assert((defSeen & ~attrFlagMask[ctype]) == 0);
for (int i = 0; i < attrDefs[ctype].size(); i++) { for (int i = 0; i < attrDefs.get(ctype).size(); i++) {
Attribute.Layout def = (Attribute.Layout) Attribute.Layout def = attrDefs.get(ctype).get(i);
attrDefs[ctype].get(i);
if (def == null) continue; // unused flag bit if (def == null) continue; // unused flag bit
if (def.bandCount == 0) continue; // empty attr if (def.bandCount == 0) continue; // empty attr
if (i < attrIndexLimit[ctype] && !testBit(defSeen, 1L<<i)) { if (i < attrIndexLimit[ctype] && !testBit(defSeen, 1L<<i)) {
@ -2102,7 +2103,7 @@ class BandStructure implements Constants {
Band[] newAB = makeNewAttributeBands(pfx, def, Band[] newAB = makeNewAttributeBands(pfx, def,
xxx_attr_bands); xxx_attr_bands);
assert(newAB.length == def.bandCount); assert(newAB.length == def.bandCount);
Band[] prevAB = (Band[]) attrBandTable.put(def, newAB); Band[] prevAB = attrBandTable.put(def, newAB);
if (prevAB != null) { if (prevAB != null) {
// We won't be using these predefined bands. // We won't be using these predefined bands.
for (int j = 0; j < prevAB.length; j++) { for (int j = 0; j < prevAB.length; j++) {
@ -2212,14 +2213,14 @@ class BandStructure implements Constants {
protected int setAttributeLayoutIndex(Attribute.Layout def, int index) { protected int setAttributeLayoutIndex(Attribute.Layout def, int index) {
int ctype = def.ctype; int ctype = def.ctype;
assert(ATTR_INDEX_OVERFLOW <= index && index < attrIndexLimit[ctype]); assert(ATTR_INDEX_OVERFLOW <= index && index < attrIndexLimit[ctype]);
List defList = attrDefs[ctype]; List<Attribute.Layout> defList = attrDefs.get(ctype);
if (index == ATTR_INDEX_OVERFLOW) { if (index == ATTR_INDEX_OVERFLOW) {
// Overflow attribute. // Overflow attribute.
index = defList.size(); index = defList.size();
defList.add(def); defList.add(def);
if (verbose > 0) if (verbose > 0)
Utils.log.info("Adding new attribute at "+def +": "+index); Utils.log.info("Adding new attribute at "+def +": "+index);
attrIndexTable.put(def, new Integer(index)); attrIndexTable.put(def, index);
return index; return index;
} }
@ -2240,7 +2241,7 @@ class BandStructure implements Constants {
// Remove index binding of any previous fixed attr. // Remove index binding of any previous fixed attr.
attrIndexTable.put(defList.get(index), null); attrIndexTable.put(defList.get(index), null);
defList.set(index, def); defList.set(index, def);
attrIndexTable.put(def, new Integer(index)); attrIndexTable.put(def, index);
return index; return index;
} }
@ -2361,7 +2362,7 @@ class BandStructure implements Constants {
//////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////
static int nextSeqForDebug; static int nextSeqForDebug;
static File dumpDir; static File dumpDir = null;
static OutputStream getDumpStream(Band b, String ext) throws IOException { static OutputStream getDumpStream(Band b, String ext) throws IOException {
return getDumpStream(b.name, b.seqForDebug, ext, b); return getDumpStream(b.name, b.seqForDebug, ext, b);
} }
@ -2512,19 +2513,19 @@ class BandStructure implements Constants {
+", "+cstr+", "+ixS+"),"); +", "+cstr+", "+ixS+"),");
} }
private HashMap prevForAssertMap; private Map<Band, Band> prevForAssertMap;
// DEBUG ONLY: Record something about the band order. // DEBUG ONLY: Record something about the band order.
boolean notePrevForAssert(Band b, Band p) { boolean notePrevForAssert(Band b, Band p) {
if (prevForAssertMap == null) if (prevForAssertMap == null)
prevForAssertMap = new HashMap(); prevForAssertMap = new HashMap<>();
prevForAssertMap.put(b, p); prevForAssertMap.put(b, p);
return true; return true;
} }
// DEBUG ONLY: Validate next input band. // DEBUG ONLY: Validate next input band.
private boolean assertReadyToReadFrom(Band b, InputStream in) throws IOException { private boolean assertReadyToReadFrom(Band b, InputStream in) throws IOException {
Band p = (Band) prevForAssertMap.get(b); Band p = prevForAssertMap.get(b);
// Any previous band must be done reading before this one starts. // Any previous band must be done reading before this one starts.
if (p != null && phaseCmp(p.phase(), DISBURSE_PHASE) < 0) { if (p != null && phaseCmp(p.phase(), DISBURSE_PHASE) < 0) {
Utils.log.warning("Previous band not done reading."); Utils.log.warning("Previous band not done reading.");
@ -2536,19 +2537,21 @@ class BandStructure implements Constants {
String name = b.name; String name = b.name;
if (optDebugBands && !name.startsWith("(")) { if (optDebugBands && !name.startsWith("(")) {
// Verify synchronization between reader & writer: // Verify synchronization between reader & writer:
StringBuffer buf = new StringBuffer(); StringBuilder buf = new StringBuilder();
int ch; int ch;
while ((ch = in.read()) > 0) while ((ch = in.read()) > 0)
buf.append((char)ch); buf.append((char)ch);
String inName = buf.toString(); String inName = buf.toString();
if (!inName.equals(name)) { if (!inName.equals(name)) {
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
sb.append("Expected "+name+" but read: "); sb.append("Expected "+name+" but read: ");
inName += (char)ch; inName += (char)ch;
while (inName.length() < 10) while (inName.length() < 10) {
inName += (char)in.read(); inName += (char) in.read();
for (int i = 0; i < inName.length(); i++) }
for (int i = 0; i < inName.length(); i++) {
sb.append(inName.charAt(i)); sb.append(inName.charAt(i));
}
Utils.log.warning(sb.toString()); Utils.log.warning(sb.toString());
return false; return false;
} }
@ -2573,7 +2576,7 @@ class BandStructure implements Constants {
// DEBUG ONLY: Maybe write a debugging cookie to next output band. // DEBUG ONLY: Maybe write a debugging cookie to next output band.
private boolean assertReadyToWriteTo(Band b, OutputStream out) throws IOException { private boolean assertReadyToWriteTo(Band b, OutputStream out) throws IOException {
Band p = (Band) prevForAssertMap.get(b); Band p = prevForAssertMap.get(b);
// Any previous band must be done writing before this one starts. // Any previous band must be done writing before this one starts.
if (p != null && phaseCmp(p.phase(), DONE_PHASE) < 0) { if (p != null && phaseCmp(p.phase(), DONE_PHASE) < 0) {
Utils.log.warning("Previous band not done writing."); Utils.log.warning("Previous band not done writing.");
@ -2654,7 +2657,7 @@ class BandStructure implements Constants {
protected static Object[] realloc(Object[] a) { protected static Object[] realloc(Object[] a) {
return realloc(a, Math.max(10, a.length*2)); return realloc(a, Math.max(10, a.length*2));
} }
static private int[] noInts = {};
protected static int[] realloc(int[] a, int len) { protected static int[] realloc(int[] a, int len) {
if (len == 0) return noInts; if (len == 0) return noInts;
if (a == null) return new int[len]; if (a == null) return new int[len];
@ -2665,7 +2668,7 @@ class BandStructure implements Constants {
protected static int[] realloc(int[] a) { protected static int[] realloc(int[] a) {
return realloc(a, Math.max(10, a.length*2)); return realloc(a, Math.max(10, a.length*2));
} }
static private byte[] noBytes = {};
protected static byte[] realloc(byte[] a, int len) { protected static byte[] realloc(byte[] a, int len) {
if (len == 0) return noBytes; if (len == 0) return noBytes;
if (a == null) return new byte[len]; if (a == null) return new byte[len];

View File

@ -38,19 +38,20 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map; import java.util.Map;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Reader for a class file that is being incorporated into a package. * Reader for a class file that is being incorporated into a package.
* @author John Rose * @author John Rose
*/ */
class ClassReader implements Constants { class ClassReader {
int verbose; int verbose;
Package pkg; Package pkg;
Class cls; Class cls;
long inPos; long inPos;
DataInputStream in; DataInputStream in;
Map attrDefs; Map<Attribute.Layout, Attribute> attrDefs;
Map attrCommands; Map attrCommands;
String unknownAttrCommand = "error";; String unknownAttrCommand = "error";;
@ -77,7 +78,7 @@ class ClassReader implements Constants {
}); });
} }
public void setAttrDefs(Map attrDefs) { public void setAttrDefs(Map<Attribute.Layout, Attribute> attrDefs) {
this.attrDefs = attrDefs; this.attrDefs = attrDefs;
} }
@ -211,27 +212,23 @@ class ClassReader implements Constants {
break; break;
case CONSTANT_Integer: case CONSTANT_Integer:
{ {
Comparable val = new Integer(in.readInt()); cpMap[i] = ConstantPool.getLiteralEntry(in.readInt());
cpMap[i] = ConstantPool.getLiteralEntry(val);
} }
break; break;
case CONSTANT_Float: case CONSTANT_Float:
{ {
Comparable val = new Float(in.readFloat()); cpMap[i] = ConstantPool.getLiteralEntry(in.readFloat());
cpMap[i] = ConstantPool.getLiteralEntry(val);
} }
break; break;
case CONSTANT_Long: case CONSTANT_Long:
{ {
Comparable val = new Long(in.readLong()); cpMap[i] = ConstantPool.getLiteralEntry(in.readLong());
cpMap[i] = ConstantPool.getLiteralEntry(val);
cpMap[++i] = null; cpMap[++i] = null;
} }
break; break;
case CONSTANT_Double: case CONSTANT_Double:
{ {
Comparable val = new Double(in.readDouble()); cpMap[i] = ConstantPool.getLiteralEntry(in.readDouble());
cpMap[i] = ConstantPool.getLiteralEntry(val);
cpMap[++i] = null; cpMap[++i] = null;
} }
break; break;
@ -353,17 +350,18 @@ class ClassReader implements Constants {
if (attrCommands != null) { if (attrCommands != null) {
Object lkey = Attribute.keyForLookup(ctype, name); Object lkey = Attribute.keyForLookup(ctype, name);
String cmd = (String) attrCommands.get(lkey); String cmd = (String) attrCommands.get(lkey);
if (cmd == "pass") { if (cmd != null) {
String message = "passing attribute bitwise in "+h; switch (cmd) {
throw new Attribute.FormatException(message, ctype, name, case "pass":
cmd); String message1 = "passing attribute bitwise in " + h;
} else if (cmd == "error") { throw new Attribute.FormatException(message1, ctype, name, cmd);
String message = "attribute not allowed in "+h; case "error":
throw new Attribute.FormatException(message, ctype, name, String message2 = "attribute not allowed in " + h;
cmd); throw new Attribute.FormatException(message2, ctype, name, cmd);
} else if (cmd == "strip") { case "strip":
skip(length, name+" attribute in "+h); skip(length, name + " attribute in " + h);
continue; continue;
}
} }
} }
// Find canonical instance of the requested attribute. // Find canonical instance of the requested attribute.
@ -408,7 +406,7 @@ class ClassReader implements Constants {
String message = "unsupported StackMap variant in "+h; String message = "unsupported StackMap variant in "+h;
throw new Attribute.FormatException(message, ctype, name, throw new Attribute.FormatException(message, ctype, name,
"pass"); "pass");
} else if (unknownAttrCommand == "strip") { } else if ("strip".equals(unknownAttrCommand)) {
// Skip the unknown attribute. // Skip the unknown attribute.
skip(length, "unknown "+name+" attribute in "+h); skip(length, "unknown "+name+" attribute in "+h);
continue; continue;
@ -422,7 +420,7 @@ class ClassReader implements Constants {
a.layout() == Package.attrInnerClassesEmpty) { a.layout() == Package.attrInnerClassesEmpty) {
// These are hardwired. // These are hardwired.
long pos0 = inPos; long pos0 = inPos;
if (a.name() == "Code") { if ("Code".equals(a.name())) {
Class.Method m = (Class.Method) h; Class.Method m = (Class.Method) h;
m.code = new Code(m); m.code = new Code(m);
try { try {
@ -471,7 +469,7 @@ class ClassReader implements Constants {
void readInnerClasses(Class cls) throws IOException { void readInnerClasses(Class cls) throws IOException {
int nc = readUnsignedShort(); int nc = readUnsignedShort();
ArrayList ics = new ArrayList(nc); ArrayList<InnerClass> ics = new ArrayList<>(nc);
for (int i = 0; i < nc; i++) { for (int i = 0; i < nc; i++) {
InnerClass ic = InnerClass ic =
new InnerClass(readClassRef(), new InnerClass(readClassRef(),

View File

@ -38,12 +38,12 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Writer for a class file that is incorporated into a package. * Writer for a class file that is incorporated into a package.
* @author John Rose * @author John Rose
*/ */
class ClassWriter implements Constants { class ClassWriter {
int verbose; int verbose;
Package pkg; Package pkg;
@ -196,8 +196,7 @@ class ClassWriter implements Constants {
return; return;
} }
writeShort(h.attributes.size()); writeShort(h.attributes.size());
for (Iterator i = h.attributes.iterator(); i.hasNext(); ) { for (Attribute a : h.attributes) {
Attribute a = (Attribute) i.next();
a.finishRefs(cpIndex); a.finishRefs(cpIndex);
writeRef(a.getNameRef()); writeRef(a.getNameRef());
if (a.layout() == Package.attrCodeEmpty || if (a.layout() == Package.attrCodeEmpty ||
@ -207,7 +206,7 @@ class ClassWriter implements Constants {
assert(out != bufOut); assert(out != bufOut);
buf.reset(); buf.reset();
out = bufOut; out = bufOut;
if (a.name() == "Code") { if ("Code".equals(a.name())) {
Class.Method m = (Class.Method) h; Class.Method m = (Class.Method) h;
writeCode(m.code); writeCode(m.code);
} else { } else {
@ -246,10 +245,9 @@ class ClassWriter implements Constants {
} }
void writeInnerClasses(Class cls) throws IOException { void writeInnerClasses(Class cls) throws IOException {
List ics = cls.getInnerClasses(); List<InnerClass> ics = cls.getInnerClasses();
writeShort(ics.size()); writeShort(ics.size());
for (Iterator i = ics.iterator(); i.hasNext(); ) { for (InnerClass ic : ics) {
InnerClass ic = (InnerClass) i.next();
writeRef(ic.thisClass); writeRef(ic.thisClass);
writeRef(ic.outerClass); writeRef(ic.outerClass);
writeRef(ic.name); writeRef(ic.name);

View File

@ -29,12 +29,13 @@ import com.sun.java.util.jar.pack.Package.Class;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Represents a chunk of bytecodes. * Represents a chunk of bytecodes.
* @author John Rose * @author John Rose
*/ */
class Code extends Attribute.Holder implements Constants { class Code extends Attribute.Holder {
Class.Method m; Class.Method m;
public Code(Class.Method m) { public Code(Class.Method m) {
@ -141,15 +142,12 @@ class Code extends Attribute.Holder implements Constants {
super.trimToSize(); super.trimToSize();
} }
protected void visitRefs(int mode, Collection refs) { protected void visitRefs(int mode, Collection<ConstantPool.Entry> refs) {
int verbose = getPackage().verbose; int verbose = getPackage().verbose;
if (verbose > 2) if (verbose > 2)
System.out.println("Reference scan "+this); System.out.println("Reference scan "+this);
Class cls = thisClass(); Class cls = thisClass();
Package pkg = cls.getPackage(); refs.addAll(Arrays.asList(handler_class));
for (int i = 0; i < handler_class.length; i++) {
refs.add(handler_class[i]);
}
if (fixups != null) { if (fixups != null) {
fixups.visitRefs(refs); fixups.visitRefs(refs);
} else { } else {
@ -196,11 +194,8 @@ class Code extends Attribute.Holder implements Constants {
map[mapLen] = (short)(PClimit + Short.MIN_VALUE); map[mapLen] = (short)(PClimit + Short.MIN_VALUE);
return map; return map;
} else { } else {
int[] map = new int[mapLen+1]; int[] map = Arrays.copyOf(insnMap, mapLen + 1);
for (int i = 0; i < mapLen; i++) { map[mapLen] = PClimit;
map[i] = (int) insnMap[i];
}
map[mapLen] = (int) PClimit;
return map; return map;
} }
} }
@ -220,10 +215,7 @@ class Code extends Attribute.Holder implements Constants {
} }
} else { } else {
int[] map = (int[]) map0; int[] map = (int[]) map0;
imap = new int[map.length-1]; imap = Arrays.copyOfRange(map, 0, map.length - 1);
for (int i = 0; i < imap.length; i++) {
imap[i] = map[i];
}
} }
return imap; return imap;
} }
@ -266,7 +258,7 @@ class Code extends Attribute.Holder implements Constants {
} else { } else {
int[] map = (int[]) map0; int[] map = (int[]) map0;
len = map.length; len = map.length;
i = Arrays.binarySearch(map, (int)bci); i = Arrays.binarySearch(map, bci);
} }
assert(i != -1); assert(i != -1);
assert(i != 0); assert(i != 0);
@ -322,7 +314,7 @@ class Code extends Attribute.Holder implements Constants {
len = map.length; len = map.length;
if (bciCode < len) if (bciCode < len)
return map[bciCode]; return map[bciCode];
i = Arrays.binarySearch(map, (int)bciCode); i = Arrays.binarySearch(map, bciCode);
if (i < 0) i = -i-1; if (i < 0) i = -i-1;
int key = bciCode-len; int key = bciCode-len;
for (;; i--) { for (;; i--) {

View File

@ -29,14 +29,15 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Define the conversions between sequences of small integers and raw bytes. * Define the conversions between sequences of small integers and raw bytes.
* This is a schema of encodings which incorporates varying lengths, * This is a schema of encodings which incorporates varying lengths,
* varying degrees of length variability, and varying amounts of signed-ness. * varying degrees of length variability, and varying amounts of signed-ness.
* @author John Rose * @author John Rose
*/ */
class Coding implements Constants, Comparable, CodingMethod, Histogram.BitMetric { class Coding implements Comparable, CodingMethod, Histogram.BitMetric {
/* /*
Coding schema for single integers, parameterized by (B,H,S): Coding schema for single integers, parameterized by (B,H,S):
@ -191,7 +192,9 @@ class Coding implements Constants, Comparable, CodingMethod, Histogram.BitMetric
if (S == 0 || range >= (long)1<<32) if (S == 0 || range >= (long)1<<32)
return saturate32(range-1); return saturate32(range-1);
long maxPos = range-1; long maxPos = range-1;
while (isNegativeCode(maxPos, S)) --maxPos; while (isNegativeCode(maxPos, S)) {
--maxPos;
}
if (maxPos < 0) return -1; // No positive codings at all. if (maxPos < 0) return -1; // No positive codings at all.
int smax = decodeSign32(maxPos, S); int smax = decodeSign32(maxPos, S);
// check for 32-bit wraparound: // check for 32-bit wraparound:
@ -213,9 +216,10 @@ class Coding implements Constants, Comparable, CodingMethod, Histogram.BitMetric
if (S == 0) { if (S == 0) {
return 0; return 0;
} }
int Smask = (1<<S)-1;
long maxNeg = range-1; long maxNeg = range-1;
while (!isNegativeCode(maxNeg, S)) --maxNeg; while (!isNegativeCode(maxNeg, S))
--maxNeg;
if (maxNeg < 0) return 0; // No negative codings at all. if (maxNeg < 0) return 0; // No negative codings at all.
return decodeSign32(maxNeg, S); return decodeSign32(maxNeg, S);
} }
@ -395,12 +399,12 @@ class Coding implements Constants, Comparable, CodingMethod, Histogram.BitMetric
return (del<<14)+(S<<11)+(B<<8)+(H<<0); return (del<<14)+(S<<11)+(B<<8)+(H<<0);
} }
private static HashMap codeMap; private static Map<Coding, Coding> codeMap;
private static synchronized Coding of(int B, int H, int S, int del) { private static synchronized Coding of(int B, int H, int S, int del) {
if (codeMap == null) codeMap = new HashMap(); if (codeMap == null) codeMap = new HashMap<>();
Coding x0 = new Coding(B, H, S, del); Coding x0 = new Coding(B, H, S, del);
Coding x1 = (Coding) codeMap.get(x0); Coding x1 = codeMap.get(x0);
if (x1 == null) codeMap.put(x0, x1 = x0); if (x1 == null) codeMap.put(x0, x1 = x0);
return x1; return x1;
} }
@ -462,6 +466,7 @@ class Coding implements Constants, Comparable, CodingMethod, Histogram.BitMetric
// %%% use byte[] buffer // %%% use byte[] buffer
for (int i = start; i < end; i++) for (int i = start; i < end; i++)
a[i] = readFrom(in); a[i] = readFrom(in);
for (int dstep = 0; dstep < del; dstep++) { for (int dstep = 0; dstep < del; dstep++) {
long state = 0; long state = 0;
for (int i = start; i < end; i++) { for (int i = start; i < end; i++) {
@ -750,14 +755,14 @@ class Coding implements Constants, Comparable, CodingMethod, Histogram.BitMetric
if (len == 0) return true; if (len == 0) return true;
if (isFullRange()) return true; if (isFullRange()) return true;
// Calculate max, min: // Calculate max, min:
int max = values[start]; int lmax = values[start];
int min = max; int lmin = lmax;
for (int i = 1; i < len; i++) { for (int i = 1; i < len; i++) {
int value = values[start+i]; int value = values[start+i];
if (max < value) max = value; if (lmax < value) lmax = value;
if (min > value) min = value; if (lmin > value) lmin = value;
} }
return canRepresent(min, max); return canRepresent(lmin, lmax);
} }
public double getBitLength(int value) { // implements BitMetric public double getBitLength(int value) { // implements BitMetric
@ -800,21 +805,20 @@ class Coding implements Constants, Comparable, CodingMethod, Histogram.BitMetric
//return Coding.of(B, H, S).getLength(deltas, 0, len); //return Coding.of(B, H, S).getLength(deltas, 0, len);
values = deltas; values = deltas;
start = 0; start = 0;
end = values.length;
} }
int sum = len; // at least 1 byte per int sum = len; // at least 1 byte per
// add extra bytes for extra-long values // add extra bytes for extra-long values
for (int n = 1; n <= B; n++) { for (int n = 1; n <= B; n++) {
// what is the coding interval [min..max] for n bytes? // what is the coding interval [min..max] for n bytes?
int max = byteMax[n-1]; int lmax = byteMax[n-1];
int min = byteMin[n-1]; int lmin = byteMin[n-1];
int longer = 0; // count of guys longer than n bytes int longer = 0; // count of guys longer than n bytes
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
int value = values[start+i]; int value = values[start+i];
if (value >= 0) { if (value >= 0) {
if (value > max) longer++; if (value > lmax) longer++;
} else { } else {
if (value < min) longer++; if (value < lmin) longer++;
} }
} }
if (longer == 0) break; // no more passes needed if (longer == 0) break; // no more passes needed

View File

@ -34,15 +34,16 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.Set;
import java.util.zip.Deflater; import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream; import java.util.zip.DeflaterOutputStream;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Heuristic chooser of basic encodings. * Heuristic chooser of basic encodings.
* Runs "zip" to measure the apparent information content after coding. * Runs "zip" to measure the apparent information content after coding.
* @author John Rose * @author John Rose
*/ */
class CodingChooser implements Constants { class CodingChooser {
int verbose; int verbose;
int effort; int effort;
boolean optUseHistogram = true; boolean optUseHistogram = true;
@ -124,10 +125,10 @@ class CodingChooser implements Constants {
= !p200.getBoolean(Utils.COM_PREFIX+"no.population.coding"); = !p200.getBoolean(Utils.COM_PREFIX+"no.population.coding");
this.optUseAdaptiveCoding this.optUseAdaptiveCoding
= !p200.getBoolean(Utils.COM_PREFIX+"no.adaptive.coding"); = !p200.getBoolean(Utils.COM_PREFIX+"no.adaptive.coding");
int stress int lstress
= p200.getInteger(Utils.COM_PREFIX+"stress.coding"); = p200.getInteger(Utils.COM_PREFIX+"stress.coding");
if (stress != 0) if (lstress != 0)
this.stress = new Random(stress); this.stress = new Random(lstress);
} }
this.effort = effort; this.effort = effort;
@ -376,9 +377,9 @@ class CodingChooser implements Constants {
" fewer bytes than regular "+regular+ " fewer bytes than regular "+regular+
"; win="+pct(zipSize1-bestZipSize, zipSize1)); "; win="+pct(zipSize1-bestZipSize, zipSize1));
} }
CodingMethod bestMethod = this.bestMethod; CodingMethod lbestMethod = this.bestMethod;
reset(null, 0, 0); // for GC reset(null, 0, 0); // for GC
return bestMethod; return lbestMethod;
} }
CodingMethod choose(int[] values, int start, int end, Coding regular) { CodingMethod choose(int[] values, int start, int end, Coding regular) {
return choose(values, start, end, regular, null); return choose(values, start, end, regular, null);
@ -742,9 +743,9 @@ class CodingChooser implements Constants {
// Steps 1/2/3 are interdependent, and may be iterated. // Steps 1/2/3 are interdependent, and may be iterated.
// Steps 4 and 5 may be decided independently afterward. // Steps 4 and 5 may be decided independently afterward.
int[] LValuesCoded = PopulationCoding.LValuesCoded; int[] LValuesCoded = PopulationCoding.LValuesCoded;
ArrayList bestFits = new ArrayList(); List<Coding> bestFits = new ArrayList<>();
ArrayList fullFits = new ArrayList(); List<Coding> fullFits = new ArrayList<>();
ArrayList longFits = new ArrayList(); List<Coding> longFits = new ArrayList<>();
final int PACK_TO_MAX_S = 1; final int PACK_TO_MAX_S = 1;
if (bestPopFVC <= 255) { if (bestPopFVC <= 255) {
bestFits.add(BandStructure.BYTE1); bestFits.add(BandStructure.BYTE1);
@ -776,16 +777,16 @@ class CodingChooser implements Constants {
} }
} }
// interleave all B greater than bestB with best and full fits // interleave all B greater than bestB with best and full fits
for (Iterator i = bestFits.iterator(); i.hasNext(); ) { for (Iterator<Coding> i = bestFits.iterator(); i.hasNext(); ) {
Coding c = (Coding) i.next(); Coding c = i.next();
if (c.B() > bestB) { if (c.B() > bestB) {
i.remove(); i.remove();
longFits.add(0, c); longFits.add(0, c);
} }
} }
} }
ArrayList allFits = new ArrayList(); List<Coding> allFits = new ArrayList<>();
for (Iterator i = bestFits.iterator(), for (Iterator<Coding> i = bestFits.iterator(),
j = fullFits.iterator(), j = fullFits.iterator(),
k = longFits.iterator(); k = longFits.iterator();
i.hasNext() || j.hasNext() || k.hasNext(); ) { i.hasNext() || j.hasNext() || k.hasNext(); ) {
@ -812,8 +813,7 @@ class CodingChooser implements Constants {
} }
if (verbose > 3) if (verbose > 3)
Utils.log.info("allFits: "+allFits); Utils.log.info("allFits: "+allFits);
for (Iterator i = allFits.iterator(); i.hasNext(); ) { for (Coding tc : allFits) {
Coding tc = (Coding) i.next();
boolean packToMax = false; boolean packToMax = false;
if (tc.S() == PACK_TO_MAX_S) { if (tc.S() == PACK_TO_MAX_S) {
// Kludge: setS(PACK_TO_MAX_S) means packToMax here. // Kludge: setS(PACK_TO_MAX_S) means packToMax here.
@ -910,7 +910,7 @@ class CodingChooser implements Constants {
" tc="+pop.tokenCoding+ " tc="+pop.tokenCoding+
" uc="+pop.unfavoredCoding); " uc="+pop.unfavoredCoding);
//pop.hist.print("pop-hist", null, System.out); //pop.hist.print("pop-hist", null, System.out);
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
sb.append("fv = {"); sb.append("fv = {");
for (int i = 1; i <= fVlen; i++) { for (int i = 1; i <= fVlen; i++) {
if ((i % 10) == 0) if ((i % 10) == 0)
@ -949,20 +949,20 @@ class CodingChooser implements Constants {
// run occupies too much space. ("Too much" means, say 5% more // run occupies too much space. ("Too much" means, say 5% more
// than the average integer size of the band as a whole.) // than the average integer size of the band as a whole.)
// Try to find a better coding for those segments. // Try to find a better coding for those segments.
int start = this.start; int lstart = this.start;
int end = this.end; int lend = this.end;
int[] values = this.values; int[] lvalues = this.values;
int len = end-start; int len = lend-lstart;
if (plainCoding.isDelta()) { if (plainCoding.isDelta()) {
values = getDeltas(0,0); //%%% not quite right! lvalues = getDeltas(0,0); //%%% not quite right!
start = 0; lstart = 0;
end = values.length; lend = lvalues.length;
} }
int[] sizes = new int[len+1]; int[] sizes = new int[len+1];
int fillp = 0; int fillp = 0;
int totalSize = 0; int totalSize = 0;
for (int i = start; i < end; i++) { for (int i = lstart; i < lend; i++) {
int val = values[i]; int val = lvalues[i];
sizes[fillp++] = totalSize; sizes[fillp++] = totalSize;
int size = plainCoding.getLength(val); int size = plainCoding.getLength(val);
assert(size < Integer.MAX_VALUE); assert(size < Integer.MAX_VALUE);
@ -1013,22 +1013,23 @@ class CodingChooser implements Constants {
double[] fuzzes = new double[meshes.length]; double[] fuzzes = new double[meshes.length];
for (int i = 0; i < meshes.length; i++) { for (int i = 0; i < meshes.length; i++) {
int mesh = meshes[i]; int mesh = meshes[i];
double fuzz; double lfuzz;
if (mesh < 10) if (mesh < 10)
fuzz = sizeFuzz3; lfuzz = sizeFuzz3;
else if (mesh < 100) else if (mesh < 100)
fuzz = sizeFuzz2; lfuzz = sizeFuzz2;
else else
fuzz = sizeFuzz; lfuzz = sizeFuzz;
fuzzes[i] = fuzz; fuzzes[i] = lfuzz;
threshes[i] = BAND_HEADER + (int)Math.ceil(mesh * avgSize * fuzz); threshes[i] = BAND_HEADER + (int)Math.ceil(mesh * avgSize * lfuzz);
} }
if (verbose > 1) { if (verbose > 1) {
System.out.print("tryAdaptiveCoding ["+len+"]"+ System.out.print("tryAdaptiveCoding ["+len+"]"+
" avgS="+avgSize+" fuzz="+sizeFuzz+ " avgS="+avgSize+" fuzz="+sizeFuzz+
" meshes: {"); " meshes: {");
for (int i = 0; i < meshes.length; i++) for (int i = 0; i < meshes.length; i++) {
System.out.print(" "+meshes[i]+"("+threshes[i]+")"); System.out.print(" " + meshes[i] + "(" + threshes[i] + ")");
}
Utils.log.info(" }"); Utils.log.info(" }");
} }
if (runHelper == null) { if (runHelper == null) {
@ -1229,20 +1230,19 @@ class CodingChooser implements Constants {
Histogram hist = getValueHistogram(); Histogram hist = getValueHistogram();
int fVlen = stressLen(hist.getTotalLength()); int fVlen = stressLen(hist.getTotalLength());
if (fVlen == 0) return coding; if (fVlen == 0) return coding;
List popvals = new ArrayList(); List<Integer> popvals = new ArrayList<>();
if (stress.nextBoolean()) { if (stress.nextBoolean()) {
// Build the population from the value list. // Build the population from the value list.
HashSet popset = new HashSet(); Set<Integer> popset = new HashSet<>();
for (int i = start; i < end; i++) { for (int i = start; i < end; i++) {
Integer val = new Integer(values[i]); if (popset.add(values[i])) popvals.add(values[i]);
if (popset.add(val)) popvals.add(val);
} }
} else { } else {
int[][] matrix = hist.getMatrix(); int[][] matrix = hist.getMatrix();
for (int mrow = 0; mrow < matrix.length; mrow++) { for (int mrow = 0; mrow < matrix.length; mrow++) {
int[] row = matrix[mrow]; int[] row = matrix[mrow];
for (int mcol = 1; mcol < row.length; mcol++) { for (int mcol = 1; mcol < row.length; mcol++) {
popvals.add(new Integer(row[mcol])); popvals.add(row[mcol]);
} }
} }
} }
@ -1269,7 +1269,7 @@ class CodingChooser implements Constants {
fVlen = popvals.size(); fVlen = popvals.size();
int[] fvals = new int[1+fVlen]; int[] fvals = new int[1+fVlen];
for (int i = 0; i < fVlen; i++) { for (int i = 0; i < fVlen; i++) {
fvals[1+i] = ((Integer)popvals.get(i)).intValue(); fvals[1+i] = (popvals.get(i)).intValue();
} }
PopulationCoding pop = new PopulationCoding(); PopulationCoding pop = new PopulationCoding();
pop.setFavoredValues(fvals, fVlen); pop.setFavoredValues(fvals, fVlen);
@ -1283,13 +1283,13 @@ class CodingChooser implements Constants {
} }
} }
if (pop.tokenCoding == null) { if (pop.tokenCoding == null) {
int min = fvals[1], max = min; int lmin = fvals[1], lmax = lmin;
for (int i = 2; i <= fVlen; i++) { for (int i = 2; i <= fVlen; i++) {
int val = fvals[i]; int val = fvals[i];
if (min > val) min = val; if (lmin > val) lmin = val;
if (max < val) max = val; if (lmax < val) lmax = val;
} }
pop.tokenCoding = stressCoding(min, max); pop.tokenCoding = stressCoding(lmin, lmax);
} }
computePopSizePrivate(pop, valueCoding, valueCoding); computePopSizePrivate(pop, valueCoding, valueCoding);
@ -1310,13 +1310,13 @@ class CodingChooser implements Constants {
try { try {
assert(!disableRunCoding); assert(!disableRunCoding);
disableRunCoding = true; // temporary, while I decide spans disableRunCoding = true; // temporary, while I decide spans
int[] allValues = (int[]) values.clone(); int[] allValues = values.clone();
CodingMethod result = null; CodingMethod result = null;
int scan = this.end; int scan = this.end;
int start = this.start; int lstart = this.start;
for (int split; scan > start; scan = split) { for (int split; scan > lstart; scan = split) {
int thisspan; int thisspan;
int rand = (scan - start < 100)? -1: stress.nextInt(); int rand = (scan - lstart < 100)? -1: stress.nextInt();
if ((rand & 7) != 0) { if ((rand & 7) != 0) {
thisspan = (spanlen==1? spanlen: stressLen(spanlen-1)+1); thisspan = (spanlen==1? spanlen: stressLen(spanlen-1)+1);
} else { } else {
@ -1325,7 +1325,7 @@ class CodingChooser implements Constants {
int KB = (rand >>>= 3) & AdaptiveCoding.KB_MAX; int KB = (rand >>>= 3) & AdaptiveCoding.KB_MAX;
for (;;) { for (;;) {
thisspan = AdaptiveCoding.decodeK(KX, KB); thisspan = AdaptiveCoding.decodeK(KX, KB);
if (thisspan <= scan - start) break; if (thisspan <= scan - lstart) break;
// Try smaller and smaller codings: // Try smaller and smaller codings:
if (KB != AdaptiveCoding.KB_DEFAULT) if (KB != AdaptiveCoding.KB_DEFAULT)
KB = AdaptiveCoding.KB_DEFAULT; KB = AdaptiveCoding.KB_DEFAULT;
@ -1335,11 +1335,13 @@ class CodingChooser implements Constants {
//System.out.println("KX="+KX+" KB="+KB+" K="+thisspan); //System.out.println("KX="+KX+" KB="+KB+" K="+thisspan);
assert(AdaptiveCoding.isCodableLength(thisspan)); assert(AdaptiveCoding.isCodableLength(thisspan));
} }
if (thisspan > scan - start) thisspan = scan - start; if (thisspan > scan - lstart) thisspan = scan - lstart;
while (!AdaptiveCoding.isCodableLength(thisspan)) --thisspan; while (!AdaptiveCoding.isCodableLength(thisspan)) {
--thisspan;
}
split = scan - thisspan; split = scan - thisspan;
assert(split < scan); assert(split < scan);
assert(split >= start); assert(split >= lstart);
// Choose a coding for the span [split..scan). // Choose a coding for the span [split..scan).
CodingMethod sc = choose(allValues, split, scan, plainCoding); CodingMethod sc = choose(allValues, split, scan, plainCoding);
if (result == null) { if (result == null) {
@ -1420,7 +1422,7 @@ class CodingChooser implements Constants {
case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOF:
throw new NoSuchElementException(); throw new NoSuchElementException();
case StreamTokenizer.TT_NUMBER: case StreamTokenizer.TT_NUMBER:
return new Integer((int) in.nval); return Integer.valueOf((int) in.nval);
default: default:
assert(false); assert(false);
return null; return null;

View File

@ -33,13 +33,14 @@ import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Representation of constant pool entries and indexes. * Representation of constant pool entries and indexes.
* @author John Rose * @author John Rose
*/ */
abstract abstract
class ConstantPool implements Constants { class ConstantPool {
private ConstantPool() {} // do not instantiate private ConstantPool() {} // do not instantiate
static int verbose() { static int verbose() {
@ -155,9 +156,6 @@ class ConstantPool implements Constants {
return null; return null;
} }
public boolean sameTagAs(Object o) {
return (o instanceof Entry) && ((Entry)o).tag == tag;
}
public boolean eq(Entry that) { // same reference public boolean eq(Entry that) { // same reference
assert(that != null); assert(that != null);
return this == that || this.equals(that); return this == that || this.equals(that);
@ -219,9 +217,9 @@ class ConstantPool implements Constants {
return value.hashCode(); return value.hashCode();
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (!sameTagAs(o)) return false;
// Use reference equality of interned strings: // Use reference equality of interned strings:
return ((Utf8Entry)o).value == value; return (o != null && o.getClass() == Utf8Entry.class
&& ((Utf8Entry) o).value.equals(value));
} }
public int compareTo(Object o) { public int compareTo(Object o) {
int x = superCompareTo(o); int x = superCompareTo(o);
@ -275,8 +273,9 @@ class ConstantPool implements Constants {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (!sameTagAs(o)) return false; return (o != null && o.getClass() == NumberEntry.class
return (((NumberEntry)o).value).equals(value); && ((NumberEntry) o).value.equals(value));
} }
public int compareTo(Object o) { public int compareTo(Object o) {
int x = superCompareTo(o); int x = superCompareTo(o);
@ -310,8 +309,8 @@ class ConstantPool implements Constants {
return ref.hashCode() + tag; return ref.hashCode() + tag;
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (!sameTagAs(o)) return false; return (o != null && o.getClass() == StringEntry.class &&
return ((StringEntry)o).ref.eq(ref); ((StringEntry)o).ref.eq(ref));
} }
public int compareTo(Object o) { public int compareTo(Object o) {
int x = superCompareTo(o); int x = superCompareTo(o);
@ -342,8 +341,8 @@ class ConstantPool implements Constants {
hashCode(); // force computation of valueHash hashCode(); // force computation of valueHash
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (!sameTagAs(o)) return false; return (o != null && o.getClass() == ClassEntry.class
return ((ClassEntry)o).ref.eq(ref); && ((ClassEntry) o).ref.eq(ref));
} }
public int compareTo(Object o) { public int compareTo(Object o) {
int x = superCompareTo(o); int x = superCompareTo(o);
@ -380,7 +379,9 @@ class ConstantPool implements Constants {
return (nameRef.hashCode() + (hc2 << 8)) ^ hc2; return (nameRef.hashCode() + (hc2 << 8)) ^ hc2;
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (!sameTagAs(o)) return false; if (o == null || o.getClass() != DescriptorEntry.class) {
return false;
}
DescriptorEntry that = (DescriptorEntry)o; DescriptorEntry that = (DescriptorEntry)o;
return this.nameRef.eq(that.nameRef) return this.nameRef.eq(that.nameRef)
&& this.typeRef.eq(that.typeRef); && this.typeRef.eq(that.typeRef);
@ -439,7 +440,9 @@ class ConstantPool implements Constants {
hashCode(); // force computation of valueHash hashCode(); // force computation of valueHash
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (!sameTagAs(o)) return false; if (o == null || o.getClass() != MemberEntry.class) {
return false;
}
MemberEntry that = (MemberEntry)o; MemberEntry that = (MemberEntry)o;
return this.classRef.eq(that.classRef) return this.classRef.eq(that.classRef)
&& this.descRef.eq(that.descRef); && this.descRef.eq(that.descRef);
@ -511,8 +514,8 @@ class ConstantPool implements Constants {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (!sameTagAs(o)) return false; return (o != null && o.getClass() == SignatureEntry.class &&
return ((SignatureEntry)o).value == value; ((SignatureEntry)o).value.equals(value));
} }
public int compareTo(Object o) { public int compareTo(Object o) {
int x = superCompareTo(o); int x = superCompareTo(o);
@ -724,7 +727,7 @@ class ConstantPool implements Constants {
protected static final ClassEntry[] noClassRefs = {}; protected static final ClassEntry[] noClassRefs = {};
/** An Index is a mapping between CP entries and small integers. */ /** An Index is a mapping between CP entries and small integers. */
public static public static final
class Index extends AbstractList { class Index extends AbstractList {
protected String debugName; protected String debugName;
protected Entry[] cpMap; protected Entry[] cpMap;
@ -894,7 +897,7 @@ class ConstantPool implements Constants {
} }
public static public static
Index makeIndex(String debugName, Collection cpMapList) { Index makeIndex(String debugName, Collection<Entry> cpMapList) {
return new Index(debugName, cpMapList); return new Index(debugName, cpMapList);
} }
@ -916,7 +919,7 @@ class ConstantPool implements Constants {
public static public static
Index[] partition(Index ix, int[] keys) { Index[] partition(Index ix, int[] keys) {
// %%% Should move this into class Index. // %%% Should move this into class Index.
ArrayList<List<Entry>> parts = new ArrayList<>(); List<List<Entry>> parts = new ArrayList<>();
Entry[] cpMap = ix.cpMap; Entry[] cpMap = ix.cpMap;
assert(keys.length == cpMap.length); assert(keys.length == cpMap.length);
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
@ -1094,12 +1097,12 @@ class ConstantPool implements Constants {
// Inverse of getOverloadingIndex // Inverse of getOverloadingIndex
public MemberEntry getOverloadingForIndex(byte tag, ClassEntry classRef, String name, int which) { public MemberEntry getOverloadingForIndex(byte tag, ClassEntry classRef, String name, int which) {
assert(name == name.intern()); assert(name.equals(name.intern()));
Index ix = getMemberIndex(tag, classRef); Index ix = getMemberIndex(tag, classRef);
int ord = 0; int ord = 0;
for (int i = 0; i < ix.cpMap.length; i++) { for (int i = 0; i < ix.cpMap.length; i++) {
MemberEntry e = (MemberEntry) ix.cpMap[i]; MemberEntry e = (MemberEntry) ix.cpMap[i];
if (e.descRef.nameRef.stringValue() == name) { if (e.descRef.nameRef.stringValue().equals(name)) {
if (ord == which) return e; if (ord == which) return e;
ord++; ord++;
} }
@ -1133,10 +1136,10 @@ class ConstantPool implements Constants {
public static public static
void completeReferencesIn(Set<Entry> cpRefs, boolean flattenSigs) { void completeReferencesIn(Set<Entry> cpRefs, boolean flattenSigs) {
cpRefs.remove(null); cpRefs.remove(null);
for (ListIterator work = for (ListIterator<Entry> work =
new ArrayList(cpRefs).listIterator(cpRefs.size()); new ArrayList<>(cpRefs).listIterator(cpRefs.size());
work.hasPrevious(); ) { work.hasPrevious(); ) {
Entry e = (Entry) work.previous(); Entry e = work.previous();
work.remove(); // pop stack work.remove(); // pop stack
assert(e != null); assert(e != null);
if (flattenSigs && e.tag == CONSTANT_Signature) { if (flattenSigs && e.tag == CONSTANT_Signature) {

View File

@ -32,7 +32,10 @@ import java.util.List;
* Shared constants * Shared constants
* @author John Rose * @author John Rose
*/ */
interface Constants { class Constants {
private Constants(){}
public final static int JAVA_MAGIC = 0xCAFEBABE; public final static int JAVA_MAGIC = 0xCAFEBABE;
/* /*

View File

@ -59,12 +59,11 @@ class Driver {
ResourceBundle.getBundle("com.sun.java.util.jar.pack.DriverResource"); ResourceBundle.getBundle("com.sun.java.util.jar.pack.DriverResource");
public static void main(String[] ava) throws IOException { public static void main(String[] ava) throws IOException {
ArrayList<String> av = new ArrayList<>(Arrays.asList(ava)); List<String> av = new ArrayList<>(Arrays.asList(ava));
boolean doPack = true; boolean doPack = true;
boolean doUnpack = false; boolean doUnpack = false;
boolean doRepack = false; boolean doRepack = false;
boolean doForceRepack = false;
boolean doZip = true; boolean doZip = true;
String logFile = null; String logFile = null;
String verboseProp = Utils.DEBUG_VERBOSE; String verboseProp = Utils.DEBUG_VERBOSE;
@ -72,17 +71,20 @@ class Driver {
{ {
// Non-standard, undocumented "--unpack" switch enables unpack mode. // Non-standard, undocumented "--unpack" switch enables unpack mode.
String arg0 = av.isEmpty() ? "" : av.get(0); String arg0 = av.isEmpty() ? "" : av.get(0);
if (arg0.equals("--pack")) { switch (arg0) {
case "--pack":
av.remove(0); av.remove(0);
} else if (arg0.equals("--unpack")) { break;
case "--unpack":
av.remove(0); av.remove(0);
doPack = false; doPack = false;
doUnpack = true; doUnpack = true;
break;
} }
} }
// Collect engine properties here: // Collect engine properties here:
HashMap<String,String> engProps = new HashMap<>(); Map<String,String> engProps = new HashMap<>();
engProps.put(verboseProp, System.getProperty(verboseProp)); engProps.put(verboseProp, System.getProperty(verboseProp));
String optionMap; String optionMap;
@ -96,7 +98,7 @@ class Driver {
} }
// Collect argument properties here: // Collect argument properties here:
HashMap<String,String> avProps = new HashMap<>(); Map<String,String> avProps = new HashMap<>();
try { try {
for (;;) { for (;;) {
String state = parseCommandOptions(av, optionMap, avProps); String state = parseCommandOptions(av, optionMap, avProps);
@ -146,7 +148,7 @@ class Driver {
} }
// See if there is any other action to take. // See if there is any other action to take.
if (state == "--config-file=") { if ("--config-file=".equals(state)) {
String propFile = av.remove(0); String propFile = av.remove(0);
InputStream propIn = new FileInputStream(propFile); InputStream propIn = new FileInputStream(propFile);
Properties fileProps = new Properties(); Properties fileProps = new Properties();
@ -157,10 +159,10 @@ class Driver {
for (Map.Entry<Object,Object> me : fileProps.entrySet()) { for (Map.Entry<Object,Object> me : fileProps.entrySet()) {
engProps.put((String) me.getKey(), (String) me.getValue()); engProps.put((String) me.getKey(), (String) me.getValue());
} }
} else if (state == "--version") { } else if ("--version".equals(state)) {
System.out.println(MessageFormat.format(RESOURCE.getString(DriverResource.VERSION), Driver.class.getName(), "1.31, 07/05/05")); System.out.println(MessageFormat.format(RESOURCE.getString(DriverResource.VERSION), Driver.class.getName(), "1.31, 07/05/05"));
return; return;
} else if (state == "--help") { } else if ("--help".equals(state)) {
printUsage(doPack, true, System.out); printUsage(doPack, true, System.out);
System.exit(1); System.exit(1);
return; return;
@ -178,14 +180,20 @@ class Driver {
// Deal with remaining non-engine properties: // Deal with remaining non-engine properties:
for (String opt : avProps.keySet()) { for (String opt : avProps.keySet()) {
String val = avProps.get(opt); String val = avProps.get(opt);
if (opt == "--repack") { switch (opt) {
doRepack = true; case "--repack":
} else if (opt == "--no-gzip") { doRepack = true;
doZip = (val == null); break;
} else if (opt == "--log-file=") { case "--no-gzip":
logFile = val; doZip = (val == null);
} else { break;
throw new InternalError(MessageFormat.format(RESOURCE.getString(DriverResource.BAD_OPTION), opt, avProps.get(opt))); case "--log-file=":
logFile = val;
break;
default:
throw new InternalError(MessageFormat.format(
RESOURCE.getString(DriverResource.BAD_OPTION),
opt, avProps.get(opt)));
} }
} }
@ -219,7 +227,9 @@ class Driver {
if (packfile.toLowerCase().endsWith(".pack") || if (packfile.toLowerCase().endsWith(".pack") ||
packfile.toLowerCase().endsWith(".pac") || packfile.toLowerCase().endsWith(".pac") ||
packfile.toLowerCase().endsWith(".gz")) { packfile.toLowerCase().endsWith(".gz")) {
System.err.println(MessageFormat.format(RESOURCE.getString(DriverResource.BAD_REPACK_OUTPUT),packfile)); System.err.println(MessageFormat.format(
RESOURCE.getString(DriverResource.BAD_REPACK_OUTPUT),
packfile));
printUsage(doPack, false, System.err); printUsage(doPack, false, System.err);
System.exit(2); System.exit(2);
} }

View File

@ -0,0 +1,174 @@
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.java.util.jar.pack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/*
* @author ksrini
*/
/*
* This class provides an ArrayList implementation which has a fixed size,
* thus all the operations which modifies the size have been rendered
* inoperative. This essentially allows us to use generified array
* lists in lieu of arrays.
*/
final class FixedList<E> implements List<E> {
private final ArrayList<E> flist;
protected FixedList(int capacity) {
flist = new ArrayList<>(capacity);
// initialize the list to null
for (int i = 0 ; i < capacity ; i++) {
flist.add(null);
}
}
@Override
public int size() {
return flist.size();
}
@Override
public boolean isEmpty() {
return flist.isEmpty();
}
@Override
public boolean contains(Object o) {
return flist.contains(o);
}
@Override
public Iterator<E> iterator() {
return flist.iterator();
}
@Override
public Object[] toArray() {
return flist.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return flist.toArray(a);
}
@Override
public boolean add(E e) throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public boolean remove(Object o) throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public boolean containsAll(Collection<?> c) {
return flist.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public boolean addAll(int index, Collection<? extends E> c) throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public boolean removeAll(Collection<?> c) throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public boolean retainAll(Collection<?> c) throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public void clear() throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public E get(int index) {
return flist.get(index);
}
@Override
public E set(int index, E element) {
return flist.set(index, element);
}
@Override
public void add(int index, E element) throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public E remove(int index) throws UnsupportedOperationException {
throw new UnsupportedOperationException("operation not permitted");
}
@Override
public int indexOf(Object o) {
return flist.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return flist.lastIndexOf(o);
}
@Override
public ListIterator<E> listIterator() {
return flist.listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
return flist.listIterator(index);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return flist.subList(fromIndex, toIndex);
}
@Override
public String toString() {
return "FixedList{" + "plist=" + flist + '}';
}
}

View File

@ -42,7 +42,7 @@ import java.util.Iterator;
* *
* @author John Rose * @author John Rose
*/ */
class Fixups extends AbstractCollection implements Constants { final class Fixups extends AbstractCollection {
byte[] bytes; // the subject of the relocations byte[] bytes; // the subject of the relocations
int head; // desc locating first reloc int head; // desc locating first reloc
int tail; // desc locating last reloc int tail; // desc locating last reloc
@ -99,7 +99,7 @@ class Fixups extends AbstractCollection implements Constants {
} }
} }
public void visitRefs(Collection refs) { public void visitRefs(Collection<Entry> refs) {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
refs.add(entries[i]); refs.add(entries[i]);
} }
@ -124,6 +124,7 @@ class Fixups extends AbstractCollection implements Constants {
return bytes; return bytes;
} }
@SuppressWarnings("unchecked")
public void setBytes(byte[] newBytes) { public void setBytes(byte[] newBytes) {
if (bytes == newBytes) return; if (bytes == newBytes) return;
ArrayList old = null; ArrayList old = null;
@ -278,7 +279,7 @@ class Fixups extends AbstractCollection implements Constants {
return new Fixup(nextDesc(), entries[thisIndex]); return new Fixup(nextDesc(), entries[thisIndex]);
} }
int nextDesc() { int nextDesc() {
int thisIndex = index++; index++;
int thisDesc = next; int thisDesc = next;
if (index < size) { if (index < size) {
// Fetch next desc eagerly, in case this fixup gets finalized. // Fetch next desc eagerly, in case this fixup gets finalized.
@ -310,6 +311,7 @@ class Fixups extends AbstractCollection implements Constants {
public boolean add(Object fixup) { public boolean add(Object fixup) {
return add((Fixup) fixup); return add((Fixup) fixup);
} }
@SuppressWarnings("unchecked")
public boolean addAll(Collection c) { public boolean addAll(Collection c) {
if (c instanceof Fixups) { if (c instanceof Fixups) {
// Use knowledge of Itr structure to avoid building little structs. // Use knowledge of Itr structure to avoid building little structs.
@ -420,7 +422,7 @@ class Fixups extends AbstractCollection implements Constants {
// Iterate over all the references in this set of fixups. // Iterate over all the references in this set of fixups.
public static public static
void visitRefs(Object fixups, Collection refs) { void visitRefs(Object fixups, Collection<Entry> refs) {
if (fixups == null) { if (fixups == null) {
} else if (!(fixups instanceof Fixups)) { } else if (!(fixups instanceof Fixups)) {
// Special convention; see above. // Special convention; see above.

View File

@ -34,7 +34,7 @@ import java.util.Arrays;
* Histogram derived from an integer array of events (int[]). * Histogram derived from an integer array of events (int[]).
* @author John Rose * @author John Rose
*/ */
class Histogram { final class Histogram {
// Compact histogram representation: 4 bytes per distinct value, // Compact histogram representation: 4 bytes per distinct value,
// plus 5 words per distinct count. // plus 5 words per distinct count.
protected final int[][] matrix; // multi-row matrix {{counti,valueij...}} protected final int[][] matrix; // multi-row matrix {{counti,valueij...}}
@ -304,7 +304,7 @@ class Histogram {
public public
String[] getRowTitles(String name) { String[] getRowTitles(String name) {
int totalUnique = getTotalLength(); int totalUnique = getTotalLength();
int totalWeight = getTotalWeight(); int ltotalWeight = getTotalWeight();
String[] histTitles = new String[matrix.length]; String[] histTitles = new String[matrix.length];
int cumWeight = 0; int cumWeight = 0;
int cumUnique = 0; int cumUnique = 0;
@ -314,7 +314,7 @@ class Histogram {
int weight = getRowWeight(i); int weight = getRowWeight(i);
cumWeight += weight; cumWeight += weight;
cumUnique += unique; cumUnique += unique;
long wpct = ((long)cumWeight * 100 + totalWeight/2) / totalWeight; long wpct = ((long)cumWeight * 100 + ltotalWeight/2) / ltotalWeight;
long upct = ((long)cumUnique * 100 + totalUnique/2) / totalUnique; long upct = ((long)cumUnique * 100 + totalUnique/2) / totalUnique;
double len = getRowBitLength(i); double len = getRowBitLength(i);
assert(0.1 > Math.abs(len - getBitLength(matrix[i][1]))); assert(0.1 > Math.abs(len - getBitLength(matrix[i][1])));
@ -346,14 +346,14 @@ class Histogram {
public public
void print(String name, String[] histTitles, PrintStream out) { void print(String name, String[] histTitles, PrintStream out) {
int totalUnique = getTotalLength(); int totalUnique = getTotalLength();
int totalWeight = getTotalWeight(); int ltotalWeight = getTotalWeight();
double tlen = getBitLength(); double tlen = getBitLength();
double avgLen = tlen / totalWeight; double avgLen = tlen / ltotalWeight;
double avg = (double) totalWeight / totalUnique; double avg = (double) ltotalWeight / totalUnique;
String title = (name String title = (name
+" len="+round(tlen,10) +" len="+round(tlen,10)
+" avgLen="+round(avgLen,10) +" avgLen="+round(avgLen,10)
+" weight("+totalWeight+")" +" weight("+ltotalWeight+")"
+" unique["+totalUnique+"]" +" unique["+totalUnique+"]"
+" avgWeight("+round(avg,100)+")"); +" avgWeight("+round(avg,100)+")");
if (histTitles == null) { if (histTitles == null) {
@ -363,9 +363,9 @@ class Histogram {
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) { for (int i = 0; i < matrix.length; i++) {
buf.setLength(0); buf.setLength(0);
buf.append(" "+histTitles[i]+" {"); buf.append(" ").append(histTitles[i]).append(" {");
for (int j = 1; j < matrix[i].length; j++) { for (int j = 1; j < matrix[i].length; j++) {
buf.append(" "+matrix[i][j]); buf.append(" ").append(matrix[i][j]);
} }
buf.append(" }"); buf.append(" }");
out.println(buf); out.println(buf);
@ -603,7 +603,7 @@ class Histogram {
private static private static
int[] maybeSort(int[] values) { int[] maybeSort(int[] values) {
if (!isSorted(values, 0, false)) { if (!isSorted(values, 0, false)) {
values = (int[]) values.clone(); values = values.clone();
Arrays.sort(values); Arrays.sort(values);
} }
return values; return values;

View File

@ -26,13 +26,15 @@
package com.sun.java.util.jar.pack; package com.sun.java.util.jar.pack;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* A parsed bytecode instruction. * A parsed bytecode instruction.
* Provides accessors to various relevant bits. * Provides accessors to various relevant bits.
* @author John Rose * @author John Rose
*/ */
class Instruction implements Constants { class Instruction {
protected byte[] bytes; // bytecodes protected byte[] bytes; // bytecodes
protected int pc; // location of this instruction protected int pc; // location of this instruction
protected int bc; // opcode of this instruction protected int bc; // opcode of this instruction
@ -91,8 +93,8 @@ class Instruction implements Constants {
/** A fake instruction at this pc whose next() will be at nextpc. */ /** A fake instruction at this pc whose next() will be at nextpc. */
public Instruction forceNextPC(int nextpc) { public Instruction forceNextPC(int nextpc) {
int length = nextpc - pc; int llength = nextpc - pc;
return new Instruction(bytes, pc, -1, -1, length); return new Instruction(bytes, pc, -1, -1, llength);
} }
public static Instruction at(byte[] bytes, int pc) { public static Instruction at(byte[] bytes, int pc) {
@ -315,12 +317,24 @@ class Instruction implements Constants {
} }
} }
/** Two insns are equal if they have the same bytes. */ /** Two instructions are equal if they have the same bytes. */
public boolean equals(Object o) { public boolean equals(Object o) {
return (o instanceof Instruction) && equals((Instruction)o); return (o != null) && (o.getClass() == Instruction.class)
&& equals((Instruction) o);
}
public int hashCode() {
int hash = 3;
hash = 11 * hash + Arrays.hashCode(this.bytes);
hash = 11 * hash + this.pc;
hash = 11 * hash + this.bc;
hash = 11 * hash + this.w;
hash = 11 * hash + this.length;
return hash;
} }
public boolean equals(Instruction that) { public boolean equals(Instruction that) {
if (this.pc != that.pc) return false;
if (this.bc != that.bc) return false; if (this.bc != that.bc) return false;
if (this.w != that.w) return false; if (this.w != that.w) return false;
if (this.length != that.length) return false; if (this.length != that.length) return false;

View File

@ -170,8 +170,8 @@ class NativeUnpack {
void run(InputStream inRaw, JarOutputStream jstream, void run(InputStream inRaw, JarOutputStream jstream,
ByteBuffer presetInput) throws IOException { ByteBuffer presetInput) throws IOException {
BufferedInputStream in = new BufferedInputStream(inRaw); BufferedInputStream in0 = new BufferedInputStream(inRaw);
this.in = in; // for readInputFn to see this.in = in0; // for readInputFn to see
_verbose = _props.getInteger(Utils.DEBUG_VERBOSE); _verbose = _props.getInteger(Utils.DEBUG_VERBOSE);
// Fix for BugId: 4902477, -unpack.modification.time = 1059010598000 // Fix for BugId: 4902477, -unpack.modification.time = 1059010598000
// TODO eliminate and fix in unpack.cpp // TODO eliminate and fix in unpack.cpp
@ -224,7 +224,7 @@ class NativeUnpack {
if (_verbose > 0) if (_verbose > 0)
Utils.log.info("bytes consumed = "+consumed); Utils.log.info("bytes consumed = "+consumed);
if (presetInput == null && if (presetInput == null &&
!Utils.isPackMagic(Utils.readMagic(in))) { !Utils.isPackMagic(Utils.readMagic(in0))) {
break; break;
} }
if (_verbose > 0 ) { if (_verbose > 0 ) {

View File

@ -52,12 +52,13 @@ import java.util.ListIterator;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Define the main data structure transmitted by pack/unpack. * Define the main data structure transmitted by pack/unpack.
* @author John Rose * @author John Rose
*/ */
class Package implements Constants { class Package {
int verbose; int verbose;
{ {
PropMap pmap = Utils.currentPropMap(); PropMap pmap = Utils.currentPropMap();
@ -109,9 +110,9 @@ class Package implements Constants {
public static final Attribute.Layout attrCodeEmpty; public static final Attribute.Layout attrCodeEmpty;
public static final Attribute.Layout attrInnerClassesEmpty; public static final Attribute.Layout attrInnerClassesEmpty;
public static final Attribute.Layout attrSourceFileSpecial; public static final Attribute.Layout attrSourceFileSpecial;
public static final Map attrDefs; public static final Map<Attribute.Layout, Attribute> attrDefs;
static { static {
HashMap<Layout, Attribute> ad = new HashMap<>(3); Map<Layout, Attribute> ad = new HashMap<>(3);
attrCodeEmpty = Attribute.define(ad, ATTR_CONTEXT_METHOD, attrCodeEmpty = Attribute.define(ad, ATTR_CONTEXT_METHOD,
"Code", "").layout(); "Code", "").layout();
attrInnerClassesEmpty = Attribute.define(ad, ATTR_CONTEXT_CLASS, attrInnerClassesEmpty = Attribute.define(ad, ATTR_CONTEXT_CLASS,
@ -130,8 +131,7 @@ class Package implements Constants {
*/ */
int getHighestClassVersion() { int getHighestClassVersion() {
int res = 0; // initial low value int res = 0; // initial low value
for (Iterator i = classes.iterator(); i.hasNext(); ) { for (Class cls : classes) {
Class cls = (Class) i.next();
int ver = cls.getVersion(); int ver = cls.getVersion();
if (res < ver) res = ver; if (res < ver) res = ver;
} }
@ -187,7 +187,7 @@ class Package implements Constants {
return classes; return classes;
} }
public public final
class Class extends Attribute.Holder implements Comparable { class Class extends Attribute.Holder implements Comparable {
public Package getPackage() { return Package.this; } public Package getPackage() { return Package.this; }
@ -232,8 +232,8 @@ class Package implements Constants {
initFile(newStub(classFile)); initFile(newStub(classFile));
} }
List getFields() { return fields == null ? noFields : fields; } List<Field> getFields() { return fields == null ? noFields : fields; }
List getMethods() { return methods == null ? noMethods : methods; } List<Method> getMethods() { return methods == null ? noMethods : methods; }
public String getName() { public String getName() {
return thisClass.stringValue(); return thisClass.stringValue();
@ -264,7 +264,7 @@ class Package implements Constants {
if (olda == null) if (olda == null)
return; // no SourceFile attr. return; // no SourceFile attr.
String obvious = getObviousSourceFile(); String obvious = getObviousSourceFile();
ArrayList ref = new ArrayList(1); List<Entry> ref = new ArrayList<>(1);
olda.visitRefs(this, VRM_PACKAGE, ref); olda.visitRefs(this, VRM_PACKAGE, ref);
Utf8Entry sfName = (Utf8Entry) ref.get(0); Utf8Entry sfName = (Utf8Entry) ref.get(0);
Attribute a = olda; Attribute a = olda;
@ -322,7 +322,7 @@ class Package implements Constants {
} }
public void setInnerClasses(Collection<InnerClass> ics) { public void setInnerClasses(Collection<InnerClass> ics) {
innerClasses = (ics == null) ? null : new ArrayList<InnerClass>(ics); innerClasses = (ics == null) ? null : new ArrayList<>(ics);
// Edit the attribute list, if necessary. // Edit the attribute list, if necessary.
Attribute a = getAttribute(attrInnerClassesEmpty); Attribute a = getAttribute(attrInnerClassesEmpty);
if (innerClasses != null && a == null) if (innerClasses != null && a == null)
@ -341,7 +341,7 @@ class Package implements Constants {
* with that of Package.this.allInnerClasses. * with that of Package.this.allInnerClasses.
*/ */
public List<InnerClass> computeGloballyImpliedICs() { public List<InnerClass> computeGloballyImpliedICs() {
HashSet<Entry> cpRefs = new HashSet<>(); Set<Entry> cpRefs = new HashSet<>();
{ // This block temporarily displaces this.innerClasses. { // This block temporarily displaces this.innerClasses.
ArrayList<InnerClass> innerClassesSaved = innerClasses; ArrayList<InnerClass> innerClassesSaved = innerClasses;
innerClasses = null; // ignore for the moment innerClasses = null; // ignore for the moment
@ -350,7 +350,7 @@ class Package implements Constants {
} }
ConstantPool.completeReferencesIn(cpRefs, true); ConstantPool.completeReferencesIn(cpRefs, true);
HashSet<Entry> icRefs = new HashSet<>(); Set<Entry> icRefs = new HashSet<>();
for (Entry e : cpRefs) { for (Entry e : cpRefs) {
// Restrict cpRefs to InnerClasses entries only. // Restrict cpRefs to InnerClasses entries only.
if (!(e instanceof ClassEntry)) continue; if (!(e instanceof ClassEntry)) continue;
@ -390,7 +390,7 @@ class Package implements Constants {
List<InnerClass> impliedICs = computeGloballyImpliedICs(); List<InnerClass> impliedICs = computeGloballyImpliedICs();
List<InnerClass> actualICs = getInnerClasses(); List<InnerClass> actualICs = getInnerClasses();
if (actualICs == null) if (actualICs == null)
actualICs = Collections.EMPTY_LIST; actualICs = Collections.emptyList();
// Symmetric difference is calculated from I, A like this: // Symmetric difference is calculated from I, A like this:
// diff = (I+A) - (I*A) // diff = (I+A) - (I*A)
@ -409,7 +409,7 @@ class Package implements Constants {
// Diff is A since I is empty. // Diff is A since I is empty.
} }
// (I*A) is non-trivial // (I*A) is non-trivial
HashSet<InnerClass> center = new HashSet<>(actualICs); Set<InnerClass> center = new HashSet<>(actualICs);
center.retainAll(new HashSet<>(impliedICs)); center.retainAll(new HashSet<>(impliedICs));
impliedICs.addAll(actualICs); impliedICs.addAll(actualICs);
impliedICs.removeAll(center); impliedICs.removeAll(center);
@ -443,7 +443,7 @@ class Package implements Constants {
} else if (actualICs == null) { } else if (actualICs == null) {
// No local IC attribute, even though some are implied. // No local IC attribute, even though some are implied.
// Signal with trivial attribute. // Signal with trivial attribute.
localICs = Collections.EMPTY_LIST; localICs = Collections.emptyList();
} else { } else {
// Transmit a non-empty diff, which will create // Transmit a non-empty diff, which will create
// a local ICs attribute. // a local ICs attribute.
@ -588,7 +588,7 @@ class Package implements Constants {
} }
public void strip(String attrName) { public void strip(String attrName) {
if (attrName == "Code") if ("Code".equals(attrName))
code = null; code = null;
if (code != null) if (code != null)
code.strip(attrName); code.strip(attrName);
@ -622,7 +622,7 @@ class Package implements Constants {
} }
public void strip(String attrName) { public void strip(String attrName) {
if (attrName == "InnerClass") if ("InnerClass".equals(attrName))
innerClasses = null; innerClasses = null;
for (int isM = 0; isM <= 1; isM++) { for (int isM = 0; isM <= 1; isM++) {
ArrayList members = (isM == 0) ? fields : methods; ArrayList members = (isM == 0) ? fields : methods;
@ -639,9 +639,7 @@ class Package implements Constants {
if (verbose > 2) Utils.log.fine("visitRefs "+this); if (verbose > 2) Utils.log.fine("visitRefs "+this);
refs.add(thisClass); refs.add(thisClass);
refs.add(superClass); refs.add(superClass);
for (int i = 0; i < interfaces.length; i++) { refs.addAll(Arrays.asList(interfaces));
refs.add(interfaces[i]);
}
for (int isM = 0; isM <= 1; isM++) { for (int isM = 0; isM <= 1; isM++) {
ArrayList members = (isM == 0) ? fields : methods; ArrayList members = (isM == 0) ? fields : methods;
if (members == null) continue; if (members == null) continue;
@ -741,7 +739,7 @@ class Package implements Constants {
} }
public List<File> getClassStubs() { public List<File> getClassStubs() {
ArrayList<File> classStubs = new ArrayList<>(classes.size()); List<File> classStubs = new ArrayList<>(classes.size());
for (Class cls : classes) { for (Class cls : classes) {
assert(cls.file.isClassStub()); assert(cls.file.isClassStub());
classStubs.add(cls.file); classStubs.add(cls.file);
@ -749,8 +747,7 @@ class Package implements Constants {
return classStubs; return classStubs;
} }
public public final class File implements Comparable {
class File implements Comparable {
String nameString; // true name of this file String nameString; // true name of this file
Utf8Entry name; Utf8Entry name;
int modtime = NO_MODTIME; int modtime = NO_MODTIME;
@ -792,8 +789,10 @@ class Package implements Constants {
// The nameString is the key. Ignore other things. // The nameString is the key. Ignore other things.
// (Note: The name might be "", in the case of a trivial class stub.) // (Note: The name might be "", in the case of a trivial class stub.)
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == null || (o.getClass() != File.class))
return false;
File that = (File)o; File that = (File)o;
return that.nameString == this.nameString; return that.nameString.equals(this.nameString);
} }
public int hashCode() { public int hashCode() {
return nameString.hashCode(); return nameString.hashCode();
@ -816,9 +815,9 @@ class Package implements Constants {
return getFileName(null); return getFileName(null);
} }
public java.io.File getFileName(java.io.File parent) { public java.io.File getFileName(java.io.File parent) {
String name = this.nameString; String lname = this.nameString;
//if (name.startsWith("./")) name = name.substring(2); //if (name.startsWith("./")) name = name.substring(2);
String fname = name.replace('/', java.io.File.separatorChar); String fname = lname.replace('/', java.io.File.separatorChar);
return new java.io.File(parent, fname); return new java.io.File(parent, fname);
} }
@ -834,7 +833,7 @@ class Package implements Constants {
} }
public long getFileLength() { public long getFileLength() {
long len = 0; long len = 0;
if (prepend == null && append == null) return 0; if (prepend == null || append == null) return 0;
for (Iterator i = prepend.iterator(); i.hasNext(); ) { for (Iterator i = prepend.iterator(); i.hasNext(); ) {
byte[] block = (byte[]) i.next(); byte[] block = (byte[]) i.next();
len += block.length; len += block.length;
@ -843,7 +842,7 @@ class Package implements Constants {
return len; return len;
} }
public void writeTo(OutputStream out) throws IOException { public void writeTo(OutputStream out) throws IOException {
if (prepend == null && append == null) return; if (prepend == null || append == null) return;
for (Iterator i = prepend.iterator(); i.hasNext(); ) { for (Iterator i = prepend.iterator(); i.hasNext(); ) {
byte[] block = (byte[]) i.next(); byte[] block = (byte[]) i.next();
out.write(block); out.write(block);
@ -859,8 +858,8 @@ class Package implements Constants {
} }
public InputStream getInputStream() { public InputStream getInputStream() {
InputStream in = new ByteArrayInputStream(append.toByteArray()); InputStream in = new ByteArrayInputStream(append.toByteArray());
if (prepend.size() == 0) return in; if (prepend.isEmpty()) return in;
ArrayList<InputStream> isa = new ArrayList<>(prepend.size()+1); List<InputStream> isa = new ArrayList<>(prepend.size()+1);
for (Iterator i = prepend.iterator(); i.hasNext(); ) { for (Iterator i = prepend.iterator(); i.hasNext(); ) {
byte[] bytes = (byte[]) i.next(); byte[] bytes = (byte[]) i.next();
isa.add(new ByteArrayInputStream(bytes)); isa.add(new ByteArrayInputStream(bytes));
@ -897,11 +896,11 @@ class Package implements Constants {
} }
// Is there a globally declared table of inner classes? // Is there a globally declared table of inner classes?
ArrayList<InnerClass> allInnerClasses = new ArrayList<>(); List<InnerClass> allInnerClasses = new ArrayList<>();
HashMap<ClassEntry, InnerClass> allInnerClassesByThis; Map<ClassEntry, InnerClass> allInnerClassesByThis;
public public
List getAllInnerClasses() { List<InnerClass> getAllInnerClasses() {
return allInnerClasses; return allInnerClasses;
} }
@ -955,16 +954,17 @@ class Package implements Constants {
if (parse == null) return false; if (parse == null) return false;
String pkgOuter = parse[0]; String pkgOuter = parse[0];
//String number = parse[1]; //String number = parse[1];
String name = parse[2]; String lname = parse[2];
String haveName = (this.name == null) ? null : this.name.stringValue(); String haveName = (this.name == null) ? null : this.name.stringValue();
String haveOuter = (outerClass == null) ? null : outerClass.stringValue(); String haveOuter = (outerClass == null) ? null : outerClass.stringValue();
boolean predictable = (name == haveName && pkgOuter == haveOuter); boolean lpredictable = (lname == haveName && pkgOuter == haveOuter);
//System.out.println("computePredictable => "+predictable); //System.out.println("computePredictable => "+predictable);
return predictable; return lpredictable;
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == null) return false; if (o == null || o.getClass() != InnerClass.class)
return false;
InnerClass that = (InnerClass)o; InnerClass that = (InnerClass)o;
return eq(this.thisClass, that.thisClass) return eq(this.thisClass, that.thisClass)
&& eq(this.outerClass, that.outerClass) && eq(this.outerClass, that.outerClass)
@ -999,7 +999,7 @@ class Package implements Constants {
// Helper for building InnerClasses attributes. // Helper for building InnerClasses attributes.
static private static private
void visitInnerClassRefs(Collection innerClasses, int mode, Collection<Entry> refs) { void visitInnerClassRefs(Collection<InnerClass> innerClasses, int mode, Collection<Entry> refs) {
if (innerClasses == null) { if (innerClasses == null) {
return; // no attribute; nothing to do return; // no attribute; nothing to do
} }
@ -1008,8 +1008,7 @@ class Package implements Constants {
} }
if (innerClasses.size() > 0) { if (innerClasses.size() > 0) {
// Count the entries themselves: // Count the entries themselves:
for (Iterator i = innerClasses.iterator(); i.hasNext(); ) { for (InnerClass c : innerClasses) {
InnerClass c = (InnerClass) i.next();
c.visitRefs(mode, refs); c.visitRefs(mode, refs);
} }
} }
@ -1117,43 +1116,43 @@ class Package implements Constants {
// what is one of { Debug, Compile, Constant, Exceptions, InnerClasses } // what is one of { Debug, Compile, Constant, Exceptions, InnerClasses }
if (verbose > 0) if (verbose > 0)
Utils.log.info("Stripping "+what.toLowerCase()+" data and attributes..."); Utils.log.info("Stripping "+what.toLowerCase()+" data and attributes...");
if (what == "Debug") { switch (what) {
strip("SourceFile"); case "Debug":
strip("LineNumberTable"); strip("SourceFile");
strip("LocalVariableTable"); strip("LineNumberTable");
strip("LocalVariableTypeTable"); strip("LocalVariableTable");
} strip("LocalVariableTypeTable");
if (what == "Compile") { break;
// Keep the inner classes normally. case "Compile":
// Although they have no effect on execution, // Keep the inner classes normally.
// the Reflection API exposes them, and JCK checks them. // Although they have no effect on execution,
// NO: // strip("InnerClasses"); // the Reflection API exposes them, and JCK checks them.
strip("Deprecated"); // NO: // strip("InnerClasses");
strip("Synthetic"); strip("Deprecated");
} strip("Synthetic");
if (what == "Exceptions") { break;
// Keep the exceptions normally. case "Exceptions":
// Although they have no effect on execution, // Keep the exceptions normally.
// the Reflection API exposes them, and JCK checks them. // Although they have no effect on execution,
strip("Exceptions"); // the Reflection API exposes them, and JCK checks them.
} strip("Exceptions");
if (what == "Constant") { break;
stripConstantFields(); case "Constant":
stripConstantFields();
break;
} }
} }
public void trimToSize() { public void trimToSize() {
classes.trimToSize(); classes.trimToSize();
for (Iterator i = classes.iterator(); i.hasNext(); ) { for (Class c : classes) {
Class c = (Class)i.next();
c.trimToSize(); c.trimToSize();
} }
files.trimToSize(); files.trimToSize();
} }
public void strip(String attrName) { public void strip(String attrName) {
for (Iterator i = classes.iterator(); i.hasNext(); ) { for (Class c : classes) {
Class c = (Class)i.next();
c.strip(attrName); c.strip(attrName);
} }
} }
@ -1166,10 +1165,9 @@ class Package implements Constants {
} }
public void stripConstantFields() { public void stripConstantFields() {
for (Iterator i = classes.iterator(); i.hasNext(); ) { for (Class c : classes) {
Class c = (Class) i.next(); for (Iterator<Class.Field> j = c.fields.iterator(); j.hasNext(); ) {
for (Iterator j = c.fields.iterator(); j.hasNext(); ) { Class.Field f = j.next();
Class.Field f = (Class.Field) j.next();
if (Modifier.isFinal(f.flags) if (Modifier.isFinal(f.flags)
// do not strip non-static finals: // do not strip non-static finals:
&& Modifier.isStatic(f.flags) && Modifier.isStatic(f.flags)
@ -1189,8 +1187,7 @@ class Package implements Constants {
c.visitRefs(mode, refs); c.visitRefs(mode, refs);
} }
if (mode != VRM_CLASSIC) { if (mode != VRM_CLASSIC) {
for (Iterator i = files.iterator(); i.hasNext(); ) { for (File f : files) {
File f = (File)i.next();
f.visitRefs(mode, refs); f.visitRefs(mode, refs);
} }
visitInnerClassRefs(allInnerClasses, mode, refs); visitInnerClassRefs(allInnerClasses, mode, refs);
@ -1202,6 +1199,7 @@ class Package implements Constants {
// compress better. It also moves classes to the end of the // compress better. It also moves classes to the end of the
// file order. It also removes JAR directory entries, which // file order. It also removes JAR directory entries, which
// are useless. // are useless.
@SuppressWarnings("unchecked")
void reorderFiles(boolean keepClassOrder, boolean stripDirectories) { void reorderFiles(boolean keepClassOrder, boolean stripDirectories) {
// First reorder the classes, if that is allowed. // First reorder the classes, if that is allowed.
if (!keepClassOrder) { if (!keepClassOrder) {
@ -1214,9 +1212,9 @@ class Package implements Constants {
// modtimes and options are not transmitted, and the stub files // modtimes and options are not transmitted, and the stub files
// for class files do not need to be transmitted at all. // for class files do not need to be transmitted at all.
// Also // Also
List stubs = getClassStubs(); List<File> stubs = getClassStubs();
for (Iterator i = files.iterator(); i.hasNext(); ) { for (Iterator<File> i = files.iterator(); i.hasNext(); ) {
File file = (File) i.next(); File file = i.next();
if (file.isClassStub() || if (file.isClassStub() ||
(stripDirectories && file.isDirectory())) { (stripDirectories && file.isDirectory())) {
i.remove(); i.remove();
@ -1259,8 +1257,8 @@ class Package implements Constants {
void trimStubs() { void trimStubs() {
// Restore enough non-trivial stubs to carry the needed class modtimes. // Restore enough non-trivial stubs to carry the needed class modtimes.
for (ListIterator i = files.listIterator(files.size()); i.hasPrevious(); ) { for (ListIterator<File> i = files.listIterator(files.size()); i.hasPrevious(); ) {
File file = (File) i.previous(); File file = i.previous();
if (!file.isTrivialClassStub()) { if (!file.isTrivialClassStub()) {
if (verbose > 1) if (verbose > 1)
Utils.log.fine("Keeping last non-trivial "+file); Utils.log.fine("Keeping last non-trivial "+file);
@ -1309,7 +1307,7 @@ class Package implements Constants {
// Use this before writing the class files. // Use this before writing the class files.
void ensureAllClassFiles() { void ensureAllClassFiles() {
HashSet<File> fileSet = new HashSet<>(files); Set<File> fileSet = new HashSet<>(files);
for (Class cls : classes) { for (Class cls : classes) {
// Add to the end of ths list: // Add to the end of ths list:
if (!fileSet.contains(cls.file)) if (!fileSet.contains(cls.file))
@ -1317,8 +1315,8 @@ class Package implements Constants {
} }
} }
static final List noObjects = Arrays.asList(new Object[0]); static final List<Object> noObjects = Arrays.asList(new Object[0]);
static final List noFields = Arrays.asList(new Class.Field[0]); static final List<Class.Field> noFields = Arrays.asList(new Class.Field[0]);
static final List noMethods = Arrays.asList(new Class.Method[0]); static final List<Class.Method> noMethods = Arrays.asList(new Class.Method[0]);
static final List noInnerClasses = Arrays.asList(new InnerClass[0]); static final List<InnerClass> noInnerClasses = Arrays.asList(new InnerClass[0]);
} }

View File

@ -32,11 +32,28 @@ import com.sun.java.util.jar.pack.ConstantPool.Index;
import com.sun.java.util.jar.pack.ConstantPool.MemberEntry; import com.sun.java.util.jar.pack.ConstantPool.MemberEntry;
import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry;
import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry;
import java.io.*;
import java.util.*;
import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.Class;
import com.sun.java.util.jar.pack.Package.File; import com.sun.java.util.jar.pack.Package.File;
import com.sun.java.util.jar.pack.Package.InnerClass; import com.sun.java.util.jar.pack.Package.InnerClass;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.PrintStream;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Reader for a package file. * Reader for a package file.
@ -418,7 +435,7 @@ class PackageReader extends BandStructure {
cp_Int.readFrom(in); cp_Int.readFrom(in);
for (int i = 0; i < cpMap.length; i++) { for (int i = 0; i < cpMap.length; i++) {
int x = cp_Int.getInt(); // coding handles signs OK int x = cp_Int.getInt(); // coding handles signs OK
cpMap[i] = ConstantPool.getLiteralEntry(new Integer(x)); cpMap[i] = ConstantPool.getLiteralEntry(x);
} }
cp_Int.doneDisbursing(); cp_Int.doneDisbursing();
break; break;
@ -428,7 +445,7 @@ class PackageReader extends BandStructure {
for (int i = 0; i < cpMap.length; i++) { for (int i = 0; i < cpMap.length; i++) {
int x = cp_Float.getInt(); int x = cp_Float.getInt();
float fx = Float.intBitsToFloat(x); float fx = Float.intBitsToFloat(x);
cpMap[i] = ConstantPool.getLiteralEntry(new Float(fx)); cpMap[i] = ConstantPool.getLiteralEntry(fx);
} }
cp_Float.doneDisbursing(); cp_Float.doneDisbursing();
break; break;
@ -444,7 +461,7 @@ class PackageReader extends BandStructure {
long hi = cp_Long_hi.getInt(); long hi = cp_Long_hi.getInt();
long lo = cp_Long_lo.getInt(); long lo = cp_Long_lo.getInt();
long x = (hi << 32) + ((lo << 32) >>> 32); long x = (hi << 32) + ((lo << 32) >>> 32);
cpMap[i] = ConstantPool.getLiteralEntry(new Long(x)); cpMap[i] = ConstantPool.getLiteralEntry(x);
} }
cp_Long_hi.doneDisbursing(); cp_Long_hi.doneDisbursing();
cp_Long_lo.doneDisbursing(); cp_Long_lo.doneDisbursing();
@ -462,7 +479,7 @@ class PackageReader extends BandStructure {
long lo = cp_Double_lo.getInt(); long lo = cp_Double_lo.getInt();
long x = (hi << 32) + ((lo << 32) >>> 32); long x = (hi << 32) + ((lo << 32) >>> 32);
double dx = Double.longBitsToDouble(x); double dx = Double.longBitsToDouble(x);
cpMap[i] = ConstantPool.getLiteralEntry(new Double(dx)); cpMap[i] = ConstantPool.getLiteralEntry(dx);
} }
cp_Double_hi.doneDisbursing(); cp_Double_hi.doneDisbursing();
cp_Double_lo.doneDisbursing(); cp_Double_lo.doneDisbursing();
@ -645,7 +662,7 @@ class PackageReader extends BandStructure {
cp_Utf8_big_suffix.doneDisbursing(); cp_Utf8_big_suffix.doneDisbursing();
} }
HashMap utf8Signatures; // Utf8Entry->SignatureEntry Map<Utf8Entry, SignatureEntry> utf8Signatures;
void readSignatureBands(Entry[] cpMap) throws IOException { void readSignatureBands(Entry[] cpMap) throws IOException {
// cp_Signature: // cp_Signature:
@ -663,7 +680,7 @@ class PackageReader extends BandStructure {
cp_Signature_classes.expectLength(getIntTotal(numSigClasses)); cp_Signature_classes.expectLength(getIntTotal(numSigClasses));
cp_Signature_classes.readFrom(in); cp_Signature_classes.readFrom(in);
cp_Signature_classes.setIndex(getCPIndex(CONSTANT_Class)); cp_Signature_classes.setIndex(getCPIndex(CONSTANT_Class));
utf8Signatures = new HashMap(); utf8Signatures = new HashMap<>();
for (int i = 0; i < cpMap.length; i++) { for (int i = 0; i < cpMap.length; i++) {
Utf8Entry formRef = (Utf8Entry) cp_Signature_form.getRef(); Utf8Entry formRef = (Utf8Entry) cp_Signature_form.getRef();
ClassEntry[] classRefs = new ClassEntry[numSigClasses[i]]; ClassEntry[] classRefs = new ClassEntry[numSigClasses[i]];
@ -863,7 +880,7 @@ class PackageReader extends BandStructure {
ic_name.expectLength(longICCount); ic_name.expectLength(longICCount);
ic_name.readFrom(in); ic_name.readFrom(in);
ic_flags.resetForSecondPass(); ic_flags.resetForSecondPass();
ArrayList icList = new ArrayList(numInnerClasses); List<InnerClass> icList = new ArrayList<>(numInnerClasses);
for (int i = 0; i < numInnerClasses; i++) { for (int i = 0; i < numInnerClasses; i++) {
int flags = ic_flags.getInt(); int flags = ic_flags.getInt();
boolean longForm = (flags & ACC_IC_LONG_FORM) != 0; boolean longForm = (flags & ACC_IC_LONG_FORM) != 0;
@ -876,7 +893,7 @@ class PackageReader extends BandStructure {
thisName = (Utf8Entry) ic_name.getRef(); thisName = (Utf8Entry) ic_name.getRef();
} else { } else {
String n = thisClass.stringValue(); String n = thisClass.stringValue();
String[] parse = pkg.parseInnerClassName(n); String[] parse = Package.parseInnerClassName(n);
assert(parse != null); assert(parse != null);
String pkgOuter = parse[0]; String pkgOuter = parse[0];
//String number = parse[1]; //String number = parse[1];
@ -905,7 +922,7 @@ class PackageReader extends BandStructure {
void readLocalInnerClasses(Class cls) throws IOException { void readLocalInnerClasses(Class cls) throws IOException {
int nc = class_InnerClasses_N.getInt(); int nc = class_InnerClasses_N.getInt();
ArrayList localICs = new ArrayList(nc); List<InnerClass> localICs = new ArrayList<>(nc);
for (int i = 0; i < nc; i++) { for (int i = 0; i < nc; i++) {
ClassEntry thisClass = (ClassEntry) class_InnerClasses_RC.getRef(); ClassEntry thisClass = (ClassEntry) class_InnerClasses_RC.getRef();
int flags = class_InnerClasses_F.getInt(); int flags = class_InnerClasses_F.getInt();
@ -994,10 +1011,8 @@ class PackageReader extends BandStructure {
return -1; return -1;
} }
Comparator entryOutputOrder = new Comparator() { Comparator<Entry> entryOutputOrder = new Comparator<>() {
public int compare(Object o0, Object o1) { public int compare(Entry e0, Entry e1) {
Entry e0 = (Entry) o0;
Entry e1 = (Entry) o1;
int k0 = getOutputIndex(e0); int k0 = getOutputIndex(e0);
int k1 = getOutputIndex(e1); int k1 = getOutputIndex(e1);
if (k0 >= 0 && k1 >= 0) if (k0 >= 0 && k1 >= 0)
@ -1034,9 +1049,8 @@ class PackageReader extends BandStructure {
} }
Entry[] reconstructLocalCPMap(Class cls) { Entry[] reconstructLocalCPMap(Class cls) {
HashSet ldcRefs = (HashSet) ldcRefMap.get(cls); Set<Entry> ldcRefs = ldcRefMap.get(cls);
HashSet cpRefs = new HashSet(); Set<Entry> cpRefs = new HashSet<>();
HashSet sigSet = new HashSet();
// look for constant pool entries: // look for constant pool entries:
cls.visitRefs(VRM_CLASSIC, cpRefs); cls.visitRefs(VRM_CLASSIC, cpRefs);
@ -1064,8 +1078,7 @@ class PackageReader extends BandStructure {
// construct a local constant pool // construct a local constant pool
int numDoubles = 0; int numDoubles = 0;
for (Iterator i = cpRefs.iterator(); i.hasNext(); ) { for (Entry e : cpRefs) {
Entry e = (Entry) i.next();
if (e.isDoubleWord()) numDoubles++; if (e.isDoubleWord()) numDoubles++;
assert(e.tag != CONSTANT_Signature) : (e); assert(e.tag != CONSTANT_Signature) : (e);
} }
@ -1075,8 +1088,7 @@ class PackageReader extends BandStructure {
// Add all ldc operands first. // Add all ldc operands first.
if (ldcRefs != null) { if (ldcRefs != null) {
assert(cpRefs.containsAll(ldcRefs)); assert(cpRefs.containsAll(ldcRefs));
for (Iterator i = ldcRefs.iterator(); i.hasNext(); ) { for (Entry e : ldcRefs) {
Entry e = (Entry) i.next();
cpMap[fillp++] = e; cpMap[fillp++] = e;
} }
assert(fillp == 1+ldcRefs.size()); assert(fillp == 1+ldcRefs.size());
@ -1085,11 +1097,10 @@ class PackageReader extends BandStructure {
} }
// Next add all the two-byte references. // Next add all the two-byte references.
HashSet wideRefs = cpRefs; Set<Entry> wideRefs = cpRefs;
cpRefs = null; // do not use! cpRefs = null; // do not use!
int narrowLimit = fillp; int narrowLimit = fillp;
for (Iterator i = wideRefs.iterator(); i.hasNext(); ) { for (Entry e : wideRefs) {
Entry e = (Entry) i.next();
cpMap[fillp++] = e; cpMap[fillp++] = e;
} }
assert(fillp == narrowLimit+wideRefs.size()); assert(fillp == narrowLimit+wideRefs.size());
@ -1144,7 +1155,7 @@ class PackageReader extends BandStructure {
method_descr.expectLength(totalNM); method_descr.expectLength(totalNM);
if (verbose > 1) Utils.log.fine("expecting #fields="+totalNF+" and #methods="+totalNM+" in #classes="+numClasses); if (verbose > 1) Utils.log.fine("expecting #fields="+totalNF+" and #methods="+totalNM+" in #classes="+numClasses);
ArrayList fields = new ArrayList(totalNF); List<Class.Field> fields = new ArrayList<>(totalNF);
field_descr.readFrom(in); field_descr.readFrom(in);
for (int i = 0; i < classes.length; i++) { for (int i = 0; i < classes.length; i++) {
Class c = classes[i]; Class c = classes[i];
@ -1160,7 +1171,7 @@ class PackageReader extends BandStructure {
countAndReadAttrs(ATTR_CONTEXT_FIELD, fields); countAndReadAttrs(ATTR_CONTEXT_FIELD, fields);
fields = null; // release to GC fields = null; // release to GC
ArrayList methods = new ArrayList(totalNM); List<Class.Method> methods = new ArrayList<>(totalNM);
method_descr.readFrom(in); method_descr.readFrom(in);
for (int i = 0; i < classes.length; i++) { for (int i = 0; i < classes.length; i++) {
Class c = classes[i]; Class c = classes[i];
@ -1182,13 +1193,12 @@ class PackageReader extends BandStructure {
} }
Code[] allCodes; Code[] allCodes;
List codesWithFlags; List<Code> codesWithFlags;
HashMap ldcRefMap = new HashMap(); // HashMap<Class, HashSet<Entry>> Map<Class, Set<Entry>> ldcRefMap = new HashMap<>();
Code[] buildCodeAttrs(List methods) { Code[] buildCodeAttrs(List<Class.Method> methods) {
ArrayList codes = new ArrayList(methods.size()); List<Code> codes = new ArrayList<>(methods.size());
for (Iterator i = methods.iterator(); i.hasNext(); ) { for (Class.Method m : methods) {
Class.Method m = (Class.Method) i.next();
if (m.getAttribute(attrCodeEmpty) != null) { if (m.getAttribute(attrCodeEmpty) != null) {
m.code = new Code(m); m.code = new Code(m);
codes.add(m.code); codes.add(m.code);
@ -1211,7 +1221,7 @@ class PackageReader extends BandStructure {
boolean attrsOK = testBit(archiveOptions, AO_HAVE_ALL_CODE_FLAGS); boolean attrsOK = testBit(archiveOptions, AO_HAVE_ALL_CODE_FLAGS);
code_headers.expectLength(allCodes.length); code_headers.expectLength(allCodes.length);
code_headers.readFrom(in); code_headers.readFrom(in);
ArrayList longCodes = new ArrayList(allCodes.length / 10); List<Code> longCodes = new ArrayList<>(allCodes.length / 10);
for (int i = 0; i < allCodes.length; i++) { for (int i = 0; i < allCodes.length; i++) {
Code c = allCodes[i]; Code c = allCodes[i];
int sc = code_headers.getByte(); int sc = code_headers.getByte();
@ -1238,8 +1248,7 @@ class PackageReader extends BandStructure {
code_max_stack.readFrom(in); code_max_stack.readFrom(in);
code_max_na_locals.readFrom(in); code_max_na_locals.readFrom(in);
code_handler_count.readFrom(in); code_handler_count.readFrom(in);
for (Iterator i = longCodes.iterator(); i.hasNext(); ) { for (Code c : longCodes) {
Code c = (Code) i.next();
c.setMaxStack( code_max_stack.getInt() ); c.setMaxStack( code_max_stack.getInt() );
c.setMaxNALocals( code_max_na_locals.getInt() ); c.setMaxNALocals( code_max_na_locals.getInt() );
c.setHandlerCount( code_handler_count.getInt() ); c.setHandlerCount( code_handler_count.getInt() );
@ -1386,8 +1395,9 @@ class PackageReader extends BandStructure {
// Fetch the attribute layout definitions which govern the bands // Fetch the attribute layout definitions which govern the bands
// we are about to read. // we are about to read.
Attribute.Layout[] defs = new Attribute.Layout[attrDefs[ctype].size()]; List<Attribute.Layout> defList = attrDefs.get(ctype);
attrDefs[ctype].toArray(defs); Attribute.Layout[] defs = new Attribute.Layout[defList.size()];
defList.toArray(defs);
IntBand xxx_flags_hi = getAttrBand(xxx_attr_bands, AB_FLAGS_HI); IntBand xxx_flags_hi = getAttrBand(xxx_attr_bands, AB_FLAGS_HI);
IntBand xxx_flags_lo = getAttrBand(xxx_attr_bands, AB_FLAGS_LO); IntBand xxx_flags_lo = getAttrBand(xxx_attr_bands, AB_FLAGS_LO);
IntBand xxx_attr_count = getAttrBand(xxx_attr_bands, AB_ATTR_COUNT); IntBand xxx_attr_count = getAttrBand(xxx_attr_bands, AB_ATTR_COUNT);
@ -1450,7 +1460,7 @@ class PackageReader extends BandStructure {
bits -= (1L<<ai); bits -= (1L<<ai);
nfa += 1; nfa += 1;
} }
ArrayList ha = new ArrayList(nfa + noa); List<Attribute> ha = new ArrayList<>(nfa + noa);
h.attributes = ha; h.attributes = ha;
bits = attrBits; // iterate again bits = attrBits; // iterate again
for (int ai = 0; bits != 0; ai++) { for (int ai = 0; bits != 0; ai++) {
@ -1516,7 +1526,7 @@ class PackageReader extends BandStructure {
if (predef != isPredefinedAttr(ctype, ai)) if (predef != isPredefinedAttr(ctype, ai))
continue; // wrong pass continue; // wrong pass
int totalCount = totalCounts[ai]; int totalCount = totalCounts[ai];
Band[] ab = (Band[]) attrBandTable.get(def); Band[] ab = attrBandTable.get(def);
if (def == attrInnerClassesEmpty) { if (def == attrInnerClassesEmpty) {
// Special case. // Special case.
// Size the bands as if using the following layout: // Size the bands as if using the following layout:
@ -1571,15 +1581,16 @@ class PackageReader extends BandStructure {
ATTR_CONTEXT_NAME[ctype]+" attribute"); ATTR_CONTEXT_NAME[ctype]+" attribute");
} }
@SuppressWarnings("unchecked")
void readAttrs(int ctype, Collection holders) throws IOException { void readAttrs(int ctype, Collection holders) throws IOException {
// Decode band values into attributes. // Decode band values into attributes.
HashSet sawDefs = new HashSet(); Set<Attribute.Layout> sawDefs = new HashSet<>();
ByteArrayOutputStream buf = new ByteArrayOutputStream(); ByteArrayOutputStream buf = new ByteArrayOutputStream();
for (Iterator i = holders.iterator(); i.hasNext(); ) { for (Iterator i = holders.iterator(); i.hasNext(); ) {
final Attribute.Holder h = (Attribute.Holder) i.next(); final Attribute.Holder h = (Attribute.Holder) i.next();
if (h.attributes == null) continue; if (h.attributes == null) continue;
for (ListIterator j = h.attributes.listIterator(); j.hasNext(); ) { for (ListIterator<Attribute> j = h.attributes.listIterator(); j.hasNext(); ) {
Attribute a = (Attribute) j.next(); Attribute a = j.next();
Attribute.Layout def = a.layout(); Attribute.Layout def = a.layout();
if (def.bandCount == 0) { if (def.bandCount == 0) {
if (def == attrInnerClassesEmpty) { if (def == attrInnerClassesEmpty) {
@ -1595,7 +1606,7 @@ class PackageReader extends BandStructure {
if (isCV) setConstantValueIndex((Class.Field)h); if (isCV) setConstantValueIndex((Class.Field)h);
if (verbose > 2) if (verbose > 2)
Utils.log.fine("read "+a+" in "+h); Utils.log.fine("read "+a+" in "+h);
final Band[] ab = (Band[]) attrBandTable.get(def); final Band[] ab = attrBandTable.get(def);
// Read one attribute of type def from ab into a byte array. // Read one attribute of type def from ab into a byte array.
buf.reset(); buf.reset();
Object fixups = a.unparse(new Attribute.ValueStream() { Object fixups = a.unparse(new Attribute.ValueStream() {
@ -1617,10 +1628,9 @@ class PackageReader extends BandStructure {
} }
// Mark the bands we just used as done disbursing. // Mark the bands we just used as done disbursing.
for (Iterator i = sawDefs.iterator(); i.hasNext(); ) { for (Attribute.Layout def : sawDefs) {
Attribute.Layout def = (Attribute.Layout) i.next();
if (def == null) continue; // unused index if (def == null) continue; // unused index
Band[] ab = (Band[]) attrBandTable.get(def); Band[] ab = attrBandTable.get(def);
for (int j = 0; j < ab.length; j++) { for (int j = 0; j < ab.length; j++) {
ab[j].doneDisbursing(); ab[j].doneDisbursing();
} }
@ -1778,7 +1788,7 @@ class PackageReader extends BandStructure {
// scratch buffer for collecting code:: // scratch buffer for collecting code::
byte[] buf = new byte[1<<12]; byte[] buf = new byte[1<<12];
// record of all switch opcodes (these are variable-length) // record of all switch opcodes (these are variable-length)
ArrayList allSwitchOps = new ArrayList(); List<Integer> allSwitchOps = new ArrayList<>();
for (int k = 0; k < allCodes.length; k++) { for (int k = 0; k < allCodes.length; k++) {
Code c = allCodes[k]; Code c = allCodes[k];
scanOneMethod: scanOneMethod:
@ -1798,7 +1808,7 @@ class PackageReader extends BandStructure {
case _tableswitch: case _tableswitch:
case _lookupswitch: case _lookupswitch:
bc_case_count.expectMoreLength(1); bc_case_count.expectMoreLength(1);
allSwitchOps.add(new Integer(bc)); allSwitchOps.add(bc);
break; break;
case _iinc: case _iinc:
bc_local.expectMoreLength(1); bc_local.expectMoreLength(1);
@ -1866,8 +1876,8 @@ class PackageReader extends BandStructure {
// To size instruction bands correctly, we need info on switches: // To size instruction bands correctly, we need info on switches:
bc_case_count.readFrom(in); bc_case_count.readFrom(in);
for (Iterator i = allSwitchOps.iterator(); i.hasNext(); ) { for (Integer i : allSwitchOps) {
int bc = ((Integer)i.next()).intValue(); int bc = i.intValue();
int caseCount = bc_case_count.getInt(); int caseCount = bc_case_count.getInt();
bc_label.expectMoreLength(1+caseCount); // default label + cases bc_label.expectMoreLength(1+caseCount); // default label + cases
bc_case_value.expectMoreLength(bc == _tableswitch ? 1 : caseCount); bc_case_value.expectMoreLength(bc == _tableswitch ? 1 : caseCount);
@ -1892,9 +1902,9 @@ class PackageReader extends BandStructure {
Class curClass = code.thisClass(); Class curClass = code.thisClass();
HashSet ldcRefSet = (HashSet) ldcRefMap.get(curClass); Set<Entry> ldcRefSet = ldcRefMap.get(curClass);
if (ldcRefSet == null) if (ldcRefSet == null)
ldcRefMap.put(curClass, ldcRefSet = new HashSet()); ldcRefMap.put(curClass, ldcRefSet = new HashSet<>());
ClassEntry thisClass = curClass.thisClass; ClassEntry thisClass = curClass.thisClass;
ClassEntry superClass = curClass.superClass; ClassEntry superClass = curClass.superClass;

View File

@ -45,10 +45,10 @@ import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.ListIterator;
import java.util.Map; import java.util.Map;
import java.util.Set;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Writer for a package file. * Writer for a package file.
@ -111,12 +111,12 @@ class PackageWriter extends BandStructure {
} }
} }
HashSet requiredEntries; // for the CP Set<Entry> requiredEntries; // for the CP
HashMap backCountTable; // for layout callables Map<Attribute.Layout, int[]> backCountTable; // for layout callables
int[][] attrCounts; // count attr. occurences int[][] attrCounts; // count attr. occurences
void setup() { void setup() {
requiredEntries = new HashSet(); requiredEntries = new HashSet<>();
setArchiveOptions(); setArchiveOptions();
trimClassAttributes(); trimClassAttributes();
collectAttributeLayouts(); collectAttributeLayouts();
@ -139,9 +139,7 @@ class PackageWriter extends BandStructure {
// Import defaults from package (deflate hint, etc.). // Import defaults from package (deflate hint, etc.).
archiveOptions |= pkg.default_options; archiveOptions |= pkg.default_options;
for (Iterator i = pkg.files.iterator(); i.hasNext(); ) { for (File file : pkg.files) {
File file = (File) i.next();
int modtime = file.modtime; int modtime = file.modtime;
int options = file.options; int options = file.options;
@ -178,16 +176,15 @@ class PackageWriter extends BandStructure {
} }
} }
// Decide on default version number (majority rule). // Decide on default version number (majority rule).
HashMap verCounts = new HashMap(); Map<Integer, int[]> verCounts = new HashMap<>();
int bestCount = 0; int bestCount = 0;
int bestVersion = -1; int bestVersion = -1;
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { for (Class cls : pkg.classes) {
Class cls = (Class) i.next();
int version = cls.getVersion(); int version = cls.getVersion();
int[] var = (int[]) verCounts.get(new Integer(version)); int[] var = verCounts.get(version);
if (var == null) { if (var == null) {
var = new int[1]; var = new int[1];
verCounts.put(new Integer(version), var); verCounts.put(version, var);
} }
int count = (var[0] += 1); int count = (var[0] += 1);
//System.out.println("version="+version+" count="+count); //System.out.println("version="+version+" count="+count);
@ -210,9 +207,7 @@ class PackageWriter extends BandStructure {
Package.versionStringOf(pkg.getHighestClassVersion())); Package.versionStringOf(pkg.getHighestClassVersion()));
// Now add explicit pseudo-attrs. to classes with odd versions. // Now add explicit pseudo-attrs. to classes with odd versions.
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { for (Class cls : pkg.classes) {
Class cls = (Class) i.next();
if (cls.getVersion() != bestVersion) { if (cls.getVersion() != bestVersion) {
Attribute a = makeClassFileVersionAttr(cls.minver, cls.majver); Attribute a = makeClassFileVersionAttr(cls.minver, cls.majver);
if (verbose > 1) { if (verbose > 1) {
@ -228,8 +223,7 @@ class PackageWriter extends BandStructure {
} }
// Decide if we are transmitting a huge resource file: // Decide if we are transmitting a huge resource file:
for (Iterator i = pkg.files.iterator(); i.hasNext(); ) { for (File file : pkg.files) {
File file = (File) i.next();
long len = file.getFileLength(); long len = file.getFileLength();
if (len != (int)len) { if (len != (int)len) {
archiveOptions |= AO_HAVE_FILE_SIZE_HI; archiveOptions |= AO_HAVE_FILE_SIZE_HI;
@ -244,10 +238,8 @@ class PackageWriter extends BandStructure {
// we must declare unconditional presence of code flags. // we must declare unconditional presence of code flags.
int cost0 = 0; int cost0 = 0;
int cost1 = 0; int cost1 = 0;
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { for (Class cls : pkg.classes) {
Class cls = (Class) i.next(); for (Class.Method m : cls.getMethods()) {
for (Iterator j = cls.getMethods().iterator(); j.hasNext(); ) {
Class.Method m = (Class.Method) j.next();
if (m.code != null) { if (m.code != null) {
if (m.code.attributeSize() == 0) { if (m.code.attributeSize() == 0) {
// cost of a useless unconditional flags byte // cost of a useless unconditional flags byte
@ -352,7 +344,7 @@ class PackageWriter extends BandStructure {
archive_header_1.putInt(pkg.default_modtime); archive_header_1.putInt(pkg.default_modtime);
archive_header_1.putInt(pkg.files.size()); archive_header_1.putInt(pkg.files.size());
} else { } else {
assert(pkg.files.size() == 0); assert(pkg.files.isEmpty());
} }
if (haveSpecial) { if (haveSpecial) {
@ -697,8 +689,7 @@ class PackageWriter extends BandStructure {
boolean haveModtime = testBit(options, AO_HAVE_FILE_MODTIME); boolean haveModtime = testBit(options, AO_HAVE_FILE_MODTIME);
boolean haveOptions = testBit(options, AO_HAVE_FILE_OPTIONS); boolean haveOptions = testBit(options, AO_HAVE_FILE_OPTIONS);
if (!haveOptions) { if (!haveOptions) {
for (Iterator i = pkg.files.iterator(); i.hasNext(); ) { for (File file : pkg.files) {
File file = (File) i.next();
if (file.isClassStub()) { if (file.isClassStub()) {
haveOptions = true; haveOptions = true;
options |= AO_HAVE_FILE_OPTIONS; options |= AO_HAVE_FILE_OPTIONS;
@ -711,9 +702,7 @@ class PackageWriter extends BandStructure {
options |= AO_HAVE_FILE_HEADERS; options |= AO_HAVE_FILE_HEADERS;
archiveOptions = options; archiveOptions = options;
} }
for (File file : pkg.files) {
for (Iterator i = pkg.files.iterator(); i.hasNext(); ) {
File file = (File) i.next();
file_name.putRef(file.name); file_name.putRef(file.name);
long len = file.getFileLength(); long len = file.getFileLength();
file_size_lo.putInt((int)len); file_size_lo.putInt((int)len);
@ -731,22 +720,20 @@ class PackageWriter extends BandStructure {
Utils.log.info("Wrote "+numFiles+" resource files"); Utils.log.info("Wrote "+numFiles+" resource files");
} }
@SuppressWarnings("unchecked")
void collectAttributeLayouts() { void collectAttributeLayouts() {
maxFlags = new int[ATTR_CONTEXT_LIMIT]; maxFlags = new int[ATTR_CONTEXT_LIMIT];
allLayouts = new HashMap[ATTR_CONTEXT_LIMIT]; allLayouts = new FixedList<>(ATTR_CONTEXT_LIMIT);
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
allLayouts[i] = new HashMap(); allLayouts.set(i, new HashMap<Attribute.Layout, int[]>());
} }
// Collect maxFlags and allLayouts. // Collect maxFlags and allLayouts.
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { for (Class cls : pkg.classes) {
Class cls = (Class) i.next();
visitAttributeLayoutsIn(ATTR_CONTEXT_CLASS, cls); visitAttributeLayoutsIn(ATTR_CONTEXT_CLASS, cls);
for (Iterator j = cls.getFields().iterator(); j.hasNext(); ) { for (Class.Field f : cls.getFields()) {
Class.Field f = (Class.Field) j.next();
visitAttributeLayoutsIn(ATTR_CONTEXT_FIELD, f); visitAttributeLayoutsIn(ATTR_CONTEXT_FIELD, f);
} }
for (Iterator j = cls.getMethods().iterator(); j.hasNext(); ) { for (Class.Method m : cls.getMethods()) {
Class.Method m = (Class.Method) j.next();
visitAttributeLayoutsIn(ATTR_CONTEXT_METHOD, m); visitAttributeLayoutsIn(ATTR_CONTEXT_METHOD, m);
if (m.code != null) { if (m.code != null) {
visitAttributeLayoutsIn(ATTR_CONTEXT_CODE, m.code); visitAttributeLayoutsIn(ATTR_CONTEXT_CODE, m.code);
@ -755,7 +742,7 @@ class PackageWriter extends BandStructure {
} }
// If there are many species of attributes, use 63-bit flags. // If there are many species of attributes, use 63-bit flags.
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
int nl = allLayouts[i].size(); int nl = allLayouts.get(i).size();
boolean haveLongFlags = haveFlagsHi(i); boolean haveLongFlags = haveFlagsHi(i);
final int TOO_MANY_ATTRS = 32 /*int flag size*/ final int TOO_MANY_ATTRS = 32 /*int flag size*/
- 12 /*typical flag bits in use*/ - 12 /*typical flag bits in use*/
@ -781,7 +768,7 @@ class PackageWriter extends BandStructure {
} }
// Collect counts for both predefs. and custom defs. // Collect counts for both predefs. and custom defs.
// Decide on custom, local attribute definitions. // Decide on custom, local attribute definitions.
backCountTable = new HashMap(); backCountTable = new HashMap<>();
attrCounts = new int[ATTR_CONTEXT_LIMIT][]; attrCounts = new int[ATTR_CONTEXT_LIMIT][];
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
// Now the remaining defs in allLayouts[i] need attr. indexes. // Now the remaining defs in allLayouts[i] need attr. indexes.
@ -793,11 +780,12 @@ class PackageWriter extends BandStructure {
assert(attrIndexLimit[i] < 64); // all bits fit into a Java long assert(attrIndexLimit[i] < 64); // all bits fit into a Java long
avHiBits &= (1L<<attrIndexLimit[i])-1; avHiBits &= (1L<<attrIndexLimit[i])-1;
int nextLoBit = 0; int nextLoBit = 0;
Map.Entry[] layoutsAndCounts = new Map.Entry[allLayouts[i].size()]; Map<Attribute.Layout, int[]> defMap = allLayouts.get(i);
allLayouts[i].entrySet().toArray(layoutsAndCounts); Map.Entry[] layoutsAndCounts = new Map.Entry[defMap.size()];
defMap.entrySet().toArray(layoutsAndCounts);
// Sort by count, most frequent first. // Sort by count, most frequent first.
// Predefs. participate in this sort, though it does not matter. // Predefs. participate in this sort, though it does not matter.
Arrays.sort(layoutsAndCounts, new Comparator() { Arrays.sort(layoutsAndCounts, new Comparator<>() {
public int compare(Object o0, Object o1) { public int compare(Object o0, Object o1) {
Map.Entry e0 = (Map.Entry) o0; Map.Entry e0 = (Map.Entry) o0;
Map.Entry e1 = (Map.Entry) o1; Map.Entry e1 = (Map.Entry) o1;
@ -814,7 +802,7 @@ class PackageWriter extends BandStructure {
Attribute.Layout def = (Attribute.Layout) e.getKey(); Attribute.Layout def = (Attribute.Layout) e.getKey();
int count = ((int[])e.getValue())[0]; int count = ((int[])e.getValue())[0];
int index; int index;
Integer predefIndex = (Integer) attrIndexTable.get(def); Integer predefIndex = attrIndexTable.get(def);
if (predefIndex != null) { if (predefIndex != null) {
// The index is already set. // The index is already set.
index = predefIndex.intValue(); index = predefIndex.intValue();
@ -872,29 +860,32 @@ class PackageWriter extends BandStructure {
// Scratch variables for processing attributes and flags. // Scratch variables for processing attributes and flags.
int[] maxFlags; int[] maxFlags;
HashMap[] allLayouts; List<Map<Attribute.Layout, int[]>> allLayouts;
void visitAttributeLayoutsIn(int ctype, Attribute.Holder h) { void visitAttributeLayoutsIn(int ctype, Attribute.Holder h) {
// Make note of which flags appear in the class file. // Make note of which flags appear in the class file.
// Set them in maxFlags. // Set them in maxFlags.
maxFlags[ctype] |= h.flags; maxFlags[ctype] |= h.flags;
for (Iterator i = h.getAttributes().iterator(); i.hasNext(); ) { for (Attribute a : h.getAttributes()) {
Attribute a = (Attribute) i.next();
Attribute.Layout def = a.layout(); Attribute.Layout def = a.layout();
int[] count = (int[]) allLayouts[ctype].get(def); Map<Attribute.Layout, int[]> defMap = allLayouts.get(ctype);
if (count == null) int[] count = defMap.get(def);
allLayouts[ctype].put(def, count = new int[1]); if (count == null) {
if (count[0] < Integer.MAX_VALUE) defMap.put(def, count = new int[1]);
}
if (count[0] < Integer.MAX_VALUE) {
count[0] += 1; count[0] += 1;
}
} }
} }
Attribute.Layout[] attrDefsWritten; Attribute.Layout[] attrDefsWritten;
@SuppressWarnings("unchecked")
void writeAttrDefs() throws IOException { void writeAttrDefs() throws IOException {
ArrayList defList = new ArrayList(); List<Object[]> defList = new ArrayList<>();
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) { for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
int limit = attrDefs[i].size(); int limit = attrDefs.get(i).size();
for (int j = 0; j < limit; j++) { for (int j = 0; j < limit; j++) {
int header = i; // ctype int header = i; // ctype
if (j < attrIndexLimit[i]) { if (j < attrIndexLimit[i]) {
@ -906,9 +897,9 @@ class PackageWriter extends BandStructure {
continue; continue;
} }
} }
Attribute.Layout def = (Attribute.Layout) attrDefs[i].get(j); Attribute.Layout def = attrDefs.get(i).get(j);
defList.add(new Object[]{ new Integer(header), def }); defList.add(new Object[]{ Integer.valueOf(header), def });
assert(new Integer(j).equals(attrIndexTable.get(def))); assert(Integer.valueOf(j).equals(attrIndexTable.get(def)));
} }
} }
// Sort the new attr defs into some "natural" order. // Sort the new attr defs into some "natural" order.
@ -934,10 +925,7 @@ class PackageWriter extends BandStructure {
attrDefsWritten = new Attribute.Layout[numAttrDefs]; attrDefsWritten = new Attribute.Layout[numAttrDefs];
PrintStream dump = !optDumpBands ? null PrintStream dump = !optDumpBands ? null
: new PrintStream(getDumpStream(attr_definition_headers, ".def")); : new PrintStream(getDumpStream(attr_definition_headers, ".def"));
int[] indexForDebug = new int[ATTR_CONTEXT_LIMIT]; int[] indexForDebug = Arrays.copyOf(attrIndexLimit, ATTR_CONTEXT_LIMIT);
for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
indexForDebug[i] = attrIndexLimit[i];
}
for (int i = 0; i < defs.length; i++) { for (int i = 0; i < defs.length; i++) {
int header = ((Integer)defs[i][0]).intValue(); int header = ((Integer)defs[i][0]).intValue();
Attribute.Layout def = (Attribute.Layout) defs[i][1]; Attribute.Layout def = (Attribute.Layout) defs[i][1];
@ -953,7 +941,7 @@ class PackageWriter extends BandStructure {
if (debug) { if (debug) {
int hdrIndex = (header >> ADH_BIT_SHIFT) - ADH_BIT_IS_LSB; int hdrIndex = (header >> ADH_BIT_SHIFT) - ADH_BIT_IS_LSB;
if (hdrIndex < 0) hdrIndex = indexForDebug[def.ctype()]++; if (hdrIndex < 0) hdrIndex = indexForDebug[def.ctype()]++;
int realIndex = ((Integer) attrIndexTable.get(def)).intValue(); int realIndex = (attrIndexTable.get(def)).intValue();
assert(hdrIndex == realIndex); assert(hdrIndex == realIndex);
} }
if (dump != null) { if (dump != null) {
@ -969,8 +957,8 @@ class PackageWriter extends BandStructure {
for (int ctype = 0; ctype < ATTR_CONTEXT_LIMIT; ctype++) { for (int ctype = 0; ctype < ATTR_CONTEXT_LIMIT; ctype++) {
MultiBand xxx_attr_bands = attrBands[ctype]; MultiBand xxx_attr_bands = attrBands[ctype];
IntBand xxx_attr_calls = getAttrBand(xxx_attr_bands, AB_ATTR_CALLS); IntBand xxx_attr_calls = getAttrBand(xxx_attr_bands, AB_ATTR_CALLS);
Attribute.Layout[] defs = new Attribute.Layout[attrDefs[ctype].size()]; Attribute.Layout[] defs = new Attribute.Layout[attrDefs.get(ctype).size()];
attrDefs[ctype].toArray(defs); attrDefs.get(ctype).toArray(defs);
for (boolean predef = true; ; predef = false) { for (boolean predef = true; ; predef = false) {
for (int ai = 0; ai < defs.length; ai++) { for (int ai = 0; ai < defs.length; ai++) {
Attribute.Layout def = defs[ai]; Attribute.Layout def = defs[ai];
@ -980,7 +968,7 @@ class PackageWriter extends BandStructure {
int totalCount = attrCounts[ctype][ai]; int totalCount = attrCounts[ctype][ai];
if (totalCount == 0) if (totalCount == 0)
continue; // irrelevant continue; // irrelevant
int[] bc = (int[]) backCountTable.get(def); int[] bc = backCountTable.get(def);
for (int j = 0; j < bc.length; j++) { for (int j = 0; j < bc.length; j++) {
if (bc[j] >= 0) { if (bc[j] >= 0) {
int backCount = bc[j]; int backCount = bc[j];
@ -998,8 +986,7 @@ class PackageWriter extends BandStructure {
} }
void trimClassAttributes() { void trimClassAttributes() {
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { for (Class cls : pkg.classes) {
Class cls = (Class) i.next();
// Replace "obvious" SourceFile attrs by null. // Replace "obvious" SourceFile attrs by null.
cls.minimizeSourceFile(); cls.minimizeSourceFile();
} }
@ -1008,14 +995,12 @@ class PackageWriter extends BandStructure {
void collectInnerClasses() { void collectInnerClasses() {
// Capture inner classes, removing them from individual classes. // Capture inner classes, removing them from individual classes.
// Irregular inner classes must stay local, though. // Irregular inner classes must stay local, though.
HashMap allICMap = new HashMap(); Map<ClassEntry, InnerClass> allICMap = new HashMap<>();
// First, collect a consistent global set. // First, collect a consistent global set.
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { for (Class cls : pkg.classes) {
Class cls = (Class) i.next();
if (!cls.hasInnerClasses()) continue; if (!cls.hasInnerClasses()) continue;
for (Iterator j = cls.getInnerClasses().iterator(); j.hasNext(); ) { for (InnerClass ic : cls.getInnerClasses()) {
InnerClass ic = (InnerClass) j.next(); InnerClass pic = allICMap.put(ic.thisClass, ic);
InnerClass pic = (InnerClass) allICMap.put(ic.thisClass, ic);
if (pic != null && !pic.equals(ic) && pic.predictable) { if (pic != null && !pic.equals(ic) && pic.predictable) {
// Different ICs. Choose the better to make global. // Different ICs. Choose the better to make global.
allICMap.put(pic.thisClass, pic); allICMap.put(pic.thisClass, pic);
@ -1036,15 +1021,13 @@ class PackageWriter extends BandStructure {
// Next, empty out of every local set the consistent entries. // Next, empty out of every local set the consistent entries.
// Calculate whether there is any remaining need to have a local // Calculate whether there is any remaining need to have a local
// set, and whether it needs to be locked. // set, and whether it needs to be locked.
for (Iterator i = pkg.classes.iterator(); i.hasNext(); ) { for (Class cls : pkg.classes) {
Class cls = (Class) i.next();
cls.minimizeLocalICs(); cls.minimizeLocalICs();
} }
} }
void writeInnerClasses() throws IOException { void writeInnerClasses() throws IOException {
for (Iterator i = pkg.getAllInnerClasses().iterator(); i.hasNext(); ) { for (InnerClass ic : pkg.getAllInnerClasses()) {
InnerClass ic = (InnerClass) i.next();
int flags = ic.flags; int flags = ic.flags;
assert((flags & ACC_IC_LONG_FORM) == 0); assert((flags & ACC_IC_LONG_FORM) == 0);
if (!ic.predictable) { if (!ic.predictable) {
@ -1064,10 +1047,9 @@ class PackageWriter extends BandStructure {
* local attribute. This is expected to be rare. * local attribute. This is expected to be rare.
*/ */
void writeLocalInnerClasses(Class cls) throws IOException { void writeLocalInnerClasses(Class cls) throws IOException {
List localICs = cls.getInnerClasses(); List<InnerClass> localICs = cls.getInnerClasses();
class_InnerClasses_N.putInt(localICs.size()); class_InnerClasses_N.putInt(localICs.size());
for (Iterator i = localICs.iterator(); i.hasNext(); ) { for(InnerClass ic : localICs) {
InnerClass ic = (InnerClass) i.next();
class_InnerClasses_RC.putRef(ic.thisClass); class_InnerClasses_RC.putRef(ic.thisClass);
// Is it redundant with the global version? // Is it redundant with the global version?
if (ic.equals(pkg.getGlobalInnerClass(ic.thisClass))) { if (ic.equals(pkg.getGlobalInnerClass(ic.thisClass))) {
@ -1121,18 +1103,16 @@ class PackageWriter extends BandStructure {
} }
void writeMembers(Class cls) throws IOException { void writeMembers(Class cls) throws IOException {
List fields = cls.getFields(); List<Class.Field> fields = cls.getFields();
class_field_count.putInt(fields.size()); class_field_count.putInt(fields.size());
for (Iterator i = fields.iterator(); i.hasNext(); ) { for (Class.Field f : fields) {
Class.Field f = (Class.Field) i.next();
field_descr.putRef(f.getDescriptor()); field_descr.putRef(f.getDescriptor());
writeAttrs(ATTR_CONTEXT_FIELD, f, cls); writeAttrs(ATTR_CONTEXT_FIELD, f, cls);
} }
List methods = cls.getMethods(); List<Class.Method> methods = cls.getMethods();
class_method_count.putInt(methods.size()); class_method_count.putInt(methods.size());
for (Iterator i = methods.iterator(); i.hasNext(); ) { for (Class.Method m : methods) {
Class.Method m = (Class.Method) i.next();
method_descr.putRef(m.getDescriptor()); method_descr.putRef(m.getDescriptor());
writeAttrs(ATTR_CONTEXT_METHOD, m, cls); writeAttrs(ATTR_CONTEXT_METHOD, m, cls);
assert((m.code != null) == (m.getAttribute(attrCodeEmpty) != null)); assert((m.code != null) == (m.getAttribute(attrCodeEmpty) != null));
@ -1206,11 +1186,10 @@ class PackageWriter extends BandStructure {
long flagMask = attrFlagMask[ctype]; // which flags are attr bits? long flagMask = attrFlagMask[ctype]; // which flags are attr bits?
long flagsToAdd = 0; long flagsToAdd = 0;
int overflowCount = 0; int overflowCount = 0;
for (ListIterator j = h.attributes.listIterator(); j.hasNext(); ) { for (Attribute a : h.attributes) {
Attribute a = (Attribute) j.next();
Attribute.Layout def = a.layout(); Attribute.Layout def = a.layout();
int index = ((Integer)attrIndexTable.get(def)).intValue(); int index = (attrIndexTable.get(def)).intValue();
assert(attrDefs[ctype].get(index) == def); assert(attrDefs.get(ctype).get(index) == def);
if (verbose > 3) if (verbose > 3)
Utils.log.fine("add attr @"+index+" "+a+" in "+h); Utils.log.fine("add attr @"+index+" "+a+" in "+h);
if (index < attrIndexLimit[ctype] && testBit(flagMask, 1L<<index)) { if (index < attrIndexLimit[ctype] && testBit(flagMask, 1L<<index)) {
@ -1239,10 +1218,10 @@ class PackageWriter extends BandStructure {
continue; continue;
} }
assert(a.fixups == null); assert(a.fixups == null);
final Band[] ab = (Band[]) attrBandTable.get(def); final Band[] ab = attrBandTable.get(def);
assert(ab != null); assert(ab != null);
assert(ab.length == def.bandCount); assert(ab.length == def.bandCount);
final int[] bc = (int[]) backCountTable.get(def); final int[] bc = backCountTable.get(def);
assert(bc != null); assert(bc != null);
assert(bc.length == def.getCallables().length); assert(bc.length == def.getCallables().length);
// Write one attribute of type def into ab. // Write one attribute of type def into ab.
@ -1306,7 +1285,7 @@ class PackageWriter extends BandStructure {
private int initOpVariant(Instruction i, Entry newClass) { private int initOpVariant(Instruction i, Entry newClass) {
if (i.getBC() != _invokespecial) return -1; if (i.getBC() != _invokespecial) return -1;
MemberEntry ref = (MemberEntry) i.getCPRef(curCPMap); MemberEntry ref = (MemberEntry) i.getCPRef(curCPMap);
if (ref.descRef.nameRef.stringValue() != "<init>") if ("<init>".equals(ref.descRef.nameRef.stringValue()) == false)
return -1; return -1;
ClassEntry refClass = ref.classRef; ClassEntry refClass = ref.classRef;
if (refClass == curClass.thisClass) if (refClass == curClass.thisClass)
@ -1618,14 +1597,16 @@ class PackageWriter extends BandStructure {
String count = "" + codeHist[bc]; String count = "" + codeHist[bc];
count = " ".substring(count.length()) + count; count = " ".substring(count.length()) + count;
String pct = "" + (codeHist[bc] * 10000 / totalBytes); String pct = "" + (codeHist[bc] * 10000 / totalBytes);
while (pct.length() < 4) pct = "0" + pct; while (pct.length() < 4) {
pct = "0" + pct;
}
pct = pct.substring(0, pct.length()-2) + "." + pct.substring(pct.length()-2); pct = pct.substring(0, pct.length()-2) + "." + pct.substring(pct.length()-2);
hist[bc] = count + " " + pct + "% " + iname; hist[bc] = count + " " + pct + "% " + iname;
} }
Arrays.sort(hist); Arrays.sort(hist);
System.out.println("Bytecode histogram ["+totalBytes+"]"); System.out.println("Bytecode histogram ["+totalBytes+"]");
for (int i = hist.length; --i >= 0; ) { for (int i = hist.length; --i >= 0; ) {
if (hist[i] == "") continue; if ("".equals(hist[i])) continue;
System.out.println(hist[i]); System.out.println(hist[i]);
} }
for (int tag = 0; tag < ldcHist.length; tag++) { for (int tag = 0; tag < ldcHist.length; tag++) {

View File

@ -69,7 +69,8 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer {
* Get the set of options for the pack and unpack engines. * Get the set of options for the pack and unpack engines.
* @return A sorted association of option key strings to option values. * @return A sorted association of option key strings to option values.
*/ */
public SortedMap<String, String> properties() { @SuppressWarnings("unchecked")
public SortedMap properties() {
return props; return props;
} }
@ -155,8 +156,8 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer {
// All the worker bees..... // All the worker bees.....
// The packer worker. // The packer worker.
@SuppressWarnings("unchecked")
private class DoPack { private class DoPack {
final int verbose = props.getInteger(Utils.DEBUG_VERBOSE); final int verbose = props.getInteger(Utils.DEBUG_VERBOSE);
@ -179,11 +180,11 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer {
unknownAttrCommand = uaMode.intern(); unknownAttrCommand = uaMode.intern();
} }
final HashMap attrDefs; final Map<Attribute.Layout, Attribute> attrDefs;
final HashMap attrCommands; final Map<Attribute.Layout, String> attrCommands;
{ {
HashMap attrDefs = new HashMap(); Map<Attribute.Layout, Attribute> lattrDefs = new HashMap<>();
HashMap attrCommands = new HashMap(); Map<Attribute.Layout, String> lattrCommands = new HashMap<>();
String[] keys = { String[] keys = {
Pack200.Packer.CLASS_ATTRIBUTE_PFX, Pack200.Packer.CLASS_ATTRIBUTE_PFX,
Pack200.Packer.FIELD_ATTRIBUTE_PFX, Pack200.Packer.FIELD_ATTRIBUTE_PFX,
@ -198,8 +199,9 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer {
}; };
for (int i = 0; i < ctypes.length; i++) { for (int i = 0; i < ctypes.length; i++) {
String pfx = keys[i]; String pfx = keys[i];
Map<String, String> map = props.prefixMap(pfx); Map<Object, Object> map = props.prefixMap(pfx);
for (String key : map.keySet()) { for (Object k : map.keySet()) {
String key = (String)k;
assert(key.startsWith(pfx)); assert(key.startsWith(pfx));
String name = key.substring(pfx.length()); String name = key.substring(pfx.length());
String layout = props.getProperty(key); String layout = props.getProperty(key);
@ -207,24 +209,18 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer {
if (Pack200.Packer.STRIP.equals(layout) || if (Pack200.Packer.STRIP.equals(layout) ||
Pack200.Packer.PASS.equals(layout) || Pack200.Packer.PASS.equals(layout) ||
Pack200.Packer.ERROR.equals(layout)) { Pack200.Packer.ERROR.equals(layout)) {
attrCommands.put(lkey, layout.intern()); lattrCommands.put(lkey, layout.intern());
} else { } else {
Attribute.define(attrDefs, ctypes[i], name, layout); Attribute.define(lattrDefs, ctypes[i], name, layout);
if (verbose > 1) { if (verbose > 1) {
Utils.log.fine("Added layout for "+Constants.ATTR_CONTEXT_NAME[i]+" attribute "+name+" = "+layout); Utils.log.fine("Added layout for "+Constants.ATTR_CONTEXT_NAME[i]+" attribute "+name+" = "+layout);
} }
assert(attrDefs.containsKey(lkey)); assert(lattrDefs.containsKey(lkey));
} }
} }
} }
if (attrDefs.size() > 0) this.attrDefs = (lattrDefs.isEmpty()) ? null : lattrDefs;
this.attrDefs = attrDefs; this.attrCommands = (lattrCommands.isEmpty()) ? null : lattrCommands;
else
this.attrDefs = null;
if (attrCommands.size() > 0)
this.attrCommands = attrCommands;
else
this.attrCommands = null;
} }
final boolean keepFileOrder final boolean keepFileOrder
@ -275,8 +271,8 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer {
{ {
// Which class files will be passed through? // Which class files will be passed through?
passFiles = props.getProperties(Pack200.Packer.PASS_FILE_PFX); passFiles = props.getProperties(Pack200.Packer.PASS_FILE_PFX);
for (ListIterator i = passFiles.listIterator(); i.hasNext(); ) { for (ListIterator<String> i = passFiles.listIterator(); i.hasNext(); ) {
String file = (String) i.next(); String file = i.next();
if (file == null) { i.remove(); continue; } if (file == null) { i.remove(); continue; }
file = Utils.getJarEntryName(file); // normalize '\\' to '/' file = Utils.getJarEntryName(file); // normalize '\\' to '/'
if (file.endsWith("/")) if (file.endsWith("/"))
@ -333,7 +329,7 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer {
pkg.reset(); pkg.reset();
} }
class InFile { final class InFile {
final String name; final String name;
final JarFile jf; final JarFile jf;
final JarEntry je; final JarEntry je;
@ -596,8 +592,8 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer {
// Package builder must have created a stub for each class. // Package builder must have created a stub for each class.
assert(pkg.files.containsAll(pkg.getClassStubs())); assert(pkg.files.containsAll(pkg.getClassStubs()));
// Order of stubs in file list must agree with classes. // Order of stubs in file list must agree with classes.
List res = pkg.files; List<Package.File> res = pkg.files;
assert((res = new ArrayList(pkg.files)) assert((res = new ArrayList<>(pkg.files))
.retainAll(pkg.getClassStubs()) || true); .retainAll(pkg.getClassStubs()) || true);
assert(res.equals(pkg.getClassStubs())); assert(res.equals(pkg.getClassStubs()));
} }

View File

@ -31,6 +31,8 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set;
import static com.sun.java.util.jar.pack.Constants.*;
/** /**
* Population-based coding. * Population-based coding.
@ -38,7 +40,7 @@ import java.util.HashSet;
* @author John Rose * @author John Rose
*/ */
// This tactic alone reduces the final zipped rt.jar by about a percent. // This tactic alone reduces the final zipped rt.jar by about a percent.
class PopulationCoding implements Constants, CodingMethod { class PopulationCoding implements CodingMethod {
Histogram vHist; // histogram of all values Histogram vHist; // histogram of all values
int[] fValues; // list of favored values int[] fValues; // list of favored values
int fVlen; // inclusive max index int fVlen; // inclusive max index
@ -62,8 +64,8 @@ class PopulationCoding implements Constants, CodingMethod {
} }
} }
public void setFavoredValues(int[] fValues) { public void setFavoredValues(int[] fValues) {
int fVlen = fValues.length-1; int lfVlen = fValues.length-1;
setFavoredValues(fValues, fVlen); setFavoredValues(fValues, lfVlen);
} }
public void setHistogram(Histogram vHist) { public void setHistogram(Histogram vHist) {
this.vHist = vHist; this.vHist = vHist;
@ -103,7 +105,7 @@ class PopulationCoding implements Constants, CodingMethod {
if (tokenCoding instanceof Coding && fValues != null) { if (tokenCoding instanceof Coding && fValues != null) {
Coding tc = (Coding) tokenCoding; Coding tc = (Coding) tokenCoding;
if (tc == fitTokenCoding(fVlen, tc.L())) if (tc == fitTokenCoding(fVlen, tc.L()))
this.L = tc.L();; this.L = tc.L();
// Otherwise, it's a non-default coding. // Otherwise, it's a non-default coding.
} }
} }
@ -217,13 +219,13 @@ class PopulationCoding implements Constants, CodingMethod {
} }
private long[] makeSymtab() { private long[] makeSymtab() {
long[] symtab = new long[fVlen]; long[] lsymtab = new long[fVlen];
for (int token = 1; token <= fVlen; token++) { for (int token = 1; token <= fVlen; token++) {
symtab[token-1] = ((long)fValues[token] << 32) | token; lsymtab[token-1] = ((long)fValues[token] << 32) | token;
} }
// Index by value: // Index by value:
Arrays.sort(symtab); Arrays.sort(lsymtab);
return symtab; return lsymtab;
} }
private Coding getTailCoding(CodingMethod c) { private Coding getTailCoding(CodingMethod c) {
@ -302,12 +304,12 @@ class PopulationCoding implements Constants, CodingMethod {
} }
int[] readFavoredValuesFrom(InputStream in, int maxForDebug) throws IOException { int[] readFavoredValuesFrom(InputStream in, int maxForDebug) throws IOException {
int[] fValues = new int[1000]; // realloc as needed int[] lfValues = new int[1000]; // realloc as needed
// The set uniqueValuesForDebug records all favored values. // The set uniqueValuesForDebug records all favored values.
// As each new value is added, we assert that the value // As each new value is added, we assert that the value
// was not already in the set. // was not already in the set.
HashSet uniqueValuesForDebug = null; Set<Integer> uniqueValuesForDebug = null;
assert((uniqueValuesForDebug = new HashSet()) != null); assert((uniqueValuesForDebug = new HashSet<>()) != null);
int fillp = 1; int fillp = 1;
maxForDebug += fillp; maxForDebug += fillp;
int min = Integer.MIN_VALUE; // farthest from the center int min = Integer.MIN_VALUE; // farthest from the center
@ -317,13 +319,14 @@ class PopulationCoding implements Constants, CodingMethod {
while (fcm instanceof AdaptiveCoding) { while (fcm instanceof AdaptiveCoding) {
AdaptiveCoding ac = (AdaptiveCoding) fcm; AdaptiveCoding ac = (AdaptiveCoding) fcm;
int len = ac.headLength; int len = ac.headLength;
while (fillp + len > fValues.length) while (fillp + len > lfValues.length) {
fValues = BandStructure.realloc(fValues); lfValues = BandStructure.realloc(lfValues);
}
int newFillp = fillp + len; int newFillp = fillp + len;
ac.headCoding.readArrayFrom(in, fValues, fillp, newFillp); ac.headCoding.readArrayFrom(in, lfValues, fillp, newFillp);
while (fillp < newFillp) { while (fillp < newFillp) {
int val = fValues[fillp++]; int val = lfValues[fillp++];
assert(uniqueValuesForDebug.add(new Integer(val))); assert(uniqueValuesForDebug.add(val));
assert(fillp <= maxForDebug); assert(fillp <= maxForDebug);
last = val; last = val;
min = moreCentral(min, val); min = moreCentral(min, val);
@ -344,10 +347,10 @@ class PopulationCoding implements Constants, CodingMethod {
state = val; state = val;
if (fillp > 1 && (val == last || val == min)) //|| val == min2 if (fillp > 1 && (val == last || val == min)) //|| val == min2
break; break;
if (fillp == fValues.length) if (fillp == lfValues.length)
fValues = BandStructure.realloc(fValues); lfValues = BandStructure.realloc(lfValues);
fValues[fillp++] = val; lfValues[fillp++] = val;
assert(uniqueValuesForDebug.add(new Integer(val))); assert(uniqueValuesForDebug.add(val));
assert(fillp <= maxForDebug); assert(fillp <= maxForDebug);
last = val; last = val;
min = moreCentral(min, val); min = moreCentral(min, val);
@ -358,17 +361,17 @@ class PopulationCoding implements Constants, CodingMethod {
int val = fc.readFrom(in); int val = fc.readFrom(in);
if (fillp > 1 && (val == last || val == min)) //|| val == min2 if (fillp > 1 && (val == last || val == min)) //|| val == min2
break; break;
if (fillp == fValues.length) if (fillp == lfValues.length)
fValues = BandStructure.realloc(fValues); lfValues = BandStructure.realloc(lfValues);
fValues[fillp++] = val; lfValues[fillp++] = val;
assert(uniqueValuesForDebug.add(new Integer(val))); assert(uniqueValuesForDebug.add(val));
assert(fillp <= maxForDebug); assert(fillp <= maxForDebug);
last = val; last = val;
min = moreCentral(min, val); min = moreCentral(min, val);
//min2 = moreCentral2(min2, val, min); //min2 = moreCentral2(min2, val, min);
} }
} }
return BandStructure.realloc(fValues, fillp); return BandStructure.realloc(lfValues, fillp);
} }
private static int moreCentral(int x, int y) { private static int moreCentral(int x, int y) {
@ -478,7 +481,7 @@ class PopulationCoding implements Constants, CodingMethod {
boolean verbose boolean verbose
= (p200 != null && = (p200 != null &&
p200.getBoolean(Utils.COM_PREFIX+"verbose.pop")); p200.getBoolean(Utils.COM_PREFIX+"verbose.pop"));
StringBuffer res = new StringBuffer(100); StringBuilder res = new StringBuilder(100);
res.append("pop(").append("fVlen=").append(fVlen); res.append("pop(").append("fVlen=").append(fVlen);
if (verbose && fValues != null) { if (verbose && fValues != null) {
res.append(" fV=["); res.append(" fV=[");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003,2010 Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -34,8 +34,8 @@ import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
@ -46,36 +46,36 @@ import java.util.jar.Pack200;
/** /**
* Control block for publishing Pack200 options to the other classes. * Control block for publishing Pack200 options to the other classes.
*/ */
class PropMap extends TreeMap {
ArrayList _listeners = new ArrayList(1); final class PropMap implements SortedMap<Object, Object> {
private final TreeMap<Object, Object> theMap = new TreeMap<>();;
private final List<PropertyChangeListener> listenerList = new ArrayList<>(1);
void addListener(PropertyChangeListener listener) { void addListener(PropertyChangeListener listener) {
_listeners.add(listener); listenerList.add(listener);
} }
void removeListener(PropertyChangeListener listener) { void removeListener(PropertyChangeListener listener) {
_listeners.remove(listener); listenerList.remove(listener);
} }
void addListeners(ArrayList listeners) { void addListeners(ArrayList<PropertyChangeListener> listeners) {
_listeners.addAll(listeners); listenerList.addAll(listeners);
} }
void removeListeners(ArrayList listeners) { void removeListeners(ArrayList<PropertyChangeListener> listeners) {
_listeners.removeAll(listeners); listenerList.removeAll(listeners);
} }
// Override: // Override:
public Object put(Object key, Object value) { public Object put(Object key, Object value) {
Object oldValue = super.put(key, value); Object oldValue = theMap.put(key, value);
if (value != oldValue && _listeners.size() > 0) { if (value != oldValue && !listenerList.isEmpty()) {
// Post the property change event. // Post the property change event.
PropertyChangeEvent event = PropertyChangeEvent event =
new PropertyChangeEvent(this, (String) key, new PropertyChangeEvent(this, (String) key,
oldValue, value); oldValue, value);
for (Iterator i = _listeners.iterator(); i.hasNext(); ) { for (PropertyChangeListener listener : listenerList) {
PropertyChangeListener listener =
(PropertyChangeListener) i.next();
listener.propertyChange(event); listener.propertyChange(event);
} }
} }
@ -85,7 +85,7 @@ class PropMap extends TreeMap {
// All this other stuff is private to the current package. // All this other stuff is private to the current package.
// Outide clients of Pack200 do not need to use it; they can // Outide clients of Pack200 do not need to use it; they can
// get by with generic SortedMap functionality. // get by with generic SortedMap functionality.
private static Map defaultProps; private static Map<Object, Object> defaultProps;
static { static {
Properties props = new Properties(); Properties props = new Properties();
@ -122,13 +122,12 @@ class PropMap extends TreeMap {
// Define certain attribute layouts by default. // Define certain attribute layouts by default.
// Do this after the previous props are put in place, // Do this after the previous props are put in place,
// to allow override if necessary. // to allow override if necessary.
InputStream propStr = null;
try { try {
String propFile = "intrinsic.properties"; String propFile = "intrinsic.properties";
InputStream propStr = PackerImpl.class.getResourceAsStream(propFile); propStr = PackerImpl.class.getResourceAsStream(propFile);
props.load(new BufferedInputStream(propStr)); props.load(new BufferedInputStream(propStr));
propStr.close(); for (Map.Entry<Object, Object> e : props.entrySet()) {
for (Iterator i = props.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry) i.next();
String key = (String) e.getKey(); String key = (String) e.getKey();
String val = (String) e.getValue(); String val = (String) e.getValue();
if (key.startsWith("attribute.")) { if (key.startsWith("attribute.")) {
@ -137,19 +136,25 @@ class PropMap extends TreeMap {
} }
} catch (IOException ee) { } catch (IOException ee) {
throw new RuntimeException(ee); throw new RuntimeException(ee);
} finally {
try {
if (propStr != null) {
propStr.close();
}
} catch (IOException ignore) {}
} }
defaultProps = (new HashMap(props)); // shrink to fit defaultProps = (new HashMap<>(props)); // shrink to fit
} }
PropMap() { PropMap() {
putAll(defaultProps); theMap.putAll(defaultProps);
} }
// Return a view of this map which includes only properties // Return a view of this map which includes only properties
// that begin with the given prefix. This is easy because // that begin with the given prefix. This is easy because
// the map is sorted, and has a subMap accessor. // the map is sorted, and has a subMap accessor.
SortedMap prefixMap(String prefix) { SortedMap<Object, Object> prefixMap(String prefix) {
int len = prefix.length(); int len = prefix.length();
if (len == 0) if (len == 0)
return this; return this;
@ -174,8 +179,8 @@ class PropMap extends TreeMap {
// Get sequence of props for "prefix", and "prefix.*". // Get sequence of props for "prefix", and "prefix.*".
List getProperties(String prefix) { List getProperties(String prefix) {
Collection values = prefixMap(prefix).values(); Collection<Object> values = prefixMap(prefix).values();
ArrayList res = new ArrayList(values.size()); List<Object> res = new ArrayList<>(values.size());
res.addAll(values); res.addAll(values);
while (res.remove(null)); while (res.remove(null));
return res; return res;
@ -240,11 +245,97 @@ class PropMap extends TreeMap {
void list(PrintWriter out) { void list(PrintWriter out) {
out.println("#"+Utils.PACK_ZIP_ARCHIVE_MARKER_COMMENT+"["); out.println("#"+Utils.PACK_ZIP_ARCHIVE_MARKER_COMMENT+"[");
Set defaults = defaultProps.entrySet(); Set defaults = defaultProps.entrySet();
for (Iterator i = entrySet().iterator(); i.hasNext(); ) { for (Map.Entry e : theMap.entrySet()) {
Map.Entry e = (Map.Entry) i.next();
if (defaults.contains(e)) continue; if (defaults.contains(e)) continue;
out.println(" " + e.getKey() + " = " + e.getValue()); out.println(" " + e.getKey() + " = " + e.getValue());
} }
out.println("#]"); out.println("#]");
} }
@Override
public int size() {
return theMap.size();
}
@Override
public boolean isEmpty() {
return theMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return theMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return theMap.containsValue(value);
}
@Override
public Object get(Object key) {
return theMap.get(key);
}
@Override
public Object remove(Object key) {
return theMap.remove(key);
}
@Override
@SuppressWarnings("unchecked")
public void putAll(Map m) {
theMap.putAll(m);
}
@Override
public void clear() {
theMap.clear();
}
@Override
public Set<Object> keySet() {
return theMap.keySet();
}
@Override
public Collection<Object> values() {
return theMap.values();
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
return theMap.entrySet();
}
@Override
@SuppressWarnings("unchecked")
public Comparator<Object> comparator() {
return (Comparator<Object>) theMap.comparator();
}
@Override
public SortedMap<Object, Object> subMap(Object fromKey, Object toKey) {
return theMap.subMap(fromKey, toKey);
}
@Override
public SortedMap<Object, Object> headMap(Object toKey) {
return theMap.headMap(toKey);
}
@Override
public SortedMap<Object, Object> tailMap(Object fromKey) {
return theMap.tailMap(fromKey);
}
@Override
public Object firstKey() {
return theMap.firstKey();
}
@Override
public Object lastKey() {
return theMap.lastKey();
}
} }

View File

@ -34,7 +34,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Set;
import java.util.SortedMap; import java.util.SortedMap;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
@ -81,7 +81,8 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker {
* Get the set of options for the pack and unpack engines. * Get the set of options for the pack and unpack engines.
* @return A sorted association of option key strings to option values. * @return A sorted association of option key strings to option values.
*/ */
public SortedMap<String, String> properties() { @SuppressWarnings("unchecked")
public SortedMap properties() {
return props; return props;
} }
@ -225,9 +226,8 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker {
props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50"); props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50");
pkg.ensureAllClassFiles(); pkg.ensureAllClassFiles();
// Now write out the files. // Now write out the files.
HashSet<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses()); Set<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
for (Iterator i = pkg.getFiles().iterator(); i.hasNext(); ) { for (Package.File file : pkg.getFiles()) {
Package.File file = (Package.File) i.next();
String name = file.nameString; String name = file.nameString;
JarEntry je = new JarEntry(Utils.getJarEntryName(name)); JarEntry je = new JarEntry(Utils.getJarEntryName(name));
boolean deflate; boolean deflate;

View File

@ -297,7 +297,7 @@ class Utils {
(int)( (1.0 - ((double)ze.getCompressedSize()/(double)ze.getSize()))*100 ) (int)( (1.0 - ((double)ze.getCompressedSize()/(double)ze.getSize()))*100 )
: 0 ; : 0 ;
// Follow unzip -lv output // Follow unzip -lv output
return (long)ze.getSize() + "\t" + ze.getMethod() return ze.getSize() + "\t" + ze.getMethod()
+ "\t" + ze.getCompressedSize() + "\t" + "\t" + ze.getCompressedSize() + "\t"
+ store + "%\t" + store + "%\t"
+ new Date(ze.getTime()) + "\t" + new Date(ze.getTime()) + "\t"

View File

@ -1393,8 +1393,11 @@ class DirectAudioDevice extends AbstractMixer {
public void run() { public void run() {
if (Printer.trace) Printer.trace(">>> DirectClip: run() threadID="+Thread.currentThread().getId()); if (Printer.trace) Printer.trace(">>> DirectClip: run() threadID="+Thread.currentThread().getId());
while (thread != null) { while (thread != null) {
if (!doIO) { // doIO is volatile, but we could check it, then get
synchronized(lock) { // pre-empted while another thread changes doIO and notifies,
// before we wait (so we sleep in wait forever).
synchronized(lock) {
if (!doIO) {
try { try {
lock.wait(); lock.wait();
} catch(InterruptedException ie) {} } catch(InterruptedException ie) {}

View File

@ -61,26 +61,43 @@ public final class RhinoScriptEngine extends AbstractScriptEngine
private ScriptEngineFactory factory; private ScriptEngineFactory factory;
private InterfaceImplementor implementor; private InterfaceImplementor implementor;
private static final int languageVersion = getLanguageVersion();
private static final int optimizationLevel = getOptimizationLevel();
static { static {
ContextFactory.initGlobal(new ContextFactory() { ContextFactory.initGlobal(new ContextFactory() {
protected Context makeContext() { protected Context makeContext() {
Context cx = super.makeContext(); Context cx = super.makeContext();
cx.setLanguageVersion(languageVersion);
cx.setOptimizationLevel(optimizationLevel);
cx.setClassShutter(RhinoClassShutter.getInstance()); cx.setClassShutter(RhinoClassShutter.getInstance());
cx.setWrapFactory(RhinoWrapFactory.getInstance()); cx.setWrapFactory(RhinoWrapFactory.getInstance());
return cx; return cx;
} }
public boolean hasFeature(Context cx, int feature) {
// we do not support E4X (ECMAScript for XML)!
if (feature == Context.FEATURE_E4X) {
return false;
} else {
return super.hasFeature(cx, feature);
}
}
}); });
} }
private static final String RHINO_JS_VERSION = "rhino.js.version";
private static int getLanguageVersion() {
int version;
String tmp = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(RHINO_JS_VERSION));
if (tmp != null) {
version = Integer.parseInt((String)tmp);
} else {
version = Context.VERSION_1_8;
}
return version;
}
private static final String RHINO_OPT_LEVEL = "rhino.opt.level";
private static int getOptimizationLevel() {
int optLevel = -1;
// disable optimizer under security manager, for now.
if (System.getSecurityManager() == null) {
optLevel = Integer.getInteger(RHINO_OPT_LEVEL, -1);
}
return optLevel;
}
/** /**
* Creates a new instance of RhinoScriptEngine * Creates a new instance of RhinoScriptEngine
@ -333,6 +350,7 @@ public final class RhinoScriptEngine extends AbstractScriptEngine
return result instanceof Undefined ? null : result; return result instanceof Undefined ? null : result;
} }
/*
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
if (args.length == 0) { if (args.length == 0) {
System.out.println("No file specified"); System.out.println("No file specified");
@ -347,4 +365,5 @@ public final class RhinoScriptEngine extends AbstractScriptEngine
engine.eval(r); engine.eval(r);
System.out.println(engine.get("x")); System.out.println(engine.get("x"));
} }
*/
} }

View File

@ -58,11 +58,11 @@ public class RhinoScriptEngineFactory extends ScriptEngineFactoryBase {
} else if (key.equals(ScriptEngine.ENGINE)) { } else if (key.equals(ScriptEngine.ENGINE)) {
return "Mozilla Rhino"; return "Mozilla Rhino";
} else if (key.equals(ScriptEngine.ENGINE_VERSION)) { } else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
return "1.6 release 2"; return "1.7 release 3 PRERELEASE";
} else if (key.equals(ScriptEngine.LANGUAGE)) { } else if (key.equals(ScriptEngine.LANGUAGE)) {
return "ECMAScript"; return "ECMAScript";
} else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) { } else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
return "1.6"; return "1.8";
} else if (key.equals("THREADING")) { } else if (key.equals("THREADING")) {
return "MULTITHREADED"; return "MULTITHREADED";
} else { } else {
@ -128,10 +128,12 @@ public class RhinoScriptEngineFactory extends ScriptEngineFactoryBase {
return ret; return ret;
} }
/*
public static void main(String[] args) { public static void main(String[] args) {
RhinoScriptEngineFactory fact = new RhinoScriptEngineFactory(); RhinoScriptEngineFactory fact = new RhinoScriptEngineFactory();
System.out.println(fact.getParameter(ScriptEngine.ENGINE_VERSION)); System.out.println(fact.getParameter(ScriptEngine.ENGINE_VERSION));
} }
*/
private static List<String> names; private static List<String> names;
private static List<String> mimeTypes; private static List<String> mimeTypes;

View File

@ -37,15 +37,6 @@ import javax.script.*;
* @since 1.6 * @since 1.6
*/ */
public final class RhinoTopLevel extends ImporterTopLevel { public final class RhinoTopLevel extends ImporterTopLevel {
// variables defined always to help Java access from JavaScript
private static final String builtinVariables =
"var com = Packages.com; \n" +
"var edu = Packages.edu; \n" +
"var javax = Packages.javax; \n" +
"var net = Packages.net; \n" +
"var org = Packages.org; \n";
RhinoTopLevel(Context cx, RhinoScriptEngine engine) { RhinoTopLevel(Context cx, RhinoScriptEngine engine) {
super(cx); super(cx);
this.engine = engine; this.engine = engine;
@ -67,9 +58,6 @@ public final class RhinoTopLevel extends ImporterTopLevel {
String names[] = { "bindings", "scope", "sync" }; String names[] = { "bindings", "scope", "sync" };
defineFunctionProperties(names, RhinoTopLevel.class, defineFunctionProperties(names, RhinoTopLevel.class,
ScriptableObject.DONTENUM); ScriptableObject.DONTENUM);
// define built-in variables
cx.evaluateString(this, builtinVariables, "<builtin>", 1, null);
} }
/** /**

View File

@ -311,9 +311,9 @@ function load(str) {
try { try {
engine.eval(reader); engine.eval(reader);
} finally { } finally {
engine.put(engine.FILENAME, oldFilename); engine.put(engine.FILENAME, oldFilename);
streamClose(stream);
} }
streamClose(stream);
} }
// file system utilities // file system utilities

View File

@ -33,27 +33,17 @@ import sun.util.logging.PlatformLogger;
import sun.awt.image.SunWritableRaster; import sun.awt.image.SunWritableRaster;
/** /**
* The splash screen can be created at application startup, before the * The splash screen can be displayed at application startup, before the
* Java Virtual Machine (JVM) starts. The splash screen is displayed as an * Java Virtual Machine (JVM) starts. The splash screen is displayed as an
* undecorated window containing an image. You can use GIF, JPEG, and PNG files * undecorated window containing an image. You can use GIF, JPEG, or PNG files
* for the image. Animation (for GIF) and transparency (for GIF, PNG) are * for the image. Animation is supported for the GIF format, while transparency
* supported. The window is positioned at the center of the screen (the * is supported both for GIF and PNG. The window is positioned at the center
* position on multi-monitor systems is not specified - it is platform and * of the screen. The position on multi-monitor systems is not specified. It is
* implementation dependent). * platform and implementation dependent. The splash screen window is closed
* The window is closed automatically as soon as the first window is displayed by * automatically as soon as the first window is displayed by Swing/AWT (may be
* Swing/AWT (may be also closed manually using the Java API, see below). * also closed manually using the Java API, see below).
* <P> * <P>
* There are two ways to show the native splash screen: * If your application is packaged in a jar file, you can use the
* <P>
* <UL>
* <LI>If your application is run from the command line or from a shortcut,
* use the "-splash:" Java application launcher option to show a splash screen.
* <BR>
* For example:
* <PRE>
* java -splash:filename.gif Test
* </PRE>
* <LI>If your application is packaged in a jar file, you can use the
* "SplashScreen-Image" option in a manifest file to show a splash screen. * "SplashScreen-Image" option in a manifest file to show a splash screen.
* Place the image in the jar archive and specify the path in the option. * Place the image in the jar archive and specify the path in the option.
* The path should not have a leading slash. * The path should not have a leading slash.
@ -64,18 +54,39 @@ import sun.awt.image.SunWritableRaster;
* Main-Class: Test * Main-Class: Test
* SplashScreen-Image: filename.gif * SplashScreen-Image: filename.gif
* </PRE> * </PRE>
* <P>
* If the Java implementation provides the command-line interface and you run
* your application by using the command line or a shortcut, use the Java
* application launcher option to show a splash screen. The Oracle reference
* implementation allows you to specify the splash screen image location with
* the {@code -splash:} option.
* <BR>
* For example:
* <PRE>
* java -splash:filename.gif Test
* </PRE>
* The command line interface has higher precedence over the manifest * The command line interface has higher precedence over the manifest
* setting. * setting.
* </UL> * <p>
* The splash screen will be displayed as faithfully as possible to present the
* whole splash screen image given the limitations of the target platform and
* display.
* <p>
* It is implied that the specified image is presented on the screen "as is",
* i.e. preserving the exact color values as specified in the image file. Under
* certain circumstances, though, the presented image may differ, e.g. when
* applying color dithering to present a 32 bits per pixel (bpp) image on a 16
* or 8 bpp screen. The native platform display configuration may also affect
* the colors of the displayed image (e.g. color profiles, etc.)
* <p> * <p>
* The {@code SplashScreen} class provides the API for controlling the splash * The {@code SplashScreen} class provides the API for controlling the splash
* screen. This class may be used to close the splash screen, change the splash * screen. This class may be used to close the splash screen, change the splash
* screen image, get the image position/size and paint in the splash screen. It * screen image, get the splash screen native window position/size, and paint
* cannot be used to create the splash screen; you should use the command line or manifest * in the splash screen. It cannot be used to create the splash screen. You
* file option for that. * should use the options provided by the Java implementation for that.
* <p> * <p>
* This class cannot be instantiated. Only a single instance of this class * This class cannot be instantiated. Only a single instance of this class
* can exist, and it may be obtained using the {@link #getSplashScreen()} * can exist, and it may be obtained by using the {@link #getSplashScreen()}
* static method. In case the splash screen has not been created at * static method. In case the splash screen has not been created at
* application startup via the command line or manifest file option, * application startup via the command line or manifest file option,
* the <code>getSplashScreen</code> method returns <code>null</code>. * the <code>getSplashScreen</code> method returns <code>null</code>.
@ -91,7 +102,7 @@ public final class SplashScreen {
/** /**
* Returns the {@code SplashScreen} object used for * Returns the {@code SplashScreen} object used for
* Java startup splash screen control. * Java startup splash screen control on systems that support display.
* *
* @throws UnsupportedOperationException if the splash screen feature is not * @throws UnsupportedOperationException if the splash screen feature is not
* supported by the current toolkit * supported by the current toolkit
@ -219,6 +230,9 @@ public final class SplashScreen {
* <p> * <p>
* You cannot control the size or position of the splash screen. * You cannot control the size or position of the splash screen.
* The splash screen size is adjusted automatically when the image changes. * The splash screen size is adjusted automatically when the image changes.
* <p>
* The image may contain transparent areas, and thus the reported bounds may
* be larger than the visible splash screen image on the screen.
* *
* @return a {@code Rectangle} containing the splash screen bounds * @return a {@code Rectangle} containing the splash screen bounds
* @throws IllegalStateException if the splash screen has already been closed * @throws IllegalStateException if the splash screen has already been closed
@ -237,6 +251,9 @@ public final class SplashScreen {
* <p> * <p>
* You cannot control the size or position of the splash screen. * You cannot control the size or position of the splash screen.
* The splash screen size is adjusted automatically when the image changes. * The splash screen size is adjusted automatically when the image changes.
* <p>
* The image may contain transparent areas, and thus the reported size may
* be larger than the visible splash screen image on the screen.
* *
* @return a {@link Dimension} object indicating the splash screen size * @return a {@link Dimension} object indicating the splash screen size
* @throws IllegalStateException if the splash screen has already been closed * @throws IllegalStateException if the splash screen has already been closed
@ -254,6 +271,10 @@ public final class SplashScreen {
* screen window. You should call {@code update()} on the * screen window. You should call {@code update()} on the
* <code>SplashScreen</code> when you want the splash screen to be * <code>SplashScreen</code> when you want the splash screen to be
* updated immediately. * updated immediately.
* <p>
* The pixel (0, 0) in the coordinate space of the graphics context
* corresponds to the origin of the splash screen native window bounds (see
* {@link #getBounds()}).
* *
* @return graphics context for the splash screen overlay surface * @return graphics context for the splash screen overlay surface
* @throws IllegalStateException if the splash screen has already been closed * @throws IllegalStateException if the splash screen has already been closed
@ -334,6 +355,11 @@ public final class SplashScreen {
* Determines whether the splash screen is visible. The splash screen may * Determines whether the splash screen is visible. The splash screen may
* be hidden using {@link #close()}, it is also hidden automatically when * be hidden using {@link #close()}, it is also hidden automatically when
* the first AWT/Swing window is made visible. * the first AWT/Swing window is made visible.
* <p>
* Note that the native platform may delay presenting the splash screen
* native window on the screen. The return value of {@code true} for this
* method only guarantees that the conditions to hide the splash screen
* window have not occurred yet.
* *
* @return true if the splash screen is visible (has not been closed yet), * @return true if the splash screen is visible (has not been closed yet),
* false otherwise * false otherwise

View File

@ -58,20 +58,20 @@ import java.util.Set;
* It is also possible to perform numeric shaping explicitly using instances * It is also possible to perform numeric shaping explicitly using instances
* of <code>NumericShaper</code>, as this code snippet demonstrates:<br> * of <code>NumericShaper</code>, as this code snippet demonstrates:<br>
* <blockquote><pre> * <blockquote><pre>
* char[] text = ...; * char[] text = ...;
* // shape all EUROPEAN digits (except zero) to ARABIC digits * // shape all EUROPEAN digits (except zero) to ARABIC digits
* NumericShaper shaper = NumericShaper.getShaper(NumericShaper.ARABIC); * NumericShaper shaper = NumericShaper.getShaper(NumericShaper.ARABIC);
* shaper.shape(text, start, count); * shaper.shape(text, start, count);
* *
* // shape European digits to ARABIC digits if preceding text is Arabic, or * // shape European digits to ARABIC digits if preceding text is Arabic, or
* // shape European digits to TAMIL digits if preceding text is Tamil, or * // shape European digits to TAMIL digits if preceding text is Tamil, or
* // leave European digits alone if there is no preceding text, or * // leave European digits alone if there is no preceding text, or
* // preceding text is neither Arabic nor Tamil * // preceding text is neither Arabic nor Tamil
* NumericShaper shaper = * NumericShaper shaper =
* NumericShaper.getContextualShaper(NumericShaper.ARABIC | * NumericShaper.getContextualShaper(NumericShaper.ARABIC |
* NumericShaper.TAMIL, * NumericShaper.TAMIL,
* NumericShaper.EUROPEAN); * NumericShaper.EUROPEAN);
* shaper.shape(text, start, count); * shaper.shape(text, start, count);
* </pre></blockquote> * </pre></blockquote>
* *
* <p><b>Bit mask- and enum-based Unicode ranges</b></p> * <p><b>Bit mask- and enum-based Unicode ranges</b></p>
@ -99,6 +99,37 @@ import java.util.Set;
* values are specified, such as {@code NumericShaper.Range.BALINESE}, * values are specified, such as {@code NumericShaper.Range.BALINESE},
* those ranges are ignored. * those ranges are ignored.
* *
* <p><b>Decimal Digits Precedence</b></p>
*
* <p>A Unicode range may have more than one set of decimal digits. If
* multiple decimal digits sets are specified for the same Unicode
* range, one of the sets will take precedence as follows.
*
* <table border=1 cellspacing=3 cellpadding=0 summary="NumericShaper constants precedence.">
* <tr>
* <th class="TableHeadingColor">Unicode Range</th>
* <th class="TableHeadingColor"><code>NumericShaper</code> Constants</th>
* <th class="TableHeadingColor">Precedence</th>
* </tr>
* <tr>
* <td rowspan="2">Arabic</td>
* <td>{@link NumericShaper#ARABIC NumericShaper.ARABIC}<br>
* {@link NumericShaper#EASTERN_ARABIC NumericShaper.EASTERN_ARABIC}</td>
* <td>{@link NumericShaper#EASTERN_ARABIC NumericShaper.EASTERN_ARABIC}</td>
* </tr>
* <tr>
* <td>{@link NumericShaper.Range#ARABIC}<br>
* {@link NumericShaper.Range#EASTERN_ARABIC}</td>
* <td>{@link NumericShaper.Range#EASTERN_ARABIC}</td>
* </tr>
* <tr>
* <td>Tai Tham</td>
* <td>{@link NumericShaper.Range#TAI_THAM_HORA}<br>
* {@link NumericShaper.Range#TAI_THAM_THAM}</td>
* <td>{@link NumericShaper.Range#TAI_THAM_THAM}</td>
* </tr>
* </table>
*
* @since 1.4 * @since 1.4
*/ */

View File

@ -625,7 +625,7 @@ public class IndexColorModel extends ColorModel {
} }
nBits[0] = nBits[1] = nBits[2] = 8; nBits[0] = nBits[1] = nBits[2] = 8;
} }
return nBits; return nBits.clone();
} }
/** /**

View File

@ -121,7 +121,7 @@ public abstract class SampleModel
*/ */
public SampleModel(int dataType, int w, int h, int numBands) public SampleModel(int dataType, int w, int h, int numBands)
{ {
float size = (float)w*h; long size = (long)w * h;
if (w <= 0 || h <= 0) { if (w <= 0 || h <= 0) {
throw new IllegalArgumentException("Width ("+w+") and height ("+ throw new IllegalArgumentException("Width ("+w+") and height ("+
h+") must be > 0"); h+") must be > 0");

View File

@ -92,7 +92,8 @@ public class SinglePixelPackedSampleModel extends SampleModel
* Constructs a SinglePixelPackedSampleModel with bitMasks.length bands. * Constructs a SinglePixelPackedSampleModel with bitMasks.length bands.
* Each sample is stored in a data array element in the position of * Each sample is stored in a data array element in the position of
* its corresponding bit mask. Each bit mask must be contiguous and * its corresponding bit mask. Each bit mask must be contiguous and
* masks must not overlap. * masks must not overlap. Bit masks exceeding data type capacity are
* truncated.
* @param dataType The data type for storing samples. * @param dataType The data type for storing samples.
* @param w The width (in pixels) of the region of the * @param w The width (in pixels) of the region of the
* image data described. * image data described.
@ -120,7 +121,8 @@ public class SinglePixelPackedSampleModel extends SampleModel
* and a scanline stride equal to scanlineStride data array elements. * and a scanline stride equal to scanlineStride data array elements.
* Each sample is stored in a data array element in the position of * Each sample is stored in a data array element in the position of
* its corresponding bit mask. Each bit mask must be contiguous and * its corresponding bit mask. Each bit mask must be contiguous and
* masks must not overlap. * masks must not overlap. Bit masks exceeding data type capacity are
* truncated.
* @param dataType The data type for storing samples. * @param dataType The data type for storing samples.
* @param w The width (in pixels) of the region of * @param w The width (in pixels) of the region of
* image data described. * image data described.
@ -153,11 +155,13 @@ public class SinglePixelPackedSampleModel extends SampleModel
this.bitOffsets = new int[numBands]; this.bitOffsets = new int[numBands];
this.bitSizes = new int[numBands]; this.bitSizes = new int[numBands];
int maxMask = (int)((1L << DataBuffer.getDataTypeSize(dataType)) - 1);
this.maxBitSize = 0; this.maxBitSize = 0;
for (int i=0; i<numBands; i++) { for (int i=0; i<numBands; i++) {
int bitOffset = 0, bitSize = 0, mask; int bitOffset = 0, bitSize = 0, mask;
mask = bitMasks[i]; this.bitMasks[i] &= maxMask;
mask = this.bitMasks[i];
if (mask != 0) { if (mask != 0) {
while ((mask & 1) == 0) { while ((mask & 1) == 0) {
mask = mask >>> 1; mask = mask >>> 1;
@ -243,30 +247,12 @@ public class SinglePixelPackedSampleModel extends SampleModel
/** Returns the number of bits per sample for all bands. */ /** Returns the number of bits per sample for all bands. */
public int[] getSampleSize() { public int[] getSampleSize() {
int mask; return bitSizes.clone();
int sampleSize[] = new int [numBands];
for (int i=0; i<numBands; i++) {
sampleSize[i] = 0;
mask = bitMasks[i] >>> bitOffsets[i];
while ((mask & 1) != 0) {
sampleSize[i] ++;
mask = mask >>> 1;
}
}
return sampleSize;
} }
/** Returns the number of bits per sample for the specified band. */ /** Returns the number of bits per sample for the specified band. */
public int getSampleSize(int band) { public int getSampleSize(int band) {
int sampleSize = 0; return bitSizes[band];
int mask = bitMasks[band] >>> bitOffsets[band];
while ((mask & 1) != 0) {
sampleSize ++;
mask = mask >>> 1;
}
return sampleSize;
} }
/** Returns the offset (in data array elements) of pixel (x,y). /** Returns the offset (in data array elements) of pixel (x,y).

View File

@ -34,7 +34,7 @@ import java.io.File;
*/ */
class DeleteOnExitHook { class DeleteOnExitHook {
private static LinkedHashSet<String> files = new LinkedHashSet<String>(); private static LinkedHashSet<String> files = new LinkedHashSet<>();
static { static {
// DeleteOnExitHook must be the last shutdown hook to be invoked. // DeleteOnExitHook must be the last shutdown hook to be invoked.
// Application shutdown hooks may add the first file to the // Application shutdown hooks may add the first file to the
@ -71,7 +71,7 @@ class DeleteOnExitHook {
files = null; files = null;
} }
ArrayList<String> toBeDeleted = new ArrayList<String>(theFiles); ArrayList<String> toBeDeleted = new ArrayList<>(theFiles);
// reverse the list to maintain previous jdk deletion order. // reverse the list to maintain previous jdk deletion order.
// Last in first deleted. // Last in first deleted.

View File

@ -1067,7 +1067,7 @@ public class File
if ((names == null) || (filter == null)) { if ((names == null) || (filter == null)) {
return names; return names;
} }
List<String> v = new ArrayList<String>(); List<String> v = new ArrayList<>();
for (int i = 0 ; i < names.length ; i++) { for (int i = 0 ; i < names.length ; i++) {
if (filter.accept(this, names[i])) { if (filter.accept(this, names[i])) {
v.add(names[i]); v.add(names[i]);
@ -1158,7 +1158,7 @@ public class File
public File[] listFiles(FilenameFilter filter) { public File[] listFiles(FilenameFilter filter) {
String ss[] = list(); String ss[] = list();
if (ss == null) return null; if (ss == null) return null;
ArrayList<File> files = new ArrayList<File>(); ArrayList<File> files = new ArrayList<>();
for (String s : ss) for (String s : ss)
if ((filter == null) || filter.accept(this, s)) if ((filter == null) || filter.accept(this, s))
files.add(new File(s, this)); files.add(new File(s, this));
@ -1195,7 +1195,7 @@ public class File
public File[] listFiles(FileFilter filter) { public File[] listFiles(FileFilter filter) {
String ss[] = list(); String ss[] = list();
if (ss == null) return null; if (ss == null) return null;
ArrayList<File> files = new ArrayList<File>(); ArrayList<File> files = new ArrayList<>();
for (String s : ss) { for (String s : ss) {
File f = new File(s, this); File f = new File(s, this);
if ((filter == null) || filter.accept(f)) if ((filter == null) || filter.accept(f))

View File

@ -56,7 +56,7 @@ class FileInputStream extends InputStream
private volatile boolean closed = false; private volatile boolean closed = false;
private static final ThreadLocal<Boolean> runningFinalize = private static final ThreadLocal<Boolean> runningFinalize =
new ThreadLocal<Boolean>(); new ThreadLocal<>();
private static boolean isRunningFinalize() { private static boolean isRunningFinalize() {
Boolean val; Boolean val;

View File

@ -69,7 +69,7 @@ class FileOutputStream extends OutputStream
private final Object closeLock = new Object(); private final Object closeLock = new Object();
private volatile boolean closed = false; private volatile boolean closed = false;
private static final ThreadLocal<Boolean> runningFinalize = private static final ThreadLocal<Boolean> runningFinalize =
new ThreadLocal<Boolean>(); new ThreadLocal<>();
private static boolean isRunningFinalize() { private static boolean isRunningFinalize() {
Boolean val; Boolean val;

View File

@ -725,7 +725,7 @@ implements Serializable {
*/ */
public FilePermissionCollection() { public FilePermissionCollection() {
perms = new ArrayList<Permission>(); perms = new ArrayList<>();
} }
/** /**
@ -830,7 +830,7 @@ implements Serializable {
// Don't call out.defaultWriteObject() // Don't call out.defaultWriteObject()
// Write out Vector // Write out Vector
Vector<Permission> permissions = new Vector<Permission>(perms.size()); Vector<Permission> permissions = new Vector<>(perms.size());
synchronized (this) { synchronized (this) {
permissions.addAll(perms); permissions.addAll(perms);
} }
@ -853,7 +853,7 @@ implements Serializable {
// Get the one we want // Get the one we want
Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null); Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null);
perms = new ArrayList<Permission>(permissions.size()); perms = new ArrayList<>(permissions.size());
perms.addAll(permissions); perms.addAll(permissions);
} }
} }

View File

@ -213,7 +213,7 @@ public class ObjectInputStream
/** table mapping primitive type names to corresponding class objects */ /** table mapping primitive type names to corresponding class objects */
private static final HashMap<String, Class<?>> primClasses private static final HashMap<String, Class<?>> primClasses
= new HashMap<String, Class<?>>(8, 1.0F); = new HashMap<>(8, 1.0F);
static { static {
primClasses.put("boolean", boolean.class); primClasses.put("boolean", boolean.class);
primClasses.put("byte", byte.class); primClasses.put("byte", byte.class);
@ -229,11 +229,11 @@ public class ObjectInputStream
private static class Caches { private static class Caches {
/** cache of subclass security audit results */ /** cache of subclass security audit results */
static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits = static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
new ConcurrentHashMap<WeakClassKey,Boolean>(); new ConcurrentHashMap<>();
/** queue for WeakReferences to audited subclasses */ /** queue for WeakReferences to audited subclasses */
static final ReferenceQueue<Class<?>> subclassAuditsQueue = static final ReferenceQueue<Class<?>> subclassAuditsQueue =
new ReferenceQueue<Class<?>>(); new ReferenceQueue<>();
} }
/** filter stream for handling block data conversion */ /** filter stream for handling block data conversion */

View File

@ -165,11 +165,11 @@ public class ObjectOutputStream
private static class Caches { private static class Caches {
/** cache of subclass security audit results */ /** cache of subclass security audit results */
static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits = static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
new ConcurrentHashMap<WeakClassKey,Boolean>(); new ConcurrentHashMap<>();
/** queue for WeakReferences to audited subclasses */ /** queue for WeakReferences to audited subclasses */
static final ReferenceQueue<Class<?>> subclassAuditsQueue = static final ReferenceQueue<Class<?>> subclassAuditsQueue =
new ReferenceQueue<Class<?>>(); new ReferenceQueue<>();
} }
/** filter stream for handling block data conversion */ /** filter stream for handling block data conversion */
@ -2413,7 +2413,7 @@ public class ObjectOutputStream
private final List<String> stack; private final List<String> stack;
DebugTraceInfoStack() { DebugTraceInfoStack() {
stack = new ArrayList<String>(); stack = new ArrayList<>();
} }
/** /**

View File

@ -84,18 +84,18 @@ public class ObjectStreamClass implements Serializable {
private static class Caches { private static class Caches {
/** cache mapping local classes -> descriptors */ /** cache mapping local classes -> descriptors */
static final ConcurrentMap<WeakClassKey,Reference<?>> localDescs = static final ConcurrentMap<WeakClassKey,Reference<?>> localDescs =
new ConcurrentHashMap<WeakClassKey,Reference<?>>(); new ConcurrentHashMap<>();
/** cache mapping field group/local desc pairs -> field reflectors */ /** cache mapping field group/local desc pairs -> field reflectors */
static final ConcurrentMap<FieldReflectorKey,Reference<?>> reflectors = static final ConcurrentMap<FieldReflectorKey,Reference<?>> reflectors =
new ConcurrentHashMap<FieldReflectorKey,Reference<?>>(); new ConcurrentHashMap<>();
/** queue for WeakReferences to local classes */ /** queue for WeakReferences to local classes */
private static final ReferenceQueue<Class<?>> localDescsQueue = private static final ReferenceQueue<Class<?>> localDescsQueue =
new ReferenceQueue<Class<?>>(); new ReferenceQueue<>();
/** queue for WeakReferences to field reflectors keys */ /** queue for WeakReferences to field reflectors keys */
private static final ReferenceQueue<Class<?>> reflectorsQueue = private static final ReferenceQueue<Class<?>> reflectorsQueue =
new ReferenceQueue<Class<?>>(); new ReferenceQueue<>();
} }
/** class associated with this descriptor (if any) */ /** class associated with this descriptor (if any) */
@ -290,7 +290,7 @@ public class ObjectStreamClass implements Serializable {
EntryFuture future = null; EntryFuture future = null;
if (entry == null) { if (entry == null) {
EntryFuture newEntry = new EntryFuture(); EntryFuture newEntry = new EntryFuture();
Reference<?> newRef = new SoftReference<EntryFuture>(newEntry); Reference<?> newRef = new SoftReference<>(newEntry);
do { do {
if (ref != null) { if (ref != null) {
Caches.localDescs.remove(key, ref); Caches.localDescs.remove(key, ref);
@ -329,7 +329,7 @@ public class ObjectStreamClass implements Serializable {
entry = th; entry = th;
} }
if (future.set(entry)) { if (future.set(entry)) {
Caches.localDescs.put(key, new SoftReference<Object>(entry)); Caches.localDescs.put(key, new SoftReference<>(entry));
} else { } else {
// nested lookup call already set future // nested lookup call already set future
entry = future.get(); entry = future.get();
@ -1130,7 +1130,7 @@ public class ObjectStreamClass implements Serializable {
private ClassDataSlot[] getClassDataLayout0() private ClassDataSlot[] getClassDataLayout0()
throws InvalidClassException throws InvalidClassException
{ {
ArrayList<ClassDataSlot> slots = new ArrayList<ClassDataSlot>(); ArrayList<ClassDataSlot> slots = new ArrayList<>();
Class<?> start = cl, end = cl; Class<?> start = cl, end = cl;
// locate closest non-serializable superclass // locate closest non-serializable superclass
@ -1566,7 +1566,7 @@ public class ObjectStreamClass implements Serializable {
ObjectStreamField[] boundFields = ObjectStreamField[] boundFields =
new ObjectStreamField[serialPersistentFields.length]; new ObjectStreamField[serialPersistentFields.length];
Set<String> fieldNames = new HashSet<String>(serialPersistentFields.length); Set<String> fieldNames = new HashSet<>(serialPersistentFields.length);
for (int i = 0; i < serialPersistentFields.length; i++) { for (int i = 0; i < serialPersistentFields.length; i++) {
ObjectStreamField spf = serialPersistentFields[i]; ObjectStreamField spf = serialPersistentFields[i];
@ -1604,7 +1604,7 @@ public class ObjectStreamClass implements Serializable {
*/ */
private static ObjectStreamField[] getDefaultSerialFields(Class<?> cl) { private static ObjectStreamField[] getDefaultSerialFields(Class<?> cl) {
Field[] clFields = cl.getDeclaredFields(); Field[] clFields = cl.getDeclaredFields();
ArrayList<ObjectStreamField> list = new ArrayList<ObjectStreamField>(); ArrayList<ObjectStreamField> list = new ArrayList<>();
int mask = Modifier.STATIC | Modifier.TRANSIENT; int mask = Modifier.STATIC | Modifier.TRANSIENT;
for (int i = 0; i < clFields.length; i++) { for (int i = 0; i < clFields.length; i++) {
@ -1855,8 +1855,8 @@ public class ObjectStreamClass implements Serializable {
writeKeys = new long[nfields]; writeKeys = new long[nfields];
offsets = new int[nfields]; offsets = new int[nfields];
typeCodes = new char[nfields]; typeCodes = new char[nfields];
ArrayList<Class<?>> typeList = new ArrayList<Class<?>>(); ArrayList<Class<?>> typeList = new ArrayList<>();
Set<Long> usedKeys = new HashSet<Long>(); Set<Long> usedKeys = new HashSet<>();
for (int i = 0; i < nfields; i++) { for (int i = 0; i < nfields; i++) {
@ -2092,7 +2092,7 @@ public class ObjectStreamClass implements Serializable {
EntryFuture future = null; EntryFuture future = null;
if (entry == null) { if (entry == null) {
EntryFuture newEntry = new EntryFuture(); EntryFuture newEntry = new EntryFuture();
Reference<?> newRef = new SoftReference<EntryFuture>(newEntry); Reference<?> newRef = new SoftReference<>(newEntry);
do { do {
if (ref != null) { if (ref != null) {
Caches.reflectors.remove(key, ref); Caches.reflectors.remove(key, ref);
@ -2118,7 +2118,7 @@ public class ObjectStreamClass implements Serializable {
entry = th; entry = th;
} }
future.set(entry); future.set(entry);
Caches.reflectors.put(key, new SoftReference<Object>(entry)); Caches.reflectors.put(key, new SoftReference<>(entry));
} }
if (entry instanceof FieldReflector) { if (entry instanceof FieldReflector) {

View File

@ -47,7 +47,7 @@ class ApplicationShutdownHooks {
} }
} }
); );
hooks = new IdentityHashMap<Thread, Thread>(); hooks = new IdentityHashMap<>();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// application shutdown hooks cannot be added if // application shutdown hooks cannot be added if
// shutdown is in progress. // shutdown is in progress.

View File

@ -648,8 +648,7 @@ class Character implements java.io.Serializable, Comparable<Character> {
*/ */
public static final class UnicodeBlock extends Subset { public static final class UnicodeBlock extends Subset {
private static Map<String, UnicodeBlock> map private static Map<String, UnicodeBlock> map = new HashMap<>(256);
= new HashMap<String, UnicodeBlock>(256);
/** /**
* Creates a UnicodeBlock with the given identifier name. * Creates a UnicodeBlock with the given identifier name.
@ -4178,7 +4177,7 @@ class Character implements java.io.Serializable, Comparable<Character> {
private static HashMap<String, Character.UnicodeScript> aliases; private static HashMap<String, Character.UnicodeScript> aliases;
static { static {
aliases = new HashMap<String, UnicodeScript>(128); aliases = new HashMap<>(128);
aliases.put("ARAB", ARABIC); aliases.put("ARAB", ARABIC);
aliases.put("ARMI", IMPERIAL_ARAMAIC); aliases.put("ARMI", IMPERIAL_ARAMAIC);
aliases.put("ARMN", ARMENIAN); aliases.put("ARMN", ARMENIAN);

View File

@ -81,7 +81,7 @@ class CharacterName {
} while (cpOff < cpEnd); } while (cpOff < cpEnd);
strPool = new byte[total - cpEnd]; strPool = new byte[total - cpEnd];
dis.readFully(strPool); dis.readFully(strPool);
refStrPool = new SoftReference<byte[]>(strPool); refStrPool = new SoftReference<>(strPool);
} catch (Exception x) { } catch (Exception x) {
throw new InternalError(x.getMessage()); throw new InternalError(x.getMessage());
} finally { } finally {

View File

@ -1306,7 +1306,7 @@ public final
return java.security.AccessController.doPrivileged( return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Class<?>[]>() { new java.security.PrivilegedAction<Class<?>[]>() {
public Class[] run() { public Class[] run() {
List<Class<?>> list = new ArrayList<Class<?>>(); List<Class<?>> list = new ArrayList<>();
Class<?> currentClass = Class.this; Class<?> currentClass = Class.this;
while (currentClass != null) { while (currentClass != null) {
Class<?>[] members = currentClass.getDeclaredClasses(); Class<?>[] members = currentClass.getDeclaredClasses();
@ -2306,9 +2306,9 @@ public final
res = Reflection.filterFields(this, getDeclaredFields0(publicOnly)); res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
if (useCaches) { if (useCaches) {
if (publicOnly) { if (publicOnly) {
declaredPublicFields = new SoftReference<Field[]>(res); declaredPublicFields = new SoftReference<>(res);
} else { } else {
declaredFields = new SoftReference<Field[]>(res); declaredFields = new SoftReference<>(res);
} }
} }
return res; return res;
@ -2330,9 +2330,9 @@ public final
// No cached value available; compute value recursively. // No cached value available; compute value recursively.
// Traverse in correct order for getField(). // Traverse in correct order for getField().
List<Field> fields = new ArrayList<Field>(); List<Field> fields = new ArrayList<>();
if (traversedInterfaces == null) { if (traversedInterfaces == null) {
traversedInterfaces = new HashSet<Class<?>>(); traversedInterfaces = new HashSet<>();
} }
// Local fields // Local fields
@ -2358,7 +2358,7 @@ public final
res = new Field[fields.size()]; res = new Field[fields.size()];
fields.toArray(res); fields.toArray(res);
if (useCaches) { if (useCaches) {
publicFields = new SoftReference<Field[]>(res); publicFields = new SoftReference<>(res);
} }
return res; return res;
} }
@ -2403,9 +2403,9 @@ public final
} }
if (useCaches) { if (useCaches) {
if (publicOnly) { if (publicOnly) {
publicConstructors = new SoftReference<Constructor<T>[]>(res); publicConstructors = new SoftReference<>(res);
} else { } else {
declaredConstructors = new SoftReference<Constructor<T>[]>(res); declaredConstructors = new SoftReference<>(res);
} }
} }
return res; return res;
@ -2440,9 +2440,9 @@ public final
res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly)); res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
if (useCaches) { if (useCaches) {
if (publicOnly) { if (publicOnly) {
declaredPublicMethods = new SoftReference<Method[]>(res); declaredPublicMethods = new SoftReference<>(res);
} else { } else {
declaredMethods = new SoftReference<Method[]>(res); declaredMethods = new SoftReference<>(res);
} }
} }
return res; return res;
@ -2598,7 +2598,7 @@ public final
methods.compactAndTrim(); methods.compactAndTrim();
res = methods.getArray(); res = methods.getArray();
if (useCaches) { if (useCaches) {
publicMethods = new SoftReference<Method[]>(res); publicMethods = new SoftReference<>(res);
} }
return res; return res;
} }
@ -2977,7 +2977,7 @@ public final
if (universe == null) if (universe == null)
throw new IllegalArgumentException( throw new IllegalArgumentException(
getName() + " is not an enum type"); getName() + " is not an enum type");
Map<String, T> m = new HashMap<String, T>(2 * universe.length); Map<String, T> m = new HashMap<>(2 * universe.length);
for (T constant : universe) for (T constant : universe)
m.put(((Enum<?>)constant).name(), constant); m.put(((Enum<?>)constant).name(), constant);
enumConstantDirectory = m; enumConstantDirectory = m;
@ -3090,7 +3090,7 @@ public final
if (superClass == null) { if (superClass == null) {
annotations = declaredAnnotations; annotations = declaredAnnotations;
} else { } else {
annotations = new HashMap<Class<? extends Annotation>, Annotation>(); annotations = new HashMap<>();
superClass.initAnnotationsIfNecessary(); superClass.initAnnotationsIfNecessary();
for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) { for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
Class<? extends Annotation> annotationClass = e.getKey(); Class<? extends Annotation> annotationClass = e.getKey();

View File

@ -247,7 +247,7 @@ public abstract class ClassLoader {
// The classes loaded by this class loader. The only purpose of this table // The classes loaded by this class loader. The only purpose of this table
// is to keep the classes from being GC'ed until the loader is GC'ed. // is to keep the classes from being GC'ed until the loader is GC'ed.
private final Vector<Class<?>> classes = new Vector<Class<?>>(); private final Vector<Class<?>> classes = new Vector<>();
// The "default" domain. Set as the default ProtectionDomain on newly // The "default" domain. Set as the default ProtectionDomain on newly
// created classes. // created classes.
@ -266,8 +266,7 @@ public abstract class ClassLoader {
// The packages defined in this class loader. Each package name is mapped // The packages defined in this class loader. Each package name is mapped
// to its corresponding Package object. // to its corresponding Package object.
// @GuardedBy("itself") // @GuardedBy("itself")
private final HashMap<String, Package> packages = private final HashMap<String, Package> packages = new HashMap<>();
new HashMap<String, Package>();
private static Void checkCreateClassLoader() { private static Void checkCreateClassLoader() {
SecurityManager security = System.getSecurityManager(); SecurityManager security = System.getSecurityManager();
@ -280,16 +279,16 @@ public abstract class ClassLoader {
private ClassLoader(Void unused, ClassLoader parent) { private ClassLoader(Void unused, ClassLoader parent) {
this.parent = parent; this.parent = parent;
if (ParallelLoaders.isRegistered(this.getClass())) { if (ParallelLoaders.isRegistered(this.getClass())) {
parallelLockMap = new ConcurrentHashMap<String, Object>(); parallelLockMap = new ConcurrentHashMap<>();
package2certs = new ConcurrentHashMap<String, Certificate[]>(); package2certs = new ConcurrentHashMap<>();
domains = domains =
Collections.synchronizedSet(new HashSet<ProtectionDomain>()); Collections.synchronizedSet(new HashSet<ProtectionDomain>());
assertionLock = new Object(); assertionLock = new Object();
} else { } else {
// no finer-grained lock; lock on the classloader instance // no finer-grained lock; lock on the classloader instance
parallelLockMap = null; parallelLockMap = null;
package2certs = new Hashtable<String, Certificate[]>(); package2certs = new Hashtable<>();
domains = new HashSet<ProtectionDomain>(); domains = new HashSet<>();
assertionLock = this; assertionLock = this;
} }
} }
@ -1182,7 +1181,7 @@ public abstract class ClassLoader {
} }
tmp[1] = findResources(name); tmp[1] = findResources(name);
return new CompoundEnumeration<URL>(tmp); return new CompoundEnumeration<>(tmp);
} }
/** /**
@ -1657,7 +1656,7 @@ public abstract class ClassLoader {
protected Package[] getPackages() { protected Package[] getPackages() {
Map<String, Package> map; Map<String, Package> map;
synchronized (packages) { synchronized (packages) {
map = new HashMap<String, Package>(packages); map = new HashMap<>(packages);
} }
Package[] pkgs; Package[] pkgs;
if (parent != null) { if (parent != null) {
@ -1764,20 +1763,17 @@ public abstract class ClassLoader {
} }
// All native library names we've loaded. // All native library names we've loaded.
private static Vector<String> loadedLibraryNames private static Vector<String> loadedLibraryNames = new Vector<>();
= new Vector<String>();
// Native libraries belonging to system classes. // Native libraries belonging to system classes.
private static Vector<NativeLibrary> systemNativeLibraries private static Vector<NativeLibrary> systemNativeLibraries
= new Vector<NativeLibrary>(); = new Vector<>();
// Native libraries associated with the class loader. // Native libraries associated with the class loader.
private Vector<NativeLibrary> nativeLibraries private Vector<NativeLibrary> nativeLibraries = new Vector<>();
= new Vector<NativeLibrary>();
// native libraries being loaded/unloaded. // native libraries being loaded/unloaded.
private static Stack<NativeLibrary> nativeLibraryContext private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>();
= new Stack<NativeLibrary>();
// The paths searched for libraries // The paths searched for libraries
private static String usr_paths[]; private static String usr_paths[];
@ -2101,8 +2097,8 @@ public abstract class ClassLoader {
* them to empty maps, effectively ignoring any present settings. * them to empty maps, effectively ignoring any present settings.
*/ */
synchronized (assertionLock) { synchronized (assertionLock) {
classAssertionStatus = new HashMap<String, Boolean>(); classAssertionStatus = new HashMap<>();
packageAssertionStatus = new HashMap<String, Boolean>(); packageAssertionStatus = new HashMap<>();
defaultAssertionStatus = false; defaultAssertionStatus = false;
} }
} }
@ -2164,8 +2160,8 @@ public abstract class ClassLoader {
private void initializeJavaAssertionMaps() { private void initializeJavaAssertionMaps() {
// assert Thread.holdsLock(assertionLock); // assert Thread.holdsLock(assertionLock);
classAssertionStatus = new HashMap<String, Boolean>(); classAssertionStatus = new HashMap<>();
packageAssertionStatus = new HashMap<String, Boolean>(); packageAssertionStatus = new HashMap<>();
AssertionStatusDirectives directives = retrieveDirectives(); AssertionStatusDirectives directives = retrieveDirectives();
for(int i = 0; i < directives.classes.length; i++) for(int i = 0; i < directives.classes.length; i++)

View File

@ -588,16 +588,13 @@ public class Package implements java.lang.reflect.AnnotatedElement {
} }
// The map of loaded system packages // The map of loaded system packages
private static Map<String, Package> pkgs private static Map<String, Package> pkgs = new HashMap<>(31);
= new HashMap<String, Package>(31);
// Maps each directory or zip file name to its corresponding url // Maps each directory or zip file name to its corresponding url
private static Map<String, URL> urls private static Map<String, URL> urls = new HashMap<>(10);
= new HashMap<String, URL>(10);
// Maps each code source url for a jar file to its manifest // Maps each code source url for a jar file to its manifest
private static Map<String, Manifest> mans private static Map<String, Manifest> mans = new HashMap<>(10);
= new HashMap<String, Manifest>(10);
private static native String getSystemPackage0(String name); private static native String getSystemPackage0(String name);
private static native String[] getSystemPackages0(); private static native String[] getSystemPackages0();

View File

@ -214,7 +214,7 @@ public final class ProcessBuilder
* @param command a string array containing the program and its arguments * @param command a string array containing the program and its arguments
*/ */
public ProcessBuilder(String... command) { public ProcessBuilder(String... command) {
this.command = new ArrayList<String>(command.length); this.command = new ArrayList<>(command.length);
for (String arg : command) for (String arg : command)
this.command.add(arg); this.command.add(arg);
} }
@ -251,7 +251,7 @@ public final class ProcessBuilder
* @return this process builder * @return this process builder
*/ */
public ProcessBuilder command(String... command) { public ProcessBuilder command(String... command) {
this.command = new ArrayList<String>(command.length); this.command = new ArrayList<>(command.length);
for (String arg : command) for (String arg : command)
this.command.add(arg); this.command.add(arg);
return this; return this;

View File

@ -2330,7 +2330,7 @@ public final class String
int off = 0; int off = 0;
int next = 0; int next = 0;
boolean limited = limit > 0; boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<String>(); ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) { while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) { if (!limited || list.size() < limit - 1) {
list.add(substring(off, next)); list.add(substring(off, next));

View File

@ -53,9 +53,9 @@ class StringCoding {
/** The cached coders for each thread */ /** The cached coders for each thread */
private final static ThreadLocal<SoftReference<StringDecoder>> decoder = private final static ThreadLocal<SoftReference<StringDecoder>> decoder =
new ThreadLocal<SoftReference<StringDecoder>>(); new ThreadLocal<>();
private final static ThreadLocal<SoftReference<StringEncoder>> encoder = private final static ThreadLocal<SoftReference<StringEncoder>> encoder =
new ThreadLocal<SoftReference<StringEncoder>>(); new ThreadLocal<>();
private static boolean warnUnsupportedCharset = true; private static boolean warnUnsupportedCharset = true;
@ -67,7 +67,7 @@ class StringCoding {
} }
private static <T> void set(ThreadLocal<SoftReference<T>> tl, T ob) { private static <T> void set(ThreadLocal<SoftReference<T>> tl, T ob) {
tl.set(new SoftReference<T>(ob)); tl.set(new SoftReference<>(ob));
} }
// Trim the given byte array to the given length // Trim the given byte array to the given length

View File

@ -1642,8 +1642,7 @@ class Thread implements Runnable {
// Get a snapshot of the list of all threads // Get a snapshot of the list of all threads
Thread[] threads = getThreads(); Thread[] threads = getThreads();
StackTraceElement[][] traces = dumpThreads(threads); StackTraceElement[][] traces = dumpThreads(threads);
Map<Thread, StackTraceElement[]> m Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
= new HashMap<Thread, StackTraceElement[]>(threads.length);
for (int i = 0; i < threads.length; i++) { for (int i = 0; i < threads.length; i++) {
StackTraceElement[] stackTrace = traces[i]; StackTraceElement[] stackTrace = traces[i];
if (stackTrace != null) { if (stackTrace != null) {
@ -1664,11 +1663,11 @@ class Thread implements Runnable {
private static class Caches { private static class Caches {
/** cache of subclass security audit results */ /** cache of subclass security audit results */
static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits = static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
new ConcurrentHashMap<WeakClassKey,Boolean>(); new ConcurrentHashMap<>();
/** queue for WeakReferences to audited subclasses */ /** queue for WeakReferences to audited subclasses */
static final ReferenceQueue<Class<?>> subclassAuditsQueue = static final ReferenceQueue<Class<?>> subclassAuditsQueue =
new ReferenceQueue<Class<?>>(); new ReferenceQueue<>();
} }
/** /**

View File

@ -828,7 +828,7 @@ public class Throwable implements Serializable {
// Use the sentinel for a zero-length list // Use the sentinel for a zero-length list
suppressed = SUPPRESSED_SENTINEL; suppressed = SUPPRESSED_SENTINEL;
} else { // Copy Throwables to new list } else { // Copy Throwables to new list
suppressed = new ArrayList<Throwable>(1); suppressed = new ArrayList<>(1);
for (Throwable t : suppressedExceptions) { for (Throwable t : suppressedExceptions) {
// Enforce constraints on suppressed exceptions in // Enforce constraints on suppressed exceptions in
// case of corrupt or malicious stream. // case of corrupt or malicious stream.
@ -911,7 +911,7 @@ public class Throwable implements Serializable {
return; return;
if (suppressedExceptions == SUPPRESSED_SENTINEL) if (suppressedExceptions == SUPPRESSED_SENTINEL)
suppressedExceptions = new ArrayList<Throwable>(1); suppressedExceptions = new ArrayList<>(1);
assert suppressedExceptions != SUPPRESSED_SENTINEL; assert suppressedExceptions != SUPPRESSED_SENTINEL;

View File

@ -794,7 +794,7 @@ public class ManagementFactory {
*/ */
public static List<Class<? extends PlatformManagedObject>> getAllPlatformMXBeanInterfaces() { public static List<Class<? extends PlatformManagedObject>> getAllPlatformMXBeanInterfaces() {
List<Class<? extends PlatformManagedObject>> result = List<Class<? extends PlatformManagedObject>> result =
new ArrayList<Class<? extends PlatformManagedObject>>(); new ArrayList<>();
for (PlatformComponent component: PlatformComponent.values()) { for (PlatformComponent component: PlatformComponent.values()) {
result.add(component.getMXBeanInterface()); result.add(component.getMXBeanInterface());
} }

View File

@ -267,7 +267,7 @@ enum PlatformComponent {
List<T> getGcMXBeanList(Class<T> gcMXBeanIntf) { List<T> getGcMXBeanList(Class<T> gcMXBeanIntf) {
List<GarbageCollectorMXBean> list = List<GarbageCollectorMXBean> list =
ManagementFactoryHelper.getGarbageCollectorMXBeans(); ManagementFactoryHelper.getGarbageCollectorMXBeans();
List<T> result = new ArrayList<T>(list.size()); List<T> result = new ArrayList<>(list.size());
for (GarbageCollectorMXBean m : list) { for (GarbageCollectorMXBean m : list) {
if (gcMXBeanIntf.isInstance(m)) { if (gcMXBeanIntf.isInstance(m)) {
result.add(gcMXBeanIntf.cast(m)); result.add(gcMXBeanIntf.cast(m));
@ -330,7 +330,7 @@ enum PlatformComponent {
} }
private static Set<String> keyProperties(String... keyNames) { private static Set<String> keyProperties(String... keyNames) {
Set<String> set = new HashSet<String>(); Set<String> set = new HashSet<>();
set.add("type"); set.add("type");
for (String s : keyNames) { for (String s : keyNames) {
set.add(s); set.add(s);
@ -364,7 +364,7 @@ enum PlatformComponent {
List<T> getMXBeans(MBeanServerConnection mbs, Class<T> mxbeanInterface) List<T> getMXBeans(MBeanServerConnection mbs, Class<T> mxbeanInterface)
throws java.io.IOException throws java.io.IOException
{ {
List<T> result = new ArrayList<T>(); List<T> result = new ArrayList<>();
for (ObjectName on : getObjectNames(mbs)) { for (ObjectName on : getObjectNames(mbs)) {
result.add(ManagementFactory. result.add(ManagementFactory.
newPlatformMXBeanProxy(mbs, newPlatformMXBeanProxy(mbs,

View File

@ -144,7 +144,7 @@ public final
// which implicitly requires that new java.lang.reflect // which implicitly requires that new java.lang.reflect
// objects be fabricated for each reflective call on Class // objects be fabricated for each reflective call on Class
// objects.) // objects.)
Constructor<T> res = new Constructor<T>(clazz, Constructor<T> res = new Constructor<>(clazz,
parameterTypes, parameterTypes,
exceptionTypes, modifiers, slot, exceptionTypes, modifiers, slot,
signature, signature,

View File

@ -232,7 +232,7 @@ public class Proxy implements java.io.Serializable {
/** maps a class loader to the proxy class cache for that loader */ /** maps a class loader to the proxy class cache for that loader */
private static Map<ClassLoader, Map<List<String>, Object>> loaderToCache private static Map<ClassLoader, Map<List<String>, Object>> loaderToCache
= new WeakHashMap<ClassLoader, Map<List<String>, Object>>(); = new WeakHashMap<>();
/** marks that a particular proxy class is currently being generated */ /** marks that a particular proxy class is currently being generated */
private static Object pendingGenerationMarker = new Object(); private static Object pendingGenerationMarker = new Object();
@ -356,7 +356,7 @@ public class Proxy implements java.io.Serializable {
String[] interfaceNames = new String[interfaces.length]; String[] interfaceNames = new String[interfaces.length];
// for detecting duplicates // for detecting duplicates
Set<Class<?>> interfaceSet = new HashSet<Class<?>>(); Set<Class<?>> interfaceSet = new HashSet<>();
for (int i = 0; i < interfaces.length; i++) { for (int i = 0; i < interfaces.length; i++) {
/* /*
@ -413,7 +413,7 @@ public class Proxy implements java.io.Serializable {
synchronized (loaderToCache) { synchronized (loaderToCache) {
cache = loaderToCache.get(loader); cache = loaderToCache.get(loader);
if (cache == null) { if (cache == null) {
cache = new HashMap<List<String>, Object>(); cache = new HashMap<>();
loaderToCache.put(loader, cache); loaderToCache.put(loader, cache);
} }
/* /*

View File

@ -84,7 +84,7 @@ class ReflectAccess implements sun.reflect.LangReflectAccess {
byte[] annotations, byte[] annotations,
byte[] parameterAnnotations) byte[] parameterAnnotations)
{ {
return new Constructor<T>(declaringClass, return new Constructor<>(declaringClass,
parameterTypes, parameterTypes,
checkedExceptions, checkedExceptions,
modifiers, modifiers,

View File

@ -364,7 +364,7 @@ public class DriverManager {
* @return the list of JDBC Drivers loaded by the caller's class loader * @return the list of JDBC Drivers loaded by the caller's class loader
*/ */
public static java.util.Enumeration<Driver> getDrivers() { public static java.util.Enumeration<Driver> getDrivers() {
java.util.Vector<Driver> result = new java.util.Vector<Driver>(); java.util.Vector<Driver> result = new java.util.Vector<>();
java.util.Vector drivers = null; java.util.Vector drivers = null;
if (!initialized) { if (!initialized) {

View File

@ -577,7 +577,7 @@ public interface Statement extends Wrapper, AutoCloseable {
* *
* @see #addBatch * @see #addBatch
* @see DatabaseMetaData#supportsBatchUpdates * @see DatabaseMetaData#supportsBatchUpdates
* @since 1.3 * @since 1.2
*/ */
int[] executeBatch() throws SQLException; int[] executeBatch() throws SQLException;

View File

@ -93,73 +93,65 @@ import java.util.Locale;
* currency * currency
* percent * percent
* <i>SubformatPattern</i> * <i>SubformatPattern</i>
*
* <i>String:</i>
* <i>StringPart<sub>opt</sub></i>
* <i>String</i> <i>StringPart</i>
*
* <i>StringPart:</i>
* ''
* ' <i>QuotedString</i> '
* <i>UnquotedString</i>
*
* <i>SubformatPattern:</i>
* <i>SubformatPatternPart<sub>opt</sub></i>
* <i>SubformatPattern</i> <i>SubformatPatternPart</i>
*
* <i>SubFormatPatternPart:</i>
* ' <i>QuotedPattern</i> '
* <i>UnquotedPattern</i>
* </pre></blockquote> * </pre></blockquote>
* *
* <p> * <p>Within a <i>String</i>, a pair of single quotes can be used to
* Within a <i>String</i>, <code>"''"</code> represents a single * quote any arbitrary characters except single quotes. For example,
* quote. A <i>QuotedString</i> can contain arbitrary characters * pattern string <code>"'{0}'"</code> represents string
* except single quotes; the surrounding single quotes are removed. * <code>"{0}"</code>, not a <i>FormatElement</i>. A single quote itself
* An <i>UnquotedString</i> can contain arbitrary characters * must be represented by doubled single quotes {@code ''} throughout a
* except single quotes and left curly brackets. Thus, a string that * <i>String</i>. For example, pattern string <code>"'{''}'"</code> is
* should result in the formatted message "'{0}'" can be written as * interpreted as a sequence of <code>'{</code> (start of quoting and a
* <code>"'''{'0}''"</code> or <code>"'''{0}'''"</code>. * left curly brace), <code>''</code> (a single quote), and
* <p> * <code>}'</code> (a right curly brace and end of quoting),
* Within a <i>SubformatPattern</i>, different rules apply. * <em>not</em> <code>'{'</code> and <code>'}'</code> (quoted left and
* A <i>QuotedPattern</i> can contain arbitrary characters * right curly braces): representing string <code>"{'}"</code>,
* except single quotes; but the surrounding single quotes are * <em>not</em> <code>"{}"</code>.
* <strong>not</strong> removed, so they may be interpreted by the *
* subformat. For example, <code>"{1,number,$'#',##}"</code> will * <p>A <i>SubformatPattern</i> is interpreted by its corresponding
* produce a number format with the pound-sign quoted, with a result * subformat, and subformat-dependent pattern rules apply. For example,
* such as: "$#31,45". * pattern string <code>"{1,number,<u>$'#',##</u>}"</code>
* An <i>UnquotedPattern</i> can contain arbitrary characters * (<i>SubformatPattern</i> with underline) will produce a number format
* except single quotes, but curly braces within it must be balanced. * with the pound-sign quoted, with a result such as: {@code
* For example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code> * "$#31,45"}. Refer to each {@code Format} subclass documentation for
* are valid subformat patterns, but <code>"ab {0'}' de"</code> and * details.
* <code>"ab } de"</code> are not. *
* <p>Any unmatched quote is treated as closed at the end of the given
* pattern. For example, pattern string {@code "'{0}"} is treated as
* pattern {@code "'{0}'"}.
*
* <p>Any curly braces within an unquoted pattern must be balanced. For
* example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code> are
* valid patterns, but <code>"ab {0'}' de"</code>, <code>"ab } de"</code>
* and <code>"''{''"</code> are not.
*
* <p> * <p>
* <dl><dt><b>Warning:</b><dd>The rules for using quotes within message * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
* format patterns unfortunately have shown to be somewhat confusing. * format patterns unfortunately have shown to be somewhat confusing.
* In particular, it isn't always obvious to localizers whether single * In particular, it isn't always obvious to localizers whether single
* quotes need to be doubled or not. Make sure to inform localizers about * quotes need to be doubled or not. Make sure to inform localizers about
* the rules, and tell them (for example, by using comments in resource * the rules, and tell them (for example, by using comments in resource
* bundle source files) which strings will be processed by MessageFormat. * bundle source files) which strings will be processed by {@code MessageFormat}.
* Note that localizers may need to use single quotes in translated * Note that localizers may need to use single quotes in translated
* strings where the original version doesn't have them. * strings where the original version doesn't have them.
* </dl> * </dl>
* <p> * <p>
* The <i>ArgumentIndex</i> value is a non-negative integer written * The <i>ArgumentIndex</i> value is a non-negative integer written
* using the digits '0' through '9', and represents an index into the * using the digits {@code '0'} through {@code '9'}, and represents an index into the
* <code>arguments</code> array passed to the <code>format</code> methods * {@code arguments} array passed to the {@code format} methods
* or the result array returned by the <code>parse</code> methods. * or the result array returned by the {@code parse} methods.
* <p> * <p>
* The <i>FormatType</i> and <i>FormatStyle</i> values are used to create * The <i>FormatType</i> and <i>FormatStyle</i> values are used to create
* a <code>Format</code> instance for the format element. The following * a {@code Format} instance for the format element. The following
* table shows how the values map to Format instances. Combinations not * table shows how the values map to {@code Format} instances. Combinations not
* shown in the table are illegal. A <i>SubformatPattern</i> must * shown in the table are illegal. A <i>SubformatPattern</i> must
* be a valid pattern string for the Format subclass used. * be a valid pattern string for the {@code Format} subclass used.
* <p> * <p>
* <table border=1 summary="Shows how FormatType and FormatStyle values map to Format instances"> * <table border=1 summary="Shows how FormatType and FormatStyle values map to Format instances">
* <tr> * <tr>
* <th id="ft">Format Type * <th id="ft" class="TableHeadingColor">FormatType
* <th id="fs">Format Style * <th id="fs" class="TableHeadingColor">FormatStyle
* <th id="sc">Subformat Created * <th id="sc" class="TableHeadingColor">Subformat Created
* <tr> * <tr>
* <td headers="ft"><i>(none)</i> * <td headers="ft"><i>(none)</i>
* <td headers="fs"><i>(none)</i> * <td headers="fs"><i>(none)</i>
@ -167,61 +159,61 @@ import java.util.Locale;
* <tr> * <tr>
* <td headers="ft" rowspan=5><code>number</code> * <td headers="ft" rowspan=5><code>number</code>
* <td headers="fs"><i>(none)</i> * <td headers="fs"><i>(none)</i>
* <td headers="sc"><code>NumberFormat.getInstance(getLocale())</code> * <td headers="sc">{@link NumberFormat#getInstance(Locale) NumberFormat.getInstance}{@code (getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>integer</code> * <td headers="fs"><code>integer</code>
* <td headers="sc"><code>NumberFormat.getIntegerInstance(getLocale())</code> * <td headers="sc">{@link NumberFormat#getIntegerInstance(Locale) NumberFormat.getIntegerInstance}{@code (getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>currency</code> * <td headers="fs"><code>currency</code>
* <td headers="sc"><code>NumberFormat.getCurrencyInstance(getLocale())</code> * <td headers="sc">{@link NumberFormat#getCurrencyInstance(Locale) NumberFormat.getCurrencyInstance}{@code (getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>percent</code> * <td headers="fs"><code>percent</code>
* <td headers="sc"><code>NumberFormat.getPercentInstance(getLocale())</code> * <td headers="sc">{@link NumberFormat#getPercentInstance(Locale) NumberFormat.getPercentInstance}{@code (getLocale())}
* <tr> * <tr>
* <td headers="fs"><i>SubformatPattern</i> * <td headers="fs"><i>SubformatPattern</i>
* <td headers="sc"><code>new DecimalFormat(subformatPattern, DecimalFormatSymbols.getInstance(getLocale()))</code> * <td headers="sc">{@code new} {@link DecimalFormat#DecimalFormat(String,DecimalFormatSymbols) DecimalFormat}{@code (subformatPattern,} {@link DecimalFormatSymbols#getInstance(Locale) DecimalFormatSymbols.getInstance}{@code (getLocale()))}
* <tr> * <tr>
* <td headers="ft" rowspan=6><code>date</code> * <td headers="ft" rowspan=6><code>date</code>
* <td headers="fs"><i>(none)</i> * <td headers="fs"><i>(none)</i>
* <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())</code> * <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>short</code> * <td headers="fs"><code>short</code>
* <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.SHORT, getLocale())</code> * <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>medium</code> * <td headers="fs"><code>medium</code>
* <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())</code> * <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>long</code> * <td headers="fs"><code>long</code>
* <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.LONG, getLocale())</code> * <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>full</code> * <td headers="fs"><code>full</code>
* <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.FULL, getLocale())</code> * <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><i>SubformatPattern</i> * <td headers="fs"><i>SubformatPattern</i>
* <td headers="sc"><code>new SimpleDateFormat(subformatPattern, getLocale())</code> * <td headers="sc">{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
* <tr> * <tr>
* <td headers="ft" rowspan=6><code>time</code> * <td headers="ft" rowspan=6><code>time</code>
* <td headers="fs"><i>(none)</i> * <td headers="fs"><i>(none)</i>
* <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())</code> * <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>short</code> * <td headers="fs"><code>short</code>
* <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.SHORT, getLocale())</code> * <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>medium</code> * <td headers="fs"><code>medium</code>
* <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())</code> * <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>long</code> * <td headers="fs"><code>long</code>
* <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.LONG, getLocale())</code> * <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><code>full</code> * <td headers="fs"><code>full</code>
* <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.FULL, getLocale())</code> * <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
* <tr> * <tr>
* <td headers="fs"><i>SubformatPattern</i> * <td headers="fs"><i>SubformatPattern</i>
* <td headers="sc"><code>new SimpleDateFormat(subformatPattern, getLocale())</code> * <td headers="sc">{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
* <tr> * <tr>
* <td headers="ft"><code>choice</code> * <td headers="ft"><code>choice</code>
* <td headers="fs"><i>SubformatPattern</i> * <td headers="fs"><i>SubformatPattern</i>
* <td headers="sc"><code>new ChoiceFormat(subformatPattern)</code> * <td headers="sc">{@code new} {@link ChoiceFormat#ChoiceFormat(String) ChoiceFormat}{@code (subformatPattern)}
* </table> * </table>
* <p> * <p>
* *
@ -321,7 +313,7 @@ import java.util.Locale;
* </pre></blockquote> * </pre></blockquote>
* *
* <p> * <p>
* Likewise, parsing with a MessageFormat object using patterns containing * Likewise, parsing with a {@code MessageFormat} object using patterns containing
* multiple occurrences of the same argument would return the last match. For * multiple occurrences of the same argument would return the last match. For
* example, * example,
* <blockquote><pre> * <blockquote><pre>
@ -343,7 +335,11 @@ import java.util.Locale;
* @see Format * @see Format
* @see NumberFormat * @see NumberFormat
* @see DecimalFormat * @see DecimalFormat
* @see DecimalFormatSymbols
* @see ChoiceFormat * @see ChoiceFormat
* @see DateFormat
* @see SimpleDateFormat
*
* @author Mark Davis * @author Mark Davis
*/ */
@ -427,18 +423,19 @@ public class MessageFormat extends Format {
* @exception IllegalArgumentException if the pattern is invalid * @exception IllegalArgumentException if the pattern is invalid
*/ */
public void applyPattern(String pattern) { public void applyPattern(String pattern) {
StringBuffer[] segments = new StringBuffer[4]; StringBuilder[] segments = new StringBuilder[4];
for (int i = 0; i < segments.length; ++i) { // Allocate only segments[SEG_RAW] here. The rest are
segments[i] = new StringBuffer(); // allocated on demand.
} segments[SEG_RAW] = new StringBuilder();
int part = 0;
int part = SEG_RAW;
int formatNumber = 0; int formatNumber = 0;
boolean inQuote = false; boolean inQuote = false;
int braceStack = 0; int braceStack = 0;
maxOffset = -1; maxOffset = -1;
for (int i = 0; i < pattern.length(); ++i) { for (int i = 0; i < pattern.length(); ++i) {
char ch = pattern.charAt(i); char ch = pattern.charAt(i);
if (part == 0) { if (part == SEG_RAW) {
if (ch == '\'') { if (ch == '\'') {
if (i + 1 < pattern.length() if (i + 1 < pattern.length()
&& pattern.charAt(i+1) == '\'') { && pattern.charAt(i+1) == '\'') {
@ -448,43 +445,61 @@ public class MessageFormat extends Format {
inQuote = !inQuote; inQuote = !inQuote;
} }
} else if (ch == '{' && !inQuote) { } else if (ch == '{' && !inQuote) {
part = 1; part = SEG_INDEX;
if (segments[SEG_INDEX] == null) {
segments[SEG_INDEX] = new StringBuilder();
}
} else { } else {
segments[part].append(ch); segments[part].append(ch);
} }
} else if (inQuote) { // just copy quotes in parts } else {
segments[part].append(ch); if (inQuote) { // just copy quotes in parts
if (ch == '\'') {
inQuote = false;
}
} else {
switch (ch) {
case ',':
if (part < 3)
part += 1;
else
segments[part].append(ch);
break;
case '{':
++braceStack;
segments[part].append(ch); segments[part].append(ch);
break; if (ch == '\'') {
case '}': inQuote = false;
if (braceStack == 0) { }
part = 0; } else {
makeFormat(i, formatNumber, segments); switch (ch) {
formatNumber++; case ',':
} else { if (part < SEG_MODIFIER) {
--braceStack; if (segments[++part] == null) {
segments[part].append(ch); segments[part] = new StringBuilder();
}
} else {
segments[part].append(ch);
}
break;
case '{':
++braceStack;
segments[part].append(ch);
break;
case '}':
if (braceStack == 0) {
part = SEG_RAW;
makeFormat(i, formatNumber, segments);
formatNumber++;
// throw away other segments
segments[SEG_INDEX] = null;
segments[SEG_TYPE] = null;
segments[SEG_MODIFIER] = null;
} else {
--braceStack;
segments[part].append(ch);
}
break;
case ' ':
// Skip any leading space chars for SEG_TYPE.
if (part != SEG_TYPE || segments[SEG_TYPE].length() > 0) {
segments[part].append(ch);
}
break;
case '\'':
inQuote = true;
// fall through, so we keep quotes in other parts
default:
segments[part].append(ch);
break;
} }
break;
case '\'':
inQuote = true;
// fall through, so we keep quotes in other parts
default:
segments[part].append(ch);
break;
} }
} }
} }
@ -506,65 +521,57 @@ public class MessageFormat extends Format {
public String toPattern() { public String toPattern() {
// later, make this more extensible // later, make this more extensible
int lastOffset = 0; int lastOffset = 0;
StringBuffer result = new StringBuffer(); StringBuilder result = new StringBuilder();
for (int i = 0; i <= maxOffset; ++i) { for (int i = 0; i <= maxOffset; ++i) {
copyAndFixQuotes(pattern, lastOffset, offsets[i],result); copyAndFixQuotes(pattern, lastOffset, offsets[i], result);
lastOffset = offsets[i]; lastOffset = offsets[i];
result.append('{'); result.append('{').append(argumentNumbers[i]);
result.append(argumentNumbers[i]); Format fmt = formats[i];
if (formats[i] == null) { if (fmt == null) {
// do nothing, string format // do nothing, string format
} else if (formats[i] instanceof DecimalFormat) { } else if (fmt instanceof NumberFormat) {
if (formats[i].equals(NumberFormat.getInstance(locale))) { if (fmt.equals(NumberFormat.getInstance(locale))) {
result.append(",number"); result.append(",number");
} else if (formats[i].equals(NumberFormat.getCurrencyInstance(locale))) { } else if (fmt.equals(NumberFormat.getCurrencyInstance(locale))) {
result.append(",number,currency"); result.append(",number,currency");
} else if (formats[i].equals(NumberFormat.getPercentInstance(locale))) { } else if (fmt.equals(NumberFormat.getPercentInstance(locale))) {
result.append(",number,percent"); result.append(",number,percent");
} else if (formats[i].equals(NumberFormat.getIntegerInstance(locale))) { } else if (fmt.equals(NumberFormat.getIntegerInstance(locale))) {
result.append(",number,integer"); result.append(",number,integer");
} else { } else {
result.append(",number," + if (fmt instanceof DecimalFormat) {
((DecimalFormat)formats[i]).toPattern()); result.append(",number,").append(((DecimalFormat)fmt).toPattern());
} else if (fmt instanceof ChoiceFormat) {
result.append(",choice,").append(((ChoiceFormat)fmt).toPattern());
} else {
// UNKNOWN
}
} }
} else if (formats[i] instanceof SimpleDateFormat) { } else if (fmt instanceof DateFormat) {
if (formats[i].equals(DateFormat.getDateInstance( int index;
DateFormat.DEFAULT,locale))) { for (index = MODIFIER_DEFAULT; index < DATE_TIME_MODIFIERS.length; index++) {
result.append(",date"); DateFormat df = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[index],
} else if (formats[i].equals(DateFormat.getDateInstance( locale);
DateFormat.SHORT,locale))) { if (fmt.equals(df)) {
result.append(",date,short"); result.append(",date");
} else if (formats[i].equals(DateFormat.getDateInstance( break;
DateFormat.DEFAULT,locale))) { }
result.append(",date,medium"); df = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[index],
} else if (formats[i].equals(DateFormat.getDateInstance( locale);
DateFormat.LONG,locale))) { if (fmt.equals(df)) {
result.append(",date,long"); result.append(",time");
} else if (formats[i].equals(DateFormat.getDateInstance( break;
DateFormat.FULL,locale))) { }
result.append(",date,full"); }
} else if (formats[i].equals(DateFormat.getTimeInstance( if (index >= DATE_TIME_MODIFIERS.length) {
DateFormat.DEFAULT,locale))) { if (fmt instanceof SimpleDateFormat) {
result.append(",time"); result.append(",date,").append(((SimpleDateFormat)fmt).toPattern());
} else if (formats[i].equals(DateFormat.getTimeInstance( } else {
DateFormat.SHORT,locale))) { // UNKNOWN
result.append(",time,short"); }
} else if (formats[i].equals(DateFormat.getTimeInstance( } else if (index != MODIFIER_DEFAULT) {
DateFormat.DEFAULT,locale))) { result.append(',').append(DATE_TIME_MODIFIER_KEYWORDS[index]);
result.append(",time,medium");
} else if (formats[i].equals(DateFormat.getTimeInstance(
DateFormat.LONG,locale))) {
result.append(",time,long");
} else if (formats[i].equals(DateFormat.getTimeInstance(
DateFormat.FULL,locale))) {
result.append(",time,full");
} else {
result.append(",date,"
+ ((SimpleDateFormat)formats[i]).toPattern());
} }
} else if (formats[i] instanceof ChoiceFormat) {
result.append(",choice,"
+ ((ChoiceFormat)formats[i]).toPattern());
} else { } else {
//result.append(", unknown"); //result.append(", unknown");
} }
@ -678,7 +685,7 @@ public class MessageFormat extends Format {
* *
* @param formatElementIndex the index of a format element within the pattern * @param formatElementIndex the index of a format element within the pattern
* @param newFormat the format to use for the specified format element * @param newFormat the format to use for the specified format element
* @exception ArrayIndexOutOfBoundsException if formatElementIndex is equal to or * @exception ArrayIndexOutOfBoundsException if {@code formatElementIndex} is equal to or
* larger than the number of format elements in the pattern string * larger than the number of format elements in the pattern string
*/ */
public void setFormat(int formatElementIndex, Format newFormat) { public void setFormat(int formatElementIndex, Format newFormat) {
@ -972,7 +979,8 @@ public class MessageFormat extends Format {
if (patternOffset >= tempLength) { if (patternOffset >= tempLength) {
next = source.length(); next = source.length();
}else{ }else{
next = source.indexOf( pattern.substring(patternOffset,tempLength), sourceOffset); next = source.indexOf(pattern.substring(patternOffset, tempLength),
sourceOffset);
} }
if (next < 0) { if (next < 0) {
@ -1226,7 +1234,7 @@ public class MessageFormat extends Format {
lastOffset = offsets[i]; lastOffset = offsets[i];
int argumentNumber = argumentNumbers[i]; int argumentNumber = argumentNumbers[i];
if (arguments == null || argumentNumber >= arguments.length) { if (arguments == null || argumentNumber >= arguments.length) {
result.append("{" + argumentNumber + "}"); result.append('{').append(argumentNumber).append('}');
continue; continue;
} }
// int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3); // int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3);
@ -1338,25 +1346,83 @@ public class MessageFormat extends Format {
} }
} }
private static final String[] typeList = // Indices for segments
{"", "", "number", "", "date", "", "time", "", "choice"}; private static final int SEG_RAW = 0;
private static final String[] modifierList = private static final int SEG_INDEX = 1;
{"", "", "currency", "", "percent", "", "integer"}; private static final int SEG_TYPE = 2;
private static final String[] dateModifierList = private static final int SEG_MODIFIER = 3; // modifier or subformat
{"", "", "short", "", "medium", "", "long", "", "full"};
// Indices for type keywords
private static final int TYPE_NULL = 0;
private static final int TYPE_NUMBER = 1;
private static final int TYPE_DATE = 2;
private static final int TYPE_TIME = 3;
private static final int TYPE_CHOICE = 4;
private static final String[] TYPE_KEYWORDS = {
"",
"number",
"date",
"time",
"choice"
};
// Indices for number modifiers
private static final int MODIFIER_DEFAULT = 0; // common in number and date-time
private static final int MODIFIER_CURRENCY = 1;
private static final int MODIFIER_PERCENT = 2;
private static final int MODIFIER_INTEGER = 3;
private static final String[] NUMBER_MODIFIER_KEYWORDS = {
"",
"currency",
"percent",
"integer"
};
// Indices for date-time modifiers
private static final int MODIFIER_SHORT = 1;
private static final int MODIFIER_MEDIUM = 2;
private static final int MODIFIER_LONG = 3;
private static final int MODIFIER_FULL = 4;
private static final String[] DATE_TIME_MODIFIER_KEYWORDS = {
"",
"short",
"medium",
"long",
"full"
};
// Date-time style values corresponding to the date-time modifiers.
private static final int[] DATE_TIME_MODIFIERS = {
DateFormat.DEFAULT,
DateFormat.SHORT,
DateFormat.MEDIUM,
DateFormat.LONG,
DateFormat.FULL,
};
private void makeFormat(int position, int offsetNumber, private void makeFormat(int position, int offsetNumber,
StringBuffer[] segments) StringBuilder[] textSegments)
{ {
String[] segments = new String[textSegments.length];
for (int i = 0; i < textSegments.length; i++) {
StringBuilder oneseg = textSegments[i];
segments[i] = (oneseg != null) ? oneseg.toString() : "";
}
// get the argument number // get the argument number
int argumentNumber; int argumentNumber;
try { try {
argumentNumber = Integer.parseInt(segments[1].toString()); // always unlocalized! argumentNumber = Integer.parseInt(segments[SEG_INDEX]); // always unlocalized!
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
throw new IllegalArgumentException("can't parse argument number: " + segments[1]); throw new IllegalArgumentException("can't parse argument number: "
+ segments[SEG_INDEX], e);
} }
if (argumentNumber < 0) { if (argumentNumber < 0) {
throw new IllegalArgumentException("negative argument number: " + argumentNumber); throw new IllegalArgumentException("negative argument number: "
+ argumentNumber);
} }
// resize format information arrays if necessary // resize format information arrays if necessary
@ -1374,120 +1440,129 @@ public class MessageFormat extends Format {
} }
int oldMaxOffset = maxOffset; int oldMaxOffset = maxOffset;
maxOffset = offsetNumber; maxOffset = offsetNumber;
offsets[offsetNumber] = segments[0].length(); offsets[offsetNumber] = segments[SEG_RAW].length();
argumentNumbers[offsetNumber] = argumentNumber; argumentNumbers[offsetNumber] = argumentNumber;
// now get the format // now get the format
Format newFormat = null; Format newFormat = null;
switch (findKeyword(segments[2].toString(), typeList)) { if (segments[SEG_TYPE].length() != 0) {
case 0: int type = findKeyword(segments[SEG_TYPE], TYPE_KEYWORDS);
break; switch (type) {
case 1: case 2:// number case TYPE_NULL:
switch (findKeyword(segments[3].toString(), modifierList)) { // Type "" is allowed. e.g., "{0,}", "{0,,}", and "{0,,#}"
case 0: // default; // are treated as "{0}".
newFormat = NumberFormat.getInstance(locale);
break; break;
case 1: case 2:// currency
newFormat = NumberFormat.getCurrencyInstance(locale); case TYPE_NUMBER:
switch (findKeyword(segments[SEG_MODIFIER], NUMBER_MODIFIER_KEYWORDS)) {
case MODIFIER_DEFAULT:
newFormat = NumberFormat.getInstance(locale);
break;
case MODIFIER_CURRENCY:
newFormat = NumberFormat.getCurrencyInstance(locale);
break;
case MODIFIER_PERCENT:
newFormat = NumberFormat.getPercentInstance(locale);
break;
case MODIFIER_INTEGER:
newFormat = NumberFormat.getIntegerInstance(locale);
break;
default: // DecimalFormat pattern
try {
newFormat = new DecimalFormat(segments[SEG_MODIFIER],
DecimalFormatSymbols.getInstance(locale));
} catch (IllegalArgumentException e) {
maxOffset = oldMaxOffset;
throw e;
}
break;
}
break; break;
case 3: case 4:// percent
newFormat = NumberFormat.getPercentInstance(locale); case TYPE_DATE:
case TYPE_TIME:
int mod = findKeyword(segments[SEG_MODIFIER], DATE_TIME_MODIFIER_KEYWORDS);
if (mod >= 0 && mod < DATE_TIME_MODIFIER_KEYWORDS.length) {
if (type == TYPE_DATE) {
newFormat = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[mod],
locale);
} else {
newFormat = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[mod],
locale);
}
} else {
// SimpleDateFormat pattern
try {
newFormat = new SimpleDateFormat(segments[SEG_MODIFIER], locale);
} catch (IllegalArgumentException e) {
maxOffset = oldMaxOffset;
throw e;
}
}
break; break;
case 5: case 6:// integer
newFormat = NumberFormat.getIntegerInstance(locale); case TYPE_CHOICE:
break; try {
default: // pattern // ChoiceFormat pattern
newFormat = new DecimalFormat(segments[3].toString(), DecimalFormatSymbols.getInstance(locale)); newFormat = new ChoiceFormat(segments[SEG_MODIFIER]);
break; } catch (Exception e) {
} maxOffset = oldMaxOffset;
break; throw new IllegalArgumentException("Choice Pattern incorrect: "
case 3: case 4: // date + segments[SEG_MODIFIER], e);
switch (findKeyword(segments[3].toString(), dateModifierList)) { }
case 0: // default
newFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
break;
case 1: case 2: // short
newFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
break;
case 3: case 4: // medium
newFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
break;
case 5: case 6: // long
newFormat = DateFormat.getDateInstance(DateFormat.LONG, locale);
break;
case 7: case 8: // full
newFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
break; break;
default: default:
newFormat = new SimpleDateFormat(segments[3].toString(), locale);
break;
}
break;
case 5: case 6:// time
switch (findKeyword(segments[3].toString(), dateModifierList)) {
case 0: // default
newFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
break;
case 1: case 2: // short
newFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
break;
case 3: case 4: // medium
newFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
break;
case 5: case 6: // long
newFormat = DateFormat.getTimeInstance(DateFormat.LONG, locale);
break;
case 7: case 8: // full
newFormat = DateFormat.getTimeInstance(DateFormat.FULL, locale);
break;
default:
newFormat = new SimpleDateFormat(segments[3].toString(), locale);
break;
}
break;
case 7: case 8:// choice
try {
newFormat = new ChoiceFormat(segments[3].toString());
} catch (Exception e) {
maxOffset = oldMaxOffset; maxOffset = oldMaxOffset;
throw new IllegalArgumentException( throw new IllegalArgumentException("unknown format type: " +
"Choice Pattern incorrect"); segments[SEG_TYPE]);
} }
break;
default:
maxOffset = oldMaxOffset;
throw new IllegalArgumentException("unknown format type: " +
segments[2].toString());
} }
formats[offsetNumber] = newFormat; formats[offsetNumber] = newFormat;
segments[1].setLength(0); // throw away other segments
segments[2].setLength(0);
segments[3].setLength(0);
} }
private static final int findKeyword(String s, String[] list) { private static final int findKeyword(String s, String[] list) {
s = s.trim().toLowerCase();
for (int i = 0; i < list.length; ++i) { for (int i = 0; i < list.length; ++i) {
if (s.equals(list[i])) if (s.equals(list[i]))
return i; return i;
} }
// Try trimmed lowercase.
String ls = s.trim().toLowerCase(Locale.ROOT);
if (ls != s) {
for (int i = 0; i < list.length; ++i) {
if (ls.equals(list[i]))
return i;
}
}
return -1; return -1;
} }
private static final void copyAndFixQuotes( private static final void copyAndFixQuotes(String source, int start, int end,
String source, int start, int end, StringBuffer target) { StringBuilder target) {
boolean quoted = false;
for (int i = start; i < end; ++i) { for (int i = start; i < end; ++i) {
char ch = source.charAt(i); char ch = source.charAt(i);
if (ch == '{') { if (ch == '{') {
target.append("'{'"); if (!quoted) {
} else if (ch == '}') { target.append('\'');
target.append("'}'"); quoted = true;
}
target.append(ch);
} else if (ch == '\'') { } else if (ch == '\'') {
target.append("''"); target.append("''");
} else { } else {
if (quoted) {
target.append('\'');
quoted = false;
}
target.append(ch); target.append(ch);
} }
} }
if (quoted) {
target.append('\'');
}
} }
/** /**

View File

@ -1662,6 +1662,81 @@ public class SimpleDateFormat extends DateFormat {
return 0; return 0;
} }
/**
* Parses numeric forms of time zone offset, such as "hh:mm", and
* sets calb to the parsed value.
*
* @param text the text to be parsed
* @param start the character position to start parsing
* @param sign 1: positive; -1: negative
* @param count 0: 'Z' or "GMT+hh:mm" parsing; 1 - 3: the number of 'X's
* @param colon true - colon required between hh and mm; false - no colon required
* @param calb a CalendarBuilder in which the parsed value is stored
* @return updated parsed position, or its negative value to indicate a parsing error
*/
private int subParseNumericZone(String text, int start, int sign, int count,
boolean colon, CalendarBuilder calb) {
int index = start;
parse:
try {
char c = text.charAt(index++);
// Parse hh
int hours;
if (!isDigit(c)) {
break parse;
}
hours = c - '0';
c = text.charAt(index++);
if (isDigit(c)) {
hours = hours * 10 + (c - '0');
} else {
// If no colon in RFC 822 or 'X' (ISO), two digits are
// required.
if (count > 0 || !colon) {
break parse;
}
--index;
}
if (hours > 23) {
break parse;
}
int minutes = 0;
if (count != 1) {
// Proceed with parsing mm
c = text.charAt(index++);
if (colon) {
if (c != ':') {
break parse;
}
c = text.charAt(index++);
}
if (!isDigit(c)) {
break parse;
}
minutes = c - '0';
c = text.charAt(index++);
if (!isDigit(c)) {
break parse;
}
minutes = minutes * 10 + (c - '0');
if (minutes > 59) {
break parse;
}
}
minutes += hours * 60;
calb.set(Calendar.ZONE_OFFSET, minutes * MILLIS_PER_MINUTE * sign)
.set(Calendar.DST_OFFSET, 0);
return index;
} catch (IndexOutOfBoundsException e) {
}
return 1 - index; // -(index - 1)
}
private boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
/** /**
* Private member function that converts the parsed date strings into * Private member function that converts the parsed date strings into
* timeFields. Returns -start (for ParsePosition) if failed. * timeFields. Returns -start (for ParsePosition) if failed.
@ -1907,248 +1982,95 @@ public class SimpleDateFormat extends DateFormat {
case PATTERN_ZONE_NAME: // 'z' case PATTERN_ZONE_NAME: // 'z'
case PATTERN_ZONE_VALUE: // 'Z' case PATTERN_ZONE_VALUE: // 'Z'
// First try to parse generic forms such as GMT-07:00. Do this first
// in case localized TimeZoneNames contains the string "GMT"
// for a zone; in that case, we don't want to match the first three
// characters of GMT+/-hh:mm etc.
{ {
int sign = 0; int sign = 0;
int offset; try {
char c = text.charAt(pos.index);
// For time zones that have no known names, look for strings if (c == '+') {
// of the form: sign = 1;
// GMT[+-]hours:minutes or } else if (c == '-') {
// GMT. sign = -1;
if ((text.length() - start) >= GMT.length() &&
text.regionMatches(true, start, GMT, 0, GMT.length())) {
int num;
calb.set(Calendar.DST_OFFSET, 0);
pos.index = start + GMT.length();
try { // try-catch for "GMT" only time zone string
char c = text.charAt(pos.index);
if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
}
} }
catch(StringIndexOutOfBoundsException e) {} if (sign == 0) {
// Try parsing a custom time zone "GMT+hh:mm" or "GMT".
if ((c == 'G' || c == 'g')
&& (text.length() - start) >= GMT.length()
&& text.regionMatches(true, start, GMT, 0, GMT.length())) {
pos.index = start + GMT.length();
if (sign == 0) { /* "GMT" without offset */ if ((text.length() - pos.index) > 0) {
calb.set(Calendar.ZONE_OFFSET, 0); c = text.charAt(pos.index);
return pos.index; if (c == '+') {
} sign = 1;
} else if (c == '-') {
// Look for hours. sign = -1;
try { }
char c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
num = c - '0';
if (text.charAt(++pos.index) != ':') {
c = text.charAt(pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
} }
num *= 10;
num += c - '0';
pos.index++;
}
if (num > 23) {
--pos.index;
break parsing;
}
if (text.charAt(pos.index) != ':') {
break parsing;
}
// Look for minutes. if (sign == 0) { /* "GMT" without offset */
offset = num * 60; calb.set(Calendar.ZONE_OFFSET, 0)
c = text.charAt(++pos.index); .set(Calendar.DST_OFFSET, 0);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */ return pos.index;
break parsing; }
}
num = c - '0';
c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
num *= 10;
num += c - '0';
if (num > 59) { // Parse the rest as "hh:mm"
break parsing; int i = subParseNumericZone(text, ++pos.index,
} sign, 0, true, calb);
} catch (StringIndexOutOfBoundsException e) { if (i > 0) {
break parsing;
}
offset += num;
// Fall through for final processing below of 'offset' and 'sign'.
} else {
// If the first character is a sign, look for numeric timezones of
// the form [+-]hhmm as specified by RFC 822. Otherwise, check
// for named time zones by looking through the locale data from
// the TimeZoneNames strings.
try {
char c = text.charAt(pos.index);
if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
} else {
// Try parsing the text as a time zone name (abbr).
int i = subParseZoneString(text, pos.index, calb);
if (i != 0) {
return i; return i;
} }
break parsing; pos.index = -i;
} else {
// Try parsing the text as a time zone
// name or abbreviation.
int i = subParseZoneString(text, pos.index, calb);
if (i > 0) {
return i;
}
pos.index = -i;
} }
} else {
// Parse the text as an RFC 822 time zone string. This code is // Parse the rest as "hhmm" (RFC 822)
// actually a little more permissive than RFC 822. It will int i = subParseNumericZone(text, ++pos.index,
// try to do its best with numbers that aren't strictly 4 sign, 0, false, calb);
// digits long. if (i > 0) {
return i;
// Look for hh.
int hours = 0;
c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
} }
hours = c - '0'; pos.index = -i;
c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
hours *= 10;
hours += c - '0';
if (hours > 23) {
break parsing;
}
// Look for mm.
int minutes = 0;
c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
minutes = c - '0';
c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
minutes *= 10;
minutes += c - '0';
if (minutes > 59) {
break parsing;
}
offset = hours * 60 + minutes;
} catch (StringIndexOutOfBoundsException e) {
break parsing;
} }
} } catch (IndexOutOfBoundsException e) {
// Do the final processing for both of the above cases. We only
// arrive here if the form GMT+/-... or an RFC 822 form was seen.
if (sign != 0) {
offset *= MILLIS_PER_MINUTE * sign;
calb.set(Calendar.ZONE_OFFSET, offset).set(Calendar.DST_OFFSET, 0);
return ++pos.index;
} }
} }
break parsing; break parsing;
case PATTERN_ISO_ZONE: // 'X' case PATTERN_ISO_ZONE: // 'X'
{ {
int sign = 0; if ((text.length() - pos.index) <= 0) {
int offset = 0; break parsing;
iso8601: {
try {
char c = text.charAt(pos.index);
if (c == 'Z') {
calb.set(Calendar.ZONE_OFFSET, 0).set(Calendar.DST_OFFSET, 0);
return ++pos.index;
}
// parse text as "+/-hh[[:]mm]" based on count
if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
}
// Look for hh.
int hours = 0;
c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
hours = c - '0';
c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
hours *= 10;
hours += c - '0';
if (hours > 23) {
break parsing;
}
if (count == 1) { // "X"
offset = hours * 60;
break iso8601;
}
c = text.charAt(++pos.index);
// Skip ':' if "XXX"
if (c == ':') {
if (count == 2) {
break parsing;
}
c = text.charAt(++pos.index);
} else {
if (count == 3) {
// missing ':'
break parsing;
}
}
// Look for mm.
int minutes = 0;
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
minutes = c - '0';
c = text.charAt(++pos.index);
if (c < '0' || c > '9') { /* must be from '0' to '9'. */
break parsing;
}
minutes *= 10;
minutes += c - '0';
if (minutes > 59) {
break parsing;
}
offset = hours * 60 + minutes;
} catch (StringIndexOutOfBoundsException e) {
break parsing;
}
} }
// Do the final processing for both of the above cases. We only int sign = 0;
// arrive here if the form GMT+/-... or an RFC 822 form was seen. char c = text.charAt(pos.index);
if (sign != 0) { if (c == 'Z') {
offset *= MILLIS_PER_MINUTE * sign; calb.set(Calendar.ZONE_OFFSET, 0).set(Calendar.DST_OFFSET, 0);
calb.set(Calendar.ZONE_OFFSET, offset).set(Calendar.DST_OFFSET, 0);
return ++pos.index; return ++pos.index;
} }
// parse text as "+/-hh[[:]mm]" based on count
if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
} else {
++pos.index;
break parsing;
}
int i = subParseNumericZone(text, ++pos.index, sign, count,
count == 3, calb);
if (i > 0) {
return i;
}
pos.index = -i;
} }
break parsing; break parsing;

View File

@ -482,8 +482,8 @@ public abstract class AbstractList<E> extends AbstractCollection<E> implements L
*/ */
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
return (this instanceof RandomAccess ? return (this instanceof RandomAccess ?
new RandomAccessSubList<E>(this, fromIndex, toIndex) : new RandomAccessSubList<>(this, fromIndex, toIndex) :
new SubList<E>(this, fromIndex, toIndex)); new SubList<>(this, fromIndex, toIndex));
} }
// Comparison and hashing // Comparison and hashing
@ -747,7 +747,7 @@ class SubList<E> extends AbstractList<E> {
} }
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
return new SubList<E>(this, fromIndex, toIndex); return new SubList<>(this, fromIndex, toIndex);
} }
private void rangeCheck(int index) { private void rangeCheck(int index) {
@ -776,6 +776,6 @@ class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
} }
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
return new RandomAccessSubList<E>(this, fromIndex, toIndex); return new RandomAccessSubList<>(this, fromIndex, toIndex);
} }
} }

View File

@ -2824,7 +2824,7 @@ public class Arrays {
* @return a list view of the specified array * @return a list view of the specified array
*/ */
public static <T> List<T> asList(T... a) { public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a); return new ArrayList<>(a);
} }
/** /**

View File

@ -1035,7 +1035,7 @@ public class Collections {
* @return an unmodifiable view of the specified collection. * @return an unmodifiable view of the specified collection.
*/ */
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) { public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
return new UnmodifiableCollection<T>(c); return new UnmodifiableCollection<>(c);
} }
/** /**
@ -1109,7 +1109,7 @@ public class Collections {
* @return an unmodifiable view of the specified set. * @return an unmodifiable view of the specified set.
*/ */
public static <T> Set<T> unmodifiableSet(Set<? extends T> s) { public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
return new UnmodifiableSet<T>(s); return new UnmodifiableSet<>(s);
} }
/** /**
@ -1141,7 +1141,7 @@ public class Collections {
* @return an unmodifiable view of the specified sorted set. * @return an unmodifiable view of the specified sorted set.
*/ */
public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) { public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
return new UnmodifiableSortedSet<T>(s); return new UnmodifiableSortedSet<>(s);
} }
/** /**
@ -1158,13 +1158,13 @@ public class Collections {
public Comparator<? super E> comparator() {return ss.comparator();} public Comparator<? super E> comparator() {return ss.comparator();}
public SortedSet<E> subSet(E fromElement, E toElement) { public SortedSet<E> subSet(E fromElement, E toElement) {
return new UnmodifiableSortedSet<E>(ss.subSet(fromElement,toElement)); return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
} }
public SortedSet<E> headSet(E toElement) { public SortedSet<E> headSet(E toElement) {
return new UnmodifiableSortedSet<E>(ss.headSet(toElement)); return new UnmodifiableSortedSet<>(ss.headSet(toElement));
} }
public SortedSet<E> tailSet(E fromElement) { public SortedSet<E> tailSet(E fromElement) {
return new UnmodifiableSortedSet<E>(ss.tailSet(fromElement)); return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
} }
public E first() {return ss.first();} public E first() {return ss.first();}
@ -1188,8 +1188,8 @@ public class Collections {
*/ */
public static <T> List<T> unmodifiableList(List<? extends T> list) { public static <T> List<T> unmodifiableList(List<? extends T> list) {
return (list instanceof RandomAccess ? return (list instanceof RandomAccess ?
new UnmodifiableRandomAccessList<T>(list) : new UnmodifiableRandomAccessList<>(list) :
new UnmodifiableList<T>(list)); new UnmodifiableList<>(list));
} }
/** /**
@ -1250,7 +1250,7 @@ public class Collections {
} }
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
return new UnmodifiableList<E>(list.subList(fromIndex, toIndex)); return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
} }
/** /**
@ -1267,7 +1267,7 @@ public class Collections {
*/ */
private Object readResolve() { private Object readResolve() {
return (list instanceof RandomAccess return (list instanceof RandomAccess
? new UnmodifiableRandomAccessList<E>(list) ? new UnmodifiableRandomAccessList<>(list)
: this); : this);
} }
} }
@ -1283,7 +1283,7 @@ public class Collections {
} }
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
return new UnmodifiableRandomAccessList<E>( return new UnmodifiableRandomAccessList<>(
list.subList(fromIndex, toIndex)); list.subList(fromIndex, toIndex));
} }
@ -1296,7 +1296,7 @@ public class Collections {
* deserialization. * deserialization.
*/ */
private Object writeReplace() { private Object writeReplace() {
return new UnmodifiableList<E>(list); return new UnmodifiableList<>(list);
} }
} }
@ -1315,7 +1315,7 @@ public class Collections {
* @return an unmodifiable view of the specified map. * @return an unmodifiable view of the specified map.
*/ */
public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) { public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
return new UnmodifiableMap<K,V>(m); return new UnmodifiableMap<>(m);
} }
/** /**
@ -1363,7 +1363,7 @@ public class Collections {
public Set<Map.Entry<K,V>> entrySet() { public Set<Map.Entry<K,V>> entrySet() {
if (entrySet==null) if (entrySet==null)
entrySet = new UnmodifiableEntrySet<K,V>(m.entrySet()); entrySet = new UnmodifiableEntrySet<>(m.entrySet());
return entrySet; return entrySet;
} }
@ -1400,7 +1400,7 @@ public class Collections {
return i.hasNext(); return i.hasNext();
} }
public Map.Entry<K,V> next() { public Map.Entry<K,V> next() {
return new UnmodifiableEntry<K,V>(i.next()); return new UnmodifiableEntry<>(i.next());
} }
public void remove() { public void remove() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@ -1411,7 +1411,7 @@ public class Collections {
public Object[] toArray() { public Object[] toArray() {
Object[] a = c.toArray(); Object[] a = c.toArray();
for (int i=0; i<a.length; i++) for (int i=0; i<a.length; i++)
a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]); a[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)a[i]);
return a; return a;
} }
@ -1422,7 +1422,7 @@ public class Collections {
Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0)); Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
for (int i=0; i<arr.length; i++) for (int i=0; i<arr.length; i++)
arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]); arr[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)arr[i]);
if (arr.length > a.length) if (arr.length > a.length)
return (T[])arr; return (T[])arr;
@ -1443,7 +1443,7 @@ public class Collections {
if (!(o instanceof Map.Entry)) if (!(o instanceof Map.Entry))
return false; return false;
return c.contains( return c.contains(
new UnmodifiableEntry<Object,Object>((Map.Entry<?,?>) o)); new UnmodifiableEntry<>((Map.Entry<?,?>) o));
} }
/** /**
@ -1517,7 +1517,7 @@ public class Collections {
* @return an unmodifiable view of the specified sorted map. * @return an unmodifiable view of the specified sorted map.
*/ */
public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) { public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
return new UnmodifiableSortedMap<K,V>(m); return new UnmodifiableSortedMap<>(m);
} }
/** /**
@ -1535,13 +1535,13 @@ public class Collections {
public Comparator<? super K> comparator() {return sm.comparator();} public Comparator<? super K> comparator() {return sm.comparator();}
public SortedMap<K,V> subMap(K fromKey, K toKey) { public SortedMap<K,V> subMap(K fromKey, K toKey) {
return new UnmodifiableSortedMap<K,V>(sm.subMap(fromKey, toKey)); return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
} }
public SortedMap<K,V> headMap(K toKey) { public SortedMap<K,V> headMap(K toKey) {
return new UnmodifiableSortedMap<K,V>(sm.headMap(toKey)); return new UnmodifiableSortedMap<>(sm.headMap(toKey));
} }
public SortedMap<K,V> tailMap(K fromKey) { public SortedMap<K,V> tailMap(K fromKey) {
return new UnmodifiableSortedMap<K,V>(sm.tailMap(fromKey)); return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
} }
public K firstKey() {return sm.firstKey();} public K firstKey() {return sm.firstKey();}
@ -1583,11 +1583,11 @@ public class Collections {
* @return a synchronized view of the specified collection. * @return a synchronized view of the specified collection.
*/ */
public static <T> Collection<T> synchronizedCollection(Collection<T> c) { public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
return new SynchronizedCollection<T>(c); return new SynchronizedCollection<>(c);
} }
static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) { static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
return new SynchronizedCollection<T>(c, mutex); return new SynchronizedCollection<>(c, mutex);
} }
/** /**
@ -1686,11 +1686,11 @@ public class Collections {
* @return a synchronized view of the specified set. * @return a synchronized view of the specified set.
*/ */
public static <T> Set<T> synchronizedSet(Set<T> s) { public static <T> Set<T> synchronizedSet(Set<T> s) {
return new SynchronizedSet<T>(s); return new SynchronizedSet<>(s);
} }
static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) { static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
return new SynchronizedSet<T>(s, mutex); return new SynchronizedSet<>(s, mutex);
} }
/** /**
@ -1754,7 +1754,7 @@ public class Collections {
* @return a synchronized view of the specified sorted set. * @return a synchronized view of the specified sorted set.
*/ */
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) { public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
return new SynchronizedSortedSet<T>(s); return new SynchronizedSortedSet<>(s);
} }
/** /**
@ -1783,18 +1783,18 @@ public class Collections {
public SortedSet<E> subSet(E fromElement, E toElement) { public SortedSet<E> subSet(E fromElement, E toElement) {
synchronized (mutex) { synchronized (mutex) {
return new SynchronizedSortedSet<E>( return new SynchronizedSortedSet<>(
ss.subSet(fromElement, toElement), mutex); ss.subSet(fromElement, toElement), mutex);
} }
} }
public SortedSet<E> headSet(E toElement) { public SortedSet<E> headSet(E toElement) {
synchronized (mutex) { synchronized (mutex) {
return new SynchronizedSortedSet<E>(ss.headSet(toElement), mutex); return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
} }
} }
public SortedSet<E> tailSet(E fromElement) { public SortedSet<E> tailSet(E fromElement) {
synchronized (mutex) { synchronized (mutex) {
return new SynchronizedSortedSet<E>(ss.tailSet(fromElement),mutex); return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
} }
} }
@ -1833,14 +1833,14 @@ public class Collections {
*/ */
public static <T> List<T> synchronizedList(List<T> list) { public static <T> List<T> synchronizedList(List<T> list) {
return (list instanceof RandomAccess ? return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<T>(list) : new SynchronizedRandomAccessList<>(list) :
new SynchronizedList<T>(list)); new SynchronizedList<>(list));
} }
static <T> List<T> synchronizedList(List<T> list, Object mutex) { static <T> List<T> synchronizedList(List<T> list, Object mutex) {
return (list instanceof RandomAccess ? return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<T>(list, mutex) : new SynchronizedRandomAccessList<>(list, mutex) :
new SynchronizedList<T>(list, mutex)); new SynchronizedList<>(list, mutex));
} }
/** /**
@ -1903,7 +1903,7 @@ public class Collections {
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
synchronized (mutex) { synchronized (mutex) {
return new SynchronizedList<E>(list.subList(fromIndex, toIndex), return new SynchronizedList<>(list.subList(fromIndex, toIndex),
mutex); mutex);
} }
} }
@ -1922,7 +1922,7 @@ public class Collections {
*/ */
private Object readResolve() { private Object readResolve() {
return (list instanceof RandomAccess return (list instanceof RandomAccess
? new SynchronizedRandomAccessList<E>(list) ? new SynchronizedRandomAccessList<>(list)
: this); : this);
} }
} }
@ -1944,7 +1944,7 @@ public class Collections {
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
synchronized (mutex) { synchronized (mutex) {
return new SynchronizedRandomAccessList<E>( return new SynchronizedRandomAccessList<>(
list.subList(fromIndex, toIndex), mutex); list.subList(fromIndex, toIndex), mutex);
} }
} }
@ -1958,7 +1958,7 @@ public class Collections {
* deserialization. * deserialization.
*/ */
private Object writeReplace() { private Object writeReplace() {
return new SynchronizedList<E>(list); return new SynchronizedList<>(list);
} }
} }
@ -1990,7 +1990,7 @@ public class Collections {
* @return a synchronized view of the specified map. * @return a synchronized view of the specified map.
*/ */
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) { public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
return new SynchronizedMap<K,V>(m); return new SynchronizedMap<>(m);
} }
/** /**
@ -2051,7 +2051,7 @@ public class Collections {
public Set<K> keySet() { public Set<K> keySet() {
synchronized (mutex) { synchronized (mutex) {
if (keySet==null) if (keySet==null)
keySet = new SynchronizedSet<K>(m.keySet(), mutex); keySet = new SynchronizedSet<>(m.keySet(), mutex);
return keySet; return keySet;
} }
} }
@ -2059,7 +2059,7 @@ public class Collections {
public Set<Map.Entry<K,V>> entrySet() { public Set<Map.Entry<K,V>> entrySet() {
synchronized (mutex) { synchronized (mutex) {
if (entrySet==null) if (entrySet==null)
entrySet = new SynchronizedSet<Map.Entry<K,V>>(m.entrySet(), mutex); entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
return entrySet; return entrySet;
} }
} }
@ -2067,7 +2067,7 @@ public class Collections {
public Collection<V> values() { public Collection<V> values() {
synchronized (mutex) { synchronized (mutex) {
if (values==null) if (values==null)
values = new SynchronizedCollection<V>(m.values(), mutex); values = new SynchronizedCollection<>(m.values(), mutex);
return values; return values;
} }
} }
@ -2129,7 +2129,7 @@ public class Collections {
* @return a synchronized view of the specified sorted map. * @return a synchronized view of the specified sorted map.
*/ */
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) { public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
return new SynchronizedSortedMap<K,V>(m); return new SynchronizedSortedMap<>(m);
} }
@ -2159,18 +2159,18 @@ public class Collections {
public SortedMap<K,V> subMap(K fromKey, K toKey) { public SortedMap<K,V> subMap(K fromKey, K toKey) {
synchronized (mutex) { synchronized (mutex) {
return new SynchronizedSortedMap<K,V>( return new SynchronizedSortedMap<>(
sm.subMap(fromKey, toKey), mutex); sm.subMap(fromKey, toKey), mutex);
} }
} }
public SortedMap<K,V> headMap(K toKey) { public SortedMap<K,V> headMap(K toKey) {
synchronized (mutex) { synchronized (mutex) {
return new SynchronizedSortedMap<K,V>(sm.headMap(toKey), mutex); return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
} }
} }
public SortedMap<K,V> tailMap(K fromKey) { public SortedMap<K,V> tailMap(K fromKey) {
synchronized (mutex) { synchronized (mutex) {
return new SynchronizedSortedMap<K,V>(sm.tailMap(fromKey),mutex); return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
} }
} }
@ -2246,7 +2246,7 @@ public class Collections {
*/ */
public static <E> Collection<E> checkedCollection(Collection<E> c, public static <E> Collection<E> checkedCollection(Collection<E> c,
Class<E> type) { Class<E> type) {
return new CheckedCollection<E>(c, type); return new CheckedCollection<>(c, type);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -2378,7 +2378,7 @@ public class Collections {
* @since 1.5 * @since 1.5
*/ */
public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) { public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
return new CheckedSet<E>(s, type); return new CheckedSet<>(s, type);
} }
/** /**
@ -2424,7 +2424,7 @@ public class Collections {
*/ */
public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s, public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
Class<E> type) { Class<E> type) {
return new CheckedSortedSet<E>(s, type); return new CheckedSortedSet<>(s, type);
} }
/** /**
@ -2484,8 +2484,8 @@ public class Collections {
*/ */
public static <E> List<E> checkedList(List<E> list, Class<E> type) { public static <E> List<E> checkedList(List<E> list, Class<E> type) {
return (list instanceof RandomAccess ? return (list instanceof RandomAccess ?
new CheckedRandomAccessList<E>(list, type) : new CheckedRandomAccessList<>(list, type) :
new CheckedList<E>(list, type)); new CheckedList<>(list, type));
} }
/** /**
@ -2550,7 +2550,7 @@ public class Collections {
} }
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
return new CheckedList<E>(list.subList(fromIndex, toIndex), type); return new CheckedList<>(list.subList(fromIndex, toIndex), type);
} }
} }
@ -2567,7 +2567,7 @@ public class Collections {
} }
public List<E> subList(int fromIndex, int toIndex) { public List<E> subList(int fromIndex, int toIndex) {
return new CheckedRandomAccessList<E>( return new CheckedRandomAccessList<>(
list.subList(fromIndex, toIndex), type); list.subList(fromIndex, toIndex), type);
} }
} }
@ -2609,7 +2609,7 @@ public class Collections {
public static <K, V> Map<K, V> checkedMap(Map<K, V> m, public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
Class<K> keyType, Class<K> keyType,
Class<V> valueType) { Class<V> valueType) {
return new CheckedMap<K,V>(m, keyType, valueType); return new CheckedMap<>(m, keyType, valueType);
} }
@ -2677,15 +2677,14 @@ public class Collections {
// - protection from malicious t // - protection from malicious t
// - correct behavior if t is a concurrent map // - correct behavior if t is a concurrent map
Object[] entries = t.entrySet().toArray(); Object[] entries = t.entrySet().toArray();
List<Map.Entry<K,V>> checked = List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);
new ArrayList<Map.Entry<K,V>>(entries.length);
for (Object o : entries) { for (Object o : entries) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o; Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object k = e.getKey(); Object k = e.getKey();
Object v = e.getValue(); Object v = e.getValue();
typeCheck(k, v); typeCheck(k, v);
checked.add( checked.add(
new AbstractMap.SimpleImmutableEntry<K,V>((K) k, (V) v)); new AbstractMap.SimpleImmutableEntry<>((K) k, (V) v));
} }
for (Map.Entry<K,V> e : checked) for (Map.Entry<K,V> e : checked)
m.put(e.getKey(), e.getValue()); m.put(e.getKey(), e.getValue());
@ -2695,7 +2694,7 @@ public class Collections {
public Set<Map.Entry<K,V>> entrySet() { public Set<Map.Entry<K,V>> entrySet() {
if (entrySet==null) if (entrySet==null)
entrySet = new CheckedEntrySet<K,V>(m.entrySet(), valueType); entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);
return entrySet; return entrySet;
} }
@ -2810,7 +2809,7 @@ public class Collections {
if (!(o instanceof Map.Entry)) if (!(o instanceof Map.Entry))
return false; return false;
return s.remove(new AbstractMap.SimpleImmutableEntry return s.remove(new AbstractMap.SimpleImmutableEntry
<Object, Object>((Map.Entry<?,?>)o)); <>((Map.Entry<?,?>)o));
} }
public boolean removeAll(Collection<?> c) { public boolean removeAll(Collection<?> c) {
@ -2843,7 +2842,7 @@ public class Collections {
static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e, static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
Class<T> valueType) { Class<T> valueType) {
return new CheckedEntry<K,V,T>(e, valueType); return new CheckedEntry<>(e, valueType);
} }
/** /**
@ -2884,7 +2883,7 @@ public class Collections {
if (!(o instanceof Map.Entry)) if (!(o instanceof Map.Entry))
return false; return false;
return e.equals(new AbstractMap.SimpleImmutableEntry return e.equals(new AbstractMap.SimpleImmutableEntry
<Object, Object>((Map.Entry<?,?>)o)); <>((Map.Entry<?,?>)o));
} }
} }
} }
@ -2927,7 +2926,7 @@ public class Collections {
public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m, public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
Class<K> keyType, Class<K> keyType,
Class<V> valueType) { Class<V> valueType) {
return new CheckedSortedMap<K,V>(m, keyType, valueType); return new CheckedSortedMap<>(m, keyType, valueType);
} }
/** /**
@ -2993,7 +2992,7 @@ public class Collections {
private static class EmptyIterator<E> implements Iterator<E> { private static class EmptyIterator<E> implements Iterator<E> {
static final EmptyIterator<Object> EMPTY_ITERATOR static final EmptyIterator<Object> EMPTY_ITERATOR
= new EmptyIterator<Object>(); = new EmptyIterator<>();
public boolean hasNext() { return false; } public boolean hasNext() { return false; }
public E next() { throw new NoSuchElementException(); } public E next() { throw new NoSuchElementException(); }
@ -3042,7 +3041,7 @@ public class Collections {
implements ListIterator<E> implements ListIterator<E>
{ {
static final EmptyListIterator<Object> EMPTY_ITERATOR static final EmptyListIterator<Object> EMPTY_ITERATOR
= new EmptyListIterator<Object>(); = new EmptyListIterator<>();
public boolean hasPrevious() { return false; } public boolean hasPrevious() { return false; }
public E previous() { throw new NoSuchElementException(); } public E previous() { throw new NoSuchElementException(); }
@ -3078,7 +3077,7 @@ public class Collections {
private static class EmptyEnumeration<E> implements Enumeration<E> { private static class EmptyEnumeration<E> implements Enumeration<E> {
static final EmptyEnumeration<Object> EMPTY_ENUMERATION static final EmptyEnumeration<Object> EMPTY_ENUMERATION
= new EmptyEnumeration<Object>(); = new EmptyEnumeration<>();
public boolean hasMoreElements() { return false; } public boolean hasMoreElements() { return false; }
public E nextElement() { throw new NoSuchElementException(); } public E nextElement() { throw new NoSuchElementException(); }
@ -3090,7 +3089,7 @@ public class Collections {
* @see #emptySet() * @see #emptySet()
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static final Set EMPTY_SET = new EmptySet<Object>(); public static final Set EMPTY_SET = new EmptySet<>();
/** /**
* Returns the empty set (immutable). This set is serializable. * Returns the empty set (immutable). This set is serializable.
@ -3150,7 +3149,7 @@ public class Collections {
* @see #emptyList() * @see #emptyList()
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static final List EMPTY_LIST = new EmptyList<Object>(); public static final List EMPTY_LIST = new EmptyList<>();
/** /**
* Returns the empty list (immutable). This list is serializable. * Returns the empty list (immutable). This list is serializable.
@ -3224,7 +3223,7 @@ public class Collections {
* @since 1.3 * @since 1.3
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static final Map EMPTY_MAP = new EmptyMap<Object,Object>(); public static final Map EMPTY_MAP = new EmptyMap<>();
/** /**
* Returns the empty map (immutable). This map is serializable. * Returns the empty map (immutable). This map is serializable.
@ -3286,7 +3285,7 @@ public class Collections {
* @return an immutable set containing only the specified object. * @return an immutable set containing only the specified object.
*/ */
public static <T> Set<T> singleton(T o) { public static <T> Set<T> singleton(T o) {
return new SingletonSet<T>(o); return new SingletonSet<>(o);
} }
static <E> Iterator<E> singletonIterator(final E e) { static <E> Iterator<E> singletonIterator(final E e) {
@ -3339,7 +3338,7 @@ public class Collections {
* @since 1.3 * @since 1.3
*/ */
public static <T> List<T> singletonList(T o) { public static <T> List<T> singletonList(T o) {
return new SingletonList<T>(o); return new SingletonList<>(o);
} }
/** /**
@ -3381,7 +3380,7 @@ public class Collections {
* @since 1.3 * @since 1.3
*/ */
public static <K,V> Map<K,V> singletonMap(K key, V value) { public static <K,V> Map<K,V> singletonMap(K key, V value) {
return new SingletonMap<K,V>(key, value); return new SingletonMap<>(key, value);
} }
/** /**
@ -3423,7 +3422,7 @@ public class Collections {
public Set<Map.Entry<K,V>> entrySet() { public Set<Map.Entry<K,V>> entrySet() {
if (entrySet==null) if (entrySet==null)
entrySet = Collections.<Map.Entry<K,V>>singleton( entrySet = Collections.<Map.Entry<K,V>>singleton(
new SimpleImmutableEntry<K,V>(k, v)); new SimpleImmutableEntry<>(k, v));
return entrySet; return entrySet;
} }
@ -3455,7 +3454,7 @@ public class Collections {
public static <T> List<T> nCopies(int n, T o) { public static <T> List<T> nCopies(int n, T o) {
if (n < 0) if (n < 0)
throw new IllegalArgumentException("List length = " + n); throw new IllegalArgumentException("List length = " + n);
return new CopiesList<T>(n, o); return new CopiesList<>(n, o);
} }
/** /**
@ -3529,7 +3528,7 @@ public class Collections {
if (fromIndex > toIndex) if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex + throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")"); ") > toIndex(" + toIndex + ")");
return new CopiesList<E>(toIndex - fromIndex, element); return new CopiesList<>(toIndex - fromIndex, element);
} }
} }
@ -3595,7 +3594,7 @@ public class Collections {
if (cmp instanceof ReverseComparator2) if (cmp instanceof ReverseComparator2)
return ((ReverseComparator2<T>)cmp).cmp; return ((ReverseComparator2<T>)cmp).cmp;
return new ReverseComparator2<T>(cmp); return new ReverseComparator2<>(cmp);
} }
/** /**
@ -3674,7 +3673,7 @@ public class Collections {
* @see ArrayList * @see ArrayList
*/ */
public static <T> ArrayList<T> list(Enumeration<T> e) { public static <T> ArrayList<T> list(Enumeration<T> e) {
ArrayList<T> l = new ArrayList<T>(); ArrayList<T> l = new ArrayList<>();
while (e.hasMoreElements()) while (e.hasMoreElements())
l.add(e.nextElement()); l.add(e.nextElement());
return l; return l;
@ -3819,7 +3818,7 @@ public class Collections {
* @since 1.6 * @since 1.6
*/ */
public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
return new SetFromMap<E>(map); return new SetFromMap<>(map);
} }
/** /**
@ -3883,7 +3882,7 @@ public class Collections {
* @since 1.6 * @since 1.6
*/ */
public static <T> Queue<T> asLifoQueue(Deque<T> deque) { public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
return new AsLIFOQueue<T>(deque); return new AsLIFOQueue<>(deque);
} }
/** /**

View File

@ -499,7 +499,7 @@ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>
int j = 0; int j = 0;
for (int i = 0; i < vals.length; i++) for (int i = 0; i < vals.length; i++)
if (vals[i] != null) if (vals[i] != null)
a[j++] = new AbstractMap.SimpleEntry<K,V>( a[j++] = new AbstractMap.SimpleEntry<>(
keyUniverse[i], unmaskNull(vals[i])); keyUniverse[i], unmaskNull(vals[i]));
return a; return a;
} }

View File

@ -110,9 +110,9 @@ public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
throw new ClassCastException(elementType + " not an enum"); throw new ClassCastException(elementType + " not an enum");
if (universe.length <= 64) if (universe.length <= 64)
return new RegularEnumSet<E>(elementType, universe); return new RegularEnumSet<>(elementType, universe);
else else
return new JumboEnumSet<E>(elementType, universe); return new JumboEnumSet<>(elementType, universe);
} }
/** /**
@ -430,7 +430,7 @@ public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
} }
Object writeReplace() { Object writeReplace() {
return new SerializationProxy<E>(this); return new SerializationProxy<>(this);
} }
// readObject method for the serialization proxy pattern // readObject method for the serialization proxy pattern

View File

@ -2490,7 +2490,7 @@ public final class Formatter implements Closeable, Flushable {
* Finds format specifiers in the format string. * Finds format specifiers in the format string.
*/ */
private FormatString[] parse(String s) { private FormatString[] parse(String s) {
ArrayList<FormatString> al = new ArrayList<FormatString>(); ArrayList<FormatString> al = new ArrayList<>();
Matcher m = fsPattern.matcher(s); Matcher m = fsPattern.matcher(s);
for (int i = 0, len = s.length(); i < len; ) { for (int i = 0, len = s.length(); i < len; ) {
if (m.find(i)) { if (m.find(i)) {

View File

@ -763,7 +763,7 @@ public class HashMap<K,V>
*/ */
void addEntry(int hash, K key, V value, int bucketIndex) { void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex]; Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e); table[bucketIndex] = new Entry<>(hash, key, value, e);
if (size++ >= threshold) if (size++ >= threshold)
resize(2 * table.length); resize(2 * table.length);
} }
@ -778,7 +778,7 @@ public class HashMap<K,V>
*/ */
void createEntry(int hash, K key, V value, int bucketIndex) { void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex]; Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e); table[bucketIndex] = new Entry<>(hash, key, value, e);
size++; size++;
} }

View File

@ -100,7 +100,7 @@ public class HashSet<E>
* default initial capacity (16) and load factor (0.75). * default initial capacity (16) and load factor (0.75).
*/ */
public HashSet() { public HashSet() {
map = new HashMap<E,Object>(); map = new HashMap<>();
} }
/** /**
@ -113,7 +113,7 @@ public class HashSet<E>
* @throws NullPointerException if the specified collection is null * @throws NullPointerException if the specified collection is null
*/ */
public HashSet(Collection<? extends E> c) { public HashSet(Collection<? extends E> c) {
map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16)); map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c); addAll(c);
} }
@ -127,7 +127,7 @@ public class HashSet<E>
* than zero, or if the load factor is nonpositive * than zero, or if the load factor is nonpositive
*/ */
public HashSet(int initialCapacity, float loadFactor) { public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<E,Object>(initialCapacity, loadFactor); map = new HashMap<>(initialCapacity, loadFactor);
} }
/** /**
@ -139,7 +139,7 @@ public class HashSet<E>
* than zero * than zero
*/ */
public HashSet(int initialCapacity) { public HashSet(int initialCapacity) {
map = new HashMap<E,Object>(initialCapacity); map = new HashMap<>(initialCapacity);
} }
/** /**
@ -156,7 +156,7 @@ public class HashSet<E>
* than zero, or if the load factor is nonpositive * than zero, or if the load factor is nonpositive
*/ */
HashSet(int initialCapacity, float loadFactor, boolean dummy) { HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor); map = new LinkedHashMap<>(initialCapacity, loadFactor);
} }
/** /**

View File

@ -455,7 +455,7 @@ public class Hashtable<K,V>
// Creates the new entry. // Creates the new entry.
Entry<K,V> e = tab[index]; Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e); tab[index] = new Entry<>(hash, key, value, e);
count++; count++;
return null; return null;
} }
@ -579,7 +579,7 @@ public class Hashtable<K,V>
if (count == 0) { if (count == 0) {
return Collections.emptyEnumeration(); return Collections.emptyEnumeration();
} else { } else {
return new Enumerator<T>(type, false); return new Enumerator<>(type, false);
} }
} }
@ -587,7 +587,7 @@ public class Hashtable<K,V>
if (count == 0) { if (count == 0) {
return Collections.emptyIterator(); return Collections.emptyIterator();
} else { } else {
return new Enumerator<T>(type, true); return new Enumerator<>(type, true);
} }
} }
@ -929,7 +929,7 @@ public class Hashtable<K,V>
} }
// Creates the new entry. // Creates the new entry.
Entry<K,V> e = tab[index]; Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e); tab[index] = new Entry<>(hash, key, value, e);
count++; count++;
} }
@ -950,7 +950,7 @@ public class Hashtable<K,V>
} }
protected Object clone() { protected Object clone() {
return new Entry<K,V>(hash, key, value, return new Entry<>(hash, key, value,
(next==null ? null : (Entry<K,V>) next.clone())); (next==null ? null : (Entry<K,V>) next.clone()));
} }

View File

@ -1134,7 +1134,7 @@ public class IdentityHashMap<K,V>
Object[] result = new Object[size]; Object[] result = new Object[size];
Iterator<Map.Entry<K,V>> it = iterator(); Iterator<Map.Entry<K,V>> it = iterator();
for (int i = 0; i < size; i++) for (int i = 0; i < size; i++)
result[i] = new AbstractMap.SimpleEntry<K,V>(it.next()); result[i] = new AbstractMap.SimpleEntry<>(it.next());
return result; return result;
} }
@ -1146,7 +1146,7 @@ public class IdentityHashMap<K,V>
.newInstance(a.getClass().getComponentType(), size); .newInstance(a.getClass().getComponentType(), size);
Iterator<Map.Entry<K,V>> it = iterator(); Iterator<Map.Entry<K,V>> it = iterator();
for (int i = 0; i < size; i++) for (int i = 0; i < size; i++)
a[i] = (T) new AbstractMap.SimpleEntry<K,V>(it.next()); a[i] = (T) new AbstractMap.SimpleEntry<>(it.next());
if (a.length > size) if (a.length > size)
a[size] = null; a[size] = null;
return a; return a;

View File

@ -89,7 +89,7 @@ class JumboEnumSet<E extends Enum<E>> extends EnumSet<E> {
* @return an iterator over the elements contained in this set * @return an iterator over the elements contained in this set
*/ */
public Iterator<E> iterator() { public Iterator<E> iterator() {
return new EnumSetIterator<E>(); return new EnumSetIterator<>();
} }
private class EnumSetIterator<E extends Enum<E>> implements Iterator<E> { private class EnumSetIterator<E extends Enum<E>> implements Iterator<E> {

View File

@ -237,7 +237,7 @@ public class LinkedHashMap<K,V>
* the chain. * the chain.
*/ */
void init() { void init() {
header = new Entry<K,V>(-1, null, null, null); header = new Entry<>(-1, null, null, null);
header.before = header.after = header; header.before = header.after = header;
} }
@ -438,7 +438,7 @@ public class LinkedHashMap<K,V>
*/ */
void createEntry(int hash, K key, V value, int bucketIndex) { void createEntry(int hash, K key, V value, int bucketIndex) {
HashMap.Entry<K,V> old = table[bucketIndex]; HashMap.Entry<K,V> old = table[bucketIndex];
Entry<K,V> e = new Entry<K,V>(hash, key, value, old); Entry<K,V> e = new Entry<>(hash, key, value, old);
table[bucketIndex] = e; table[bucketIndex] = e;
e.addBefore(header); e.addBefore(header);
size++; size++;

View File

@ -122,7 +122,7 @@ public class LinkedList<E>
*/ */
private void linkFirst(E e) { private void linkFirst(E e) {
final Node<E> f = first; final Node<E> f = first;
final Node<E> newNode = new Node<E>(null, e, f); final Node<E> newNode = new Node<>(null, e, f);
first = newNode; first = newNode;
if (f == null) if (f == null)
last = newNode; last = newNode;
@ -137,7 +137,7 @@ public class LinkedList<E>
*/ */
void linkLast(E e) { void linkLast(E e) {
final Node<E> l = last; final Node<E> l = last;
final Node<E> newNode = new Node<E>(l, e, null); final Node<E> newNode = new Node<>(l, e, null);
last = newNode; last = newNode;
if (l == null) if (l == null)
first = newNode; first = newNode;
@ -153,7 +153,7 @@ public class LinkedList<E>
void linkBefore(E e, Node<E> succ) { void linkBefore(E e, Node<E> succ) {
// assert succ != null; // assert succ != null;
final Node<E> pred = succ.prev; final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<E>(pred, e, succ); final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode; succ.prev = newNode;
if (pred == null) if (pred == null)
first = newNode; first = newNode;
@ -419,7 +419,7 @@ public class LinkedList<E>
for (Object o : a) { for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o; @SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<E>(pred, e, null); Node<E> newNode = new Node<>(pred, e, null);
if (pred == null) if (pred == null)
first = newNode; first = newNode;
else else

View File

@ -187,7 +187,7 @@ public abstract class ListResourceBundle extends ResourceBundle {
return; return;
Object[][] contents = getContents(); Object[][] contents = getContents();
HashMap<String,Object> temp = new HashMap<String,Object>(contents.length); HashMap<String,Object> temp = new HashMap<>(contents.length);
for (int i = 0; i < contents.length; ++i) { for (int i = 0; i < contents.length; ++i) {
// key must be non-null String, value must be non-null // key must be non-null String, value must be non-null
String key = (String) contents[i][0]; String key = (String) contents[i][0];

View File

@ -1449,10 +1449,15 @@ public final class Locale implements Cloneable, Serializable {
* three-letter language abbreviation is not available for this locale. * three-letter language abbreviation is not available for this locale.
*/ */
public String getISO3Language() throws MissingResourceException { public String getISO3Language() throws MissingResourceException {
String language3 = getISO3Code(_baseLocale.getLanguage(), LocaleISOData.isoLanguageTable); String lang = _baseLocale.getLanguage();
if (lang.length() == 3) {
return lang;
}
String language3 = getISO3Code(lang, LocaleISOData.isoLanguageTable);
if (language3 == null) { if (language3 == null) {
throw new MissingResourceException("Couldn't find 3-letter language code for " throw new MissingResourceException("Couldn't find 3-letter language code for "
+ _baseLocale.getLanguage(), "FormatData_" + toString(), "ShortLanguage"); + lang, "FormatData_" + toString(), "ShortLanguage");
} }
return language3; return language3;
} }

View File

@ -538,7 +538,7 @@ public class PriorityQueue<E> extends AbstractQueue<E>
cursor--; cursor--;
else { else {
if (forgetMeNot == null) if (forgetMeNot == null)
forgetMeNot = new ArrayDeque<E>(); forgetMeNot = new ArrayDeque<>();
forgetMeNot.add(moved); forgetMeNot.add(moved);
} }
} else if (lastRetElt != null) { } else if (lastRetElt != null) {

View File

@ -1011,7 +1011,7 @@ class Properties extends Hashtable<Object,Object> {
* @since 1.6 * @since 1.6
*/ */
public Set<String> stringPropertyNames() { public Set<String> stringPropertyNames() {
Hashtable<String, String> h = new Hashtable<String, String>(); Hashtable<String, String> h = new Hashtable<>();
enumerateStringProperties(h); enumerateStringProperties(h);
return h.keySet(); return h.keySet();
} }

View File

@ -71,7 +71,7 @@ class RegularEnumSet<E extends Enum<E>> extends EnumSet<E> {
* @return an iterator over the elements contained in this set * @return an iterator over the elements contained in this set
*/ */
public Iterator<E> iterator() { public Iterator<E> iterator() {
return new EnumSetIterator<E>(); return new EnumSetIterator<>();
} }
private class EnumSetIterator<E extends Enum<E>> implements Iterator<E> { private class EnumSetIterator<E extends Enum<E>> implements Iterator<E> {

View File

@ -191,7 +191,7 @@ public final class ServiceLoader<S>
private ClassLoader loader; private ClassLoader loader;
// Cached providers, in instantiation order // Cached providers, in instantiation order
private LinkedHashMap<String,S> providers = new LinkedHashMap<String,S>(); private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
// The current lazy-lookup iterator // The current lazy-lookup iterator
private LazyIterator lookupIterator; private LazyIterator lookupIterator;
@ -291,7 +291,7 @@ public final class ServiceLoader<S>
{ {
InputStream in = null; InputStream in = null;
BufferedReader r = null; BufferedReader r = null;
ArrayList<String> names = new ArrayList<String>(); ArrayList<String> names = new ArrayList<>();
try { try {
in = u.openStream(); in = u.openStream();
r = new BufferedReader(new InputStreamReader(in, "utf-8")); r = new BufferedReader(new InputStreamReader(in, "utf-8"));
@ -463,7 +463,7 @@ public final class ServiceLoader<S>
public static <S> ServiceLoader<S> load(Class<S> service, public static <S> ServiceLoader<S> load(Class<S> service,
ClassLoader loader) ClassLoader loader)
{ {
return new ServiceLoader<S>(service, loader); return new ServiceLoader<>(service, loader);
} }
/** /**

View File

@ -196,7 +196,7 @@ class TimSort<T> {
* extending short natural runs to minRun elements, and merging runs * extending short natural runs to minRun elements, and merging runs
* to maintain stack invariant. * to maintain stack invariant.
*/ */
TimSort<T> ts = new TimSort<T>(a, c); TimSort<T> ts = new TimSort<>(a, c);
int minRun = minRunLength(nRemaining); int minRun = minRunLength(nRemaining);
do { do {
// Identify next run // Identify next run

View File

@ -533,7 +533,7 @@ public class TreeMap<K,V>
// throw NullPointerException // throw NullPointerException
// //
// compare(key, key); // type check // compare(key, key); // type check
root = new Entry<K,V>(key, value, null); root = new Entry<>(key, value, null);
size = 1; size = 1;
modCount++; modCount++;
return null; return null;
@ -569,7 +569,7 @@ public class TreeMap<K,V>
return t.setValue(value); return t.setValue(value);
} while (t != null); } while (t != null);
} }
Entry<K,V> e = new Entry<K,V>(key, value, parent); Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0) if (cmp < 0)
parent.left = e; parent.left = e;
else else
@ -1069,14 +1069,14 @@ public class TreeMap<K,V>
} }
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
E toElement, boolean toInclusive) { E toElement, boolean toInclusive) {
return new KeySet<E>(m.subMap(fromElement, fromInclusive, return new KeySet<>(m.subMap(fromElement, fromInclusive,
toElement, toInclusive)); toElement, toInclusive));
} }
public NavigableSet<E> headSet(E toElement, boolean inclusive) { public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new KeySet<E>(m.headMap(toElement, inclusive)); return new KeySet<>(m.headMap(toElement, inclusive));
} }
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new KeySet<E>(m.tailMap(fromElement, inclusive)); return new KeySet<>(m.tailMap(fromElement, inclusive));
} }
public SortedSet<E> subSet(E fromElement, E toElement) { public SortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false); return subSet(fromElement, true, toElement, false);
@ -1205,7 +1205,7 @@ public class TreeMap<K,V>
*/ */
static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) { static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
return (e == null) ? null : return (e == null) ? null :
new AbstractMap.SimpleImmutableEntry<K,V>(e); new AbstractMap.SimpleImmutableEntry<>(e);
} }
/** /**
@ -2406,7 +2406,7 @@ public class TreeMap<K,V>
value = (defaultVal != null ? defaultVal : (V) str.readObject()); value = (defaultVal != null ? defaultVal : (V) str.readObject());
} }
Entry<K,V> middle = new Entry<K,V>(key, value, null); Entry<K,V> middle = new Entry<>(key, value, null);
// color nodes in non-full bottommost level red // color nodes in non-full bottommost level red
if (level == redLevel) if (level == redLevel)

View File

@ -138,7 +138,7 @@ public class TreeSet<E> extends AbstractSet<E>
* ordering} of the elements will be used. * ordering} of the elements will be used.
*/ */
public TreeSet(Comparator<? super E> comparator) { public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<E,Object>(comparator)); this(new TreeMap<>(comparator));
} }
/** /**
@ -195,7 +195,7 @@ public class TreeSet<E> extends AbstractSet<E>
* @since 1.6 * @since 1.6
*/ */
public NavigableSet<E> descendingSet() { public NavigableSet<E> descendingSet() {
return new TreeSet<E>(m.descendingMap()); return new TreeSet<>(m.descendingMap());
} }
/** /**
@ -322,7 +322,7 @@ public class TreeSet<E> extends AbstractSet<E>
*/ */
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
E toElement, boolean toInclusive) { E toElement, boolean toInclusive) {
return new TreeSet<E>(m.subMap(fromElement, fromInclusive, return new TreeSet<>(m.subMap(fromElement, fromInclusive,
toElement, toInclusive)); toElement, toInclusive));
} }
@ -335,7 +335,7 @@ public class TreeSet<E> extends AbstractSet<E>
* @since 1.6 * @since 1.6
*/ */
public NavigableSet<E> headSet(E toElement, boolean inclusive) { public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new TreeSet<E>(m.headMap(toElement, inclusive)); return new TreeSet<>(m.headMap(toElement, inclusive));
} }
/** /**
@ -347,7 +347,7 @@ public class TreeSet<E> extends AbstractSet<E>
* @since 1.6 * @since 1.6
*/ */
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new TreeSet<E>(m.tailMap(fromElement, inclusive)); return new TreeSet<>(m.tailMap(fromElement, inclusive));
} }
/** /**
@ -477,7 +477,7 @@ public class TreeSet<E> extends AbstractSet<E>
throw new InternalError(); throw new InternalError();
} }
clone.m = new TreeMap<E,Object>(m); clone.m = new TreeMap<>(m);
return clone; return clone;
} }
@ -524,9 +524,9 @@ public class TreeSet<E> extends AbstractSet<E>
// Create backing TreeMap // Create backing TreeMap
TreeMap<E,Object> tm; TreeMap<E,Object> tm;
if (c==null) if (c==null)
tm = new TreeMap<E,Object>(); tm = new TreeMap<>();
else else
tm = new TreeMap<E,Object>(c); tm = new TreeMap<>(c);
m = tm; m = tm;
// Read in size // Read in size

View File

@ -171,7 +171,7 @@ public class WeakHashMap<K,V>
/** /**
* Reference queue for cleared WeakEntries * Reference queue for cleared WeakEntries
*/ */
private final ReferenceQueue<Object> queue = new ReferenceQueue<Object>(); private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
/** /**
* The number of times this WeakHashMap has been structurally modified. * The number of times this WeakHashMap has been structurally modified.
@ -439,7 +439,7 @@ public class WeakHashMap<K,V>
modCount++; modCount++;
Entry<K,V> e = tab[i]; Entry<K,V> e = tab[i];
tab[i] = new Entry<K,V>(k, value, queue, h, e); tab[i] = new Entry<>(k, value, queue, h, e);
if (++size >= threshold) if (++size >= threshold)
resize(tab.length * 2); resize(tab.length * 2);
return null; return null;
@ -955,10 +955,9 @@ public class WeakHashMap<K,V>
} }
private List<Map.Entry<K,V>> deepCopy() { private List<Map.Entry<K,V>> deepCopy() {
List<Map.Entry<K,V>> list = List<Map.Entry<K,V>> list = new ArrayList<>(size());
new ArrayList<Map.Entry<K,V>>(size());
for (Map.Entry<K,V> e : this) for (Map.Entry<K,V> e : this)
list.add(new AbstractMap.SimpleEntry<K,V>(e)); list.add(new AbstractMap.SimpleEntry<>(e));
return list; return list;
} }

View File

@ -732,14 +732,14 @@ public abstract class Pack200 {
private synchronized static Object newInstance(String prop) { private synchronized static Object newInstance(String prop) {
String implName = "(unknown)"; String implName = "(unknown)";
try { try {
Class impl = (prop == PACK_PROVIDER)? packerImpl: unpackerImpl; Class impl = (PACK_PROVIDER.equals(prop))? packerImpl: unpackerImpl;
if (impl == null) { if (impl == null) {
// The first time, we must decide which class to use. // The first time, we must decide which class to use.
implName = java.security.AccessController.doPrivileged( implName = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(prop,"")); new sun.security.action.GetPropertyAction(prop,""));
if (implName != null && !implName.equals("")) if (implName != null && !implName.equals(""))
impl = Class.forName(implName); impl = Class.forName(implName);
else if (prop == PACK_PROVIDER) else if (PACK_PROVIDER.equals(prop))
impl = com.sun.java.util.jar.pack.PackerImpl.class; impl = com.sun.java.util.jar.pack.PackerImpl.class;
else else
impl = com.sun.java.util.jar.pack.UnpackerImpl.class; impl = com.sun.java.util.jar.pack.UnpackerImpl.class;

View File

@ -127,7 +127,7 @@ public class FileHandler extends StreamHandler {
private FileOutputStream lockStream; private FileOutputStream lockStream;
private File files[]; private File files[];
private static final int MAX_LOCKS = 100; private static final int MAX_LOCKS = 100;
private static java.util.HashMap<String, String> locks = new java.util.HashMap<String, String>(); private static java.util.HashMap<String, String> locks = new java.util.HashMap<>();
// A metered stream is a subclass of OutputStream that // A metered stream is a subclass of OutputStream that
// (a) forwards all its output to a target stream // (a) forwards all its output to a target stream

View File

@ -59,7 +59,7 @@ import java.util.ResourceBundle;
*/ */
public class Level implements java.io.Serializable { public class Level implements java.io.Serializable {
private static java.util.ArrayList<Level> known = new java.util.ArrayList<Level>(); private static java.util.ArrayList<Level> known = new java.util.ArrayList<>();
private static String defaultBundle = "sun.util.logging.resources.logging"; private static String defaultBundle = "sun.util.logging.resources.logging";
/** /**

View File

@ -156,8 +156,7 @@ public class LogManager {
private final static Level defaultLevel = Level.INFO; private final static Level defaultLevel = Level.INFO;
// Table of named Loggers that maps names to Loggers. // Table of named Loggers that maps names to Loggers.
private Hashtable<String,LoggerWeakRef> namedLoggers = private Hashtable<String,LoggerWeakRef> namedLoggers = new Hashtable<>();
new Hashtable<String,LoggerWeakRef>();
// Tree of named Loggers // Tree of named Loggers
private LogNode root = new LogNode(null); private LogNode root = new LogNode(null);
private Logger rootLogger; private Logger rootLogger;
@ -422,7 +421,7 @@ public class LogManager {
// loggerRefQueue holds LoggerWeakRef objects for Logger objects // loggerRefQueue holds LoggerWeakRef objects for Logger objects
// that have been GC'ed. // that have been GC'ed.
private final ReferenceQueue<Logger> loggerRefQueue private final ReferenceQueue<Logger> loggerRefQueue
= new ReferenceQueue<Logger>(); = new ReferenceQueue<>();
// Package-level inner class. // Package-level inner class.
// Helper class for managing WeakReferences to Logger objects. // Helper class for managing WeakReferences to Logger objects.
@ -672,7 +671,7 @@ public class LogManager {
name = ""; name = "";
} }
if (node.children == null) { if (node.children == null) {
node.children = new HashMap<String,LogNode>(); node.children = new HashMap<>();
} }
LogNode child = node.children.get(head); LogNode child = node.children.get(head);
if (child == null) { if (child == null) {
@ -856,7 +855,7 @@ public class LogManager {
} }
hands = hands.trim(); hands = hands.trim();
int ix = 0; int ix = 0;
Vector<String> result = new Vector<String>(); Vector<String> result = new Vector<>();
while (ix < hands.length()) { while (ix < hands.length()) {
int end = ix; int end = ix;
while (end < hands.length()) { while (end < hands.length()) {

Some files were not shown because too many files have changed in this diff Show More