diff --git a/jdk/.hgtags b/jdk/.hgtags index 7a9bbb24e71..fdf62aef521 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -256,3 +256,4 @@ ab06ba2894313a47e4969ca37792ff119c49e711 jdk9-b10 47feccd164b7187a0147693a922ee47c6629643c jdk9-b11 83d9bc20973de232cae45b139fdff8a4549c130f jdk9-b12 c7c8002d02721e02131d104549ebeb8b379fb8d2 jdk9-b13 +5c7a17a81afd0906b53ee31d95a3211c96ff6b25 jdk9-b14 diff --git a/jdk/make/CopyIntoClasses.gmk b/jdk/make/CopyIntoClasses.gmk index 36b0919fa2f..b3a216fb90e 100644 --- a/jdk/make/CopyIntoClasses.gmk +++ b/jdk/make/CopyIntoClasses.gmk @@ -111,20 +111,8 @@ else ALL_META-INF_DIRS := $(ALL_META-INF_DIRS_share) endif -ifndef OPENJDK - ALL_META-INF_DIRS += $(JDK_TOPDIR)/src/closed/share/classes/sun/java2d/cmm/kcms/META-INF -endif - SRC_SERVICES_FILES := $(wildcard $(addsuffix /services/*, $(ALL_META-INF_DIRS))) -ifdef OPENJDK - SRC_SERVICES_FILES := $(filter-out %sun/dc/META-INF/services/sun.java2d.pipe.RenderingEngine, $(SRC_SERVICES_FILES)) - SRC_SERVICES_FILES := $(filter-out %sun/java2d/cmm/kcms/META-INF/services/sun.java2d.cmm.CMMServiceProvider, $(SRC_SERVICES_FILES)) -else - SRC_SERVICES_FILES := $(filter-out %sun/java2d/pisces/META-INF/services/sun.java2d.pipe.RenderingEngine, $(SRC_SERVICES_FILES)) - SRC_SERVICES_FILES := $(filter-out %sun/java2d/cmm/lcms/META-INF/services/sun.java2d.cmm.CMMServiceProvider, $(SRC_SERVICES_FILES)) -endif - # The number of services files are relatively few. If the increase in numbers, then # we have to use ListPathsSafelyNow here. # Change $(JDK_TOPDIR)/src/.../META-INF/services/yyyy into $(JDK_OUTPUTDIR)/classes/META-INF/services/yyyy diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index fd2e516be70..06a5672d00a 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -318,7 +318,7 @@ ifeq ($(OPENJDK_TARGET_OS), aix) endif ifeq ($(OPENJDK_TARGET_OS), macosx) - LIBAWT_FILES += awt_LoadLibrary.c img_colors.c + LIBAWT_FILES += awt_LoadLibrary.c LIBAWT_CFLAGS += -F/System/Library/Frameworks/JavaVM.framework/Frameworks endif @@ -606,7 +606,6 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),) debug_mem.c \ debug_trace.c \ debug_util.c \ - awt_Plugin.c \ gnome_interface.c \ gtk2_interface.c \ swing_GTKEngine.c \ @@ -657,17 +656,34 @@ endif ########################################################################################## +LIBLCMS_DIR := $(JDK_TOPDIR)/src/share/native/sun/java2d/cmm/lcms + +ifeq ($(USE_EXTERNAL_LCMS), true) + # If we're using an external library, we'll just need the wrapper part. + # By including it explicitely, all other files will be excluded. + BUILD_LIBLCMS_INCLUDE_FILES := LCMS.c + BUILD_LIBLCMS_HEADERS := +else + BUILD_LIBLCMS_INCLUDE_FILES := + # If we're using the bundled library, we'll need to include it in the + # include path explicitly. Otherwise the system headers will be used. + BUILD_LIBLCMS_HEADERS := -I$(LIBLCMS_DIR) +endif + # TODO: Update awt lib path when awt is converted $(eval $(call SetupNativeCompilation,BUILD_LIBLCMS, \ LIBRARY := lcms, \ OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \ - SRC := $(JDK_TOPDIR)/src/share/native/sun/java2d/cmm/lcms, \ + SRC := $(LIBLCMS_DIR), \ + INCLUDE_FILES := $(BUILD_LIBLCMS_INCLUDE_FILES), \ LANG := C, \ OPTIMIZATION := HIGHEST, \ CFLAGS := $(filter-out -xc99=%none, $(CFLAGS_JDKLIB)) \ $(SHARED_LIBRARY_FLAGS) \ -I$(JDK_TOPDIR)/src/share/native/sun/java2d \ - -I$(JDK_TOPDIR)/src/share/native/sun/awt/debug, \ + -I$(JDK_TOPDIR)/src/share/native/sun/awt/debug \ + $(BUILD_LIBLCMS_HEADERS) \ + $(LCMS_CFLAGS), \ CFLAGS_solaris := -xc99=no_lib, \ CFLAGS_windows := -DCMS_IS_WINDOWS_, \ MAPFILE := $(JDK_TOPDIR)/make/mapfiles/liblcms/mapfile-vers, \ @@ -675,10 +691,10 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBLCMS, \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_solaris := /usr/lib$(OPENJDK_TARGET_CPU_ISADIR)/libm.so.2, \ LDFLAGS_windows := $(WIN_AWT_LIB) $(WIN_JAVA_LIB), \ - LDFLAGS_SUFFIX_solaris := -lawt -ljava -ljvm -lc, \ - LDFLAGS_SUFFIX_macosx := $(LIBM) -lawt -ljava -ljvm, \ - LDFLAGS_SUFFIX_linux := -lm -lawt -ljava -ljvm, \ - LDFLAGS_SUFFIX_aix := -lm -lawt -ljava -ljvm,\ + LDFLAGS_SUFFIX_solaris := -lawt -ljava -ljvm -lc $(LCMS_LIBS), \ + LDFLAGS_SUFFIX_macosx := $(LIBM) -lawt -ljava -ljvm $(LCMS_LIBS), \ + LDFLAGS_SUFFIX_linux := -lm -lawt -ljava -ljvm $(LCMS_LIBS), \ + LDFLAGS_SUFFIX_aix := -lm -lawt -ljava -ljvm $(LCMS_LIBS),\ VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \ RC_FLAGS := $(RC_FLAGS) \ -D "JDK_FNAME=lcms.dll" \ diff --git a/jdk/make/mapfiles/libawt/mapfile-mawt-vers b/jdk/make/mapfiles/libawt/mapfile-mawt-vers index a50c13a62e5..b8ea1636c88 100644 --- a/jdk/make/mapfiles/libawt/mapfile-mawt-vers +++ b/jdk/make/mapfiles/libawt/mapfile-mawt-vers @@ -1,5 +1,5 @@ # -# Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2001, 2014, 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 @@ -249,11 +249,6 @@ SUNWprivate_1.1 { Java_sun_awt_motif_XsessionWMcommand; Java_sun_awt_motif_XsessionWMcommand_New; - # Java Plugin - getAwtLockFunctions; - getAwtData; - getAwtDisplay; - # libfontmanager entry points AWTIsHeadless; AWTCountFonts; diff --git a/jdk/make/mapfiles/libawt/mapfile-vers b/jdk/make/mapfiles/libawt/mapfile-vers index 05ca7d538dd..b1c6a39ec1e 100644 --- a/jdk/make/mapfiles/libawt/mapfile-vers +++ b/jdk/make/mapfiles/libawt/mapfile-vers @@ -1,5 +1,5 @@ # -# Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 2014, 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 @@ -173,13 +173,6 @@ SUNWprivate_1.1 { Java_sun_awt_motif_XsessionWMcommand; Java_sun_awt_motif_XsessionWMcommand_New; - # Java Plugin - # This is in awt_LoadLibrary.c and falls through to libmawt. - # Evidently plugin needs this for backward compatability. - getAwtLockFunctions; - getAwtData; - getAwtDisplay; - # libfontmanager entry points AWTIsHeadless; GrPrim_Sg2dGetCompInfo; diff --git a/jdk/make/mapfiles/libawt/mapfile-vers-linux b/jdk/make/mapfiles/libawt/mapfile-vers-linux index f8967e09462..922b015c68c 100644 --- a/jdk/make/mapfiles/libawt/mapfile-vers-linux +++ b/jdk/make/mapfiles/libawt/mapfile-vers-linux @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2014, 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 @@ -152,13 +152,6 @@ SUNWprivate_1.1 { # Evidently CDE needs this for backward compatability. Java_sun_awt_motif_XsessionWMcommand; - # Java Plugin - # This is in awt_LoadLibrary.c and falls through to libmawt. - # Evidently plugin needs this for backward compatability. - getAwtLockFunctions; - getAwtData; - getAwtDisplay; - # libfontmanager entry points AWTIsHeadless; GrPrim_Sg2dGetCompInfo; @@ -283,11 +276,6 @@ SUNWprivate_1.1 { # CDE private entry point Java_sun_awt_motif_XsessionWMcommand; - # Java Plugin - getAwtLockFunctions; - getAwtData; - getAwtDisplay; - # libfontmanager entry points AWTIsHeadless; AWTCountFonts; diff --git a/jdk/make/mapfiles/libawt_xawt/mapfile-vers b/jdk/make/mapfiles/libawt_xawt/mapfile-vers index 15089a114ca..3ae8af3ddbf 100644 --- a/jdk/make/mapfiles/libawt_xawt/mapfile-vers +++ b/jdk/make/mapfiles/libawt_xawt/mapfile-vers @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2014, 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 @@ -449,12 +449,6 @@ SUNWprivate_1.1 { awt_Lock; awt_GetComponent; - # Java Plugin - # This is in awt_LoadLibrary.c and falls through to libmawt. - # Evidently plugin needs this for backward compatability. - getAwtLockFunctions; - getAwtData; - getAwtDisplay; #XAWT entry point for CDE Java_sun_awt_motif_XsessionWMcommand; Java_sun_awt_motif_XsessionWMcommand_New; diff --git a/jdk/make/mapfiles/libjpeg/mapfile-vers-closed b/jdk/make/mapfiles/libjpeg/mapfile-vers-closed index 9b3724c4994..6f84d2da352 100644 --- a/jdk/make/mapfiles/libjpeg/mapfile-vers-closed +++ b/jdk/make/mapfiles/libjpeg/mapfile-vers-closed @@ -31,10 +31,6 @@ SUNWprivate_1.1 { Java_sun_awt_image_JPEGImageDecoder_initIDs; Java_sun_awt_image_JPEGImageDecoder_readImage; - Java_sun_awt_image_codec_JPEGImageDecoderImpl_initDecoder; - Java_sun_awt_image_codec_JPEGImageDecoderImpl_readJPEGStream; - Java_sun_awt_image_codec_JPEGImageEncoderImpl_initEncoder; - Java_sun_awt_image_codec_JPEGImageEncoderImpl_writeJPEGStream; Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_initReaderIDs; Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_initJPEGImageReader; diff --git a/jdk/make/profile-rtjar-includes.txt b/jdk/make/profile-rtjar-includes.txt index 95b3357f183..b20031a017e 100644 --- a/jdk/make/profile-rtjar-includes.txt +++ b/jdk/make/profile-rtjar-includes.txt @@ -239,6 +239,4 @@ FULL_JRE_INCLUDE_METAINF_SERVICES := \ META-INF/services/javax.sound.sampled.spi.AudioFileReader \ META-INF/services/javax.sound.sampled.spi.AudioFileWriter \ META-INF/services/javax.sound.sampled.spi.FormatConversionProvider \ - META-INF/services/javax.sound.sampled.spi.MixerProvider \ - META-INF/services/sun.java2d.cmm.PCMM \ - META-INF/services/sun.java2d.pipe.RenderingEngine + META-INF/services/javax.sound.sampled.spi.MixerProvider diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java index dde9b1be337..9fbf67283cd 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java @@ -121,6 +121,10 @@ class AquaComboBoxPopup extends BasicComboPopup { public void show() { final int startItemCount = comboBox.getItemCount(); + if (startItemCount == 0) { + return; + } + final Rectangle popupBounds = adjustPopupAndGetBounds(); if (popupBounds == null) return; // null means don't show diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java b/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java index be6a787a45b..4838ba48879 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java @@ -46,10 +46,8 @@ import com.apple.laf.AquaIcon.JRSUIControlSpec; import com.apple.laf.AquaIcon.SystemIcon; import com.apple.laf.AquaUtils.RecyclableObject; import com.apple.laf.AquaUtils.RecyclableSingleton; -import java.util.Arrays; -import java.util.List; -import sun.awt.image.MultiResolutionBufferedImage; import sun.awt.image.MultiResolutionImage; +import sun.awt.image.MultiResolutionCachedImage; public class AquaImageFactory { public static IconUIResource getConfirmImageIcon() { @@ -57,7 +55,7 @@ public class AquaImageFactory { return new IconUIResource(new AquaIcon.CachingScalingIcon(kAlertIconSize, kAlertIconSize) { Image createImage() { - return getThisApplicationsIcon(kAlertIconSize, kAlertIconSize); + return getGenericJavaIcon(); } }); } @@ -83,24 +81,6 @@ public class AquaImageFactory { return getAppIconCompositedOn(lockIcon); } - static Image getThisApplicationsIcon(final int width, final int height) { - final String path = getPathToThisApplication(); - - if (path == null) { - return getGenericJavaIcon(); - } - - if (path.endsWith("/Home/bin")) { - return getGenericJavaIcon(); - } - - if (path.startsWith("/usr/bin")) { - return getGenericJavaIcon(); - } - - return AquaUtils.getCImageCreator().createImageOfFile(path, height, width); - } - static Image getGenericJavaIcon() { return java.security.AccessController.doPrivileged(new PrivilegedAction() { public Image run() { @@ -125,9 +105,9 @@ public class AquaImageFactory { private static final int kAlertIconSize = 64; static IconUIResource getAppIconCompositedOn(final Image background) { - if (background instanceof MultiResolutionBufferedImage) { + if (background instanceof MultiResolutionCachedImage) { int width = background.getWidth(null); - Image mrIconImage = ((MultiResolutionBufferedImage) background).map( + Image mrIconImage = ((MultiResolutionCachedImage) background).map( rv -> getAppIconImageCompositedOn(rv, rv.getWidth(null) / width)); return new IconUIResource(new ImageIcon(mrIconImage)); } @@ -144,7 +124,7 @@ public class AquaImageFactory { final Icon smallAppIconScaled = new AquaIcon.CachingScalingIcon( kAlertSubIconSize, kAlertSubIconSize) { Image createImage() { - return getThisApplicationsIcon(kAlertSubIconSize, kAlertSubIconSize); + return getGenericJavaIcon(); } }; @@ -306,21 +286,7 @@ public class AquaImageFactory { private static Image getNSIcon(String imageName) { Image icon = Toolkit.getDefaultToolkit() .getImage("NSImage://" + imageName); - - if (icon instanceof MultiResolutionImage) { - return icon; - } - - int w = icon.getWidth(null); - int h = icon.getHeight(null); - - Dimension[] sizes = new Dimension[]{ - new Dimension(w, h), new Dimension(2 * w, 2 * h) - }; - - return new MultiResolutionBufferedImage(icon, sizes, (width, height) -> - AquaUtils.getCImageCreator().createImageFromName( - imageName, width, height)); + return icon; } public static class NineSliceMetrics { @@ -530,4 +496,4 @@ public class AquaImageFactory { public static Color getSelectionInactiveForegroundColorUIResource() { return new SystemColorProxy(LWCToolkit.getAppleColor(LWCToolkit.INACTIVE_SELECTION_FOREGROUND_COLOR)); } -} \ No newline at end of file +} diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaPainter.java b/jdk/src/macosx/classes/com/apple/laf/AquaPainter.java index ee4fcba1a4d..a2ebaf1c920 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaPainter.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaPainter.java @@ -174,11 +174,7 @@ abstract class AquaPainter { bounds, controlState); Image img = cache.getImage(key); if (img == null) { - - Image baseImage = createImage(imgX, imgY, imgW, imgH, bounds, - control, controlState); - - img = new MultiResolutionBufferedImage(baseImage, + img = new MultiResolutionCachedImage(imgW, imgH, (rvWidth, rvHeight) -> createImage(imgX, imgY, rvWidth, rvHeight, bounds, control, controlState)); diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java b/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java index a20897f7b31..078435b161b 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java @@ -48,7 +48,7 @@ import sun.security.action.GetPropertyAction; import sun.swing.SwingUtilities2; import com.apple.laf.AquaImageFactory.SlicedImageControl; -import sun.awt.image.MultiResolutionBufferedImage; +import sun.awt.image.MultiResolutionCachedImage; final class AquaUtils { @@ -124,8 +124,8 @@ final class AquaUtils { static Image generateLightenedImage(final Image image, final int percent) { final GrayFilter filter = new GrayFilter(true, percent); - return (image instanceof MultiResolutionBufferedImage) - ? ((MultiResolutionBufferedImage) image).map( + return (image instanceof MultiResolutionCachedImage) + ? ((MultiResolutionCachedImage) image).map( rv -> generateLightenedImage(rv, filter)) : generateLightenedImage(image, filter); } diff --git a/jdk/src/macosx/classes/sun/font/CFontManager.java b/jdk/src/macosx/classes/sun/font/CFontManager.java index ad2bfab62ba..8e1cead53c2 100644 --- a/jdk/src/macosx/classes/sun/font/CFontManager.java +++ b/jdk/src/macosx/classes/sun/font/CFontManager.java @@ -40,7 +40,7 @@ import javax.swing.plaf.FontUIResource; import sun.awt.FontConfiguration; import sun.awt.HeadlessToolkit; -import sun.misc.ThreadGroupUtils; +import sun.awt.util.ThreadGroupUtils; import sun.lwawt.macosx.*; public class CFontManager extends SunFontManager { diff --git a/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java b/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java index bb360d6d677..27d43b1bfce 100644 --- a/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java +++ b/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java @@ -171,7 +171,9 @@ final class LWChoicePeer extends LWComponentPeer> SwingUtilities.invokeLater(() -> { JPopupMenu popupMenu = getPopupMenu(); // Need to override the invoker for proper grab handling - if (popupMenu != null && popupMenu.getInvoker() != getTarget()) { + if (popupMenu != null + && popupMenu.isShowing() + && popupMenu.getInvoker() != getTarget()) { // The popup is now visible with correct location // Save it and restore after toggling visibility and changing invoker Point loc = popupMenu.getLocationOnScreen(); diff --git a/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java b/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java index 5880d06be4d..354f2538012 100644 --- a/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java +++ b/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java @@ -63,8 +63,6 @@ import javax.swing.JComponent; import javax.swing.SwingUtilities; import javax.swing.RepaintManager; -import sun.lwawt.macosx.CDropTarget; - import com.sun.java.swing.SwingUtilities3; public abstract class LWComponentPeer @@ -137,7 +135,7 @@ public abstract class LWComponentPeer private final Object dropTargetLock = new Object(); private int fNumDropTargets = 0; - private CDropTarget fDropTarget = null; + private PlatformDropTarget fDropTarget = null; private final PlatformComponent platformComponent; @@ -1063,11 +1061,11 @@ public abstract class LWComponentPeer // if it's the first (or last) one for the component. Otherwise this call is a no-op. if (++fNumDropTargets == 1) { // Having a non-null drop target would be an error but let's check just in case: - if (fDropTarget != null) - System.err.println("CComponent.addDropTarget(): current drop target is non-null."); - + if (fDropTarget != null) { + throw new IllegalStateException("Current drop target is not null"); + } // Create a new drop target: - fDropTarget = CDropTarget.createDropTarget(dt, target, this); + fDropTarget = LWToolkit.getLWToolkit().createDropTarget(dt, target, this); } } } diff --git a/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java b/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java index 8dd9467eed6..315a19a7ff3 100644 --- a/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java +++ b/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java @@ -28,6 +28,7 @@ package sun.lwawt; import java.awt.*; import java.awt.List; import java.awt.datatransfer.*; +import java.awt.dnd.DropTarget; import java.awt.image.*; import java.awt.peer.*; import java.security.*; @@ -35,7 +36,7 @@ import java.util.*; import sun.awt.*; import sun.print.*; -import sun.misc.ThreadGroupUtils; +import sun.awt.util.ThreadGroupUtils; import static sun.lwawt.LWWindowPeer.PeerType; @@ -440,6 +441,10 @@ public abstract class LWToolkit extends SunToolkit implements Runnable { protected abstract FileDialogPeer createFileDialogPeer(FileDialog target); + protected abstract PlatformDropTarget createDropTarget(DropTarget dropTarget, + Component component, + LWComponentPeer peer); + // ---- UTILITY METHODS ---- // /* diff --git a/jdk/src/solaris/native/sun/awt/awt_Plugin.h b/jdk/src/macosx/classes/sun/lwawt/PlatformDropTarget.java similarity index 55% rename from jdk/src/solaris/native/sun/awt/awt_Plugin.h rename to jdk/src/macosx/classes/sun/lwawt/PlatformDropTarget.java index 434fabb7216..e2a9a70e70f 100644 --- a/jdk/src/solaris/native/sun/awt/awt_Plugin.h +++ b/jdk/src/macosx/classes/sun/lwawt/PlatformDropTarget.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -23,32 +23,12 @@ * questions. */ -/* - * Fix 4221246: Export functions for Netscape to use to get AWT info - */ +package sun.lwawt; -#ifndef _AWT_PLUGIN_H_ -#define _AWT_PLUGIN_H_ +public interface PlatformDropTarget { -#include -#include -#include - -void getAwtLockFunctions(void (**AwtLock)(JNIEnv *), - void (**AwtUnlock)(JNIEnv *), - void (**AwtNoFlushUnlock)(JNIEnv *), - void *); - -void getExtAwtData(Display *, - int32_t, - int32_t *, /* awt_depth */ - Colormap *, /* awt_cmap */ - Visual **, /* awt_visInfo.visual */ - int32_t *, /* awt_num_colors */ - void *); - -void getAwtData(int32_t *, Colormap *, Visual **, int32_t *, void *); - -Display *getAwtDisplay(void); - -#endif /* _AWT_PLUGIN_H_ */ + /** + * Release native dragging destination, if any + */ + void dispose(); +} diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java index 26d2347ff15..c07356057ee 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java @@ -31,6 +31,7 @@ import sun.awt.image.ImageRepresentation; import java.io.*; import java.net.URL; +import java.nio.charset.Charset; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.*; @@ -126,7 +127,7 @@ public class CDataTransferer extends DataTransferer { if (format == CF_URL && URL.class.equals(flavor.getRepresentationClass())) { - String charset = getDefaultTextCharset(); + String charset = Charset.defaultCharset().name(); if (transferable != null && transferable.isDataFlavorSupported(javaTextEncodingFlavor)) { try { charset = new String((byte[])transferable.getTransferData(javaTextEncodingFlavor), "UTF-8"); diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java index 910e1407a36..d4f4353d9ec 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java @@ -25,54 +25,37 @@ package sun.lwawt.macosx; -import java.awt.Component; -import java.awt.peer.ComponentPeer; +import sun.lwawt.LWComponentPeer; +import sun.lwawt.PlatformDropTarget; + +import java.awt.*; import java.awt.dnd.DropTarget; -import sun.lwawt.LWComponentPeer; -import sun.lwawt.PlatformWindow; +final class CDropTarget implements PlatformDropTarget { + private long fNativeDropTarget; -public final class CDropTarget { - - Component fComponent; - ComponentPeer fPeer; - DropTarget fDropTarget; - private long fNativeDropTarget; - - public static CDropTarget createDropTarget(DropTarget dropTarget, Component component, ComponentPeer peer) { - return new CDropTarget(dropTarget, component, peer); - } - - private CDropTarget(DropTarget dropTarget, Component component, ComponentPeer peer) { - super(); - - fDropTarget = dropTarget; - fComponent = component; - fPeer = peer; - - long nativePeer = CPlatformWindow.getNativeViewPtr(((LWComponentPeer) peer).getPlatformWindow()); + CDropTarget(DropTarget dropTarget, Component component, LWComponentPeer peer) { + long nativePeer = CPlatformWindow.getNativeViewPtr(peer.getPlatformWindow()); if (nativePeer == 0L) return; // Unsupported for a window without a native view (plugin) // Create native dragging destination: - fNativeDropTarget = this.createNativeDropTarget(dropTarget, component, peer, nativePeer); + fNativeDropTarget = createNativeDropTarget(dropTarget, component, nativePeer); if (fNativeDropTarget == 0) { throw new IllegalStateException("CDropTarget.createNativeDropTarget() failed."); } } - public DropTarget getDropTarget() { - return fDropTarget; - } - + @Override public void dispose() { - // Release native dragging destination, if any: if (fNativeDropTarget != 0) { - this.releaseNativeDropTarget(fNativeDropTarget); + releaseNativeDropTarget(fNativeDropTarget); fNativeDropTarget = 0; } } - protected native long createNativeDropTarget(DropTarget dropTarget, Component component, ComponentPeer peer, long nativePeer); + protected native long createNativeDropTarget(DropTarget dropTarget, + Component component, + long nativePeer); protected native void releaseNativeDropTarget(long nativeDropTarget); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java index 17815d4882e..69bdab05734 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java @@ -32,7 +32,7 @@ import java.awt.image.*; import java.util.Arrays; import java.util.List; import sun.awt.image.MultiResolutionImage; -import sun.awt.image.MultiResolutionBufferedImage; +import sun.awt.image.MultiResolutionCachedImage; import sun.awt.image.SunWritableRaster; @@ -62,41 +62,41 @@ public class CImage extends CFRetainedResource { // This is used to create a CImage with an NSImage pointer. It MUST be a CFRetained // NSImage, and the CImage takes ownership of the non-GC retain. If callers need the // NSImage themselves, they MUST call retain on the NSImage themselves. - public BufferedImage createImageUsingNativeSize(final long image) { + public Image createImageUsingNativeSize(final long image) { if (image == 0) return null; final Dimension2D size = nativeGetNSImageSize(image); - return createBufferedImage(image, size.getWidth(), size.getHeight()); + return createImage(image, size.getWidth(), size.getHeight()); } // the width and height passed in as a parameter could differ than the width and the height of the NSImage (image), in that case, the image will be scaled - BufferedImage createBufferedImage(long image, double width, double height) { + Image createImage(long image, double width, double height) { if (image == 0) throw new Error("Unable to instantiate CImage with null native image reference."); return createImageWithSize(image, width, height); } - public BufferedImage createImageWithSize(final long image, final double width, final double height) { + public Image createImageWithSize(final long image, final double width, final double height) { final CImage img = new CImage(image); img.resize(width, height); return img.toImage(); } // This is used to create a CImage that represents the icon of the given file. - public BufferedImage createImageOfFile(final String file, final int width, final int height) { - return createBufferedImage(nativeCreateNSImageOfFileFromLaunchServices(file), width, height); + public Image createImageOfFile(final String file, final int width, final int height) { + return createImage(nativeCreateNSImageOfFileFromLaunchServices(file), width, height); } - public BufferedImage createImageFromFile(final String file, final double width, final double height) { + public Image createImageFromFile(final String file, final double width, final double height) { final long image = nativeCreateNSImageFromFileContents(file); nativeSetNSImageSize(image, width, height); - return createBufferedImage(image, width, height); + return createImage(image, width, height); } - public BufferedImage createSystemImageFromSelector(final String iconSelector, final int width, final int height) { - return createBufferedImage(nativeCreateNSImageFromIconSelector(getSelectorAsInt(iconSelector)), width, height); + public Image createSystemImageFromSelector(final String iconSelector, final int width, final int height) { + return createImage(nativeCreateNSImageFromIconSelector(getSelectorAsInt(iconSelector)), width, height); } public Image createImageFromName(final String name, final int width, final int height) { - return createBufferedImage(nativeCreateNSImageFromImageName(name), width, height); + return createImage(nativeCreateNSImageFromImageName(name), width, height); } public Image createImageFromName(final String name) { @@ -232,7 +232,7 @@ public class CImage extends CFRetainedResource { } /** @return A MultiResolution image created from nsImagePtr, or null. */ - private BufferedImage toImage() { + private Image toImage() { if (ptr == 0) return null; final Dimension2D size = nativeGetNSImageSize(ptr); @@ -243,11 +243,11 @@ public class CImage extends CFRetainedResource { = nativeGetNSImageRepresentationSizes(ptr, size.getWidth(), size.getHeight()); - BufferedImage baseImage = toImage(w, h, w, h); - - return sizes == null || sizes.length < 2 ? baseImage - : new MultiResolutionBufferedImage(baseImage, sizes, - (width, height) -> toImage(w, h, width, height)); + return sizes == null || sizes.length < 2 ? + new MultiResolutionCachedImage(w, h, (width, height) + -> toImage(w, h, width, height)) + : new MultiResolutionCachedImage(w, h, sizes, (width, height) + -> toImage(w, h, width, height)); } private BufferedImage toImage(int srcWidth, int srcHeight, int dstWidth, int dstHeight) { diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java index fc72ef79474..0acc67feed6 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java @@ -309,6 +309,10 @@ public final class CWarningWindow extends CPlatformWindow @Override public void dispose() { cancelTasks(); + SurfaceData surfaceData = contentView.getSurfaceData(); + if (surfaceData != null) { + surfaceData.invalidate(); + } super.dispose(); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java b/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java index 4a153fc94d4..2bb5d4ac508 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java @@ -611,19 +611,20 @@ public final class LWCToolkit extends LWToolkit { } /** - * Kicks an event over to the appropriate eventqueue and waits for it to + * Kicks an event over to the appropriate event queue and waits for it to * finish To avoid deadlocking, we manually run the NSRunLoop while waiting * Any selector invoked using ThreadUtilities performOnMainThread will be * processed in doAWTRunLoop The InvocationEvent will call * LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual - * runloop Does not dispatch native events while in the loop + * run loop. Does not dispatch native events while in the loop */ public static void invokeAndWait(Runnable runnable, Component component) throws InvocationTargetException { - final long mediator = createAWTRunLoopMediator(); + Objects.requireNonNull(component, "Null component provided to invokeAndWait"); + long mediator = createAWTRunLoopMediator(); InvocationEvent invocationEvent = - new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), + new InvocationEvent(component, runnable, () -> { if (mediator != 0) { @@ -632,49 +633,42 @@ public final class LWCToolkit extends LWToolkit { }, true); - if (component != null) { - AppContext appContext = SunToolkit.targetToAppContext(component); - SunToolkit.postEvent(appContext, invocationEvent); - - // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock - SunToolkit.flushPendingEvents(appContext); - } else { - // This should be the equivalent to EventQueue.invokeAndWait - ((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent); - } - + AppContext appContext = SunToolkit.targetToAppContext(component); + SunToolkit.postEvent(appContext, invocationEvent); + // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock + SunToolkit.flushPendingEvents(appContext); doAWTRunLoop(mediator, false); - Throwable eventException = invocationEvent.getException(); - if (eventException != null) { - if (eventException instanceof UndeclaredThrowableException) { - eventException = ((UndeclaredThrowableException)eventException).getUndeclaredThrowable(); - } - throw new InvocationTargetException(eventException); - } + checkException(invocationEvent); } public static void invokeLater(Runnable event, Component component) throws InvocationTargetException { - final InvocationEvent invocationEvent = - new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), event); + Objects.requireNonNull(component, "Null component provided to invokeLater"); - if (component != null) { - final AppContext appContext = SunToolkit.targetToAppContext(component); - SunToolkit.postEvent(appContext, invocationEvent); + InvocationEvent invocationEvent = new InvocationEvent(component, event); - // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock - SunToolkit.flushPendingEvents(appContext); - } else { - // This should be the equivalent to EventQueue.invokeAndWait - ((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent); - } + AppContext appContext = SunToolkit.targetToAppContext(component); + SunToolkit.postEvent(SunToolkit.targetToAppContext(component), invocationEvent); + // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock + SunToolkit.flushPendingEvents(appContext); - final Throwable eventException = invocationEvent.getException(); + checkException(invocationEvent); + } + + /** + * Checks if exception occurred while {@code InvocationEvent} was processed and rethrows it as + * an {@code InvocationTargetException} + * + * @param event the event to check for an exception + * @throws InvocationTargetException if exception occurred when event was processed + */ + private static void checkException(InvocationEvent event) throws InvocationTargetException { + Throwable eventException = event.getException(); if (eventException == null) return; if (eventException instanceof UndeclaredThrowableException) { - throw new InvocationTargetException(((UndeclaredThrowableException)eventException).getUndeclaredThrowable()); + eventException = ((UndeclaredThrowableException)eventException).getUndeclaredThrowable(); } throw new InvocationTargetException(eventException); } @@ -686,11 +680,6 @@ public final class LWCToolkit extends LWToolkit { */ native static void performOnMainThreadAfterDelay(Runnable r, long delay); - // This exists purely to get around permissions issues with getSystemEventQueueImpl - EventQueue getSystemEventQueueForInvokeAndWait() { - return getSystemEventQueueImpl(); - } - // DnD support @Override @@ -712,7 +701,14 @@ public final class LWCToolkit extends LWToolkit { return (T)dgr; } -// InputMethodSupport Method + @Override + protected PlatformDropTarget createDropTarget(DropTarget dropTarget, + Component component, + LWComponentPeer peer) { + return new CDropTarget(dropTarget, component, peer); + } + + // InputMethodSupport Method /** * Returns the default keyboard locale of the underlying operating system */ diff --git a/jdk/src/macosx/native/sun/awt/AWTView.m b/jdk/src/macosx/native/sun/awt/AWTView.m index bcc832190f4..830fb77e82b 100644 --- a/jdk/src/macosx/native/sun/awt/AWTView.m +++ b/jdk/src/macosx/native/sun/awt/AWTView.m @@ -27,6 +27,7 @@ #import #import +#import "jni_util.h" #import "ThreadUtilities.h" #import "AWTView.h" @@ -391,14 +392,12 @@ AWT_ASSERT_APPKIT_THREAD; (jint)absP.x, (jint)absP.y, [event deltaY], [event deltaX]); - if (jEvent == nil) { - // Unable to create event by some reason. - return; - } + CHECK_NULL(jEvent); static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView"); static JNF_MEMBER_CACHE(jm_deliverMouseEvent, jc_PlatformView, "deliverMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V"); JNFCallVoidMethod(env, m_cPlatformView, jm_deliverMouseEvent, jEvent); + (*env)->DeleteLocalRef(env, jEvent); } - (void) resetTrackingArea { @@ -447,20 +446,22 @@ AWT_ASSERT_APPKIT_THREAD; static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent"); static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;)V"); - jobject jevent = JNFNewObject(env, jctor_NSEvent, + jobject jEvent = JNFNewObject(env, jctor_NSEvent, [event type], [event modifierFlags], [event keyCode], characters); + CHECK_NULL(jEvent); static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView"); static JNF_MEMBER_CACHE(jm_deliverKeyEvent, jc_PlatformView, "deliverKeyEvent", "(Lsun/lwawt/macosx/NSEvent;)V"); - JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jevent); + JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jEvent); if (characters != NULL) { (*env)->DeleteLocalRef(env, characters); } + (*env)->DeleteLocalRef(env, jEvent); } -(void) deliverResize: (NSRect) rect { diff --git a/jdk/src/macosx/native/sun/awt/AWTWindow.m b/jdk/src/macosx/native/sun/awt/AWTWindow.m index c2577584886..6a9c1166e84 100644 --- a/jdk/src/macosx/native/sun/awt/AWTWindow.m +++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m @@ -261,7 +261,8 @@ AWT_ASSERT_APPKIT_THREAD; // returns id for the topmost window under mouse + (NSInteger) getTopmostWindowUnderMouseID { - + NSInteger result = -1; + NSRect screenRect = [[NSScreen mainScreen] frame]; NSPoint nsMouseLocation = [NSEvent mouseLocation]; CGPoint cgMouseLocation = CGPointMake(nsMouseLocation.x, screenRect.size.height - nsMouseLocation.y); @@ -274,11 +275,13 @@ AWT_ASSERT_APPKIT_THREAD; CGRect rect; CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[window objectForKey:(id)kCGWindowBounds], &rect); if (CGRectContainsPoint(rect, cgMouseLocation)) { - return [[window objectForKey:(id)kCGWindowNumber] integerValue]; + result = [[window objectForKey:(id)kCGWindowNumber] integerValue]; + break; } } } - return -1; + [windows release]; + return result; } // checks that this window is under the mouse cursor and this point is not overlapped by others windows diff --git a/jdk/src/macosx/native/sun/awt/CDropTarget.h b/jdk/src/macosx/native/sun/awt/CDropTarget.h index b6cd156562b..3b87485add7 100644 --- a/jdk/src/macosx/native/sun/awt/CDropTarget.h +++ b/jdk/src/macosx/native/sun/awt/CDropTarget.h @@ -48,7 +48,7 @@ + (CDropTarget *) currentDropTarget; // Common methods: -- (id)init:(jobject)dropTarget component:(jobject)jcomponent peer:(jobject)jpeer control:(id)control; +- (id)init:(jobject)dropTarget component:(jobject)jcomponent control:(id)control; - (void)controlModelControlValid; - (void)removeFromView:(JNIEnv *)env; diff --git a/jdk/src/macosx/native/sun/awt/CDropTarget.m b/jdk/src/macosx/native/sun/awt/CDropTarget.m index 41b0a192c61..7e038ab7715 100644 --- a/jdk/src/macosx/native/sun/awt/CDropTarget.m +++ b/jdk/src/macosx/native/sun/awt/CDropTarget.m @@ -65,7 +65,7 @@ extern JNFClassInfo jc_CDropTargetContextPeer; return sCurrentDropTarget; } -- (id)init:(jobject)jdropTarget component:(jobject)jcomponent peer:(jobject)jpeer control:(id)control +- (id)init:(jobject)jdropTarget component:(jobject)jcomponent control:(id)control { self = [super init]; DLog2(@"[CDropTarget init]: %@\n", self); @@ -714,13 +714,13 @@ extern JNFClassInfo jc_CDropTargetContextPeer; * Signature: (Ljava/awt/dnd/DropTarget;Ljava/awt/Component;Ljava/awt/peer/ComponentPeer;J)J */ JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CDropTarget_createNativeDropTarget - (JNIEnv *env, jobject jthis, jobject jdroptarget, jobject jcomponent, jobject jpeer, jlong jnativepeer) + (JNIEnv *env, jobject jthis, jobject jdroptarget, jobject jcomponent, jlong jnativepeer) { CDropTarget* dropTarget = nil; JNF_COCOA_ENTER(env); id controlObj = (id) jlong_to_ptr(jnativepeer); - dropTarget = [[CDropTarget alloc] init:jdroptarget component:jcomponent peer:jpeer control:controlObj]; + dropTarget = [[CDropTarget alloc] init:jdroptarget component:jcomponent control:controlObj]; JNF_COCOA_EXIT(env); return ptr_to_jlong(dropTarget); diff --git a/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m b/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m index 9b94b82abbc..a1813b6154d 100644 --- a/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m +++ b/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2014, 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 @@ -66,7 +66,8 @@ static CFMutableArrayRef getAllValidDisplayModes(jint displayID){ CFArrayAppendValue(validModes, cRef); } } - + CFRelease(allModes); + CGDisplayModeRef currentMode = CGDisplayCopyDisplayMode(displayID); BOOL containsCurrentMode = NO; @@ -81,6 +82,7 @@ static CFMutableArrayRef getAllValidDisplayModes(jint displayID){ if (!containsCurrentMode) { CFArrayAppendValue(validModes, currentMode); } + CGDisplayModeRelease(currentMode); return validModes; } @@ -154,14 +156,12 @@ JNIEXPORT jdouble JNICALL Java_sun_awt_CGraphicsDevice_nativeGetXResolution (JNIEnv *env, jclass class, jint displayID) { - // TODO: this is the physically correct answer, but we probably want - // to use NSScreen API instead... + // CGDisplayScreenSize can return 0 if displayID is invalid CGSize size = CGDisplayScreenSize(displayID); CGRect rect = CGDisplayBounds(displayID); // 1 inch == 25.4 mm jfloat inches = size.width / 25.4f; - jfloat dpi = rect.size.width / inches; - return dpi; + return inches > 0 ? rect.size.width / inches : 72; } /* @@ -173,14 +173,12 @@ JNIEXPORT jdouble JNICALL Java_sun_awt_CGraphicsDevice_nativeGetYResolution (JNIEnv *env, jclass class, jint displayID) { - // TODO: this is the physically correct answer, but we probably want - // to use NSScreen API instead... + // CGDisplayScreenSize can return 0 if displayID is invalid CGSize size = CGDisplayScreenSize(displayID); CGRect rect = CGDisplayBounds(displayID); // 1 inch == 25.4 mm jfloat inches = size.height / 25.4f; - jfloat dpi = rect.size.height / inches; - return dpi; + return inches > 0 ? rect.size.height / inches : 72; } /* @@ -235,17 +233,19 @@ Java_sun_awt_CGraphicsDevice_nativeSetDisplayMode { JNF_COCOA_ENTER(env); CFArrayRef allModes = getAllValidDisplayModes(displayID); - CGDisplayModeRef closestMatch = getBestModeForParameters(allModes, (int)w, (int)h, (int)bpp, (int)refrate); + __block CGError retCode = kCGErrorSuccess; if (closestMatch != NULL) { - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ + CGDisplayModeRetain(closestMatch); + [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ CGDisplayConfigRef config; retCode = CGBeginDisplayConfiguration(&config); if (retCode == kCGErrorSuccess) { CGConfigureDisplayWithDisplayMode(config, displayID, closestMatch, NULL); retCode = CGCompleteDisplayConfiguration(config, kCGConfigureForAppOnly); } + CGDisplayModeRelease(closestMatch); }]; } else { [JNFException raise:env as:kIllegalArgumentException reason:"Invalid display mode"]; @@ -253,8 +253,7 @@ Java_sun_awt_CGraphicsDevice_nativeSetDisplayMode if (retCode != kCGErrorSuccess){ [JNFException raise:env as:kIllegalArgumentException reason:"Unable to set display mode!"]; - } - + } CFRelease(allModes); JNF_COCOA_EXIT(env); } diff --git a/jdk/src/macosx/native/sun/awt/CImage.m b/jdk/src/macosx/native/sun/awt/CImage.m index b6db3458047..e4ef6306031 100644 --- a/jdk/src/macosx/native/sun/awt/CImage.m +++ b/jdk/src/macosx/native/sun/awt/CImage.m @@ -76,17 +76,17 @@ static void CImage_CopyNSImageIntoArray static NSBitmapImageRep* CImage_CreateImageRep(JNIEnv *env, jintArray buffer, jint width, jint height) { - NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL - pixelsWide:width - pixelsHigh:height - bitsPerSample:8 - samplesPerPixel:4 - hasAlpha:YES - isPlanar:NO - colorSpaceName:NSDeviceRGBColorSpace - bitmapFormat:NSAlphaFirstBitmapFormat - bytesPerRow:width*4 // TODO: use explicit scanStride - bitsPerPixel:32]; + NSBitmapImageRep* imageRep = [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL + pixelsWide:width + pixelsHigh:height + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSDeviceRGBColorSpace + bitmapFormat:NSAlphaFirstBitmapFormat + bytesPerRow:width*4 // TODO: use explicit scanStride + bitsPerPixel:32] autorelease]; jint *imgData = (jint *)[imageRep bitmapData]; if (imgData == NULL) return 0L; @@ -115,9 +115,8 @@ JNF_COCOA_ENTER(env); NSBitmapImageRep* imageRep = CImage_CreateImageRep(env, buffer, width, height); if (imageRep) { - NSImage *nsImage = [[[NSImage alloc] initWithSize:NSMakeSize(width, height)] retain]; + NSImage *nsImage = [[NSImage alloc] initWithSize:NSMakeSize(width, height)]; [nsImage addRepresentation:imageRep]; - [imageRep release]; result = ptr_to_jlong(nsImage); } @@ -160,7 +159,7 @@ JNF_COCOA_ENTER(env); (*env)->ReleaseIntArrayElements(env, widths, ws, JNI_ABORT); } if ([reps count]) { - NSImage *nsImage = [[[NSImage alloc] initWithSize:NSMakeSize(0, 0)] retain]; + NSImage *nsImage = [[NSImage alloc] initWithSize:NSMakeSize(0, 0)]; [nsImage addRepresentations: reps]; result = ptr_to_jlong(nsImage); } @@ -184,7 +183,7 @@ JNF_COCOA_ENTER(env); IconRef iconRef; if (noErr == GetIconRef(kOnSystemDisk, kSystemIconsCreator, selector, &iconRef)) { - image = [[[NSImage alloc] initWithIconRef:iconRef] retain]; + image = [[NSImage alloc] initWithIconRef:iconRef]; ReleaseIconRef(iconRef); } @@ -206,7 +205,7 @@ JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CImage_nativeCreateNSImageFromFile JNF_COCOA_ENTER(env); NSString *path = JNFNormalizedNSStringForPath(env, file); - image = [[[NSImage alloc] initByReferencingFile:path] retain]; + image = [[NSImage alloc] initByReferencingFile:path]; JNF_COCOA_EXIT(env); @@ -435,7 +434,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_lwawt_macosx_CImage_nativeGetPlatformImage JNF_COCOA_ENTER(env); - NSBitmapImageRep* imageRep = [CImage_CreateImageRep(env, buffer, width, height) autorelease]; + NSBitmapImageRep* imageRep = CImage_CreateImageRep(env, buffer, width, height); if (imageRep) { NSData *tiffImage = [imageRep TIFFRepresentation]; jsize tiffSize = (jsize)[tiffImage length]; diff --git a/jdk/src/macosx/native/sun/awt/CTrayIcon.m b/jdk/src/macosx/native/sun/awt/CTrayIcon.m index 79ae024f76f..35adf3b866d 100644 --- a/jdk/src/macosx/native/sun/awt/CTrayIcon.m +++ b/jdk/src/macosx/native/sun/awt/CTrayIcon.m @@ -25,6 +25,7 @@ #import #import +#import "jni_util.h" #import "CTrayIcon.h" #import "ThreadUtilities.h" @@ -146,14 +147,12 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize) { (jint)absP.x, (jint)absP.y, [event deltaY], [event deltaX]); - if (jEvent == nil) { - // Unable to create event by some reason. - return; - } + CHECK_NULL(jEvent); static JNF_CLASS_CACHE(jc_TrayIcon, "sun/lwawt/macosx/CTrayIcon"); static JNF_MEMBER_CACHE(jm_handleMouseEvent, jc_TrayIcon, "handleMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V"); JNFCallVoidMethod(env, peer, jm_handleMouseEvent, jEvent); + (*env)->DeleteLocalRef(env, jEvent); } @end //AWTTrayIcon diff --git a/jdk/src/macosx/native/sun/awt/LWCToolkit.m b/jdk/src/macosx/native/sun/awt/LWCToolkit.m index c78834547c3..7347ecdd251 100644 --- a/jdk/src/macosx/native/sun/awt/LWCToolkit.m +++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2014, 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 @@ -157,61 +157,6 @@ JNF_COCOA_ENTER(env); JNF_COCOA_EXIT(env); } -static JNF_CLASS_CACHE(jc_Component, "java/awt/Component"); -static JNF_MEMBER_CACHE(jf_Component_appContext, jc_Component, "appContext", "Lsun/awt/AppContext;"); -static JNF_CLASS_CACHE(jc_MenuComponent, "java/awt/MenuComponent"); -static JNF_MEMBER_CACHE(jf_MenuComponent_appContext, jc_MenuComponent, "appContext", "Lsun/awt/AppContext;"); - -/* - * Class: sun_awt_SunToolkit - * Method: getAppContext - * Signature: (Ljava/awt/Object;)Lsun/awt/AppContext; - */ -JNIEXPORT jobject JNICALL -Java_sun_awt_SunToolkit_getAppContext -(JNIEnv *env, jclass cls, jobject obj) -{ - jobject appContext = NULL; - -JNF_COCOA_ENTER(env); - - if (JNFIsInstanceOf(env, obj, &jc_Component)) { - appContext = JNFGetObjectField(env, obj, jf_Component_appContext); - } else if (JNFIsInstanceOf(env, obj, &jc_MenuComponent)) { - appContext = JNFGetObjectField(env, obj, jf_MenuComponent_appContext); - } - -JNF_COCOA_EXIT(env); - - return appContext; -} - -/* - * Class: sun_awt_SunToolkit - * Method: setAppContext - * Signature: (Ljava/lang/Object;Lsun/awt/AppContext;)Z - */ -JNIEXPORT jboolean JNICALL -Java_sun_awt_SunToolkit_setAppContext -(JNIEnv *env, jclass cls, jobject obj, jobject appContext) -{ - jboolean isComponent; - -JNF_COCOA_ENTER(env); - - if (JNFIsInstanceOf(env, obj, &jc_Component)) { - JNFSetObjectField(env, obj, jf_Component_appContext, appContext); - isComponent = JNI_TRUE; - } else if (JNFIsInstanceOf(env, obj, &jc_MenuComponent)) { - JNFSetObjectField(env, obj, jf_MenuComponent_appContext, appContext); - isComponent = JNI_FALSE; - } - -JNF_COCOA_EXIT(env); - - return isComponent; -} - /* * Class: sun_lwawt_macosx_LWCToolkit * Method: beep diff --git a/jdk/src/macosx/native/sun/awt/awt.m b/jdk/src/macosx/native/sun/awt/awt.m index 0f553d0e69f..f5fe3ea9eba 100644 --- a/jdk/src/macosx/native/sun/awt/awt.m +++ b/jdk/src/macosx/native/sun/awt/awt.m @@ -435,7 +435,7 @@ JNF_COCOA_ENTER(env); forceEmbeddedMode = YES; } JNIEnv* env = [ThreadUtilities getJNIEnvUncached]; - jclass jc_ThreadGroupUtils = (*env)->FindClass(env, "sun/misc/ThreadGroupUtils"); + jclass jc_ThreadGroupUtils = (*env)->FindClass(env, "sun/awt/util/ThreadGroupUtils"); jmethodID sjm_getRootThreadGroup = (*env)->GetStaticMethodID(env, jc_ThreadGroupUtils, "getRootThreadGroup", "()Ljava/lang/ThreadGroup;"); jobject rootThreadGroup = (*env)->CallStaticObjectMethod(env, jc_ThreadGroupUtils, sjm_getRootThreadGroup); [ThreadUtilities setAppkitThreadGroup:(*env)->NewGlobalRef(env, rootThreadGroup)]; diff --git a/jdk/src/macosx/native/sun/osxapp/AWT_debug.h b/jdk/src/macosx/native/sun/osxapp/AWT_debug.h index 1d02a824f3a..46f57cc6d73 100644 --- a/jdk/src/macosx/native/sun/osxapp/AWT_debug.h +++ b/jdk/src/macosx/native/sun/osxapp/AWT_debug.h @@ -32,9 +32,10 @@ #define kInternalError "java/lang/InternalError" #define AWT_DEBUG_LOG(str) \ - NSLog(@"Cocoa AWT: %@ %@", str, [NSThread callStackSymbols]) + NSLog(@"\tCocoa AWT: %@ %@", str, [NSThread callStackSymbols]) #define AWT_DEBUG_BUG_REPORT_MESSAGE \ - NSLog(@"\tPlease file a bug report at http://java.net/jira/browse/MACOSX_PORT with this message and a reproducible test case.") + NSLog(@"\tPlease file a bug report at http://bugreport.java.com/bugreport \ +with this message and a reproducible test case.") #endif diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java index 13f2d9349d0..3b2a081d860 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java @@ -664,6 +664,12 @@ public class PNGImageReader extends ImageReader { try { while (true) { int chunkLength = stream.readInt(); + + // verify the chunk length first + if (chunkLength < 0 || chunkLength + 4 < 0) { + throw new IIOException("Invalid chunk length " + chunkLength); + } + int chunkType = stream.readInt(); if (chunkType == IDAT_TYPE) { @@ -692,7 +698,7 @@ public class PNGImageReader extends ImageReader { // verify the chunk length if (chunkLength < 0) { - throw new IIOException("Invalid chunk lenght " + chunkLength); + throw new IIOException("Invalid chunk length " + chunkLength); }; try { diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java index d86b4ec92ac..b35e60d7ec6 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java @@ -1683,6 +1683,7 @@ public class GTKLookAndFeel extends SynthLookAndFeel { * adjustments that windows/metal do. This is because gtk doesn't * provide margins/insets for checkbox/radiobuttons. */ + @SuppressWarnings("fallthrough") private static class GnomeLayoutStyle extends DefaultLayoutStyle { private static GnomeLayoutStyle INSTANCE = new GnomeLayoutStyle(); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index 00530fa19ea..a6c1c895757 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -2409,6 +2409,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel // Windows LayoutStyle. From: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp + @SuppressWarnings("fallthrough") private class WindowsLayoutStyle extends DefaultLayoutStyle { @Override public int getPreferredGap(JComponent component1, diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java index 279bdb72b79..418f326165f 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java @@ -51,6 +51,8 @@ import static com.sun.java.swing.plaf.windows.XPStyle.Skin; public class WindowsScrollBarUI extends BasicScrollBarUI { private Grid thumbGrid; private Grid highlightGrid; + private Dimension horizontalThumbSize; + private Dimension verticalThumbSize; /** * Creates a UI for a JScrollBar. @@ -65,11 +67,32 @@ public class WindowsScrollBarUI extends BasicScrollBarUI { protected void installDefaults() { super.installDefaults(); - if (XPStyle.getXP() != null) { + XPStyle xp = XPStyle.getXP(); + if (xp != null) { scrollbar.setBorder(null); + horizontalThumbSize = getSize(scrollbar, xp, Part.SBP_THUMBBTNHORZ); + verticalThumbSize = getSize(scrollbar, xp, Part.SBP_THUMBBTNVERT); + } else { + horizontalThumbSize = null; + verticalThumbSize = null; } } + private static Dimension getSize(Component component, XPStyle xp, Part part) { + Skin skin = xp.getSkin(component, part); + return new Dimension(skin.getWidth(), skin.getHeight()); + } + + @Override + protected Dimension getMinimumThumbSize() { + if ((horizontalThumbSize == null) || (verticalThumbSize == null)) { + return super.getMinimumThumbSize(); + } + return JScrollBar.HORIZONTAL == scrollbar.getOrientation() + ? horizontalThumbSize + : verticalThumbSize; + } + public void uninstallUI(JComponent c) { super.uninstallUI(c); thumbGrid = highlightGrid = null; diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java index c5101177f40..117e9d7b7b1 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java @@ -182,7 +182,6 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI { if (sortOrder != null) { switch(sortOrder) { case ASCENDING: - /* falls through */ case DESCENDING: switch (state) { case NORMAL: @@ -197,6 +196,7 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI { default: /* do nothing */ } + break; default : /* do nothing */ } diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java index 65a675ffdf5..d41c94480e9 100644 --- a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java +++ b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, 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 @@ -459,10 +459,10 @@ public final class Connection implements Runnable { // will be woken up before readTimeout only if reply is // available ldr.wait(readTimeout); - waited = true; } else { ldr.wait(15 * 1000); // 15 second timeout } + waited = true; } else { break; } @@ -474,7 +474,7 @@ public final class Connection implements Runnable { } if ((rber == null) && waited) { - removeRequest(ldr); + abandonRequest(ldr, null); throw new NamingException("LDAP response read timed out, timeout used:" + readTimeout + "ms." ); diff --git a/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java b/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java index e6a7ba2d9cb..1d0393d35eb 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java +++ b/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java @@ -48,7 +48,7 @@ abstract class AbstractLine implements Line { protected Control[] controls; AbstractMixer mixer; private boolean open = false; - private final Vector listeners = new Vector(); + private final Vector listeners = new Vector<>(); /** * Contains event dispatcher per thread group. diff --git a/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java b/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java index 4323970cafa..93c3926aaed 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java +++ b/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java @@ -70,7 +70,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice /** List of Receivers and Transmitters that opened the device implicitely. */ - private List openKeepingObjects; + private List openKeepingObjects; /** * This is the device handle returned from native code @@ -284,6 +284,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice } + @SuppressWarnings("unchecked") // Cast of result of clone public final List getReceivers() { List recs; synchronized (traRecLock) { @@ -313,6 +314,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice } + @SuppressWarnings("unchecked") // Cast of result of clone public final List getTransmitters() { List tras; synchronized (traRecLock) { @@ -372,9 +374,9 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice /** Return the list of objects that have opened the device implicitely. */ - private synchronized List getOpenKeepingObjects() { + private synchronized List getOpenKeepingObjects() { if (openKeepingObjects == null) { - openKeepingObjects = new ArrayList(); + openKeepingObjects = new ArrayList<>(); } return openKeepingObjects; } diff --git a/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java b/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java index 1055fc6859e..83378615b77 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java +++ b/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java @@ -90,13 +90,13 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { /** * Source lines (ports) currently open */ - private final Vector sourceLines = new Vector(); + private final Vector sourceLines = new Vector<>(); /** * Target lines currently open. */ - private final Vector targetLines = new Vector(); + private final Vector targetLines = new Vector<>(); /** @@ -151,7 +151,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { public final Line.Info[] getSourceLineInfo(Line.Info info) { int i; - Vector vec = new Vector(); + Vector vec = new Vector<>(); for (i = 0; i < sourceLineInfo.length; i++) { @@ -162,7 +162,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { Line.Info[] returnedArray = new Line.Info[vec.size()]; for (i = 0; i < returnedArray.length; i++) { - returnedArray[i] = (Line.Info)vec.elementAt(i); + returnedArray[i] = vec.elementAt(i); } return returnedArray; @@ -172,7 +172,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { public final Line.Info[] getTargetLineInfo(Line.Info info) { int i; - Vector vec = new Vector(); + Vector vec = new Vector<>(); for (i = 0; i < targetLineInfo.length; i++) { @@ -183,7 +183,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { Line.Info[] returnedArray = new Line.Info[vec.size()]; for (i = 0; i < returnedArray.length; i++) { - returnedArray[i] = (Line.Info)vec.elementAt(i); + returnedArray[i] = vec.elementAt(i); } return returnedArray; @@ -231,7 +231,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { localLines = new Line[sourceLines.size()]; for (int i = 0; i < localLines.length; i++) { - localLines[i] = (Line)sourceLines.elementAt(i); + localLines[i] = sourceLines.elementAt(i); } } @@ -248,7 +248,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { localLines = new Line[targetLines.size()]; for (int i = 0; i < localLines.length; i++) { - localLines[i] = (Line)targetLines.elementAt(i); + localLines[i] = targetLines.elementAt(i); } } @@ -453,7 +453,8 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { return; } - Vector localSourceLines = (Vector)sourceLines.clone(); + @SuppressWarnings("unchecked") + Vector localSourceLines = (Vector)sourceLines.clone(); for (int i = 0; i < localSourceLines.size(); i++) { // if any other open line is running, return @@ -468,7 +469,8 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { } } - Vector localTargetLines = (Vector)targetLines.clone(); + @SuppressWarnings("unchecked") + Vector localTargetLines = (Vector)targetLines.clone(); for (int i = 0; i < localTargetLines.size(); i++) { // if any other open line is running, return diff --git a/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java b/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java index 367f318b06a..fbe63f6ff16 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java +++ b/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java @@ -213,7 +213,7 @@ public final class AlawCodec extends SunCodec { private AudioFormat[] getOutputFormats(AudioFormat inputFormat) { - Vector formats = new Vector(); + Vector formats = new Vector<>(); AudioFormat format; if ( AudioFormat.Encoding.PCM_SIGNED.equals(inputFormat.getEncoding())) { @@ -248,7 +248,7 @@ public final class AlawCodec extends SunCodec { AudioFormat[] formatArray = new AudioFormat[formats.size()]; for (int i = 0; i < formatArray.length; i++) { - formatArray[i] = (AudioFormat)(formats.elementAt(i)); + formatArray[i] = formats.elementAt(i); } return formatArray; } diff --git a/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java b/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java index d4305523526..16bfaa20790 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java +++ b/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java @@ -68,7 +68,7 @@ public final class AudioSynthesizerPropertyInfo { * The valueClass field specifies class * used in value field. */ - public Class valueClass = null; + public Class valueClass = null; /** * An array of possible values if the value for the field * AudioSynthesizerPropertyInfo.value may be selected diff --git a/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java b/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java index 7c938bbb1c4..becf4981ba7 100644 --- a/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java +++ b/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java @@ -94,7 +94,7 @@ final class DirectAudioDevice extends AbstractMixer { } private DirectDLI createDataLineInfo(boolean isSource) { - Vector formats = new Vector(); + Vector formats = new Vector<>(); AudioFormat[] hardwareFormatArray = null; AudioFormat[] formatArray = null; @@ -107,7 +107,7 @@ final class DirectAudioDevice extends AbstractMixer { int formatArraySize = size; hardwareFormatArray = new AudioFormat[size]; for (int i = 0; i < size; i++) { - AudioFormat format = (AudioFormat)formats.elementAt(i); + AudioFormat format = formats.elementAt(i); hardwareFormatArray[i] = format; int bits = format.getSampleSizeInBits(); boolean isSigned = format.getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED); @@ -265,7 +265,7 @@ final class DirectAudioDevice extends AbstractMixer { return ((DirectAudioDeviceProvider.DirectAudioDeviceInfo) getMixerInfo()).getMaxSimulLines(); } - private static void addFormat(Vector v, int bits, int frameSizeInBytes, int channels, float sampleRate, + private static void addFormat(Vector v, int bits, int frameSizeInBytes, int channels, float sampleRate, int encoding, boolean signed, boolean bigEndian) { AudioFormat.Encoding enc = null; switch (encoding) { @@ -338,7 +338,7 @@ final class DirectAudioDevice extends AbstractMixer { private static final class DirectDLI extends DataLine.Info { final AudioFormat[] hardwareFormats; - private DirectDLI(Class clazz, AudioFormat[] formatArray, + private DirectDLI(Class clazz, AudioFormat[] formatArray, AudioFormat[] hardwareFormatArray, int minBuffer, int maxBuffer) { super(clazz, formatArray, minBuffer, maxBuffer); @@ -1457,7 +1457,7 @@ final class DirectAudioDevice extends AbstractMixer { } // class DirectBAOS - + @SuppressWarnings("rawtypes") private static native void nGetFormats(int mixerIndex, int deviceID, boolean isSource, Vector formats); diff --git a/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java b/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java index 54b948af168..49709891bd0 100644 --- a/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java +++ b/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java @@ -57,7 +57,7 @@ final class EventDispatcher implements Runnable { /** * List of events */ - private final ArrayList eventQueue = new ArrayList(); + private final ArrayList eventQueue = new ArrayList<>(); /** @@ -186,7 +186,7 @@ final class EventDispatcher implements Runnable { } if (eventQueue.size() > 0) { // Remove the event from the queue and dispatch it to the listeners. - eventInfo = (EventInfo) eventQueue.remove(0); + eventInfo = eventQueue.remove(0); } } // end of synchronized @@ -230,7 +230,7 @@ final class EventDispatcher implements Runnable { /** * Send audio and MIDI events. */ - void sendAudioEvents(Object event, List listeners) { + void sendAudioEvents(Object event, List listeners) { if ((listeners == null) || (listeners.size() == 0)) { // nothing to do @@ -392,7 +392,7 @@ final class EventDispatcher implements Runnable { * @param event the event to be dispatched * @param listeners listener list; will be copied */ - EventInfo(Object event, List listeners) { + EventInfo(Object event, List listeners) { this.event = event; this.listeners = listeners.toArray(); } diff --git a/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java b/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java index 9f19a8734e3..9c93d06dc23 100644 --- a/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java +++ b/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java @@ -118,7 +118,7 @@ public final class JDK13Services { (the part before the hash sign), if available. If the property is not set or the value has no provider class name part, null is returned. */ - public static synchronized String getDefaultProviderClassName(Class typeClass) { + public static synchronized String getDefaultProviderClassName(Class typeClass) { String value = null; String defaultProviderSpec = getDefaultProvider(typeClass); if (defaultProviderSpec != null) { @@ -144,7 +144,7 @@ public final class JDK13Services { part after the hash sign), if available. If the property is not set or the value has no instance name part, null is returned. */ - public static synchronized String getDefaultInstanceName(Class typeClass) { + public static synchronized String getDefaultInstanceName(Class typeClass) { String value = null; String defaultProviderSpec = getDefaultProvider(typeClass); if (defaultProviderSpec != null) { @@ -165,7 +165,7 @@ public final class JDK13Services { @return The complete value of the property, if available. If the property is not set, null is returned. */ - private static synchronized String getDefaultProvider(Class typeClass) { + private static synchronized String getDefaultProvider(Class typeClass) { if (!SourceDataLine.class.equals(typeClass) && !TargetDataLine.class.equals(typeClass) && !Clip.class.equals(typeClass) diff --git a/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java b/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java index 1f397724e3f..5044dfeaa17 100644 --- a/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java +++ b/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java @@ -106,9 +106,9 @@ public final class MidiInDeviceProvider extends AbstractMidiDeviceProvider { * the new instance will not reflect that state... */ static final class MidiInDeviceInfo extends AbstractMidiDeviceProvider.Info { - private final Class providerClass; + private final Class providerClass; - private MidiInDeviceInfo(int index, Class providerClass) { + private MidiInDeviceInfo(int index, Class providerClass) { super(nGetName(index), nGetVendor(index), nGetDescription(index), nGetVersion(index), index); this.providerClass = providerClass; } diff --git a/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java b/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java index 75583ab1e65..eaacf0991be 100644 --- a/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java +++ b/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java @@ -104,9 +104,9 @@ public final class MidiOutDeviceProvider extends AbstractMidiDeviceProvider { * the new instance will not reflect that state... */ static final class MidiOutDeviceInfo extends AbstractMidiDeviceProvider.Info { - private final Class providerClass; + private final Class providerClass; - private MidiOutDeviceInfo(int index, Class providerClass) { + private MidiOutDeviceInfo(int index, Class providerClass) { super(nGetName(index), nGetVendor(index), nGetDescription(index), nGetVersion(index), index); this.providerClass = providerClass; } diff --git a/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java b/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java index a3f62efd29e..eecd33fe0b5 100644 --- a/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java +++ b/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java @@ -295,7 +295,7 @@ public final class MidiUtils { public synchronized void refresh(Sequence seq) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList<>(); Track[] tracks = seq.getTracks(); if (tracks.length > 0) { // tempo events only occur in track 0 @@ -313,7 +313,7 @@ public final class MidiUtils { int size = list.size() + 1; firstTempoIsFake = true; if ((size > 1) - && (((MidiEvent) list.get(0)).getTick() == 0)) { + && (list.get(0).getTick() == 0)) { // do not need to add an initial tempo event at the beginning size--; firstTempoIsFake = false; @@ -328,7 +328,7 @@ public final class MidiUtils { e++; } for (int i = 0; i < list.size(); i++, e++) { - MidiEvent evt = (MidiEvent) list.get(i); + MidiEvent evt = list.get(i); ticks[e] = evt.getTick(); tempos[e] = getTempoMPQ(evt.getMessage()); } diff --git a/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java b/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java index 9a4f1a874b3..dbed920e6fa 100644 --- a/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java +++ b/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java @@ -91,7 +91,7 @@ public final class PCMtoPCMCodec extends SunCodec { // filter out targetEncoding from the old getOutputFormats( sourceFormat ) method AudioFormat[] formats = getOutputFormats( sourceFormat ); - Vector newFormats = new Vector(); + Vector newFormats = new Vector<>(); for(int i=0; i formats = new Vector<>(); AudioFormat format; int sampleSize = inputFormat.getSampleSizeInBits(); @@ -335,7 +335,7 @@ public final class PCMtoPCMCodec extends SunCodec { for (int i = 0; i < formatArray.length; i++) { - formatArray[i] = (AudioFormat)(formats.elementAt(i)); + formatArray[i] = formats.elementAt(i); } } diff --git a/jdk/src/share/classes/com/sun/media/sound/PortMixer.java b/jdk/src/share/classes/com/sun/media/sound/PortMixer.java index 705648004ff..ee0fbd064ae 100644 --- a/jdk/src/share/classes/com/sun/media/sound/PortMixer.java +++ b/jdk/src/share/classes/com/sun/media/sound/PortMixer.java @@ -253,12 +253,12 @@ final class PortMixer extends AbstractMixer { long newID = ((PortMixer) mixer).getID(); if ((id == 0) || (newID != id) || (controls.length == 0)) { id = newID; - Vector vector = new Vector(); + Vector vector = new Vector<>(); synchronized (vector) { nGetControls(id, portIndex, vector); controls = new Control[vector.size()]; for (int i = 0; i < controls.length; i++) { - controls[i] = (Control) vector.elementAt(i); + controls[i] = vector.elementAt(i); } } } else { @@ -494,6 +494,7 @@ final class PortMixer extends AbstractMixer { private static native String nGetPortName(long id, int portIndex); // fills the vector with the controls for this port + @SuppressWarnings("rawtypes") private static native void nGetControls(long id, int portIndex, Vector vector); // getters/setters for controls diff --git a/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java b/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java index 6ea2ec4b3c6..7252723e776 100644 --- a/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java +++ b/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java @@ -122,7 +122,7 @@ final class RealTimeSequencer extends AbstractMidiDevice /** * List of tracks to which we're recording */ - private final List recordingTracks = new ArrayList(); + private final List recordingTracks = new ArrayList<>(); private long loopStart = 0; @@ -133,13 +133,13 @@ final class RealTimeSequencer extends AbstractMidiDevice /** * Meta event listeners */ - private final ArrayList metaEventListeners = new ArrayList(); + private final ArrayList metaEventListeners = new ArrayList<>(); /** * Control change listeners */ - private final ArrayList controllerEventListeners = new ArrayList(); + private final ArrayList controllerEventListeners = new ArrayList<>(); /** automatic connection support */ @@ -645,7 +645,7 @@ final class RealTimeSequencer extends AbstractMidiDevice boolean flag = false; for(int i=0; i < controllerEventListeners.size(); i++) { - cve = (ControllerListElement) controllerEventListeners.get(i); + cve = controllerEventListeners.get(i); if (cve.listener.equals(listener)) { cve.addControllers(controllers); @@ -669,7 +669,7 @@ final class RealTimeSequencer extends AbstractMidiDevice ControllerListElement cve = null; boolean flag = false; for (int i=0; i < controllerEventListeners.size(); i++) { - cve = (ControllerListElement) controllerEventListeners.get(i); + cve = controllerEventListeners.get(i); if (cve.listener.equals(listener)) { cve.removeControllers(controllers); flag = true; @@ -940,9 +940,9 @@ final class RealTimeSequencer extends AbstractMidiDevice } ShortMessage msg = (ShortMessage) message; int controller = msg.getData1(); - List sendToListeners = new ArrayList(); + List sendToListeners = new ArrayList<>(); for (int i = 0; i < size; i++) { - ControllerListElement cve = (ControllerListElement) controllerEventListeners.get(i); + ControllerListElement cve = controllerEventListeners.get(i); for(int j = 0; j < cve.controllers.length; j++) { if (cve.controllers[j] == controller) { sendToListeners.add(cve.listener); @@ -1213,13 +1213,13 @@ final class RealTimeSequencer extends AbstractMidiDevice this.channel = channel; } - static RecordingTrack get(List recordingTracks, Track track) { + static RecordingTrack get(List recordingTracks, Track track) { synchronized(recordingTracks) { int size = recordingTracks.size(); for (int i = 0; i < size; i++) { - RecordingTrack current = (RecordingTrack)recordingTracks.get(i); + RecordingTrack current = recordingTracks.get(i); if (current.track == track) { return current; } @@ -1228,12 +1228,12 @@ final class RealTimeSequencer extends AbstractMidiDevice return null; } - static Track get(List recordingTracks, int channel) { + static Track get(List recordingTracks, int channel) { synchronized(recordingTracks) { int size = recordingTracks.size(); for (int i = 0; i < size; i++) { - RecordingTrack current = (RecordingTrack)recordingTracks.get(i); + RecordingTrack current = recordingTracks.get(i); if ((current.channel == channel) || (current.channel == -1)) { return current.track; } diff --git a/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java b/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java index 01a64c2dddf..2c6dff99fea 100644 --- a/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java +++ b/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java @@ -949,7 +949,7 @@ public final class SoftSynthesizer implements AudioSynthesizer, Object v = (info == null) ? null : info.get(item2.name); v = (v != null) ? v : storedProperties.getProperty(item2.name); if (v != null) { - Class c = (item2.valueClass); + Class c = (item2.valueClass); if (c.isInstance(v)) item2.value = v; else if (v instanceof String) { diff --git a/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java b/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java index 7dda283a0da..337fe199788 100644 --- a/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java +++ b/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java @@ -198,7 +198,7 @@ public final class UlawCodec extends SunCodec { /* public AudioFormat[] getOutputFormats(AudioFormat inputFormat) { */ private AudioFormat[] getOutputFormats(AudioFormat inputFormat) { - Vector formats = new Vector(); + Vector formats = new Vector<>(); AudioFormat format; if ((inputFormat.getSampleSizeInBits() == 16) @@ -235,7 +235,7 @@ public final class UlawCodec extends SunCodec { AudioFormat[] formatArray = new AudioFormat[formats.size()]; for (int i = 0; i < formatArray.length; i++) { - formatArray[i] = (AudioFormat)(formats.elementAt(i)); + formatArray[i] = formats.elementAt(i); } return formatArray; } diff --git a/jdk/src/share/classes/java/awt/AWTKeyStroke.java b/jdk/src/share/classes/java/awt/AWTKeyStroke.java index c4e07b45530..4be729b8c89 100644 --- a/jdk/src/share/classes/java/awt/AWTKeyStroke.java +++ b/jdk/src/share/classes/java/awt/AWTKeyStroke.java @@ -86,7 +86,8 @@ public class AWTKeyStroke implements Serializable { * Must be called under locked AWTKeyStro */ private static Class getAWTKeyStrokeClass() { - Class clazz = (Class)AppContext.getAppContext().get(AWTKeyStroke.class); + @SuppressWarnings("unchecked") + Class clazz = (Class)AppContext.getAppContext().get(AWTKeyStroke.class); if (clazz == null) { clazz = AWTKeyStroke.class; AppContext.getAppContext().put(AWTKeyStroke.class, AWTKeyStroke.class); @@ -182,6 +183,7 @@ public class AWTKeyStroke implements Serializable { throw new IllegalArgumentException("subclass cannot be null"); } synchronized (AWTKeyStroke.class) { + @SuppressWarnings("unchecked") Class keyStrokeClass = (Class)AppContext.getAppContext().get(AWTKeyStroke.class); if (keyStrokeClass != null && keyStrokeClass.equals(subclass)){ // Already registered @@ -192,7 +194,7 @@ public class AWTKeyStroke implements Serializable { throw new ClassCastException("subclass is not derived from AWTKeyStroke"); } - Constructor ctor = getCtor(subclass); + Constructor ctor = getCtor(subclass); String couldNotInstantiate = "subclass could not be instantiated"; @@ -227,12 +229,12 @@ public class AWTKeyStroke implements Serializable { threat as accessible flag is set only for this Constructor object, not for Class constructor. */ - private static Constructor getCtor(final Class clazz) + private static Constructor getCtor(final Class clazz) { - Constructor ctor = AccessController.doPrivileged(new PrivilegedAction() { - public Constructor run() { + Constructor ctor = AccessController.doPrivileged(new PrivilegedAction>() { + public Constructor run() { try { - Constructor ctor = clazz.getDeclaredConstructor((Class[]) null); + Constructor ctor = clazz.getDeclaredConstructor((Class[]) null); if (ctor != null) { ctor.setAccessible(true); } @@ -249,6 +251,7 @@ public class AWTKeyStroke implements Serializable { private static synchronized AWTKeyStroke getCachedStroke (char keyChar, int keyCode, int modifiers, boolean onKeyRelease) { + @SuppressWarnings("unchecked") Map cache = (Map)AppContext.getAppContext().get(APP_CONTEXT_CACHE_KEY); AWTKeyStroke cacheKey = (AWTKeyStroke)AppContext.getAppContext().get(APP_CONTEXT_KEYSTROKE_KEY); diff --git a/jdk/src/share/classes/java/awt/CardLayout.java b/jdk/src/share/classes/java/awt/CardLayout.java index 3ffb19fbee7..5e813fffbe9 100644 --- a/jdk/src/share/classes/java/awt/CardLayout.java +++ b/jdk/src/share/classes/java/awt/CardLayout.java @@ -560,6 +560,7 @@ public class CardLayout implements LayoutManager2, /** * Reads serializable fields from stream. */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index a7573c09a3c..cd6ae69de1d 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -6184,7 +6184,7 @@ public abstract class Component implements ImageObserver, MenuContainer, /** * Parameter types of coalesceEvents(AWTEvent,AWTEVent). */ - private static final Class[] coalesceEventsParams = { + private static final Class[] coalesceEventsParams = { AWTEvent.class, AWTEvent.class }; diff --git a/jdk/src/share/classes/java/awt/GraphicsEnvironment.java b/jdk/src/share/classes/java/awt/GraphicsEnvironment.java index 66ab39a45b1..e9e9080dba6 100644 --- a/jdk/src/share/classes/java/awt/GraphicsEnvironment.java +++ b/jdk/src/share/classes/java/awt/GraphicsEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, 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 @@ -95,18 +95,18 @@ public abstract class GraphicsEnvironment { String nm = AccessController.doPrivileged(new GetPropertyAction("java.awt.graphicsenv", null)); try { // long t0 = System.currentTimeMillis(); - Class geCls; + Class geCls; try { // First we try if the bootclassloader finds the requested // class. This way we can avoid to run in a privileged block. - geCls = (Class)Class.forName(nm); + geCls = Class.forName(nm); } catch (ClassNotFoundException ex) { // If the bootclassloader fails, we try again with the // application classloader. ClassLoader cl = ClassLoader.getSystemClassLoader(); - geCls = (Class)Class.forName(nm, true, cl); + geCls = Class.forName(nm, true, cl); } - ge = geCls.newInstance(); + ge = (GraphicsEnvironment)geCls.newInstance(); // long t1 = System.currentTimeMillis(); // System.out.println("GE creation took " + (t1-t0)+ "ms."); if (isHeadless()) { diff --git a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java index b02bb5b0dba..8758a2b50e3 100644 --- a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java +++ b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java @@ -348,6 +348,7 @@ public abstract class KeyboardFocusManager * Component of those Windows that has no such array of its own explicitly * set. */ + @SuppressWarnings({"unchecked", "rawtypes"}) private Set[] defaultFocusTraversalKeys = new Set[4]; /** @@ -422,7 +423,7 @@ public abstract class KeyboardFocusManager targetSet.add(AWTKeyStroke.getAWTKeyStroke(tokens.nextToken())); } return (targetSet.isEmpty()) - ? Collections.EMPTY_SET + ? Collections.emptySet() : Collections.unmodifiableSet(targetSet); } @@ -436,7 +437,7 @@ public abstract class KeyboardFocusManager work_set.add(defaultFocusTraversalKeyStrokes[i][j]); } defaultFocusTraversalKeys[i] = (work_set.isEmpty()) - ? Collections.EMPTY_SET + ? Collections.emptySet() : Collections.unmodifiableSet(work_set); } initPeer(); @@ -1750,11 +1751,12 @@ public abstract class KeyboardFocusManager * @see #addKeyEventDispatcher * @see #removeKeyEventDispatcher */ + @SuppressWarnings("unchecked") // Cast of result of clone protected synchronized java.util.List getKeyEventDispatchers() { return (keyEventDispatchers != null) - ? (java.util.List)keyEventDispatchers.clone() + ? (java.util.List)keyEventDispatchers.clone() : null; } @@ -1841,11 +1843,12 @@ public abstract class KeyboardFocusManager * @see #addKeyEventPostProcessor * @see #removeKeyEventPostProcessor */ + @SuppressWarnings("unchecked") // Cast of result of clone protected java.util.List getKeyEventPostProcessors() { return (keyEventPostProcessors != null) - ? (java.util.List)keyEventPostProcessors.clone() + ? (java.util.List)keyEventPostProcessors.clone() : null; } @@ -1907,8 +1910,7 @@ public abstract class KeyboardFocusManager * javax.swing.JComponent.runInputVerifier() using reflection. */ static synchronized Component getMostRecentFocusOwner(Window window) { - WeakReference weakValue = - (WeakReference)mostRecentFocusOwners.get(window); + WeakReference weakValue = mostRecentFocusOwners.get(window); return weakValue == null ? null : weakValue.get(); } diff --git a/jdk/src/share/classes/java/awt/Menu.java b/jdk/src/share/classes/java/awt/Menu.java index 629371868d1..ae8e50ea7e1 100644 --- a/jdk/src/share/classes/java/awt/Menu.java +++ b/jdk/src/share/classes/java/awt/Menu.java @@ -66,7 +66,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { AWTAccessor.setMenuAccessor( new AWTAccessor.MenuAccessor() { - public Vector getItems(Menu menu) { + public Vector getItems(Menu menu) { return menu.items; } }); @@ -78,7 +78,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { * @serial * @see #countItems() */ - Vector items = new Vector<>(); + Vector items = new Vector<>(); /** * This field indicates whether the menu has the @@ -252,7 +252,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { * be called on the toolkit thread. */ final MenuItem getItemImpl(int index) { - return (MenuItem)items.elementAt(index); + return items.elementAt(index); } /** @@ -544,7 +544,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { // HeadlessException will be thrown from MenuComponent's readObject s.defaultReadObject(); for(int i = 0; i < items.size(); i++) { - MenuItem item = (MenuItem)items.elementAt(i); + MenuItem item = items.elementAt(i); item.parent = this; } } diff --git a/jdk/src/share/classes/java/awt/SystemTray.java b/jdk/src/share/classes/java/awt/SystemTray.java index 7f3a5c31893..e542dfc1712 100644 --- a/jdk/src/share/classes/java/awt/SystemTray.java +++ b/jdk/src/share/classes/java/awt/SystemTray.java @@ -259,7 +259,9 @@ public class SystemTray { Vector icons = null; synchronized (this) { oldArray = systemTray.getTrayIcons(); - icons = (Vector)AppContext.getAppContext().get(TrayIcon.class); + @SuppressWarnings("unchecked") + Vector tmp = (Vector)AppContext.getAppContext().get(TrayIcon.class); + icons = tmp; if (icons == null) { icons = new Vector(3); AppContext.getAppContext().put(TrayIcon.class, icons); @@ -304,6 +306,7 @@ public class SystemTray { TrayIcon[] oldArray = null, newArray = null; synchronized (this) { oldArray = systemTray.getTrayIcons(); + @SuppressWarnings("unchecked") Vector icons = (Vector)AppContext.getAppContext().get(TrayIcon.class); // TrayIcon with no peer is not contained in the array. if (icons == null || !icons.remove(trayIcon)) { @@ -335,6 +338,7 @@ public class SystemTray { * @see TrayIcon */ public TrayIcon[] getTrayIcons() { + @SuppressWarnings("unchecked") Vector icons = (Vector)AppContext.getAppContext().get(TrayIcon.class); if (icons != null) { return icons.toArray(new TrayIcon[icons.size()]); diff --git a/jdk/src/share/classes/java/awt/datatransfer/MimeTypeParameterList.java b/jdk/src/share/classes/java/awt/datatransfer/MimeTypeParameterList.java index f4816b65d87..3a79886c2b4 100644 --- a/jdk/src/share/classes/java/awt/datatransfer/MimeTypeParameterList.java +++ b/jdk/src/share/classes/java/awt/datatransfer/MimeTypeParameterList.java @@ -296,14 +296,14 @@ class MimeTypeParameterList implements Cloneable { /** * @return a clone of this object */ - + @SuppressWarnings("unchecked") // Cast from clone public Object clone() { MimeTypeParameterList newObj = null; try { newObj = (MimeTypeParameterList)super.clone(); } catch (CloneNotSupportedException cannotHappen) { } - newObj.parameters = (Hashtable)parameters.clone(); + newObj.parameters = (Hashtable)parameters.clone(); return newObj; } diff --git a/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java b/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java index bc6e1642001..fd54c9414a0 100644 --- a/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java +++ b/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java @@ -38,13 +38,14 @@ import java.net.URL; import java.net.MalformedURLException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; -import java.util.WeakHashMap; import sun.awt.AppContext; import sun.awt.datatransfer.DataTransferer; @@ -101,20 +102,12 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ private static final String HTML_TEXT_BASE_TYPE = "text/html"; - /** - * This constant is passed to flavorToNativeLookup() to indicate that a - * a native should be synthesized, stored, and returned by encoding the - * DataFlavor's MIME type in case if the DataFlavor is not found in - * 'flavorToNative' map. - */ - private static final boolean SYNTHESIZE_IF_NOT_FOUND = true; - /** * Maps native Strings to Lists of DataFlavors (or base type Strings for * text DataFlavors). * Do not use the field directly, use getNativeToFlavor() instead. */ - private final Map> nativeToFlavor = new HashMap<>(); + private final Map> nativeToFlavor = new HashMap<>(); /** * Accessor to nativeToFlavor map. Since we use lazy initialization we must @@ -123,7 +116,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * * @return nativeToFlavor */ - private Map> getNativeToFlavor() { + private Map> getNativeToFlavor() { if (!isMapInitialized) { initSystemFlavorMap(); } @@ -135,7 +128,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * native Strings. * Do not use the field directly, use getFlavorToNative() instead. */ - private final Map> flavorToNative = new HashMap<>(); + private final Map> flavorToNative = new HashMap<>(); /** * Accessor to flavorToNative map. Since we use lazy initialization we must @@ -144,29 +137,52 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * * @return flavorToNative */ - private synchronized Map> getFlavorToNative() { + private synchronized Map> getFlavorToNative() { if (!isMapInitialized) { initSystemFlavorMap(); } return flavorToNative; } + /** + * Maps a text DataFlavor primary mime-type to the native. Used only to store + * standard mappings registered in the flavormap.properties + * Do not use this field directly, use getTextTypeToNative() instead. + */ + private Map> textTypeToNative = new HashMap<>(); + /** * Shows if the object has been initialized. */ private boolean isMapInitialized = false; /** - * Caches the result of getNativesForFlavor(). Maps DataFlavors to - * SoftReferences which reference Lists of String natives. + * An accessor to textTypeToNative map. Since we use lazy initialization we + * must use this accessor instead of direct access to the field which may not + * be initialized yet. This method will initialize the field if needed. + * + * @return textTypeToNative */ - private Map>> getNativesForFlavorCache = new HashMap<>(); + private synchronized Map> getTextTypeToNative() { + if (!isMapInitialized) { + initSystemFlavorMap(); + // From this point the map should not be modified + textTypeToNative = Collections.unmodifiableMap(textTypeToNative); + } + return textTypeToNative; + } + + /** + * Caches the result of getNativesForFlavor(). Maps DataFlavors to + * SoftReferences which reference LinkedHashSet of String natives. + */ + private final SoftCache nativesForFlavorCache = new SoftCache<>(); /** * Caches the result getFlavorsForNative(). Maps String natives to - * SoftReferences which reference Lists of DataFlavors. + * SoftReferences which reference LinkedHashSet of DataFlavors. */ - private Map>> getFlavorsForNativeCache = new HashMap<>(); + private final SoftCache flavorsForNativeCache = new SoftCache<>(); /** * Dynamic mapping generation used for text mappings should not be applied @@ -174,7 +190,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * explicitly specified with setFlavorsForNative() or * setNativesForFlavor(). This keeps all such keys. */ - private Set disabledMappingGenerationKeys = new HashSet(); + private Set disabledMappingGenerationKeys = new HashSet<>(); /** * Returns the default FlavorMap for this thread's ClassLoader. @@ -404,7 +420,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { flavor = new DataFlavor(value); } catch (Exception e) { try { - flavor = new DataFlavor(value, (String)null); + flavor = new DataFlavor(value, null); } catch (Exception ee) { ee.printStackTrace(); continue; @@ -412,11 +428,11 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } final LinkedHashSet dfs = new LinkedHashSet<>(); - dfs.add(flavor); if ("text".equals(flavor.getPrimaryType())) { dfs.addAll(convertMimeTypeToDataFlavors(value)); + store(flavor.mimeType.getBaseType(), key, getTextTypeToNative()); } for (DataFlavor df : dfs) { @@ -505,10 +521,10 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * the appropriate Map location, but rather will be appended to a List * stored in that location. */ - private void store(H hashed, L listed, Map> map) { - List list = map.get(hashed); + private void store(H hashed, L listed, Map> map) { + LinkedHashSet list = map.get(hashed); if (list == null) { - list = new ArrayList<>(1); + list = new LinkedHashSet<>(1); map.put(hashed, list); } if (!list.contains(listed)) { @@ -522,17 +538,16 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * case, a new DataFlavor is synthesized, stored, and returned, if and * only if the specified native is encoded as a Java MIME type. */ - private List nativeToFlavorLookup(String nat) { - List flavors = getNativeToFlavor().get(nat); + private LinkedHashSet nativeToFlavorLookup(String nat) { + LinkedHashSet flavors = getNativeToFlavor().get(nat); if (nat != null && !disabledMappingGenerationKeys.contains(nat)) { DataTransferer transferer = DataTransferer.getInstance(); if (transferer != null) { - List platformFlavors = + LinkedHashSet platformFlavors = transferer.getPlatformMappingsForNative(nat); if (!platformFlavors.isEmpty()) { if (flavors != null) { - platformFlavors.removeAll(new HashSet<>(flavors)); // Prepending the platform-specific mappings ensures // that the flavors added with // addFlavorForUnencodedNative() are at the end of @@ -558,24 +573,22 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } if (flavor != null) { - flavors = new ArrayList<>(1); + flavors = new LinkedHashSet<>(1); getNativeToFlavor().put(nat, flavors); flavors.add(flavor); - getFlavorsForNativeCache.remove(nat); - getFlavorsForNativeCache.remove(null); + flavorsForNativeCache.remove(nat); - List natives = getFlavorToNative().get(flavor); + LinkedHashSet natives = getFlavorToNative().get(flavor); if (natives == null) { - natives = new ArrayList<>(1); + natives = new LinkedHashSet<>(1); getFlavorToNative().put(flavor, natives); } natives.add(nat); - getNativesForFlavorCache.remove(flavor); - getNativesForFlavorCache.remove(null); + nativesForFlavorCache.remove(flavor); } } - return (flavors != null) ? flavors : new ArrayList<>(0); + return (flavors != null) ? flavors : new LinkedHashSet<>(0); } /** @@ -586,18 +599,18 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * encoding the DataFlavor's MIME type. Otherwise an empty List is returned * and 'flavorToNative' remains unaffected. */ - private List flavorToNativeLookup(final DataFlavor flav, - final boolean synthesize) { - List natives = getFlavorToNative().get(flav); + private LinkedHashSet flavorToNativeLookup(final DataFlavor flav, + final boolean synthesize) { + + LinkedHashSet natives = getFlavorToNative().get(flav); if (flav != null && !disabledMappingGenerationKeys.contains(flav)) { DataTransferer transferer = DataTransferer.getInstance(); if (transferer != null) { - List platformNatives = + LinkedHashSet platformNatives = transferer.getPlatformMappingsForFlavor(flav); if (!platformNatives.isEmpty()) { if (natives != null) { - platformNatives.removeAll(new HashSet<>(natives)); // Prepend the platform-specific mappings to ensure // that the natives added with // addUnencodedNativeForFlavor() are at the end of @@ -612,26 +625,25 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { if (natives == null) { if (synthesize) { String encoded = encodeDataFlavor(flav); - natives = new ArrayList<>(1); + natives = new LinkedHashSet<>(1); getFlavorToNative().put(flav, natives); natives.add(encoded); - getNativesForFlavorCache.remove(flav); - getNativesForFlavorCache.remove(null); - List flavors = getNativeToFlavor().get(encoded); + LinkedHashSet flavors = getNativeToFlavor().get(encoded); if (flavors == null) { - flavors = new ArrayList<>(1); + flavors = new LinkedHashSet<>(1); getNativeToFlavor().put(encoded, flavors); } flavors.add(flav); - getFlavorsForNativeCache.remove(encoded); - getFlavorsForNativeCache.remove(null); + + nativesForFlavorCache.remove(flav); + flavorsForNativeCache.remove(encoded); } else { - natives = new ArrayList<>(0); + natives = new LinkedHashSet<>(0); } } - return natives; + return new LinkedHashSet<>(natives); } /** @@ -659,103 +671,63 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * @see #encodeDataFlavor * @since 1.4 */ + @Override public synchronized List getNativesForFlavor(DataFlavor flav) { - List retval = null; - - // Check cache, even for null flav - SoftReference> ref = getNativesForFlavorCache.get(flav); - if (ref != null) { - retval = ref.get(); - if (retval != null) { - // Create a copy, because client code can modify the returned - // list. - return new ArrayList<>(retval); - } + LinkedHashSet retval = nativesForFlavorCache.check(flav); + if (retval != null) { + return new ArrayList<>(retval); } if (flav == null) { - retval = new ArrayList<>(getNativeToFlavor().keySet()); + retval = new LinkedHashSet<>(getNativeToFlavor().keySet()); } else if (disabledMappingGenerationKeys.contains(flav)) { // In this case we shouldn't synthesize a native for this flavor, // since its mappings were explicitly specified. - retval = flavorToNativeLookup(flav, !SYNTHESIZE_IF_NOT_FOUND); + retval = flavorToNativeLookup(flav, false); } else if (DataTransferer.isFlavorCharsetTextType(flav)) { + retval = new LinkedHashSet<>(0); // For text/* flavors, flavor-to-native mappings specified in // flavormap.properties are stored per flavor's base type. if ("text".equals(flav.getPrimaryType())) { - retval = getAllNativesForType(flav.mimeType.getBaseType()); - if (retval != null) { - // To prevent the List stored in the map from modification. - retval = new ArrayList(retval); + LinkedHashSet textTypeNatives = + getTextTypeToNative().get(flav.mimeType.getBaseType()); + if (textTypeNatives != null) { + retval.addAll(textTypeNatives); } } // Also include text/plain natives, but don't duplicate Strings - List textPlainList = getAllNativesForType(TEXT_PLAIN_BASE_TYPE); - - if (textPlainList != null && !textPlainList.isEmpty()) { - // To prevent the List stored in the map from modification. - // This also guarantees that removeAll() is supported. - textPlainList = new ArrayList<>(textPlainList); - if (retval != null && !retval.isEmpty()) { - // Use HashSet to get constant-time performance for search. - textPlainList.removeAll(new HashSet<>(retval)); - retval.addAll(textPlainList); - } else { - retval = textPlainList; - } + LinkedHashSet textTypeNatives = + getTextTypeToNative().get(TEXT_PLAIN_BASE_TYPE); + if (textTypeNatives != null) { + retval.addAll(textTypeNatives); } - if (retval == null || retval.isEmpty()) { - retval = flavorToNativeLookup(flav, SYNTHESIZE_IF_NOT_FOUND); + if (retval.isEmpty()) { + retval = flavorToNativeLookup(flav, true); } else { // In this branch it is guaranteed that natives explicitly // listed for flav's MIME type were added with // addUnencodedNativeForFlavor(), so they have lower priority. - List explicitList = - flavorToNativeLookup(flav, !SYNTHESIZE_IF_NOT_FOUND); - - // flavorToNativeLookup() never returns null. - // It can return an empty List, however. - if (!explicitList.isEmpty()) { - // To prevent the List stored in the map from modification. - // This also guarantees that removeAll() is supported. - explicitList = new ArrayList<>(explicitList); - // Use HashSet to get constant-time performance for search. - explicitList.removeAll(new HashSet<>(retval)); - retval.addAll(explicitList); - } + retval.addAll(flavorToNativeLookup(flav, false)); } } else if (DataTransferer.isFlavorNoncharsetTextType(flav)) { - retval = getAllNativesForType(flav.mimeType.getBaseType()); + retval = getTextTypeToNative().get(flav.mimeType.getBaseType()); if (retval == null || retval.isEmpty()) { - retval = flavorToNativeLookup(flav, SYNTHESIZE_IF_NOT_FOUND); + retval = flavorToNativeLookup(flav, true); } else { // In this branch it is guaranteed that natives explicitly // listed for flav's MIME type were added with // addUnencodedNativeForFlavor(), so they have lower priority. - List explicitList = - flavorToNativeLookup(flav, !SYNTHESIZE_IF_NOT_FOUND); - - // flavorToNativeLookup() never returns null. - // It can return an empty List, however. - if (!explicitList.isEmpty()) { - // To prevent the List stored in the map from modification. - // This also guarantees that add/removeAll() are supported. - retval = new ArrayList<>(retval); - explicitList = new ArrayList<>(explicitList); - // Use HashSet to get constant-time performance for search. - explicitList.removeAll(new HashSet<>(retval)); - retval.addAll(explicitList); - } + retval.addAll(flavorToNativeLookup(flav, false)); } } else { - retval = flavorToNativeLookup(flav, SYNTHESIZE_IF_NOT_FOUND); + retval = flavorToNativeLookup(flav, true); } - getNativesForFlavorCache.put(flav, new SoftReference<>(retval)); + nativesForFlavorCache.put(flav, retval); // Create a copy, because client code can modify the returned list. return new ArrayList<>(retval); } @@ -791,62 +763,38 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * @see #encodeJavaMIMEType * @since 1.4 */ + @Override public synchronized List getFlavorsForNative(String nat) { - - // Check cache, even for null nat - SoftReference> ref = getFlavorsForNativeCache.get(nat); - if (ref != null) { - List retval = ref.get(); - if (retval != null) { - return new ArrayList<>(retval); - } + LinkedHashSet returnValue = flavorsForNativeCache.check(nat); + if (returnValue != null) { + return new ArrayList<>(returnValue); + } else { + returnValue = new LinkedHashSet<>(); } - final LinkedHashSet returnValue = - new LinkedHashSet<>(); - if (nat == null) { - final List natives = getNativesForFlavor(null); - - for (String n : natives) - { - final List flavors = getFlavorsForNative(n); - - for (DataFlavor df : flavors) - { - returnValue.add(df); - } + for (String n : getNativesForFlavor(null)) { + returnValue.addAll(getFlavorsForNative(n)); } } else { - - final List flavors = nativeToFlavorLookup(nat); - + final LinkedHashSet flavors = nativeToFlavorLookup(nat); if (disabledMappingGenerationKeys.contains(nat)) { - return flavors; + return new ArrayList<>(flavors); } - final List flavorsAndBaseTypes = - nativeToFlavorLookup(nat); + final LinkedHashSet flavorsWithSynthesized = + nativeToFlavorLookup(nat); - for (DataFlavor df : flavorsAndBaseTypes) { + for (DataFlavor df : flavorsWithSynthesized) { returnValue.add(df); if ("text".equals(df.getPrimaryType())) { - try { - returnValue.addAll( - convertMimeTypeToDataFlavors( - new MimeType(df.getMimeType() - ).getBaseType())); - } catch (MimeTypeParseException e) { - e.printStackTrace(); - } + String baseType = df.mimeType.getBaseType(); + returnValue.addAll(convertMimeTypeToDataFlavors(baseType)); } } - } - - final List arrayList = new ArrayList<>(returnValue); - getFlavorsForNativeCache.put(nat, new SoftReference<>(arrayList)); - return new ArrayList<>(arrayList); + flavorsForNativeCache.put(nat, returnValue); + return new ArrayList<>(returnValue); } private static Set convertMimeTypeToDataFlavors( @@ -862,7 +810,6 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } catch (MimeTypeParseException mtpe) { // Cannot happen, since we checked all mappings // on load from flavormap.properties. - assert(false); } if (DataTransferer.doesSubtypeSupportCharset(subType, null)) { @@ -941,10 +888,10 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } private static final String [] htmlDocumntTypes = - new String [] {"all", "selection", "fragment"}; + new String [] {"all", "selection", "fragment"}; - private static LinkedHashSet handleHtmlMimeTypes( - String baseType, String mimeType) { + private static LinkedHashSet handleHtmlMimeTypes(String baseType, + String mimeType) { LinkedHashSet returnValues = new LinkedHashSet<>(); @@ -981,14 +928,14 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * @see #getNativesForFlavor * @see #encodeDataFlavor */ - public synchronized Map - getNativesForFlavors(DataFlavor[] flavors) + @Override + public synchronized Map getNativesForFlavors(DataFlavor[] flavors) { // Use getNativesForFlavor to generate extra natives for text flavors // and stringFlavor if (flavors == null) { - List flavor_list = getFlavorsForNative(null); + List flavor_list = getFlavorsForNative(null); flavors = new DataFlavor[flavor_list.size()]; flavor_list.toArray(flavors); } @@ -1027,15 +974,14 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * @see #getFlavorsForNative * @see #encodeJavaMIMEType */ - public synchronized Map - getFlavorsForNatives(String[] natives) + @Override + public synchronized Map getFlavorsForNatives(String[] natives) { // Use getFlavorsForNative to generate extra flavors for text natives - if (natives == null) { - List native_list = getNativesForFlavor(null); - natives = new String[native_list.size()]; - native_list.toArray(natives); + List nativesList = getNativesForFlavor(null); + natives = new String[nativesList.size()]; + nativesList.toArray(natives); } Map retval = new HashMap<>(natives.length, 1.0f); @@ -1044,7 +990,6 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { DataFlavor flav = (flavors.isEmpty())? null : flavors.get(0); retval.put(aNative, flav); } - return retval; } @@ -1070,20 +1015,16 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ public synchronized void addUnencodedNativeForFlavor(DataFlavor flav, String nat) { - if (flav == null || nat == null) { - throw new NullPointerException("null arguments not permitted"); - } + Objects.requireNonNull(nat, "Null native not permitted"); + Objects.requireNonNull(flav, "Null flavor not permitted"); - List natives = getFlavorToNative().get(flav); + LinkedHashSet natives = getFlavorToNative().get(flav); if (natives == null) { - natives = new ArrayList<>(1); + natives = new LinkedHashSet<>(1); getFlavorToNative().put(flav, natives); - } else if (natives.contains(nat)) { - return; } natives.add(nat); - getNativesForFlavorCache.remove(flav); - getNativesForFlavorCache.remove(null); + nativesForFlavorCache.remove(flav); } /** @@ -1116,18 +1057,15 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ public synchronized void setNativesForFlavor(DataFlavor flav, String[] natives) { - if (flav == null || natives == null) { - throw new NullPointerException("null arguments not permitted"); - } + Objects.requireNonNull(natives, "Null natives not permitted"); + Objects.requireNonNull(flav, "Null flavors not permitted"); getFlavorToNative().remove(flav); for (String aNative : natives) { addUnencodedNativeForFlavor(flav, aNative); } disabledMappingGenerationKeys.add(flav); - // Clear the cache to handle the case of empty natives. - getNativesForFlavorCache.remove(flav); - getNativesForFlavorCache.remove(null); + nativesForFlavorCache.remove(flav); } /** @@ -1150,20 +1088,16 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ public synchronized void addFlavorForUnencodedNative(String nat, DataFlavor flav) { - if (nat == null || flav == null) { - throw new NullPointerException("null arguments not permitted"); - } + Objects.requireNonNull(nat, "Null native not permitted"); + Objects.requireNonNull(flav, "Null flavor not permitted"); - List flavors = getNativeToFlavor().get(nat); + LinkedHashSet flavors = getNativeToFlavor().get(nat); if (flavors == null) { - flavors = new ArrayList<>(1); + flavors = new LinkedHashSet<>(1); getNativeToFlavor().put(nat, flavors); - } else if (flavors.contains(flav)) { - return; } flavors.add(flav); - getFlavorsForNativeCache.remove(nat); - getFlavorsForNativeCache.remove(null); + flavorsForNativeCache.remove(nat); } /** @@ -1195,18 +1129,15 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ public synchronized void setFlavorsForNative(String nat, DataFlavor[] flavors) { - if (nat == null || flavors == null) { - throw new NullPointerException("null arguments not permitted"); - } + Objects.requireNonNull(nat, "Null native not permitted"); + Objects.requireNonNull(flavors, "Null flavors not permitted"); getNativeToFlavor().remove(nat); for (DataFlavor flavor : flavors) { addFlavorForUnencodedNative(nat, flavor); } disabledMappingGenerationKeys.add(nat); - // Clear the cache to handle the case of empty flavors. - getFlavorsForNativeCache.remove(nat); - getFlavorsForNativeCache.remove(null); + flavorsForNativeCache.remove(nat); } /** @@ -1307,17 +1238,29 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { : null; } - private List getAllNativesForType(String type) { - Set retval = null; - for (DataFlavor dataFlavor : convertMimeTypeToDataFlavors(type)) { - List natives = getFlavorToNative().get(dataFlavor); - if (natives != null && !natives.isEmpty()) { - if (retval == null) { - retval = new LinkedHashSet<>(); - } - retval.addAll(natives); + private static final class SoftCache { + Map>> cache; + + public void put(K key, LinkedHashSet value) { + if (cache == null) { + cache = new HashMap<>(1); } + cache.put(key, new SoftReference<>(value)); + } + + public void remove(K key) { + if (cache == null) return; + cache.remove(null); + cache.remove(key); + } + + public LinkedHashSet check(K key) { + if (cache == null) return null; + SoftReference> ref = cache.get(key); + if (ref != null) { + return ref.get(); + } + return null; } - return retval == null ? null : new ArrayList<>(retval); } } diff --git a/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java b/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java index e8827f44358..3dff336a794 100644 --- a/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java +++ b/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, 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 @@ -357,6 +357,7 @@ public class DragGestureEvent extends EventObject { action = newAction; // Pre-1.4 support. 'events' was previously non-transient + @SuppressWarnings("rawtypes") List newEvents; try { newEvents = (List)f.get("events", null); diff --git a/jdk/src/share/classes/java/awt/geom/Area.java b/jdk/src/share/classes/java/awt/geom/Area.java index 507f212b4ea..ae5ab2f683b 100644 --- a/jdk/src/share/classes/java/awt/geom/Area.java +++ b/jdk/src/share/classes/java/awt/geom/Area.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, 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 @@ -97,9 +97,9 @@ import sun.awt.geom.AreaOp; * @since 1.2 */ public class Area implements Shape, Cloneable { - private static Vector EmptyCurves = new Vector(); + private static Vector EmptyCurves = new Vector<>(); - private Vector curves; + private Vector curves; /** * Default constructor which creates an empty area. @@ -127,8 +127,8 @@ public class Area implements Shape, Cloneable { } } - private static Vector pathToCurves(PathIterator pi) { - Vector curves = new Vector(); + private static Vector pathToCurves(PathIterator pi) { + Vector curves = new Vector<>(); int windingRule = pi.getWindingRule(); // coords array is big enough for holding: // coordinates returned from currentSegment (6) @@ -334,7 +334,7 @@ public class Area implements Shape, Cloneable { * @since 1.2 */ public void reset() { - curves = new Vector(); + curves = new Vector<>(); invalidateBounds(); } @@ -357,9 +357,9 @@ public class Area implements Shape, Cloneable { * @since 1.2 */ public boolean isPolygonal() { - Enumeration enum_ = curves.elements(); + Enumeration enum_ = curves.elements(); while (enum_.hasMoreElements()) { - if (((Curve) enum_.nextElement()).getOrder() > 1) { + if (enum_.nextElement().getOrder() > 1) { return false; } } @@ -381,8 +381,8 @@ public class Area implements Shape, Cloneable { if (size > 3) { return false; } - Curve c1 = (Curve) curves.get(1); - Curve c2 = (Curve) curves.get(2); + Curve c1 = curves.get(1); + Curve c2 = curves.get(2); if (c1.getOrder() != 1 || c2.getOrder() != 1) { return false; } @@ -411,10 +411,10 @@ public class Area implements Shape, Cloneable { if (curves.size() < 3) { return true; } - Enumeration enum_ = curves.elements(); + Enumeration enum_ = curves.elements(); enum_.nextElement(); // First Order0 "moveto" while (enum_.hasMoreElements()) { - if (((Curve) enum_.nextElement()).getOrder() == 0) { + if (enum_.nextElement().getOrder() == 0) { return false; } } @@ -431,11 +431,11 @@ public class Area implements Shape, Cloneable { } Rectangle2D r = new Rectangle2D.Double(); if (curves.size() > 0) { - Curve c = (Curve) curves.get(0); + Curve c = curves.get(0); // First point is always an order 0 curve (moveto) r.setRect(c.getX0(), c.getY0(), 0, 0); for (int i = 1; i < curves.size(); i++) { - ((Curve) curves.get(i)).enlarge(r); + curves.get(i).enlarge(r); } } return (cachedBounds = r); @@ -507,7 +507,7 @@ public class Area implements Shape, Cloneable { if (other == null) { return false; } - Vector c = new AreaOp.XorOp().calculate(this.curves, other.curves); + Vector c = new AreaOp.XorOp().calculate(this.curves, other.curves); return c.isEmpty(); } @@ -555,10 +555,10 @@ public class Area implements Shape, Cloneable { if (!getCachedBounds().contains(x, y)) { return false; } - Enumeration enum_ = curves.elements(); + Enumeration enum_ = curves.elements(); int crossings = 0; while (enum_.hasMoreElements()) { - Curve c = (Curve) enum_.nextElement(); + Curve c = enum_.nextElement(); crossings += c.crossingsFor(x, y); } return ((crossings & 1) == 1); @@ -658,16 +658,16 @@ public class Area implements Shape, Cloneable { class AreaIterator implements PathIterator { private AffineTransform transform; - private Vector curves; + private Vector curves; private int index; private Curve prevcurve; private Curve thiscurve; - public AreaIterator(Vector curves, AffineTransform at) { + public AreaIterator(Vector curves, AffineTransform at) { this.curves = curves; this.transform = at; if (curves.size() >= 1) { - thiscurve = (Curve) curves.get(0); + thiscurve = curves.get(0); } } @@ -689,7 +689,7 @@ class AreaIterator implements PathIterator { prevcurve = thiscurve; index++; if (index < curves.size()) { - thiscurve = (Curve) curves.get(index); + thiscurve = curves.get(index); if (thiscurve.getOrder() != 0 && prevcurve.getX1() == thiscurve.getX0() && prevcurve.getY1() == thiscurve.getY0()) diff --git a/jdk/src/share/classes/java/awt/image/BufferedImage.java b/jdk/src/share/classes/java/awt/image/BufferedImage.java index bb272aacf69..0c819349135 100644 --- a/jdk/src/share/classes/java/awt/image/BufferedImage.java +++ b/jdk/src/share/classes/java/awt/image/BufferedImage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, 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 @@ -76,7 +76,7 @@ public class BufferedImage extends java.awt.Image ColorModel colorModel; WritableRaster raster; OffScreenImageSource osis; - Hashtable properties; + Hashtable properties; boolean isAlphaPremultiplied;// If true, alpha has been premultiplied in // color channels @@ -1106,7 +1106,7 @@ public class BufferedImage extends java.awt.Image public ImageProducer getSource() { if (osis == null) { if (properties == null) { - properties = new Hashtable(); + properties = new Hashtable<>(); } osis = new OffScreenImageSource(this, properties); } diff --git a/jdk/src/share/classes/java/awt/image/CropImageFilter.java b/jdk/src/share/classes/java/awt/image/CropImageFilter.java index 4d75c9e0427..a1d241d33ed 100644 --- a/jdk/src/share/classes/java/awt/image/CropImageFilter.java +++ b/jdk/src/share/classes/java/awt/image/CropImageFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, 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 @@ -79,6 +79,7 @@ public class CropImageFilter extends ImageFilter { * with the filtering operation. */ public void setProperties(Hashtable props) { + @SuppressWarnings("unchecked") Hashtable p = (Hashtable)props.clone(); p.put("croprect", new Rectangle(cropX, cropY, cropW, cropH)); super.setProperties(p); diff --git a/jdk/src/share/classes/java/awt/image/FilteredImageSource.java b/jdk/src/share/classes/java/awt/image/FilteredImageSource.java index 2f58c096474..a7013159008 100644 --- a/jdk/src/share/classes/java/awt/image/FilteredImageSource.java +++ b/jdk/src/share/classes/java/awt/image/FilteredImageSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, 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 @@ -68,7 +68,7 @@ public class FilteredImageSource implements ImageProducer { filter = imgf; } - private Hashtable proxies; + private Hashtable proxies; /** * Adds the specified ImageConsumer @@ -94,7 +94,7 @@ public class FilteredImageSource implements ImageProducer { */ public synchronized void addConsumer(ImageConsumer ic) { if (proxies == null) { - proxies = new Hashtable(); + proxies = new Hashtable<>(); } if (!proxies.containsKey(ic)) { ImageFilter imgf = filter.getFilterInstance(ic); @@ -137,7 +137,7 @@ public class FilteredImageSource implements ImageProducer { */ public synchronized void removeConsumer(ImageConsumer ic) { if (proxies != null) { - ImageFilter imgf = (ImageFilter) proxies.get(ic); + ImageFilter imgf = proxies.get(ic); if (imgf != null) { src.removeConsumer(imgf); proxies.remove(ic); @@ -173,9 +173,9 @@ public class FilteredImageSource implements ImageProducer { */ public void startProduction(ImageConsumer ic) { if (proxies == null) { - proxies = new Hashtable(); + proxies = new Hashtable<>(); } - ImageFilter imgf = (ImageFilter) proxies.get(ic); + ImageFilter imgf = proxies.get(ic); if (imgf == null) { imgf = filter.getFilterInstance(ic); proxies.put(ic, imgf); @@ -200,7 +200,7 @@ public class FilteredImageSource implements ImageProducer { */ public void requestTopDownLeftRightResend(ImageConsumer ic) { if (proxies != null) { - ImageFilter imgf = (ImageFilter) proxies.get(ic); + ImageFilter imgf = proxies.get(ic); if (imgf != null) { imgf.resendTopDownLeftRight(src); } diff --git a/jdk/src/share/classes/java/awt/image/ImageFilter.java b/jdk/src/share/classes/java/awt/image/ImageFilter.java index 0b64d726b8e..33198346e03 100644 --- a/jdk/src/share/classes/java/awt/image/ImageFilter.java +++ b/jdk/src/share/classes/java/awt/image/ImageFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, 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 @@ -104,6 +104,7 @@ public class ImageFilter implements ImageConsumer, Cloneable { * @exception NullPointerException if props is null */ public void setProperties(Hashtable props) { + @SuppressWarnings("unchecked") Hashtable p = (Hashtable)props.clone(); Object o = p.get("filters"); if (o == null) { diff --git a/jdk/src/share/classes/java/awt/image/MemoryImageSource.java b/jdk/src/share/classes/java/awt/image/MemoryImageSource.java index 7046f5e4667..501714fda1f 100644 --- a/jdk/src/share/classes/java/awt/image/MemoryImageSource.java +++ b/jdk/src/share/classes/java/awt/image/MemoryImageSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, 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 @@ -111,8 +111,8 @@ public class MemoryImageSource implements ImageProducer { Object pixels; int pixeloffset; int pixelscan; - Hashtable properties; - Vector theConsumers = new Vector(); + Hashtable properties; + Vector theConsumers = new Vector<>(); boolean animating; boolean fullbuffers; @@ -197,7 +197,7 @@ public class MemoryImageSource implements ImageProducer { } private void initialize(int w, int h, ColorModel cm, - Object pix, int off, int scan, Hashtable props) { + Object pix, int off, int scan, Hashtable props) { width = w; height = h; model = cm; @@ -205,7 +205,7 @@ public class MemoryImageSource implements ImageProducer { pixeloffset = off; pixelscan = scan; if (props == null) { - props = new Hashtable(); + props = new Hashtable<>(); } properties = props; } @@ -343,9 +343,9 @@ public class MemoryImageSource implements ImageProducer { public synchronized void setAnimated(boolean animated) { this.animating = animated; if (!animating) { - Enumeration enum_ = theConsumers.elements(); + Enumeration enum_ = theConsumers.elements(); while (enum_.hasMoreElements()) { - ImageConsumer ic = (ImageConsumer) enum_.nextElement(); + ImageConsumer ic = enum_.nextElement(); ic.imageComplete(ImageConsumer.STATICIMAGEDONE); if (isConsumer(ic)) { ic.imageComplete(ImageConsumer.IMAGEERROR); @@ -376,9 +376,9 @@ public class MemoryImageSource implements ImageProducer { } this.fullbuffers = fullbuffers; if (animating) { - Enumeration enum_ = theConsumers.elements(); + Enumeration enum_ = theConsumers.elements(); while (enum_.hasMoreElements()) { - ImageConsumer ic = (ImageConsumer) enum_.nextElement(); + ImageConsumer ic = enum_.nextElement(); ic.setHints(fullbuffers ? (ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES) @@ -474,9 +474,9 @@ public class MemoryImageSource implements ImageProducer { if ((w <= 0 || h <= 0) && !framenotify) { return; } - Enumeration enum_ = theConsumers.elements(); + Enumeration enum_ = theConsumers.elements(); while (enum_.hasMoreElements()) { - ImageConsumer ic = (ImageConsumer) enum_.nextElement(); + ImageConsumer ic = enum_.nextElement(); if (w > 0 && h > 0) { sendPixels(ic, x, y, w, h); } diff --git a/jdk/src/share/classes/java/awt/image/ReplicateScaleFilter.java b/jdk/src/share/classes/java/awt/image/ReplicateScaleFilter.java index 04a6fdfe52a..7330439f2c5 100644 --- a/jdk/src/share/classes/java/awt/image/ReplicateScaleFilter.java +++ b/jdk/src/share/classes/java/awt/image/ReplicateScaleFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, 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 @@ -121,6 +121,7 @@ public class ReplicateScaleFilter extends ImageFilter { * with the filtering operation. */ public void setProperties(Hashtable props) { + @SuppressWarnings("unchecked") Hashtable p = (Hashtable)props.clone(); String key = "rescale"; String val = destWidth + "x" + destHeight; diff --git a/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java b/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java index ca12bfc4c4b..bf14e8ce2d3 100644 --- a/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java +++ b/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java @@ -153,6 +153,7 @@ public class ParameterBlock implements Cloneable, Serializable { * * @return an Object clone of the ParameterBlock. */ + @SuppressWarnings("unchecked") // casts from clone public Object clone() { ParameterBlock theClone; @@ -164,10 +165,10 @@ public class ParameterBlock implements Cloneable, Serializable { } if (sources != null) { - theClone.setSources((Vector)sources.clone()); + theClone.setSources((Vector)sources.clone()); } if (parameters != null) { - theClone.setParameters((Vector)parameters.clone()); + theClone.setParameters((Vector)parameters.clone()); } return (Object) theClone; } @@ -280,7 +281,7 @@ public class ParameterBlock implements Cloneable, Serializable { /** Clears the list of source images. */ public void removeSources() { - sources = new Vector(); + sources = new Vector<>(); } /** @@ -313,7 +314,7 @@ public class ParameterBlock implements Cloneable, Serializable { /** Clears the list of parameters. */ public void removeParameters() { - parameters = new Vector(); + parameters = new Vector<>(); } /** @@ -696,9 +697,9 @@ public class ParameterBlock implements Cloneable, Serializable { * of the parameters. * @return an array of Class objects. */ - public Class [] getParamClasses() { + public Class[] getParamClasses() { int numParams = getNumParameters(); - Class [] classes = new Class[numParams]; + Class[] classes = new Class[numParams]; int i; for (i = 0; i < numParams; i++) { diff --git a/jdk/src/share/classes/java/awt/image/renderable/RenderableImageOp.java b/jdk/src/share/classes/java/awt/image/renderable/RenderableImageOp.java index 6c51f65a8bf..9d5aaa954a8 100644 --- a/jdk/src/share/classes/java/awt/image/renderable/RenderableImageOp.java +++ b/jdk/src/share/classes/java/awt/image/renderable/RenderableImageOp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, 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 @@ -87,11 +87,11 @@ public class RenderableImageOp implements RenderableImage { return getRenderableSources(); } - private Vector getRenderableSources() { - Vector sources = null; + private Vector getRenderableSources() { + Vector sources = null; if (paramBlock.getNumSources() > 0) { - sources = new Vector(); + sources = new Vector<>(); int i = 0; while (i < paramBlock.getNumSources()) { Object o = paramBlock.getSource(i); @@ -314,19 +314,19 @@ public class RenderableImageOp implements RenderableImage { // contains RenderableImage sources, they will be replaced by // RenderedImages. ParameterBlock renderedParamBlock = (ParameterBlock)paramBlock.clone(); - Vector sources = getRenderableSources(); + Vector sources = getRenderableSources(); try { // This assumes that if there is no renderable source, that there // is a rendered source in paramBlock if (sources != null) { - Vector renderedSources = new Vector(); + Vector renderedSources = new Vector<>(); for (int i = 0; i < sources.size(); i++) { rcOut = myCRIF.mapRenderContext(i, renderContext, paramBlock, this); RenderedImage rdrdImage = - ((RenderableImage)sources.elementAt(i)).createRendering(rcOut); + ((RenderableImage)sources.elementAt(i)).createRendering(rcOut); if (rdrdImage == null) { return null; } diff --git a/jdk/src/share/classes/java/awt/image/renderable/RenderableImageProducer.java b/jdk/src/share/classes/java/awt/image/renderable/RenderableImageProducer.java index c5e357a28c2..206869ae1bf 100644 --- a/jdk/src/share/classes/java/awt/image/renderable/RenderableImageProducer.java +++ b/jdk/src/share/classes/java/awt/image/renderable/RenderableImageProducer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, 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 @@ -68,7 +68,7 @@ public class RenderableImageProducer implements ImageProducer, Runnable { RenderContext rc; /** A Vector of image consumers. */ - Vector ics = new Vector(); + Vector ics = new Vector<>(); /** * Constructs a new RenderableImageProducer from a RenderableImage @@ -177,12 +177,12 @@ public class RenderableImageProducer implements ImageProducer, Runnable { int width = raster.getWidth(); int height = raster.getHeight(); - Enumeration icList; + Enumeration icList; ImageConsumer ic; // Set up the ImageConsumers icList = ics.elements(); while (icList.hasMoreElements()) { - ic = (ImageConsumer)icList.nextElement(); + ic = icList.nextElement(); ic.setDimensions(width,height); ic.setHints(ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES | @@ -204,7 +204,7 @@ public class RenderableImageProducer implements ImageProducer, Runnable { // Now send the scanline to the Consumers icList = ics.elements(); while (icList.hasMoreElements()) { - ic = (ImageConsumer)icList.nextElement(); + ic = icList.nextElement(); ic.setPixels(0, j, width, 1, colorModel, pix, 0, width); } } @@ -212,7 +212,7 @@ public class RenderableImageProducer implements ImageProducer, Runnable { // Now tell the consumers we're done. icList = ics.elements(); while (icList.hasMoreElements()) { - ic = (ImageConsumer)icList.nextElement(); + ic = icList.nextElement(); ic.imageComplete(ImageConsumer.STATICIMAGEDONE); } } diff --git a/jdk/src/share/classes/java/awt/print/Book.java b/jdk/src/share/classes/java/awt/print/Book.java index 672b842e8e7..eaab083789c 100644 --- a/jdk/src/share/classes/java/awt/print/Book.java +++ b/jdk/src/share/classes/java/awt/print/Book.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, 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 @@ -47,7 +47,7 @@ public class Book implements Pageable { /** * The set of pages that make up the Book. */ - private Vector mPages; + private Vector mPages; /* Instance Methods */ @@ -55,7 +55,7 @@ public class Book implements Pageable { * Creates a new, empty Book. */ public Book() { - mPages = new Vector(); + mPages = new Vector<>(); } /** @@ -167,7 +167,7 @@ public class Book implements Pageable { private BookPage getPage(int pageIndex) throws ArrayIndexOutOfBoundsException { - return (BookPage) mPages.elementAt(pageIndex); + return mPages.elementAt(pageIndex); } /** diff --git a/jdk/src/share/classes/java/awt/print/PrinterJob.java b/jdk/src/share/classes/java/awt/print/PrinterJob.java index b9b0d134d64..0c80d1490d4 100644 --- a/jdk/src/share/classes/java/awt/print/PrinterJob.java +++ b/jdk/src/share/classes/java/awt/print/PrinterJob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, 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 @@ -74,9 +74,9 @@ public abstract class PrinterJob { if (security != null) { security.checkPrintJobAccess(); } - return (PrinterJob) java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + return java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public PrinterJob run() { String nm = System.getProperty("java.awt.printerjob", null); try { return (PrinterJob)Class.forName(nm).newInstance(); diff --git a/jdk/src/share/classes/java/beans/MethodDescriptor.java b/jdk/src/share/classes/java/beans/MethodDescriptor.java index da2f754c97e..1e169046746 100644 --- a/jdk/src/share/classes/java/beans/MethodDescriptor.java +++ b/jdk/src/share/classes/java/beans/MethodDescriptor.java @@ -162,6 +162,16 @@ public class MethodDescriptor extends FeatureDescriptor { : null; } + private static Method resolve(Method oldMethod, Method newMethod) { + if (oldMethod == null) { + return newMethod; + } + if (newMethod == null) { + return oldMethod; + } + return !oldMethod.isSynthetic() && newMethod.isSynthetic() ? oldMethod : newMethod; + } + /* * Package-private constructor * Merge two method descriptors. Where they conflict, give the @@ -173,8 +183,7 @@ public class MethodDescriptor extends FeatureDescriptor { MethodDescriptor(MethodDescriptor x, MethodDescriptor y) { super(x, y); - Method method = y.methodRef.get(); - this.methodRef.set(null != method ? method : x.methodRef.get()); + this.methodRef.set(resolve(x.methodRef.get(), y.methodRef.get())); params = x.params; if (y.params != null) { params = y.params; diff --git a/jdk/src/share/classes/javax/accessibility/AccessibleContext.java b/jdk/src/share/classes/javax/accessibility/AccessibleContext.java index 15f0f7f3983..b7f584b95db 100644 --- a/jdk/src/share/classes/javax/accessibility/AccessibleContext.java +++ b/jdk/src/share/classes/javax/accessibility/AccessibleContext.java @@ -25,6 +25,9 @@ package javax.accessibility; +import sun.awt.AWTAccessor; +import sun.awt.AppContext; + import java.util.Locale; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; @@ -79,6 +82,26 @@ import java.awt.IllegalComponentStateException; */ public abstract class AccessibleContext { + /** + * The AppContext that should be used to dispatch events for this + * AccessibleContext + */ + private volatile AppContext targetAppContext; + + static { + AWTAccessor.setAccessibleContextAccessor(new AWTAccessor.AccessibleContextAccessor() { + @Override + public void setAppContext(AccessibleContext accessibleContext, AppContext appContext) { + accessibleContext.targetAppContext = appContext; + } + + @Override + public AppContext getAppContext(AccessibleContext accessibleContext) { + return accessibleContext.targetAppContext; + } + }); + } + /** * Constant used to determine when the accessibleName property has * changed. The old value in the PropertyChangeEvent will be the old diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java index 7829a900bf2..cc476452126 100644 --- a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java +++ b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, 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 @@ -35,7 +35,7 @@ import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.UnsupportedAudioFileException; /** - * Provider for audio file reading services. Classes providing concrete + * Provider for audio file reading services. Classes providing concrete * implementations can parse the format information from one or more types of * audio file, and can produce audio input streams from files of these types. * @@ -45,93 +45,106 @@ import javax.sound.sampled.UnsupportedAudioFileException; public abstract class AudioFileReader { /** - * Obtains the audio file format of the input stream provided. The stream must - * point to valid audio file data. In general, audio file readers may + * Obtains the audio file format of the input stream provided. The stream + * must point to valid audio file data. In general, audio file readers may * need to read some data from the stream before determining whether they - * support it. These parsers must - * be able to mark the stream, read enough data to determine whether they - * support the stream, and, if not, reset the stream's read pointer to its original - * position. If the input stream does not support this, this method may fail - * with an IOException. - * @param stream the input stream from which file format information should be - * extracted - * @return an AudioFileFormat object describing the audio file format - * @throws UnsupportedAudioFileException if the stream does not point to valid audio - * file data recognized by the system + * support it. These parsers must be able to mark the stream, read enough + * data to determine whether they support the stream, and, if not, reset the + * stream's read pointer to its original position. If the input stream does + * not support this, this method may fail with an {@code IOException}. + * + * @param stream the input stream from which file format information should + * be extracted + * @return an {@code AudioFileFormat} object describing the audio file + * format + * @throws UnsupportedAudioFileException if the stream does not point to + * valid audio file data recognized by the system * @throws IOException if an I/O exception occurs * @see InputStream#markSupported * @see InputStream#mark */ - public abstract AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException; + public abstract AudioFileFormat getAudioFileFormat(InputStream stream) + throws UnsupportedAudioFileException, IOException; /** - * Obtains the audio file format of the URL provided. The URL must - * point to valid audio file data. - * @param url the URL from which file format information should be - * extracted - * @return an AudioFileFormat object describing the audio file format - * @throws UnsupportedAudioFileException if the URL does not point to valid audio - * file data recognized by the system + * Obtains the audio file format of the URL provided. The URL must point to + * valid audio file data. + * + * @param url the URL from which file format information should be + * extracted + * @return an {@code AudioFileFormat} object describing the audio file + * format + * @throws UnsupportedAudioFileException if the URL does not point to valid + * audio file data recognized by the system * @throws IOException if an I/O exception occurs */ - public abstract AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException; + public abstract AudioFileFormat getAudioFileFormat(URL url) + throws UnsupportedAudioFileException, IOException; /** - * Obtains the audio file format of the File provided. The File must - * point to valid audio file data. - * @param file the File from which file format information should be - * extracted - * @return an AudioFileFormat object describing the audio file format - * @throws UnsupportedAudioFileException if the File does not point to valid audio - * file data recognized by the system + * Obtains the audio file format of the {@code File} provided. + * The {@code File} must point to valid audio file data. + * + * @param file the {@code File} from which file format information + * should be extracted + * @return an {@code AudioFileFormat} object describing the audio file + * format + * @throws UnsupportedAudioFileException if the {@code File} does not point + * to valid audio file data recognized by the system * @throws IOException if an I/O exception occurs */ - public abstract AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException; + public abstract AudioFileFormat getAudioFileFormat(File file) + throws UnsupportedAudioFileException, IOException; /** - * Obtains an audio input stream from the input stream provided. The stream must - * point to valid audio file data. In general, audio file readers may + * Obtains an audio input stream from the input stream provided. The stream + * must point to valid audio file data. In general, audio file readers may * need to read some data from the stream before determining whether they - * support it. These parsers must - * be able to mark the stream, read enough data to determine whether they - * support the stream, and, if not, reset the stream's read pointer to its original - * position. If the input stream does not support this, this method may fail - * with an IOException. - * @param stream the input stream from which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data contained - * in the input stream. - * @throws UnsupportedAudioFileException if the stream does not point to valid audio - * file data recognized by the system + * support it. These parsers must be able to mark the stream, read enough + * data to determine whether they support the stream, and, if not, reset the + * stream's read pointer to its original position. If the input stream does + * not support this, this method may fail with an {@code IOException}. + * + * @param stream the input stream from which the {@code AudioInputStream} + * should be constructed + * @return an {@code AudioInputStream} object based on the audio file data + * contained in the input stream. + * @throws UnsupportedAudioFileException if the stream does not point to + * valid audio file data recognized by the system * @throws IOException if an I/O exception occurs * @see InputStream#markSupported * @see InputStream#mark */ - public abstract AudioInputStream getAudioInputStream(InputStream stream) throws UnsupportedAudioFileException, IOException; + public abstract AudioInputStream getAudioInputStream(InputStream stream) + throws UnsupportedAudioFileException, IOException; /** - * Obtains an audio input stream from the URL provided. The URL must - * point to valid audio file data. - * @param url the URL for which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data pointed - * to by the URL - * @throws UnsupportedAudioFileException if the URL does not point to valid audio - * file data recognized by the system + * Obtains an audio input stream from the URL provided. The URL must point + * to valid audio file data. + * + * @param url the URL for which the {@code AudioInputStream} should be + * constructed + * @return an {@code AudioInputStream} object based on the audio file data + * pointed to by the URL + * @throws UnsupportedAudioFileException if the URL does not point to valid + * audio file data recognized by the system * @throws IOException if an I/O exception occurs */ - public abstract AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException; + public abstract AudioInputStream getAudioInputStream(URL url) + throws UnsupportedAudioFileException, IOException; /** - * Obtains an audio input stream from the File provided. The File must - * point to valid audio file data. - * @param file the File for which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data pointed - * to by the File - * @throws UnsupportedAudioFileException if the File does not point to valid audio - * file data recognized by the system + * Obtains an audio input stream from the {@code File} provided. + * The {@code File} must point to valid audio file data. + * + * @param file the {@code File} for which the {@code AudioInputStream} + * should be constructed + * @return an {@code AudioInputStream} object based on the audio file data + * pointed to by the File + * @throws UnsupportedAudioFileException if the {@code File} does not point + * to valid audio file data recognized by the system * @throws IOException if an I/O exception occurs */ - public abstract AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException; + public abstract AudioInputStream getAudioInputStream(File file) + throws UnsupportedAudioFileException, IOException; } diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileWriter.java b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileWriter.java index 0207a3b7124..a4cc31bdf18 100644 --- a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileWriter.java +++ b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, 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 @@ -26,16 +26,15 @@ package javax.sound.sampled.spi; import java.io.File; -import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; -import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioInputStream; +import static javax.sound.sampled.AudioFileFormat.Type; /** - * Provider for audio file writing services. Classes providing concrete + * Provider for audio file writing services. Classes providing concrete * implementations can write one or more types of audio file from an audio * stream. * @@ -47,22 +46,23 @@ public abstract class AudioFileWriter { /** * Obtains the file types for which file writing support is provided by this * audio file writer. - * @return array of file types. If no file types are supported, - * an array of length 0 is returned. + * + * @return array of file types. If no file types are supported, an array of + * length 0 is returned. */ - public abstract AudioFileFormat.Type[] getAudioFileTypes(); - + public abstract Type[] getAudioFileTypes(); /** - * Indicates whether file writing support for the specified file type is provided - * by this audio file writer. - * @param fileType the file type for which write capabilities are queried - * @return true if the file type is supported, - * otherwise false + * Indicates whether file writing support for the specified file type is + * provided by this audio file writer. + * + * @param fileType the file type for which write capabilities are queried + * @return {@code true} if the file type is supported, otherwise + * {@code false} */ - public boolean isFileTypeSupported(AudioFileFormat.Type fileType) { + public boolean isFileTypeSupported(Type fileType) { - AudioFileFormat.Type types[] = getAudioFileTypes(); + Type types[] = getAudioFileTypes(); for(int i=0; itrue if the file type is supported for this audio input stream, - * otherwise false + * Indicates whether an audio file of the type specified can be written from + * the audio input stream indicated. + * + * @param fileType file type for which write capabilities are queried + * @param stream for which file writing support is queried + * @return {@code true} if the file type is supported for this audio input + * stream, otherwise {@code false} */ - public boolean isFileTypeSupported(AudioFileFormat.Type fileType, AudioInputStream stream) { + public boolean isFileTypeSupported(Type fileType, AudioInputStream stream) { - AudioFileFormat.Type types[] = getAudioFileTypes( stream ); + Type types[] = getAudioFileTypes( stream ); for(int i=0; i - * The source format represents the format of the incoming - * audio data, which will be converted. + * The source format represents the format of the incoming audio data, which + * will be converted. *

- * The target format represents the format of the processed, converted - * audio data. This is the format of the data that can be read from - * the stream returned by one of the getAudioInputStream methods. + * The target format represents the format of the processed, converted audio + * data. This is the format of the data that can be read from the stream + * returned by one of the {@code getAudioInputStream} methods. * * @author Kara Kytle * @since 1.3 */ public abstract class FormatConversionProvider { - - // NEW METHODS - /** - * Obtains the set of source format encodings from which format - * conversion services are provided by this provider. + * Obtains the set of source format encodings from which format conversion + * services are provided by this provider. + * * @return array of source format encodings. If for some reason provider - * does not provide any conversion services, an array of length 0 is - * returned. + * does not provide any conversion services, an array of length 0 is + * returned. */ - public abstract AudioFormat.Encoding[] getSourceEncodings(); - + public abstract Encoding[] getSourceEncodings(); /** - * Obtains the set of target format encodings to which format - * conversion services are provided by this provider. + * Obtains the set of target format encodings to which format conversion + * services are provided by this provider. + * * @return array of target format encodings. If for some reason provider - * does not provide any conversion services, an array of length 0 is - * returned. + * does not provide any conversion services, an array of length 0 is + * returned. */ - public abstract AudioFormat.Encoding[] getTargetEncodings(); - + public abstract Encoding[] getTargetEncodings(); /** * Indicates whether the format converter supports conversion from the * specified source format encoding. - * @param sourceEncoding the source format encoding for which support is queried - * @return true if the encoding is supported, otherwise false + * + * @param sourceEncoding the source format encoding for which support is + * queried + * @return {@code true} if the encoding is supported, otherwise + * {@code false} */ - public boolean isSourceEncodingSupported(AudioFormat.Encoding sourceEncoding){ + public boolean isSourceEncodingSupported(Encoding sourceEncoding) { - AudioFormat.Encoding sourceEncodings[] = getSourceEncodings(); + Encoding sourceEncodings[] = getSourceEncodings(); for(int i=0; itrue if the encoding is supported, otherwise false + * + * @param targetEncoding the target format encoding for which support is + * queried + * @return {@code true} if the encoding is supported, otherwise + * {@code false} */ - public boolean isTargetEncodingSupported(AudioFormat.Encoding targetEncoding){ + public boolean isTargetEncodingSupported(Encoding targetEncoding) { - AudioFormat.Encoding targetEncodings[] = getTargetEncodings(); + Encoding targetEncodings[] = getTargetEncodings(); for(int i=0; itrue if the conversion is supported, otherwise false + * Indicates whether the format converter supports conversion to a + * particular encoding from a particular format. + * + * @param targetEncoding desired encoding of the outgoing data + * @param sourceFormat format of the incoming data + * @return {@code true} if the conversion is supported, otherwise + * {@code false} */ - public boolean isConversionSupported(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat){ + public boolean isConversionSupported(Encoding targetEncoding, + AudioFormat sourceFormat) { - AudioFormat.Encoding targetEncodings[] = getTargetEncodings(sourceFormat); + Encoding targetEncodings[] = getTargetEncodings(sourceFormat); for(int i=0; itrue if the conversion is supported, otherwise false + * + * @param targetFormat desired format of outgoing data + * @param sourceFormat format of the incoming data + * @return {@code true} if the conversion is supported, otherwise + * {@code false} */ - public boolean isConversionSupported(AudioFormat targetFormat, AudioFormat sourceFormat){ + public boolean isConversionSupported(AudioFormat targetFormat, + AudioFormat sourceFormat) { AudioFormat targetFormats[] = getTargetFormats( targetFormat.getEncoding(), sourceFormat ); @@ -173,28 +177,33 @@ public abstract class FormatConversionProvider { return false; } + /** + * Obtains an audio input stream with the specified encoding from the given + * audio input stream. + * + * @param targetEncoding desired encoding of the stream after processing + * @param sourceStream stream from which data to be processed should be + * read + * @return stream from which processed data with the specified target + * encoding may be read + * @throws IllegalArgumentException if the format combination supplied is + * not supported. + */ + public abstract AudioInputStream getAudioInputStream( + Encoding targetEncoding, AudioInputStream sourceStream); /** - * Obtains an audio input stream with the specified encoding from the given audio - * input stream. - * @param targetEncoding desired encoding of the stream after processing - * @param sourceStream stream from which data to be processed should be read - * @return stream from which processed data with the specified target encoding may be read + * Obtains an audio input stream with the specified format from the given + * audio input stream. + * + * @param targetFormat desired data format of the stream after processing + * @param sourceStream stream from which data to be processed should be + * read + * @return stream from which processed data with the specified format may be + * read * @throws IllegalArgumentException if the format combination supplied is - * not supported. + * not supported. */ - public abstract AudioInputStream getAudioInputStream(AudioFormat.Encoding targetEncoding, AudioInputStream sourceStream); - - - /** - * Obtains an audio input stream with the specified format from the given audio - * input stream. - * @param targetFormat desired data format of the stream after processing - * @param sourceStream stream from which data to be processed should be read - * @return stream from which processed data with the specified format may be read - * @throws IllegalArgumentException if the format combination supplied is - * not supported. - */ - public abstract AudioInputStream getAudioInputStream(AudioFormat targetFormat, AudioInputStream sourceStream); - + public abstract AudioInputStream getAudioInputStream( + AudioFormat targetFormat, AudioInputStream sourceStream); } diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/MixerProvider.java b/jdk/src/share/classes/javax/sound/sampled/spi/MixerProvider.java index d1167c0b8a6..638de86b320 100644 --- a/jdk/src/share/classes/javax/sound/sampled/spi/MixerProvider.java +++ b/jdk/src/share/classes/javax/sound/sampled/spi/MixerProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, 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 @@ -28,28 +28,27 @@ package javax.sound.sampled.spi; import javax.sound.sampled.Mixer; /** - * A provider or factory for a particular mixer type. - * This mechanism allows the implementation to determine - * how resources are managed in creation / management of - * a mixer. + * A provider or factory for a particular mixer type. This mechanism allows the + * implementation to determine how resources are managed in creation / + * management of a mixer. * * @author Kara Kytle * @since 1.3 */ public abstract class MixerProvider { - /** * Indicates whether the mixer provider supports the mixer represented by * the specified mixer info object. *

- * The full set of mixer info objects that represent the mixers supported - * by this {@code MixerProvider} may be obtained - * through the {@code getMixerInfo} method. + * The full set of mixer info objects that represent the mixers supported by + * this {@code MixerProvider} may be obtained through the + * {@code getMixerInfo} method. * - * @param info an info object that describes the mixer for which support is queried - * @return {@code true} if the specified mixer is supported, - * otherwise {@code false} + * @param info an info object that describes the mixer for which support is + * queried + * @return {@code true} if the specified mixer is supported, otherwise + * {@code false} * @see #getMixerInfo() */ public boolean isMixerSupported(Mixer.Info info) { @@ -64,38 +63,34 @@ public abstract class MixerProvider { return false; } - /** - * Obtains the set of info objects representing the mixer - * or mixers provided by this MixerProvider. + * Obtains the set of info objects representing the mixer or mixers provided + * by this MixerProvider. *

- * The {@code isMixerSupported} method returns {@code true} - * for all the info objects returned by this method. - * The corresponding mixer instances for the info objects - * are returned by the {@code getMixer} method. + * The {@code isMixerSupported} method returns {@code true} for all the info + * objects returned by this method. The corresponding mixer instances for + * the info objects are returned by the {@code getMixer} method. * * @return a set of mixer info objects - * @see #getMixer(javax.sound.sampled.Mixer.Info) getMixer(Mixer.Info) - * @see #isMixerSupported(javax.sound.sampled.Mixer.Info) isMixerSupported(Mixer.Info) + * @see #getMixer(Mixer.Info) + * @see #isMixerSupported(Mixer.Info) */ public abstract Mixer.Info[] getMixerInfo(); - /** * Obtains an instance of the mixer represented by the info object. *

* The full set of the mixer info objects that represent the mixers - * supported by this {@code MixerProvider} may be obtained - * through the {@code getMixerInfo} method. - * Use the {@code isMixerSupported} method to test whether - * this {@code MixerProvider} supports a particular mixer. + * supported by this {@code MixerProvider} may be obtained through the + * {@code getMixerInfo} method. Use the {@code isMixerSupported} method to + * test whether this {@code MixerProvider} supports a particular mixer. * - * @param info an info object that describes the desired mixer + * @param info an info object that describes the desired mixer * @return mixer instance * @throws IllegalArgumentException if the info object specified does not - * match the info object for a mixer supported by this MixerProvider. + * match the info object for a mixer supported by this MixerProvider * @see #getMixerInfo() - * @see #isMixerSupported(javax.sound.sampled.Mixer.Info) isMixerSupported(Mixer.Info) + * @see #isMixerSupported(Mixer.Info) */ public abstract Mixer getMixer(Mixer.Info info); } diff --git a/jdk/src/share/classes/javax/swing/JComponent.java b/jdk/src/share/classes/javax/swing/JComponent.java index 98c4d7fb5dd..2d2745957e7 100644 --- a/jdk/src/share/classes/javax/swing/JComponent.java +++ b/jdk/src/share/classes/javax/swing/JComponent.java @@ -3986,7 +3986,18 @@ public abstract class JComponent extends Container implements Serializable, * @see AccessibleKeyBinding * @since 1.4 */ - public AccessibleKeyBinding getAccessibleKeyBinding() { + public AccessibleKeyBinding getAccessibleKeyBinding(){ + // Try to get the linked label's mnemonic if it exists + Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY); + if (o instanceof Accessible){ + AccessibleContext ac = ((Accessible) o).getAccessibleContext(); + if (ac != null){ + AccessibleComponent comp = ac.getAccessibleComponent(); + if (! (comp instanceof AccessibleExtendedComponent)) + return null; + return ((AccessibleExtendedComponent)comp).getAccessibleKeyBinding(); + } + } return null; } } // inner class AccessibleJComponent diff --git a/jdk/src/share/classes/javax/swing/border/LineBorder.java b/jdk/src/share/classes/javax/swing/border/LineBorder.java index c03183292f7..3ddb1ccda5f 100644 --- a/jdk/src/share/classes/javax/swing/border/LineBorder.java +++ b/jdk/src/share/classes/javax/swing/border/LineBorder.java @@ -144,8 +144,8 @@ public class LineBorder extends AbstractBorder int offs = this.thickness; int size = offs + offs; if (this.roundedCorners) { - int arc = offs + size; - outer = new RoundRectangle2D.Float(x, y, width, height, arc, arc); + float arc = .2f * offs; + outer = new RoundRectangle2D.Float(x, y, width, height, offs, offs); inner = new RoundRectangle2D.Float(x + offs, y + offs, width - size, height - size, arc, arc); } else { diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java index 6a64676673b..b1aea28c79f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java @@ -2271,6 +2271,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel // From the JLF Design Guidelines: // http://www.oracle.com/technetwork/java/jlf-135985.html + @SuppressWarnings("fallthrough") private static class MetalLayoutStyle extends DefaultLayoutStyle { private static MetalLayoutStyle INSTANCE = new MetalLayoutStyle(); @@ -2407,4 +2408,4 @@ public class MetalLookAndFeel extends BasicLookAndFeel return 0; } } -} \ No newline at end of file +} diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf b/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf index 39010042190..394721e1c41 100644 --- a/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf +++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf @@ -1,7 +1,7 @@ + + + + + Unsigned applet can retrieve the dragged information before drop action occurs + + + +

DragInterceptorAppletTest
Bug ID: 6887703

+ +

This is an AUTOMATIC test, simply wait for completion

+ + + + diff --git a/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorAppletTest.java b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorAppletTest.java new file mode 100644 index 00000000000..5f70e2de35b --- /dev/null +++ b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorAppletTest.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2007, 2014, 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. + * + * 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. + */ + +/* + test + @bug 6887703 + @summary Unsigned applet can retrieve the dragged information before drop action occurs + @author : area=dnd + @run applet DragInterceptorAppletTest.html +*/ + +/** + * DragInterceptorAppletTest.java + * + * summary: Unsigned applet can retrieve the dragged information before drop action occurs + */ + +import static java.lang.Thread.sleep; + +import test.java.awt.regtesthelpers.process.ProcessCommunicator; +import test.java.awt.regtesthelpers.process.ProcessResults; +import test.java.awt.regtesthelpers.Util; +import java.applet.Applet; +import java.awt.*; +import java.awt.event.InputEvent; + +public class DragInterceptorAppletTest extends Applet { + + public void init() { + setLayout(new BorderLayout()); + }//End init() + + public void start() { + + SourceFrame sourceFrame = new SourceFrame(); + + Util.waitForIdle(null); + + String [] args = new String [] { + String.valueOf(sourceFrame.getNextLocationX()), + String.valueOf(sourceFrame.getNextLocationY()), + String.valueOf(sourceFrame.getDragSourcePointX()), + String.valueOf(sourceFrame.getDragSourcePointY()), + }; + String classpath = System.getProperty("java.class.path"); + ProcessResults processResults = + ProcessCommunicator.executeChildProcess(this.getClass(),classpath,args); + + verifyTestResults(processResults); + + }// start() + + private static void verifyTestResults(ProcessResults processResults) { + + switch (processResults.getExitValue()) { + case InterprocessMessages.DATA_WAS_INTERCEPTED_AND_EXCEPTION_HANDLER_WAS_NOT_TRIGGERED: + processResults.printProcessErrorOutput(System.err); + throw new RuntimeException("TEST IS FAILED: Target applet can intercept data " + + "without a clipboard permission and an exception handler was not triggered."); + //Unreachable... + + case InterprocessMessages.DATA_WAS_INTERCEPTED: + processResults.printProcessErrorOutput(System.err); + throw new RuntimeException("TEST IS FAILED: Target applet can intercept data " + + "without a clipboard permission"); + //Unreachable... + + case InterprocessMessages.EXCEPTION_HANDLER_WAS_NOT_TRIGGERED: + processResults.printProcessErrorOutput(System.err); + throw new RuntimeException("TEST IS FAILED: An exception handler was not triggered."); + //Unreachable... + + } + + // The child process throws an exception. do not look at the stderr. + processResults.verifyStdErr(System.err); + processResults.verifyProcessExitValue(System.err); + processResults.printProcessStandartOutput(System.out); + } + + //We cannot make an instance of the applet without the default constructor + public DragInterceptorAppletTest() { + super(); + } + + //We need in this constructor to pass frame position between JVMs + public DragInterceptorAppletTest(Point targetFrameLocation, Point dragSourcePoint) + throws InterruptedException + { + DragInterceptorFrame targetFrame = new DragInterceptorFrame(targetFrameLocation); + + Util.waitForIdle(null); + + final Robot robot = Util.createRobot(); + + robot.mouseMove((int)dragSourcePoint.getX(),(int)dragSourcePoint.getY()); + sleep(100); + robot.mousePress(InputEvent.BUTTON1_MASK); + sleep(100); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + sleep(100); + + Util.drag(robot, dragSourcePoint, targetFrame.getDropTargetPoint(), + InputEvent.BUTTON1_MASK); + + sleep(2000); + ProcessCommunicator.destroyProcess(); + } + + enum InterprocessArguments { + TARGET_FRAME_X_POSITION_ARGUMENT, + TARGET_FRAME_Y_POSITION_ARGUMENT, + DRAG_SOURCE_POINT_X_ARGUMENT, + DRAG_SOURCE_POINT_Y_ARGUMENT; + + int extract (String [] args) { + return Integer.parseInt(args[this.ordinal()]); + } + } + + public static void main (String [] args) { + Point dragSourcePoint = new Point(InterprocessArguments.DRAG_SOURCE_POINT_X_ARGUMENT.extract(args), + InterprocessArguments.DRAG_SOURCE_POINT_Y_ARGUMENT.extract(args)); + Point targetFrameLocation = new Point(InterprocessArguments.TARGET_FRAME_X_POSITION_ARGUMENT.extract(args), + InterprocessArguments.TARGET_FRAME_Y_POSITION_ARGUMENT.extract(args)); + try { + new DragInterceptorAppletTest(targetFrameLocation, dragSourcePoint); + } catch (InterruptedException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + +}// class DragInterceptorAppletTest diff --git a/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorFrame.java b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorFrame.java new file mode 100644 index 00000000000..69d4a014ba9 --- /dev/null +++ b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorFrame.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2007, 2014, 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. + * + * 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. + */ + +import java.awt.*; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.dnd.*; +import java.io.IOException; +import java.security.Permission; +import java.security.AccessControlException; + +class DragInterceptorFrame extends Frame implements DropTargetListener { + + private static int exitMessage = InterprocessMessages.TEST_PASSED; + private static boolean dataIsAccessible = false; + private static boolean exceptionHasBeenThrown = false; + + DragInterceptorFrame(Point location) { + System.setSecurityManager(new ClipboardDefender()); + initGUI(location); + setDropTarget(new DropTarget(this, DnDConstants.ACTION_COPY, + this)); + } + + private void initGUI(Point location) { + this.setLocation(location); + this.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + DragInterceptorFrame.this.dispose(); + } + }); + setSize (200, 200); + this.setVisible(true); + } + + public void dragEnter(DropTargetDragEvent dtde) { + // We want to set the exception handler on EDT + Thread.currentThread().setUncaughtExceptionHandler ( + new Thread.UncaughtExceptionHandler() { + public void uncaughtException(Thread t, Throwable e) { + exceptionHasBeenThrown = true; + } + } + ); + examineTransferable(dtde); + } + + public void dragOver(DropTargetDragEvent dtde) { + examineTransferable(dtde); + } + + public void dropActionChanged(DropTargetDragEvent dtde) { + examineTransferable(dtde); + } + + public void dragExit(DropTargetEvent dte) {} + + public void drop(DropTargetDropEvent dtde) { + + if (dataIsAccessible && !exceptionHasBeenThrown) { + exitMessage = InterprocessMessages.DATA_WAS_INTERCEPTED_AND_EXCEPTION_HANDLER_WAS_NOT_TRIGGERED; + } else if (dataIsAccessible) { + exitMessage = InterprocessMessages.DATA_WAS_INTERCEPTED; + } else if (!exceptionHasBeenThrown) { + exitMessage = InterprocessMessages.EXCEPTION_HANDLER_WAS_NOT_TRIGGERED; + } + + // This returns the diagnostic code from the child VM + System.exit(exitMessage); + } + + Point getDropTargetPoint() { + return new Point((int)getLocationOnScreen().getX()+(getWidth()/2), + (int)getLocationOnScreen().getY()+(getHeight()/2)); + } + + private void examineTransferable(DropTargetDragEvent dtde) { + if (dtde.getCurrentDataFlavorsAsList().contains(DataFlavor.stringFlavor)) { + dtde.acceptDrag(DnDConstants.ACTION_COPY); + try{ + if (null != dtde.getTransferable().getTransferData(DataFlavor.stringFlavor)) { + dataIsAccessible = true; + } + } catch (IOException e) { + e.printStackTrace(); + exitMessage = InterprocessMessages.UNEXPECTED_IO_EXCEPTION; + } catch (UnsupportedFlavorException e) { + e.printStackTrace(); + exitMessage = InterprocessMessages.UNEXPECTED_UNSUPPORTED_FLAVOR_EXCEPTION; + } + } + } + + static class ClipboardDefender extends SecurityManager { + public void checkPermission(Permission p) { + if (p instanceof java.awt.AWTPermission && + p.getName().equals("accessClipboard")) { + throw new AccessControlException("access denied "); + } + } + } + + public static void main(String[] args) { + new DragInterceptorFrame(new Point(200,200)); + } +} diff --git a/jdk/test/java/awt/dnd/DragInterceptorAppletTest/InterprocessMessages.java b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/InterprocessMessages.java new file mode 100644 index 00000000000..6506565cd05 --- /dev/null +++ b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/InterprocessMessages.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2007, 2014, 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. + * + * 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. + */ + +public interface InterprocessMessages { + final static int TEST_PASSED = 0; + final static int DATA_WAS_INTERCEPTED = 212; + final static int EXCEPTION_HANDLER_WAS_NOT_TRIGGERED = 213; + final static int DATA_WAS_INTERCEPTED_AND_EXCEPTION_HANDLER_WAS_NOT_TRIGGERED = 214; + + final static int UNEXPECTED_IO_EXCEPTION = 400; + final static int UNEXPECTED_UNSUPPORTED_FLAVOR_EXCEPTION = 401; +} diff --git a/jdk/test/java/awt/dnd/DragInterceptorAppletTest/SourceFrame.java b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/SourceFrame.java new file mode 100644 index 00000000000..7a7c833b91a --- /dev/null +++ b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/SourceFrame.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2007, 2014, 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. + * + * 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. + */ + +import test.java.awt.regtesthelpers.Util; + +import java.awt.*; +import java.awt.datatransfer.StringSelection; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; + +class SourceFrame extends Frame implements DragGestureListener { + + SourceFrame() { + super("Source File List Frame"); + initGUI(); + new DragSource().createDefaultDragGestureRecognizer(this, + DnDConstants.ACTION_COPY,this); + } + + private void initGUI() { + this.addWindowListener(Util.getClosingWindowAdapter()); + this.setLocation(300,250); + this.setSize(200,200); + this.setVisible(true); + } + + int getNextLocationX() { + return getX()+getWidth(); + } + + int getNextLocationY() { + return getY(); + } + + int getDragSourcePointX() { + return (int)getLocationOnScreen().getX()+(getWidth()/2); + } + + int getDragSourcePointY() { + return (int)getLocationOnScreen().getY()+ (getHeight()/2); + } + + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(null, new StringSelection("A TEXT")); + } +} diff --git a/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.html b/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.html new file mode 100644 index 00000000000..2b3aa7aa60c --- /dev/null +++ b/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.html @@ -0,0 +1,43 @@ + + + + + + + + + +

InterJVMGetDropSuccessTest
Bug ID: 4658741

+ +

This is an AUTOMATIC test, simply wait for completion

+ + + + diff --git a/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java b/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java new file mode 100644 index 00000000000..9307fa26df5 --- /dev/null +++ b/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java @@ -0,0 +1,499 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +/* + test + @bug 4658741 + @summary verifies that getDropSuccess() returns correct value for inter-JVM DnD + @author das@sparc.spb.su area=dnd + @run applet InterJVMGetDropSuccessTest.html +*/ + +// Note there is no @ in front of test above. This is so that the +// harness will not mistake this file as a test file. It should +// only see the html file as a test file. (the harness runs all +// valid test files, so it would run this test twice if this file +// were valid as well as the html file.) +// Also, note the area= after Your Name in the author tag. Here, you +// should put which functional area the test falls in. See the +// AWT-core home page -> test areas and/or -> AWT team for a list of +// areas. +// Note also the 'InterJVMGetDropSuccessTest.html' in the run tag. This should +// be changed to the name of the test. + + +/** + * InterJVMGetDropSuccessTest.java + * + * summary: verifies that getDropSuccess() returns correct value for inter-JVM DnD + */ + +import java.applet.Applet; +import java.awt.*; +import java.awt.datatransfer.*; +import java.awt.dnd.*; +import java.awt.event.*; +import java.io.*; +import javax.swing.*; + + +//Automated tests should run as applet tests if possible because they +// get their environments cleaned up, including AWT threads, any +// test created threads, and any system resources used by the test +// such as file descriptors. (This is normally not a problem as +// main tests usually run in a separate VM, however on some platforms +// such as the Mac, separate VMs are not possible and non-applet +// tests will cause problems). Also, you don't have to worry about +// synchronisation stuff in Applet tests they way you do in main +// tests... + + +public class InterJVMGetDropSuccessTest extends Applet { + + private int returnCode = Util.CODE_NOT_RETURNED; + private boolean successCodes[] = { true, false }; + private int dropCount = 0; + + final Frame frame = new Frame("Target Frame"); + + final DropTargetListener dropTargetListener = new DropTargetAdapter() { + public void drop(DropTargetDropEvent dtde) { + dtde.acceptDrop(DnDConstants.ACTION_COPY); + dtde.dropComplete(successCodes[dropCount]); + dropCount++; + } + }; + final DropTarget dropTarget = new DropTarget(frame, dropTargetListener); + + public void init() { + //Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + + String[] instructions = + { + "This is an AUTOMATIC test", + "simply wait until it is done" + }; + Sysout.createDialog( ); + Sysout.printInstructions( instructions ); + + frame.setTitle("Test frame"); + frame.setBounds(100, 100, 150, 150); + } // init() + + public void start() { + + frame.setVisible(true); + + try { + Thread.sleep(Util.FRAME_ACTIVATION_TIMEOUT); + + Point p = frame.getLocationOnScreen(); + Dimension d = frame.getSize(); + + String javaPath = System.getProperty("java.home", ""); + String command = javaPath + File.separator + "bin" + + File.separator + "java -cp " + System.getProperty("test.classes", ".") + + " Child " + + p.x + " " + p.y + " " + d.width + " " + d.height; + + Process process = Runtime.getRuntime().exec(command); + returnCode = process.waitFor(); + + InputStream errorStream = process.getErrorStream(); + int count = errorStream.available(); + if (count > 0) { + byte[] b = new byte[count]; + errorStream.read(b); + System.err.println("========= Child VM System.err ========"); + System.err.print(new String(b)); + System.err.println("======================================"); + } + + InputStream outputStream = process.getInputStream(); + count = outputStream.available(); + if (count > 0) { + byte[] b = new byte[count]; + outputStream.read(b); + System.err.println("========= Child VM System.out ========"); + System.err.print(new String(b)); + System.err.println("======================================"); + } + } catch (Throwable e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + switch (returnCode) { + case Util.CODE_NOT_RETURNED: + throw new RuntimeException("Child VM: failed to start"); + case Util.CODE_FAILURE: + throw new RuntimeException("Child VM: abnormal termination"); + default: + if (dropCount == 2) { + int expectedRetCode = 0; + if (successCodes[0]) { + expectedRetCode |= Util.CODE_FIRST_SUCCESS; + } + if (successCodes[1]) { + expectedRetCode |= Util.CODE_SECOND_SUCCESS; + } + if (expectedRetCode != returnCode) { + throw new RuntimeException("The test failed. Expected:" + + expectedRetCode + ". Returned:" + + returnCode); + } + } + break; + } + } // start() +} // class InterJVMGetDropSuccessTest + +final class Util implements AWTEventListener { + public static final int CODE_NOT_RETURNED = -1; + public static final int CODE_FIRST_SUCCESS = 0x2; + public static final int CODE_SECOND_SUCCESS = 0x2; + public static final int CODE_FAILURE = 0x1; + + public static final int FRAME_ACTIVATION_TIMEOUT = 3000; + + static final Object SYNC_LOCK = new Object(); + static final int MOUSE_RELEASE_TIMEOUT = 1000; + + static final Util theInstance = new Util(); + + static { + Toolkit.getDefaultToolkit().addAWTEventListener(theInstance, AWTEvent.MOUSE_EVENT_MASK); + } + + public static Point getCenterLocationOnScreen(Component c) { + Point p = c.getLocationOnScreen(); + Dimension d = c.getSize(); + p.translate(d.width / 2, d.height / 2); + return p; + } + + public static int sign(int n) { + return n < 0 ? -1 : n == 0 ? 0 : 1; + } + + private Component clickedComponent = null; + + private void reset() { + clickedComponent = null; + } + + public void eventDispatched(AWTEvent e) { + if (e.getID() == MouseEvent.MOUSE_RELEASED) { + clickedComponent = (Component)e.getSource(); + synchronized (SYNC_LOCK) { + SYNC_LOCK.notifyAll(); + } + } + } + + public static boolean pointInComponent(Robot robot, Point p, Component comp) + throws InterruptedException { + return theInstance.pointInComponentImpl(robot, p, comp); + } + + private boolean pointInComponentImpl(Robot robot, Point p, Component comp) + throws InterruptedException { + robot.waitForIdle(); + reset(); + robot.mouseMove(p.x, p.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + synchronized (SYNC_LOCK) { + robot.mouseRelease(InputEvent.BUTTON1_MASK); + SYNC_LOCK.wait(MOUSE_RELEASE_TIMEOUT); + } + + Component c = clickedComponent; + + while (c != null && c != comp) { + c = c.getParent(); + } + + return c == comp; + } +} + +class Child { + static class DragSourceDropListener extends DragSourceAdapter { + private boolean finished = false; + private boolean dropSuccess = false; + + public void reset() { + finished = false; + dropSuccess = false; + } + + public boolean isDropFinished() { + return finished; + } + + public boolean getDropSuccess() { + return dropSuccess; + } + + public void dragDropEnd(DragSourceDropEvent dsde) { + finished = true; + dropSuccess = dsde.getDropSuccess(); + synchronized (Util.SYNC_LOCK) { + Util.SYNC_LOCK.notifyAll(); + } + } + } + + final Frame frame = new Frame("Source Frame"); + final DragSource dragSource = DragSource.getDefaultDragSource(); + final DragSourceDropListener dragSourceListener = new DragSourceDropListener(); + final Transferable transferable = new StringSelection("TEXT"); + final DragGestureListener dragGestureListener = new DragGestureListener() { + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(null, transferable, dragSourceListener); + } + }; + final DragGestureRecognizer dragGestureRecognizer = + dragSource.createDefaultDragGestureRecognizer(frame, DnDConstants.ACTION_COPY, + dragGestureListener); + + public static void main(String[] args) { + Child child = new Child(); + child.run(args); + } + + public void run(String[] args) { + try { + if (args.length != 4) { + throw new RuntimeException("Incorrect command line arguments."); + } + + int x = Integer.parseInt(args[0]); + int y = Integer.parseInt(args[1]); + int w = Integer.parseInt(args[2]); + int h = Integer.parseInt(args[3]); + + frame.setBounds(300, 200, 150, 150); + frame.setVisible(true); + + Thread.sleep(Util.FRAME_ACTIVATION_TIMEOUT); + + Point sourcePoint = Util.getCenterLocationOnScreen(frame); + + Point targetPoint = new Point(x + w / 2, y + h / 2); + + Robot robot = new Robot(); + robot.mouseMove(sourcePoint.x, sourcePoint.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + for (Point p = new Point(sourcePoint); !p.equals(targetPoint); + p.translate(Util.sign(targetPoint.x - p.x), + Util.sign(targetPoint.y - p.y))) { + robot.mouseMove(p.x, p.y); + Thread.sleep(50); + } + + synchronized (Util.SYNC_LOCK) { + robot.mouseRelease(InputEvent.BUTTON1_MASK); + Util.SYNC_LOCK.wait(Util.FRAME_ACTIVATION_TIMEOUT); + } + + if (!dragSourceListener.isDropFinished()) { + throw new RuntimeException("Drop not finished"); + } + + boolean success1 = dragSourceListener.getDropSuccess(); + + dragSourceListener.reset(); + robot.mouseMove(sourcePoint.x, sourcePoint.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + for (Point p = new Point(sourcePoint); !p.equals(targetPoint); + p.translate(Util.sign(targetPoint.x - p.x), + Util.sign(targetPoint.y - p.y))) { + robot.mouseMove(p.x, p.y); + Thread.sleep(50); + } + + synchronized (Util.SYNC_LOCK) { + robot.mouseRelease(InputEvent.BUTTON1_MASK); + Util.SYNC_LOCK.wait(Util.FRAME_ACTIVATION_TIMEOUT); + } + + if (!dragSourceListener.isDropFinished()) { + throw new RuntimeException("Drop not finished"); + } + + boolean success2 = dragSourceListener.getDropSuccess(); + int retCode = 0; + + if (success1) { + retCode |= Util.CODE_FIRST_SUCCESS; + } + if (success2) { + retCode |= Util.CODE_SECOND_SUCCESS; + } + // This returns the diagnostic code from the child VM + System.exit(retCode); + } catch (Throwable e) { + e.printStackTrace(); + // This returns the diagnostic code from the child VM + System.exit(Util.CODE_FAILURE); + } + } // run() +} // class child + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout + { + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.show(); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.show(); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + + }// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog + { + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("South", messageText); + + pack(); + + show(); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + } + + }// TestDialog class diff --git a/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.html b/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.html new file mode 100644 index 00000000000..c19a0a02354 --- /dev/null +++ b/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.html @@ -0,0 +1,45 @@ + + + + + + + + + +

NoFormatsCrashTest
Bug ID: 4870762

+ +

This is an AUTOMATIC test, simply wait for completion

+ + + + + diff --git a/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.java b/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.java new file mode 100644 index 00000000000..3be0adc666e --- /dev/null +++ b/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.java @@ -0,0 +1,488 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +/* + test + @bug 4870762 + @summary tests that a drop target JVM doesn't crash if the source doesn't export + data in native formats. + @author das@sparc.spb.su area=dnd + @compile NoFormatsCrashTest.java + @run applet NoFormatsCrashTest.html +*/ + +// Note there is no @ in front of test above. This is so that the +// harness will not mistake this file as a test file. It should +// only see the html file as a test file. (the harness runs all +// valid test files, so it would run this test twice if this file +// were valid as well as the html file.) +// Also, note the area= after Your Name in the author tag. Here, you +// should put which functional area the test falls in. See the +// AWT-core home page -> test areas and/or -> AWT team for a list of +// areas. +// Note also the 'NoFormatsCrashTest.html' in the run tag. This should +// be changed to the name of the test. + + +/** + * NoFormatsCrashTest.java + * + * summary: tests that a drop target JVM doesn't crash if the source doesn't export + * data in native formats. + */ + +import java.applet.Applet; +import java.awt.*; +import java.awt.datatransfer.*; +import java.awt.dnd.*; +import java.awt.event.*; +import java.io.*; + + +//Automated tests should run as applet tests if possible because they +// get their environments cleaned up, including AWT threads, any +// test created threads, and any system resources used by the test +// such as file descriptors. (This is normally not a problem as +// main tests usually run in a separate VM, however on some platforms +// such as the Mac, separate VMs are not possible and non-applet +// tests will cause problems). Also, you don't have to worry about +// synchronisation stuff in Applet tests they way you do in main +// tests... + + +public class NoFormatsCrashTest extends Applet { + + final Frame frame = new Frame(); + private volatile Process process; + + static final int FRAME_ACTIVATION_TIMEOUT = 2000; + + public static void main(String[] args) { + NoFormatsCrashTest test = new NoFormatsCrashTest(); + test.run(args); + } + + public void run(String[] args) { + try { + if (args.length != 4) { + throw new RuntimeException("Incorrect command line arguments."); + } + + int x = Integer.parseInt(args[0]); + int y = Integer.parseInt(args[1]); + int w = Integer.parseInt(args[2]); + int h = Integer.parseInt(args[3]); + + Panel panel = new DragSourcePanel(); + + frame.setTitle("Drag source frame"); + frame.setLocation(500, 200); + frame.add(panel); + frame.pack(); + frame.setVisible(true); + + Thread.sleep(FRAME_ACTIVATION_TIMEOUT); + + Point sourcePoint = panel.getLocationOnScreen(); + Dimension d = panel.getSize(); + sourcePoint.translate(d.width / 2, d.height / 2); + + Point targetPoint = new Point(x + w / 2, y + h / 2); + + Robot robot = new Robot(); + robot.mouseMove(sourcePoint.x, sourcePoint.y); + robot.keyPress(KeyEvent.VK_CONTROL); + robot.mousePress(InputEvent.BUTTON1_MASK); + for (; !sourcePoint.equals(targetPoint); + sourcePoint.translate(sign(targetPoint.x - sourcePoint.x), + sign(targetPoint.y - sourcePoint.y))) { + robot.mouseMove(sourcePoint.x, sourcePoint.y); + Thread.sleep(50); + } + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.keyRelease(KeyEvent.VK_CONTROL); + + Thread.sleep(FRAME_ACTIVATION_TIMEOUT); + + if (process.isAlive()) { + process.destroy(); + } + } catch (Throwable e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } // run() + + public void init() { + //Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + + String[] instructions = + { + "This is an AUTOMATIC test", + "simply wait until it is done" + }; + Sysout.createDialog( ); + Sysout.printInstructions( instructions ); + + frame.setTitle("Drop target frame"); + frame.setLocation(200, 200); + + } // init() + + public void start() { + DropTargetPanel panel = new DropTargetPanel(); + frame.add(panel); + frame.pack(); + frame.setVisible(true); + + try { + Thread.sleep(FRAME_ACTIVATION_TIMEOUT); + + Point p = frame.getLocationOnScreen(); + Dimension d = frame.getSize(); + + String javaPath = System.getProperty("java.home", ""); + String command = javaPath + File.separator + "bin" + + File.separator + "java -cp " + System.getProperty("test.classes", ".") + + " NoFormatsCrashTest " + + p.x + " " + p.y + " " + d.width + " " + d.height; + + process = Runtime.getRuntime().exec(command); + ProcessResults pres = ProcessResults.doWaitFor(process); + System.err.println("Child VM return code: " + pres.exitValue); + + if (pres.stderr != null && pres.stderr.length() > 0) { + System.err.println("========= Child VM System.err ========"); + System.err.print(pres.stderr); + System.err.println("======================================"); + } + + if (pres.stdout != null && pres.stdout.length() > 0) { + System.err.println("========= Child VM System.out ========"); + System.err.print(pres.stdout); + System.err.println("======================================"); + } + + } catch (Throwable e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + + if (panel.isTestFailed()) { + throw new RuntimeException(); + } + } // start() + + public static int sign(int n) { + return n < 0 ? -1 : n > 0 ? 1 : 0; + } +} // class NoFormatsCrashTest + +class TestTransferable implements Transferable { + + public static DataFlavor dataFlavor = null; + static final Object data = new Object(); + + static { + DataFlavor df = null; + try { + df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + + "; class=java.lang.Object"); + } catch (ClassNotFoundException e) { + throw new ExceptionInInitializerError(e); + } + dataFlavor = df; + } + + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor[] { dataFlavor }; + } + + public boolean isDataFlavorSupported(DataFlavor df) { + return dataFlavor.equals(df); + } + + public Object getTransferData(DataFlavor df) + throws UnsupportedFlavorException, IOException { + if (!isDataFlavorSupported(df)) { + throw new UnsupportedFlavorException(df); + } + return data; + } +} + +class DragSourcePanel extends Panel { + public DragSourcePanel() { + final Transferable t = new TestTransferable(); + final DragSourceListener dsl = new DragSourceAdapter() { + public void dragDropEnd(DragSourceDropEvent dtde) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // This finishes child VM + System.exit(0); + } + }; + final DragGestureListener dgl = new DragGestureListener() { + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(null, t, dsl); + } + }; + final DragSource ds = DragSource.getDefaultDragSource(); + final DragGestureRecognizer dgr = + ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, + dgl); + } + + public Dimension getPreferredSize() { + return new Dimension(100, 100); + } +} + +class DropTargetPanel extends Panel { + private boolean testFailed = false; + public DropTargetPanel() { + final DropTargetListener dtl = new DropTargetAdapter() { + public void dragOver(DropTargetDragEvent dtde) { + try { + dtde.getCurrentDataFlavorsAsList(); + } catch (Exception e) { + testFailed = true; + e.printStackTrace(); + } + } + public void drop(DropTargetDropEvent dtde) { + dtde.rejectDrop(); + } + }; + final DropTarget dt = new DropTarget(this, dtl); + } + + public boolean isTestFailed() { + return testFailed; + } + + public Dimension getPreferredSize() { + return new Dimension(100, 100); + } +} + +class ProcessResults { + public int exitValue; + public String stdout; + public String stderr; + + public ProcessResults() { + exitValue = -1; + stdout = ""; + stderr = ""; + } + + /** + * Method to perform a "wait" for a process and return its exit value. + * This is a workaround for Process.waitFor() never returning. + */ + public static ProcessResults doWaitFor(Process p) { + ProcessResults pres = new ProcessResults(); + + InputStream in = null; + InputStream err = null; + + try { + in = p.getInputStream(); + err = p.getErrorStream(); + + boolean finished = false; + + while (!finished) { + try { + while (in.available() > 0) { + pres.stdout += (char)in.read(); + } + while (err.available() > 0) { + pres.stderr += (char)err.read(); + } + // Ask the process for its exitValue. If the process + // is not finished, an IllegalThreadStateException + // is thrown. If it is finished, we fall through and + // the variable finished is set to true. + pres.exitValue = p.exitValue(); + finished = true; + } + catch (IllegalThreadStateException e) { + // Process is not finished yet; + // Sleep a little to save on CPU cycles + Thread.currentThread().sleep(500); + } + } + if (in != null) in.close(); + if (err != null) err.close(); + } + catch (Throwable e) { + System.err.println("doWaitFor(): unexpected exception"); + e.printStackTrace(); + throw new RuntimeException(e); + } + return pres; + } +} + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout + { + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.show(); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.show(); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + + }// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog + { + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("South", messageText); + + pack(); + + show(); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + } + + }// TestDialog class diff --git a/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java b/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java index 8c0e6db916a..8177a2d2ab3 100644 --- a/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java +++ b/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2014, 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 @@ -25,21 +25,22 @@ package test.java.awt.regtesthelpers.process; import java.io.*; -/** This class is created to solve interprocess communication problems. +/** + * This class is created to solve interprocess communication problems. * When you need to write a regression test which should verify inter jvm * behavior such as DnD data transfer, Clipboard data transfer, focus * transfer etc., you could use the next scenario: * * 1. Write an implementation for the parent JVM, using applet test. - * 2. Write an implimentation for the child JVM or native application, using + * 2. Write an implementation for the child JVM or native application, using * main() function. * 3. Execute child process using ProcessCommunicator.executeChildProcess() * method. - * 4. You can decide whetherthe test is passed on the basis of + * 4. You can decide whether the test is passed on the basis of * ProcessResults class data. * - * Note: The class is not thread safe. You should access its methods only from the same - * thread. + * Note: The class is not thread safe. You should access its methods only from + * the same thread. */ public class ProcessCommunicator { @@ -48,31 +49,34 @@ public class ProcessCommunicator { private static final String javaPath = javaHome + File.separator + "bin" + File.separator + "java "; private static String command = ""; + private static volatile Process process; private ProcessCommunicator() {} - /** The same as {#link #executeChildProcess(Class,String)} except - * the {@code classPathArgument} parameter. The class path - * parameter is for the debug purposes + /** + * The same as {#link #executeChildProcess(Class,String)} except + * the {@code classPathArgument} parameter. The class path + * parameter is for the debug purposes * - * @param classToExecute is passed to the child JVM - * @param classPathArguments class path for the child JVM - * @param args arguments that will be passed to the executed class - * @return results of the executed {@code Process} + * @param classToExecute is passed to the child JVM + * @param classPathArguments class path for the child JVM + * @param args arguments that will be passed to the executed class + * @return results of the executed {@code Process} */ public static ProcessResults executeChildProcess(final Class classToExecute, final String classPathArguments, final String [] args) { try { String command = buildCommand(classToExecute, classPathArguments, args); - Process process = Runtime.getRuntime().exec(command); + process = Runtime.getRuntime().exec(command); return doWaitFor(process); } catch (IOException e) { throw new RuntimeException(e); } } - /** Executes child {code Process} + /** + * Executes child {code Process} * * @param classToExecute class to be executed as a child java process * @param args args to be passed in to the child process @@ -86,11 +90,11 @@ public class ProcessCommunicator { /** * Waits for a process and return its results. - * This is a workaround for Process.waitFor() never returning. + * This is a workaround for {@code Process.waitFor()} never returning. * * @return results of the executed {@code Process} */ - private static ProcessResults doWaitFor(final Process p) { + public static ProcessResults doWaitFor(final Process p) { ProcessResults pres = new ProcessResults(); final InputStream in; @@ -133,13 +137,14 @@ public class ProcessCommunicator { return pres; } - /** Builds command on the basis of the passed class name, - * class path and arguments. + /** + * Builds command on the basis of the passed class name, + * class path and arguments. * * @param classToExecute with class will be executed in the new JVM * @param classPathArguments java class path (only for test purposes) * @param args arguments for the new application. This could be used - * to pass some information from the parnent to child JVM. + * to pass some information from the parent to child JVM. * @return command to execute the {@code Process} */ private static String buildCommand(final Class classToExecute, @@ -162,11 +167,24 @@ public class ProcessCommunicator { return command; } - /** Could be used for the debug purposes. + /** + * Could be used for the debug purposes. * - * @return command that was build to execute the child process + * @return command that was build to execute the child process */ public static String getExecutionCommand () { return command; } + + /** + * Terminates the process created by {@code executeChildProcess} methods. + */ + public static void destroyProcess() { + if (process != null) { + if (process.isAlive()) { + process.destroy(); + } + process = null; + } + } } diff --git a/jdk/test/java/awt/security/WarningWindowDisposeTest/WarningWindowDisposeCrashTest.java b/jdk/test/java/awt/security/WarningWindowDisposeTest/WarningWindowDisposeCrashTest.java new file mode 100644 index 00000000000..298059054d9 --- /dev/null +++ b/jdk/test/java/awt/security/WarningWindowDisposeTest/WarningWindowDisposeCrashTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +/* + @test + @bug 8041490 + @summary tests that the WarningWindow's surface is invalidated on dispose + @author Petr Pchelko + @run main/othervm WarningWindowDisposeCrashTest +*/ + + +import sun.applet.AppletSecurity; +import sun.awt.SunToolkit; + +import java.awt.*; + +public class WarningWindowDisposeCrashTest { + public static void main(String[] args) throws Exception { + System.setSecurityManager(new AppletSecurity() { + @Override + public void checkPackageAccess (String s){ + } + }); + + Frame f = new Frame(); + f.setVisible(true); + ((SunToolkit) Toolkit.getDefaultToolkit()).realSync(); + Thread.sleep(1000); + f.dispose(); + // If the bug is present VM could crash after this call + for (int i = 0; i < 1000; i++) Toolkit.getDefaultToolkit().sync(); + } +} diff --git a/jdk/test/java/beans/Introspector/Test8040656.java b/jdk/test/java/beans/Introspector/Test8040656.java new file mode 100644 index 00000000000..73e80ac377f --- /dev/null +++ b/jdk/test/java/beans/Introspector/Test8040656.java @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +import java.beans.Introspector; +import java.beans.MethodDescriptor; + +/* + * @test + * @bug 8040656 + * @summary Tests that a normal method is preferred to a synthetic one + * @author Sergey Malenkov + */ + +public class Test8040656 { + public static void main(String[] args) throws Exception { + test(String.class, C.class); + test(String.class, C1.class); + test(String.class, C2.class); + test(String.class, C3.class); + test(String.class, C4.class); + test(String.class, C5.class); + test(String.class, C6.class); + test(String.class, C7.class); + test(String.class, C8.class); + test(String.class, C9.class); + } + + private static void test(Class type, Class bean) throws Exception { + for (MethodDescriptor md : Introspector.getBeanInfo(bean).getMethodDescriptors()) { + if (md.getName().equals("getFoo")) { + if (type != md.getMethod().getReturnType()) { + throw new Error("unexpected type"); + } + } + } + } + + public interface A { + public Object getFoo(); + } + + public class C implements A { + @Override + public String getFoo() { + return null; + } + } + + public class C1 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + } + + public class C2 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + } + + public class C3 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + } + + public class C4 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + } + + public class C5 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + } + + public class C6 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + + public String getFoo6() { + return null; + } + } + + public class C7 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + + public String getFoo6() { + return null; + } + + public String getFoo7() { + return null; + } + } + + public class C8 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + + public String getFoo6() { + return null; + } + + public String getFoo7() { + return null; + } + + public String getFoo8() { + return null; + } + } + + public class C9 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + + public String getFoo6() { + return null; + } + + public String getFoo7() { + return null; + } + + public String getFoo8() { + return null; + } + + public String getFoo9() { + return null; + } + } +} diff --git a/jdk/test/javax/imageio/plugins/png/ReadMalformedPngTest.java b/jdk/test/javax/imageio/plugins/png/ReadMalformedPngTest.java new file mode 100644 index 00000000000..7aadebc627b --- /dev/null +++ b/jdk/test/javax/imageio/plugins/png/ReadMalformedPngTest.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +/** + * @test + * @bug 6945174 + * @summary Test verifies that PNG image readr throw correct exception + * if image contains a chunk with incorrect length. + * @run main ReadMalformedPngTest + */ + +import java.awt.Color; +import java.awt.GradientPaint; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import javax.imageio.IIOException; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageTypeSpecifier; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.metadata.IIOMetadata; +import javax.imageio.metadata.IIOMetadataNode; +import javax.imageio.stream.ImageOutputStream; +import org.w3c.dom.Node; + +public class ReadMalformedPngTest { + + public static void main(String[] args) throws IOException { + ByteArrayInputStream bais = new ByteArrayInputStream(createTestPng()); + + IIOException expected = null; + try { + ImageIO.read(bais); + } catch (IIOException e) { + expected = e; + } catch (Throwable e) { + throw new RuntimeException("Test failed!", e); + } + + if (expected == null) { + throw new RuntimeException("Test failed."); + } + + System.out.println("Test passed."); + } + + private static byte[] createTestPng() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + BufferedImage img = createTestImage(); + + try { + ImageOutputStream ios = ImageIO.createImageOutputStream(baos); + + ImageWriter w = ImageIO.getImageWritersByFormatName("PNG").next(); + + w.setOutput(ios); + + ImageWriteParam p = w.getDefaultWriteParam(); + + ImageTypeSpecifier t = ImageTypeSpecifier.createFromRenderedImage(img); + + IIOMetadata m = w.getDefaultImageMetadata(t, p); + + String nativeMetadataFormat = m.getNativeMetadataFormatName(); + + Node root = m.getAsTree(nativeMetadataFormat); + + IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry"); + textEntry.setAttribute("keyword", "comment"); + textEntry.setAttribute("value", "This is a test image for JDK-6945174"); + + IIOMetadataNode text = new IIOMetadataNode("tEXt"); + text.appendChild(textEntry); + + root.appendChild(text); + + m.mergeTree(nativeMetadataFormat, root); + + IIOImage iio_img = new IIOImage(img, null, m); + + w.write(iio_img); + + w.dispose(); + ios.flush(); + ios.close(); + } catch (IOException e) { + throw new RuntimeException("Test failed.", e); + } + + baos.flush(); + + byte[] data = baos.toByteArray(); + + adjustCommentLength(Integer.MAX_VALUE + 0x1000, data); + + return data; + } + + private static void adjustCommentLength(int v, byte[] data) { + final int pos = getCommentPos(data); + data[pos + 3] = (byte) (v & 0xFF); + v = v >> 8; + data[pos + 2] = (byte) (v & 0xFF); + v = v >> 8; + data[pos + 1] = (byte) (v & 0xFF); + v = v >> 8; + data[pos + 0] = (byte) (v & 0xFF); + } + + private static int getCommentPos(byte[] d) { + int p = 8; + while (p + 8 < d.length) { + if (d[p + 4] == (byte) 0x74 && d[p + 5] == (byte) 0x45 && + d[p + 6] == (byte) 0x58 && d[p + 7] == (byte) 0x74) + { + return p; + } + p++; + } + throw new RuntimeException("Test chunk was not found!"); + } + + private static BufferedImage createTestImage() { + final int w = 128; + final int h = 128; + + BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR); + Graphics2D g = img.createGraphics(); + g.setPaint(new GradientPaint(0, 0, Color.blue, + w, h, Color.red)); + g.fillRect(0, 0, w, h); + g.dispose(); + return img; + } +} diff --git a/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java b/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java index 5cb1dc5047f..2d36db7a171 100644 --- a/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java +++ b/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java @@ -28,7 +28,7 @@ import javax.swing.JMenuBar; import javax.swing.SwingUtilities; /* @test - * @bug 8031573 + * @bug 8031573 8040279 * @summary [macosx] Checkmarks of JCheckBoxMenuItems aren't rendered * in high resolution on Retina * @author Alexander Scherbatiy diff --git a/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java b/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java index 42f976b03c0..185537f3b5b 100644 --- a/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java +++ b/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java @@ -31,7 +31,7 @@ import sun.awt.OSInfo; /** * @test - * @bug 8024926 + * @bug 8024926 8040279 * @summary [macosx] AquaIcon HiDPI support * @author Alexander Scherbatiy * @run applet/manual=yesno bug8024926.html diff --git a/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.html b/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.html new file mode 100644 index 00000000000..a473b819d1c --- /dev/null +++ b/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.html @@ -0,0 +1,32 @@ + + + + +Choose the variable applet size and try to resize the applet. +The test passes the thumb is painted correctly. + + + + + diff --git a/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.java b/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.java new file mode 100644 index 00000000000..44bb33abd94 --- /dev/null +++ b/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +import java.awt.Container; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; + +import javax.swing.JApplet; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JScrollBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +/* + * @test + * @bug 8039464 + * @summary Tests enabling/disabling of titled border's caption + * @author Sergey Malenkov + * @run applet/manual=yesno Test8039464.html + */ + +public class Test8039464 extends JApplet { + static { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + throw new Error("unexpected", exception); + } + } + + @Override + public void init() { + init(this); + } + + private static void init(Container container) { + container.setLayout(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 1; + JLabel label = new JLabel(); + Dimension size = new Dimension(111, 0); + label.setPreferredSize(size); + label.setMinimumSize(size); + container.add(label, gbc); + gbc.gridx = 1; + gbc.weightx = 1; + container.add(new JScrollBar(JScrollBar.HORIZONTAL, 1, 111, 1, 1111), gbc); + gbc.gridx = 2; + gbc.gridy = 0; + gbc.weightx = 0; + gbc.weighty = 1; + container.add(new JScrollBar(JScrollBar.VERTICAL, 1, 111, 1, 1111), gbc); + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + JFrame frame = new JFrame("8039464"); + init(frame); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + }); + } +} diff --git a/jdk/test/javax/swing/JTextField/8036819/bug8036819.java b/jdk/test/javax/swing/JTextField/8036819/bug8036819.java new file mode 100644 index 00000000000..558be4c9769 --- /dev/null +++ b/jdk/test/javax/swing/JTextField/8036819/bug8036819.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +/* + * @test + * @library ../../regtesthelpers + * @build Util + * @bug 8036819 + * @summary JAB: mnemonics not read for textboxes + * @author Vivi An + * @run main bug8036819 + */ + +import javax.swing.*; +import javax.swing.event.*; +import java.awt.event.*; +import java.awt.*; +import sun.awt.SunToolkit; +import javax.accessibility.*; + +public class bug8036819 { + + public static volatile Boolean passed = false; + + public static void main(String args[]) throws Throwable { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + toolkit.realSync(); + + Robot robo = new Robot(); + robo.setAutoDelay(300); + + // Using mnemonic key to focus on the textfield + Util.hitMnemonics(robo, KeyEvent.VK_P); + toolkit.realSync(); + + if (!passed){ + throw new RuntimeException("Test failed."); + } + } + + private static void createAndShowGUI() { + JFrame mainFrame = new JFrame("bug 8036819"); + + JLabel usernameLabel = new JLabel("Username: "); + JTextField usernameField = new JTextField(20); + usernameLabel.setDisplayedMnemonic(KeyEvent.VK_U); + usernameLabel.setLabelFor(usernameField); + + JLabel pwdLabel = new JLabel("Password: "); + JTextField pwdField = new JTextField(20); + pwdLabel.setDisplayedMnemonic(KeyEvent.VK_P); + pwdLabel.setLabelFor(pwdField); + + pwdField.addKeyListener( + new KeyListener(){ + @Override + public void keyPressed(KeyEvent keyEvent) { + } + + @Override + public void keyTyped(KeyEvent keyEvent) { + } + + @Override + public void keyReleased(KeyEvent keyEvent){ + JComponent comp = (JComponent) pwdField; + AccessibleContext ac = comp.getAccessibleContext(); + AccessibleExtendedComponent aec = (AccessibleExtendedComponent)ac.getAccessibleComponent(); + AccessibleKeyBinding akb = aec.getAccessibleKeyBinding(); + if (akb != null){ + int count = akb.getAccessibleKeyBindingCount(); + if (count != 1){ + passed = false; + return; + } + + // there is 1 accessible key for the text field + System.out.println("Retrieved AccessibleKeyBinding for textfield " + count); + + // the key code is KeyEvent.VK_P + Object o = akb.getAccessibleKeyBinding(0); + if (o instanceof KeyStroke){ + javax.swing.KeyStroke key = (javax.swing.KeyStroke)o; + System.out.println("keystroke is " + key.getKeyCode()); + if (key.getKeyCode() == KeyEvent.VK_P) + passed = true; + } + } + } + } + ); + + mainFrame.getContentPane().add(usernameLabel); + mainFrame.getContentPane().add(usernameField); + mainFrame.getContentPane().add(pwdLabel); + mainFrame.getContentPane().add(pwdField); + + mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + mainFrame.setLayout(new FlowLayout(FlowLayout.LEFT)); + + mainFrame.setSize(200, 200); + mainFrame.setLocation(200, 200); + mainFrame.setVisible(true); + mainFrame.toFront(); + } + } diff --git a/jdk/test/javax/swing/border/Test4252164.java b/jdk/test/javax/swing/border/Test4252164.java index 007e732cf2a..923df715054 100644 --- a/jdk/test/javax/swing/border/Test4252164.java +++ b/jdk/test/javax/swing/border/Test4252164.java @@ -23,7 +23,7 @@ /* * @test - * @bug 4252164 + * @bug 4252164 8041917 * @summary Tests rounded LineBorder for components * @author Sergey Malenkov * @run applet/manual=yesno Test4252164.html diff --git a/jdk/test/javax/swing/plaf/nimbus/8041725/bug8041725.java b/jdk/test/javax/swing/plaf/nimbus/8041725/bug8041725.java new file mode 100644 index 00000000000..d668a3411de --- /dev/null +++ b/jdk/test/javax/swing/plaf/nimbus/8041725/bug8041725.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +/* @test + @bug 8041725 + @summary JList selection colors are not UIResource instances in Nimbus L&F + @author Anton Litvinov +*/ + +import java.awt.*; +import javax.swing.*; +import javax.swing.plaf.*; +import javax.swing.plaf.nimbus.*; + +public class bug8041725 { + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel(new NimbusLookAndFeel()); + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + JFrame frame = new JFrame("bug8041725"); + frame.setSize(200, 200); + JList list = new JList(new String[]{"Item1", "Item2", "Item3"}); + frame.getContentPane().add(list); + frame.pack(); + frame.setVisible(true); + + System.err.println("Test #1: No items are selected, list is enabled."); + testSelectionColors(list); + + System.err.println("Test #2: No items are selected, list is disabled."); + list.setEnabled(false); + testSelectionColors(list); + + System.err.println("Test #3: One item is selected, list is disabled."); + list.setSelectedIndex(0); + testSelectionColors(list); + + System.err.println("Test #4: One item is selected, list is enabled."); + list.setEnabled(true); + testSelectionColors(list); + + frame.dispose(); + } + }); + } + + private static void testSelectionColors(JList list) { + Color selBackColor = list.getSelectionBackground(); + if (!(selBackColor instanceof UIResource)) { + throw new RuntimeException(String.format( + "JList.getSelectionBackground() returned instance of '%s' instead of UIResource.", + selBackColor.getClass())); + } + Color selForeColor = list.getSelectionForeground(); + if (!(selForeColor instanceof UIResource)) { + throw new RuntimeException(String.format( + "JList.getSelectionForeground() returned instance of '%s' instead of UIResource.", + selForeColor.getClass())); + } + } +} diff --git a/jdk/test/javax/swing/text/StyledEditorKit/8016833/bug8016833.java b/jdk/test/javax/swing/text/StyledEditorKit/8016833/bug8016833.java index 601a31de688..1dec0972346 100644 --- a/jdk/test/javax/swing/text/StyledEditorKit/8016833/bug8016833.java +++ b/jdk/test/javax/swing/text/StyledEditorKit/8016833/bug8016833.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -190,9 +190,9 @@ public class bug8016833 { // not too wide assertTrue(out3.getWidth() * 0.8 < out2.getWidth()); // not too low - assertTrue(out3.getY() - (out1.getY() + out2.getHeight()) < 3); + assertTrue(out3.getY() - (out1.getY() + out2.getHeight() - 1) < 4); // not too high - assertTrue(out3.getY() - (out1.getY() + out2.getHeight()) > 0); + assertTrue(out3.getY() - (out1.getY() + out2.getHeight() - 1) > 0); } void testStrikthrough() { @@ -217,7 +217,7 @@ public class bug8016833 { // not too wide assertTrue(out3.getWidth() * 0.8 < out2.getWidth()); // not too low - assertTrue(out3.getY() - (out1.getY() + out2.getHeight()) < 0); + assertTrue(out3.getY() - (out1.getY() + out2.getHeight() - 1) < 0); // not too high assertTrue(out3.getY() - out1.getY() > 1); } diff --git a/jdk/test/javax/xml/ws/8043129/MailTest.java b/jdk/test/javax/xml/ws/8043129/MailTest.java new file mode 100644 index 00000000000..3d32a7d4dd8 --- /dev/null +++ b/jdk/test/javax/xml/ws/8043129/MailTest.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +/* + * @test + * @bug 8043129 + * @summary JAF initialisation in SAAJ clashing with the one in javax.mail + * @author mkos + * @library javax.mail.jar + * @build MailTest + * @run main MailTest + */ + +import javax.activation.CommandMap; +import javax.activation.MailcapCommandMap; +import javax.mail.BodyPart; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.Session; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; +import javax.xml.soap.AttachmentPart; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPMessage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Properties; + +public class MailTest { + + String host = null; + String user = ""; + String password = null; + String from = null; + String to = null; + + public static void main(String[] args) { + MailTest t = new MailTest(); + + t.user = "somebody@somewhere.com"; + t.from = "somebody@somewhere.com"; + t.to = "somebody@somewhere.com"; + + t.user = "somebody@somewhere.com"; + t.password = "somepassword"; + t.host = "somehost"; + + t.sendMail(); //this works + + t.addSoapAttachement(); + t.sendMail(); //after addAttachmentPart to soapmessage it do not work + + // workaroundJAFSetup(); + // t.sendMail(); //after workaround works again + } + + void addSoapAttachement() { + try { + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage message = messageFactory.createMessage(); + AttachmentPart a = message.createAttachmentPart(); + a.setContentType("binary/octet-stream"); + message.addAttachmentPart(a); + } catch (SOAPException e) { + e.printStackTrace(); + } + } + + void sendMail() { + + try { + Properties props = new Properties(); + props.put("mail.smtp.host", host); + props.put("mail.smtp.auth", "true"); + + Session session = Session.getInstance(props); + session.setDebug(true); + + // Define message + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress(from)); + message.addRecipients(Message.RecipientType.TO, to); + message.setSubject("this is a multipart test"); + + Multipart multipart = new MimeMultipart(); + + BodyPart messageBodyPart1 = new MimeBodyPart(); + messageBodyPart1.setText("please send also this Content\n ciao!"); + multipart.addBodyPart(messageBodyPart1); + + BodyPart messageBodyPart2 = new MimeBodyPart(); + messageBodyPart2.setContent("please send also this Content
ciao!", "text/html; charset=UTF-8"); + multipart.addBodyPart(messageBodyPart2); + + message.setContent(multipart); + + /* + Transport tr = session.getTransport("smtp"); + tr.connect(host,user, password); + tr.sendMessage(message,InternetAddress.parse(to)); + tr.close(); + */ + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + message.writeTo(baos); + String output = baos.toString(); + System.out.println("output = " + output); + if (output.contains("also this Content")) { + System.out.println("Test PASSED."); + } else { + System.out.println("Test FAILED, missing content."); + throw new IllegalStateException("Test FAILED, missing content."); + } + } catch (MessagingException ignored) { + } catch (IOException ignored) { + } + } + + // this is how the error can be worked around ... + static void workaroundJAFSetup() { + MailcapCommandMap mailMap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); + mailMap.addMailcap("multipart/mixed;;x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); + } +} diff --git a/jdk/test/javax/xml/ws/8043129/javax.mail.jar b/jdk/test/javax/xml/ws/8043129/javax.mail.jar new file mode 100644 index 00000000000..7da28712d88 Binary files /dev/null and b/jdk/test/javax/xml/ws/8043129/javax.mail.jar differ diff --git a/jdk/test/sun/awt/dnd/8024061/bug8024061.java b/jdk/test/sun/awt/dnd/8024061/bug8024061.java new file mode 100644 index 00000000000..07165c09a61 --- /dev/null +++ b/jdk/test/sun/awt/dnd/8024061/bug8024061.java @@ -0,0 +1,357 @@ +/* + * Copyright (c) 2014, 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. + * + * 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. + */ + +/* @test + * @bug 8024061 + * @summary Checks that no exception is thrown if dragGestureRecognized + * takes a while to complete. + */ +import sun.awt.OSInfo; +import sun.awt.OSInfo.OSType; +import sun.awt.SunToolkit; + +import java.awt.*; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DragSourceDragEvent; +import java.awt.dnd.DragSourceDropEvent; +import java.awt.dnd.DragSourceEvent; +import java.awt.dnd.DragSourceListener; +import java.awt.dnd.DropTarget; +import java.awt.dnd.DropTargetDragEvent; +import java.awt.dnd.DropTargetDropEvent; +import java.awt.dnd.DropTargetEvent; +import java.awt.dnd.DropTargetListener; +import java.awt.event.InputEvent; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import javax.swing.*; + +/** + * If dragGestureRecognized() takes a while to complete and if user performs a drag quickly, + * an exception is thrown from DropTargetListener.dragEnter when it calls + * DropTargetDragEvent.getTransferable(). + *

+ * This class introduces a delay in dragGestureRecognized() to cause the exception. + */ +public class bug8024061 { + private static final DataFlavor DropObjectFlavor; + private static final int DELAY = 1000; + + private final DnDPanel panel1 = new DnDPanel(Color.yellow); + private final DnDPanel panel2 = new DnDPanel(Color.pink); + private final JFrame frame; + + private static final CountDownLatch lock = new CountDownLatch(1); + private static volatile Exception dragEnterException = null; + + static { + DataFlavor flavor = null; + try { + flavor = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + DropObjectFlavor = flavor; + } + + bug8024061() { + frame = new JFrame("DnDWithRobot"); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + + Dimension d = new Dimension(100, 100); + + panel1.setPreferredSize(d); + panel2.setPreferredSize(d); + + Container content = frame.getContentPane(); + content.setLayout(new GridLayout(1, 2, 5, 5)); + content.add(panel1); + content.add(panel2); + + frame.pack(); + + DropObject drop = new DropObject(); + drop.place(panel1, new Point(10, 10)); + frame.setVisible(true); + } + + public static void main(String[] args) throws AWTException, InvocationTargetException, InterruptedException { + OSType type = OSInfo.getOSType(); + if (type != OSType.LINUX && type != OSType.SOLARIS) { + System.out.println("This test is for Linux and Solaris only... " + + "skipping!"); + return; + } + + final bug8024061[] dnd = {null}; + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + dnd[0] = new bug8024061(); + } + }); + final Robot robot = new Robot(); + robot.setAutoDelay(10); + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + toolkit.realSync(); + + JFrame frame = dnd[0].frame; + Point point = frame.getLocationOnScreen(); + Point here = new Point(point.x + 35, point.y + 45); + Point there = new Point(point.x + 120, point.y + 45); + here.x += 25; + robot.mouseMove(here.x, here.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + while (here.x < there.x) { + here.x += 20; + robot.mouseMove(here.x, here.y); + System.out.println("x = " + here.x); + } + robot.mouseRelease(InputEvent.BUTTON1_MASK); + toolkit.realSync(); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + System.out.println("finished"); + + try { + if (lock.await(5, TimeUnit.SECONDS)) { + if (dragEnterException == null) { + System.out.println("Test passed."); + } else { + System.out.println("Test failed."); + dragEnterException.printStackTrace(); + throw new RuntimeException(dragEnterException); + } + } else { + System.out.println("Test failed. Timeout reached"); + throw new RuntimeException("Timed out waiting for dragEnter()"); + } + } finally { + frame.dispose(); + } + } + + class DropObject implements Transferable { + DnDPanel panel; + Color color = Color.CYAN; + int width = 50; + int height = 50; + int x; + int y; + + void draw(Graphics2D g) { + Color savedColor = g.getColor(); + g.setColor(color); + g.fillRect(x, y, width, height); + g.setColor(Color.lightGray); + g.drawRect(x, y, width, height); + g.setColor(savedColor); + } + + boolean contains(int x, int y) { + return (x > this.x && x < this.x + width) + && (y > this.y && y < this.y + height); + } + + @Override + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor[]{DropObjectFlavor}; + } + + void place(DnDPanel panel, Point location) { + if (panel != this.panel) { + x = location.x; + y = location.y; + if (this.panel != null) { + this.panel.setDropObject(null); + this.panel.repaint(); + } + this.panel = panel; + this.panel.setDropObject(this); + this.panel.repaint(); + } + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return DropObjectFlavor.equals(flavor); + } + + @Override + public Object getTransferData(DataFlavor flavor) + throws UnsupportedFlavorException, IOException { + if (isDataFlavorSupported(flavor)) { + return this; + } else { + throw new UnsupportedFlavorException(flavor); + } + } + } + + class DnDPanel extends JPanel { + DropObject dropObject; + final DragSource dragSource; + final DropTarget dropTarget; + final Color color; + final DragGestureListener dgListener; + final DragSourceListener dsListener; + final DropTargetListener dtListener; + + DnDPanel(Color color) { + this.color = color; + this.dragSource = DragSource.getDefaultDragSource(); + dgListener = new DragGestureListener() { + @Override + public void dragGestureRecognized(DragGestureEvent dge) { + Point location = dge.getDragOrigin(); + if (dropObject != null && dropObject.contains(location.x, location.y)) { + dragSource.startDrag(dge, DragSource.DefaultCopyNoDrop, dropObject, dsListener); + try { + Thread.sleep(DELAY); + } catch (InterruptedException e) { + } + } + } + }; + + dsListener = new DragSourceListener() { + @Override + public void dragEnter(DragSourceDragEvent dsde) { + } + + @Override + public void dragOver(DragSourceDragEvent dsde) { + } + + @Override + public void dropActionChanged(DragSourceDragEvent dsde) { + } + + @Override + public void dragExit(DragSourceEvent dse) { + } + + @Override + public void dragDropEnd(DragSourceDropEvent dsde) { + } + }; + + dtListener = new DropTargetListener() { + @Override + public void dragEnter(DropTargetDragEvent dtde) { + if (dropObject != null) { + dtde.rejectDrag(); + return; + } + dtde.acceptDrag(DnDConstants.ACTION_MOVE); + try { + Transferable t = dtde.getTransferable(); + Object data = t.getTransferData(DropObjectFlavor); + if (data != null) { + throw new Exception("getTransferData returned non-null"); + } + } catch (Exception e) { + dragEnterException = e; + e.printStackTrace(); + } finally { + lock.countDown(); + } + } + + @Override + public void dragOver(DropTargetDragEvent dtde) { + if (dropObject != null) { + dtde.rejectDrag(); + return; + } + dtde.acceptDrag(DnDConstants.ACTION_MOVE); + } + + @Override + public void dropActionChanged(DropTargetDragEvent dtde) { + } + + @Override + public void dragExit(DropTargetEvent dte) { + } + + @Override + public void drop(DropTargetDropEvent dtde) { + if (dropObject != null) { + dtde.rejectDrop(); + return; + } + try { + dtde.acceptDrop(DnDConstants.ACTION_MOVE); + Transferable t = dtde.getTransferable(); + DropObject dropObject = (DropObject) t.getTransferData(DropObjectFlavor); + Point location = dtde.getLocation(); + dropObject.place(DnDPanel.this, location); + dtde.dropComplete(true); + } catch (Exception e) { + e.printStackTrace(); + } + + } + }; + + dragSource.createDefaultDragGestureRecognizer(this, + DnDConstants.ACTION_MOVE, dgListener); + + dropTarget = new DropTarget(this, DnDConstants.ACTION_MOVE, dtListener, true); + + } + + public void paintComponent(Graphics g) { + super.paintComponent(g); + Color savedColor = g.getColor(); + g.setColor(color); + g.fillRect(0, 0, getWidth(), getHeight()); + g.setColor(savedColor); + if (dropObject != null) { + dropObject.draw((Graphics2D) g); + } + } + + void setDropObject(DropObject dropObject) { + this.dropObject = dropObject; + } + + DropObject findDropObject(int x, int y) { + if (dropObject != null && dropObject.contains(x, y)) { + return dropObject; + } + return null; + } + } +}