changeset 5190:aa0ad405f70b jdk7u6-b17

Merge
author lana
date Thu, 28 Jun 2012 14:11:05 -0700
parents cc19202f6179 a73386183d31
children 4a6917092af8 28e43b980aee
files
diffstat 105 files changed, 3500 insertions(+), 1318 deletions(-) [+]
line wrap: on
line diff
--- a/make/common/Defs-embedded.gmk	Wed Jun 27 17:19:47 2012 -0700
+++ b/make/common/Defs-embedded.gmk	Thu Jun 28 14:11:05 2012 -0700
@@ -42,7 +42,7 @@
 OTHER_CPPFLAGS += -DJAVASE_EMBEDDED
 
 # Product naming
-PRODUCT_SUFFIX = SE Runtime Environment for Embedded
+PRODUCT_SUFFIX = SE Embedded Runtime Environment
 RUNTIME_NAME = $(PRODUCT_NAME) $(PRODUCT_SUFFIX)
 
 # Reduced JRE locations
--- a/make/jprt.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/make/jprt.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -89,6 +89,7 @@
     ${jprt.my.test.target.set:TESTNAME=jdk_text},		\
     ${jprt.my.test.target.set:TESTNAME=jdk_tools1},		\
     ${jprt.my.test.target.set:TESTNAME=jdk_tools2},		\
+    ${jprt.my.test.target.set:TESTNAME=jdk_jfr},		\
     ${jprt.my.test.target.set:TESTNAME=jdk_misc}
 
 # All vm test targets (testset=all)
--- a/make/sun/osxapp/Makefile	Wed Jun 27 17:19:47 2012 -0700
+++ b/make/sun/osxapp/Makefile	Thu Jun 28 14:11:05 2012 -0700
@@ -28,6 +28,11 @@
 PRODUCT = sun
 include $(BUILDDIR)/common/Defs.gmk
 
+GEN_DIR=$(GENSRCDIR)/sun/osxapp
+ICON_DATA = $(GEN_DIR)/AWTIconData.h
+
+CLASSES_INIT += $(ICON_DATA)
+
 #
 # Files
 #
@@ -63,6 +68,7 @@
 	-framework QuartzCore
 
 CPPFLAGS += \
+        -I$(GEN_DIR) \
         $(call NativeSrcDirList,-I,/native/sun/osxapp)
 
 
@@ -70,6 +76,34 @@
   CPPFLAGS += -DINTERNAL_BUILD
 endif
 
-clean clobber::
+TEMPDIR_CLASSES = $(TEMPDIR)/classes
 
-.PHONY:
+$(TEMPDIR_CLASSES)/sun/osxapp/ToBin.class: ToBin.java
+	@$(prep-target)
+	$(BOOT_JAVAC_CMD) -d $(TEMPDIR_CLASSES) $<
+
+ifdef OPENJDK
+    ICONS_PATH_PREFIX=$(PLATFORM_SRC_MACOS)
+else
+    ICONS_PATH_PREFIX=$(CLOSED_SRC)/macosx
+endif
+
+generated.clean:
+	$(RM) -r $(GEN_DIR)/*.h
+
+ICONPATH=$(ICONS_PATH_PREFIX)/native/sun/osxapp/resource/icons
+ICON = $(ICONPATH)/JavaApp.icns
+
+$(GEN_DIR)/AWTIconData.h: $(TEMPDIR_CLASSES)/sun/osxapp/ToBin.class $(ICON) 
+	$(prep-target)
+	$(RM) $(ICON_DATA)
+	$(ECHO) "static unsigned char sAWTIconData[] = { " >> $(ICON_DATA);  \
+	$(CAT) $(ICON) | \
+	    $(BOOT_JAVA_CMD) -cp $(TEMPDIR_CLASSES) -Djava.awt.headless=true \
+	    sun.osxapp.ToBin >> $(ICON_DATA); \
+	$(ECHO) "};" >> $(ICON_DATA);
+
+
+clean clobber:: generated.clean
+
+.PHONY: generated.clean
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/sun/osxapp/ToBin.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.osxapp;
+
+import java.io.*;
+
+public class ToBin {
+    public static void main(String[] args) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        int nRead;
+        byte[] data = new byte[4096];
+
+        while ((nRead = System.in.read(data, 0, data.length)) != -1) {
+            baos.write(data, 0, nRead);
+        }
+
+        baos.flush();
+
+        byte[] buf = baos.toByteArray();
+        for (int i = 0; i < buf.length; i++) {
+            System.out.print(String.format("0x%1$02X", buf[i]) + ", ");
+            if (i % 20 == 0) {
+                System.out.println();
+            }
+        }
+    }
+}
--- a/src/macosx/classes/sun/awt/CGraphicsDevice.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/awt/CGraphicsDevice.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 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
@@ -29,6 +29,7 @@
 import java.awt.GraphicsDevice;
 import java.awt.Window;
 import java.awt.AWTPermission;
+import java.awt.DisplayMode;
 
 import sun.java2d.opengl.CGLGraphicsConfig;
 
@@ -178,4 +179,36 @@
             peer.exitFullScreenMode();
         }
     }
+
+    @Override
+    public boolean isDisplayChangeSupported() {
+        return true;
+    }
+
+    @Override
+    public void setDisplayMode(DisplayMode dm) {
+        if (dm == null) {
+            throw new IllegalArgumentException("Attempt to set null as a DisplayMode");
+        }
+        nativeSetDisplayMode(displayID, dm.getWidth(), dm.getHeight(), dm.getBitDepth(), dm.getRefreshRate());
+        if (isFullScreenSupported() && getFullScreenWindow() != null) {
+            getFullScreenWindow().setSize(dm.getWidth(), dm.getHeight());
+        }
+    }
+
+    @Override
+    public DisplayMode getDisplayMode() {
+        return nativeGetDisplayMode(displayID);
+    }
+
+    @Override
+    public DisplayMode[] getDisplayModes() {
+        return nativeGetDisplayModes(displayID);
+    }
+
+    private native void nativeSetDisplayMode(int displayID, int w, int h, int bpp, int refrate);
+
+    private native DisplayMode nativeGetDisplayMode(int displayID);
+
+    private native DisplayMode[] nativeGetDisplayModes(int displayID);
 }
--- a/src/macosx/classes/sun/awt/CGraphicsEnvironment.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/awt/CGraphicsEnvironment.java	Thu Jun 28 14:11:05 2012 -0700
@@ -194,29 +194,25 @@
        return true;
     }
 
-    private Font[] allFontsWithLogical;
     static String[] sLogicalFonts = { "Serif", "SansSerif", "Monospaced", "Dialog", "DialogInput" };
 
     @Override
     public Font[] getAllFonts() {
-        if (allFontsWithLogical == null)
+
+        Font[] newFonts;
+        Font[] superFonts = super.getAllFonts();
+
+        int numLogical = sLogicalFonts.length;
+        int numOtherFonts = superFonts.length;
+
+        newFonts = new Font[numOtherFonts + numLogical];
+        System.arraycopy(superFonts,0,newFonts,numLogical,numOtherFonts);
+
+        for (int i = 0; i < numLogical; i++)
         {
-            Font[] newFonts;
-            Font[] superFonts = super.getAllFonts();
-
-            int numLogical = sLogicalFonts.length;
-            int numOtherFonts = superFonts.length;
-
-            newFonts = new Font[numOtherFonts + numLogical];
-            System.arraycopy(superFonts,0,newFonts,numLogical,numOtherFonts);
-
-            for (int i = 0; i < numLogical; i++)
-            {
-                newFonts[i] = new Font(sLogicalFonts[i], Font.PLAIN, 1);
-            }
-            allFontsWithLogical = newFonts;
+            newFonts[i] = new Font(sLogicalFonts[i], Font.PLAIN, 1);
         }
-        return java.util.Arrays.copyOf(allFontsWithLogical, allFontsWithLogical.length);
+        return newFonts;
     }
 
 }
--- a/src/macosx/classes/sun/lwawt/LWButtonPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWButtonPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -47,8 +47,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         setLabel(getTarget().getLabel());
         synchronized (getDelegateLock()) {
             getDelegate().addActionListener(this);
--- a/src/macosx/classes/sun/lwawt/LWCheckboxPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWCheckboxPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -61,8 +61,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         setLabel(getTarget().getLabel());
         setState(getTarget().getState());
         setCheckboxGroup(getTarget().getCheckboxGroup());
--- a/src/macosx/classes/sun/lwawt/LWChoicePeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWChoicePeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -55,8 +55,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         final Choice choice = getTarget();
         final JComboBox<String> combo = getDelegate();
         synchronized (getDelegateLock()) {
--- a/src/macosx/classes/sun/lwawt/LWComponentPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWComponentPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -81,19 +81,10 @@
     // lock is not used as there are many peers related ops
     // to be done on the toolkit thread, and we don't want to
     // depend on a public lock on this thread
-    private final static Object peerTreeLock =
+    private static final Object peerTreeLock =
             new StringBuilder("LWComponentPeer.peerTreeLock");
 
-    /**
-     * A custom tree-lock used for the hierarchy of the delegate Swing
-     * components.
-     * The lock synchronizes access to the delegate
-     * internal state. Think of it as a 'virtual EDT'.
-     */
-//    private final Object delegateTreeLock =
-//        new StringBuilder("LWComponentPeer.delegateTreeLock");
-
-    private T target;
+    private final T target;
 
     // Container peer. It may not be the peer of the target's direct
     // parent, for example, in the case of hw/lw mixing. However,
@@ -108,10 +99,10 @@
     // be updated when the component is reparented to another container
     private LWWindowPeer windowPeer;
 
-    private AtomicBoolean disposed = new AtomicBoolean(false);
+    private final AtomicBoolean disposed = new AtomicBoolean(false);
 
     // Bounds are relative to parent peer
-    private Rectangle bounds = new Rectangle();
+    private final Rectangle bounds = new Rectangle();
     private Region region;
 
     // Component state. Should be accessed under the state lock
@@ -122,9 +113,11 @@
     private Color foreground;
     private Font font;
 
-    // Paint area to coalesce all the paint events and store
-    // the target dirty area
-    private RepaintArea targetPaintArea;
+    /**
+     * Paint area to coalesce all the paint events and store the target dirty
+     * area.
+     */
+    private final RepaintArea targetPaintArea;
 
     //   private volatile boolean paintPending;
     private volatile boolean isLayouting;
@@ -137,7 +130,7 @@
     private int fNumDropTargets = 0;
     private CDropTarget fDropTarget = null;
 
-    private PlatformComponent platformComponent;
+    private final PlatformComponent platformComponent;
 
     private final class DelegateContainer extends Container {
         {
@@ -175,6 +168,7 @@
     }
 
     public LWComponentPeer(T target, PlatformComponent platformComponent) {
+        targetPaintArea = new LWRepaintArea();
         this.target = target;
         this.platformComponent = platformComponent;
 
@@ -201,10 +195,13 @@
                 synchronized (getDelegateLock()) {
                     delegate = createDelegate();
                     if (delegate != null) {
+                        delegate.setVisible(false);
                         delegateContainer = new DelegateContainer();
                         delegateContainer.add(delegate);
                         delegateContainer.addNotify();
                         delegate.addNotify();
+                        resetColorsAndFont(delegate);
+                        delegate.setOpaque(true);
                     } else {
                         return;
                     }
@@ -278,27 +275,28 @@
         return getDelegate();
     }
 
-    /*
-     * Initializes this peer by fetching all the properties from the target.
-     * The call to initialize() is not placed to LWComponentPeer ctor to
-     * let the subclass ctor to finish completely first. Instead, it's the
-     * LWToolkit object who is responsible for initialization.
+    /**
+     * Initializes this peer. The call to initialize() is not placed to
+     * LWComponentPeer ctor to let the subclass ctor to finish completely first.
+     * Instead, it's the LWToolkit object who is responsible for initialization.
+     * Note that we call setVisible() at the end of initialization.
      */
-    public void initialize() {
+    public final void initialize() {
         platformComponent.initialize(target, this, getPlatformWindow());
-        targetPaintArea = new LWRepaintArea();
-        if (getDelegate() != null) {
-            synchronized (getDelegateLock()) {
-                resetColorsAndFont(delegate);
-                getDelegate().setOpaque(true);
-            }
-        }
+        initializeImpl();
+        setVisible(target.isVisible());
+    }
+
+    /**
+     * Fetching general properties from the target. Should be overridden in
+     * subclasses to initialize specific peers properties.
+     */
+    void initializeImpl() {
         setBackground(target.getBackground());
         setForeground(target.getForeground());
         setFont(target.getFont());
         setBounds(target.getBounds());
         setEnabled(target.isEnabled());
-        setVisible(target.isVisible());
     }
 
     private static void resetColorsAndFont(final Container c) {
@@ -314,15 +312,18 @@
         return stateLock;
     }
 
-    // Synchronize all operations with the Swing delegates under
-    // AWT tree lock, using a new separate lock to synchronize
-    // access to delegates may lead deadlocks
+    /**
+     * Synchronize all operations with the Swing delegates under AWT tree lock,
+     * using a new separate lock to synchronize access to delegates may lead
+     * deadlocks. Think of it as a 'virtual EDT'.
+     *
+     * @return DelegateLock
+     */
     final Object getDelegateLock() {
-        //return delegateTreeLock;
         return getTarget().getTreeLock();
     }
 
-    protected final static Object getPeerTreeLock() {
+    protected static final Object getPeerTreeLock() {
         return peerTreeLock;
     }
 
@@ -613,6 +614,17 @@
                 windowLocation.y + locationInWindow.y);
     }
 
+    /**
+     * Returns the cursor of the peer, which is cursor of the target by default,
+     * but peer can override this behavior.
+     *
+     * @param p Point relative to the peer.
+     * @return Cursor of the peer or null if default cursor should be used.
+     */
+    protected Cursor getCursor(final Point p) {
+        return getTarget().getCursor();
+    }
+
     @Override
     public void setBackground(final Color c) {
         final Color oldBg = getBackground();
@@ -747,14 +759,17 @@
     }
 
     @Override
-    public void setVisible(boolean v) {
+    public void setVisible(final boolean v) {
         synchronized (getStateLock()) {
             if (visible == v) {
                 return;
             }
             visible = v;
         }
+        setVisibleImpl(v);
+    }
 
+    protected void setVisibleImpl(final boolean v) {
         final D delegate = getDelegate();
 
         if (delegate != null) {
@@ -1344,7 +1359,7 @@
      *
      * @see #isVisible()
      */
-    protected boolean isShowing() {
+    protected final boolean isShowing() {
         synchronized (getPeerTreeLock()) {
             if (isVisible()) {
                 final LWContainerPeer container = getContainerPeer();
--- a/src/macosx/classes/sun/lwawt/LWCursorManager.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWCursorManager.java	Thu Jun 28 14:11:05 2012 -0700
@@ -36,32 +36,34 @@
 
 public abstract class LWCursorManager {
 
-    // A flag to indicate if the update is scheduled, so we don't
-    // process it twice
-    private AtomicBoolean updatePending = new AtomicBoolean(false);
+    /**
+     * A flag to indicate if the update is scheduled, so we don't process it
+     * twice.
+     */
+    private final AtomicBoolean updatePending = new AtomicBoolean(false);
 
     protected LWCursorManager() {
     }
 
-    /*
+    /**
      * Sets the cursor to correspond the component currently under mouse.
      *
      * This method should not be executed on the toolkit thread as it
      * calls to user code (e.g. Container.findComponentAt).
      */
-    public void updateCursor() {
+    public final void updateCursor() {
         updatePending.set(false);
         updateCursorImpl();
     }
 
-    /*
+    /**
      * Schedules updating the cursor on the corresponding event dispatch
      * thread for the given window.
      *
      * This method is called on the toolkit thread as a result of a
      * native update cursor request (e.g. WM_SETCURSOR on Windows).
      */
-    public void updateCursorLater(LWWindowPeer window) {
+    public final void updateCursorLater(final LWWindowPeer window) {
         if (updatePending.compareAndSet(false, true)) {
             Runnable r = new Runnable() {
                 @Override
@@ -74,45 +76,58 @@
     }
 
     private void updateCursorImpl() {
-        LWWindowPeer windowUnderCursor = LWWindowPeer.getWindowUnderCursor();
-        Point cursorPos = getCursorPosition();
-        LWComponentPeer<?, ?> componentUnderCursor = null;
-        // TODO: it's possible to get the component under cursor directly as
-        // it's stored in LWWindowPee anyway (lastMouseEventPeer)
-        if (windowUnderCursor != null) {
-            componentUnderCursor = windowUnderCursor.findPeerAt(cursorPos.x, cursorPos.y);
+        final Point cursorPos = getCursorPosition();
+        final Component c = findComponent(cursorPos);
+        final Cursor cursor;
+        final Object peer = LWToolkit.targetToPeer(c);
+        if (peer instanceof LWComponentPeer) {
+            final LWComponentPeer<?, ?> lwpeer = (LWComponentPeer<?, ?>) peer;
+            final Point p = lwpeer.getLocationOnScreen();
+            cursor = lwpeer.getCursor(new Point(cursorPos.x - p.x,
+                                                cursorPos.y - p.y));
+        } else {
+            cursor = (c != null) ? c.getCursor() : null;
         }
-        Cursor cursor = null;
-        if (componentUnderCursor != null) {
-            Component c = componentUnderCursor.getTarget();
+        setCursor(cursor);
+    }
+
+    /**
+     * Returns the first visible, enabled and showing component under cursor.
+     * Returns null for modal blocked windows.
+     *
+     * @param cursorPos Current cursor position.
+     * @return Component or null.
+     */
+    private static final Component findComponent(final Point cursorPos) {
+        final LWComponentPeer<?, ?> peer = LWWindowPeer.getPeerUnderCursor();
+        Component c = null;
+        if (peer != null && peer.getWindowPeerOrSelf().getBlocker() == null) {
+            c = peer.getTarget();
             if (c instanceof Container) {
-                Point p = componentUnderCursor.getLocationOnScreen();
-                c = ((Container)c).findComponentAt(cursorPos.x - p.x, cursorPos.y - p.y);
+                final Point p = peer.getLocationOnScreen();
+                c = ((Container) c).findComponentAt(cursorPos.x - p.x,
+                                                    cursorPos.y - p.y);
             }
-            // Traverse up to the first visible, enabled and showing component
             while (c != null) {
                 if (c.isVisible() && c.isEnabled() && (c.getPeer() != null)) {
                     break;
                 }
                 c = c.getParent();
             }
-            if (c != null) {
-                cursor = c.getCursor();
-            }
         }
-        // TODO: default cursor for modal blocked windows
-        setCursor(windowUnderCursor, cursor);
+        return c;
     }
 
-    /*
+    /**
      * Returns the current cursor position.
      */
     // TODO: make it public to reuse for MouseInfo
     protected abstract Point getCursorPosition();
 
-    /*
-     * Sets a cursor. The cursor can be null if the mouse is not over a Java window.
+    /**
+     * Sets a cursor. The cursor can be null if the mouse is not over a Java
+     * window.
+     * @param cursor the new {@code Cursor}.
      */
-    protected abstract void setCursor(LWWindowPeer windowUnderCursor, Cursor cursor);
-
+    protected abstract void setCursor(Cursor cursor);
 }
--- a/src/macosx/classes/sun/lwawt/LWLabelPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWLabelPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -56,8 +56,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         setText(getTarget().getText());
         setAlignment(getTarget().getAlignment());
     }
--- a/src/macosx/classes/sun/lwawt/LWListPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWListPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -49,8 +49,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         setMultipleMode(getTarget().isMultipleMode());
         final int[] selectedIndices = getTarget().getSelectedIndexes();
         synchronized (getDelegateLock()) {
--- a/src/macosx/classes/sun/lwawt/LWScrollBarPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWScrollBarPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -54,8 +54,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         final Scrollbar target = getTarget();
         setValues(target.getValue(), target.getVisibleAmount(),
                   target.getMinimum(), target.getMaximum());
--- a/src/macosx/classes/sun/lwawt/LWScrollPanePeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWScrollPanePeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -86,8 +86,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         final int policy = getTarget().getScrollbarDisplayPolicy();
         synchronized (getDelegateLock()) {
             getDelegate().getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
--- a/src/macosx/classes/sun/lwawt/LWTextAreaPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWTextAreaPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -27,6 +27,7 @@
 package sun.lwawt;
 
 import java.awt.Component;
+import java.awt.Cursor;
 import java.awt.Dimension;
 import java.awt.Point;
 import java.awt.TextArea;
@@ -58,8 +59,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         final int visibility = getTarget().getScrollbarVisibility();
         synchronized (getDelegateLock()) {
             setScrollBarVisibility(visibility);
@@ -72,6 +73,15 @@
     }
 
     @Override
+    protected Cursor getCursor(final Point p) {
+        final boolean isContains;
+        synchronized (getDelegateLock()) {
+            isContains = getDelegate().getViewport().getBounds().contains(p);
+        }
+        return isContains ? super.getCursor(p) : null;
+    }
+
+    @Override
     protected Component getDelegateFocusOwner() {
         return getTextComponent();
     }
--- a/src/macosx/classes/sun/lwawt/LWTextComponentPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWTextComponentPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -63,8 +63,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         synchronized (getDelegateLock()) {
             // This listener should be added before setText().
             getTextComponent().getDocument().addDocumentListener(this);
--- a/src/macosx/classes/sun/lwawt/LWTextFieldPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWTextFieldPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -54,8 +54,8 @@
     }
 
     @Override
-    public void initialize() {
-        super.initialize();
+    void initializeImpl() {
+        super.initializeImpl();
         setEchoChar(getTarget().getEchoChar());
         synchronized (getDelegateLock()) {
             getDelegate().addActionListener(this);
--- a/src/macosx/classes/sun/lwawt/LWWindowPeer.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/LWWindowPeer.java	Thu Jun 28 14:11:05 2012 -0700
@@ -145,8 +145,6 @@
             // similar to what Apple's Java do.
             // Since JDK7 we should rely on setOpacity() only.
             // this.opacity = c.getAlpha();
-            // System.out.println("Delegate assigns alpha (we ignore setOpacity()):"
-            // +this.opacity);
         }
 
         if (!target.isForegroundSet()) {
@@ -159,23 +157,29 @@
     }
 
     @Override
-    public void initialize() {
+    void initializeImpl() {
+        super.initializeImpl();
         if (getTarget() instanceof Frame) {
-            setTitle(((Frame)getTarget()).getTitle());
-            setState(((Frame)getTarget()).getExtendedState());
+            setTitle(((Frame) getTarget()).getTitle());
+            setState(((Frame) getTarget()).getExtendedState());
         } else if (getTarget() instanceof Dialog) {
-            setTitle(((Dialog)getTarget()).getTitle());
+            setTitle(((Dialog) getTarget()).getTitle());
         }
 
         setAlwaysOnTop(getTarget().isAlwaysOnTop());
         updateMinimumSize();
 
-        setOpacity(getTarget().getOpacity());
+        final float opacity = getTarget().getOpacity();
+        if (opacity < 1.0f) {
+            setOpacity(opacity);
+        }
+
         setOpaque(getTarget().isOpaque());
 
-        super.initialize();
-
         updateInsets(platformWindow.getInsets());
+        if (getSurfaceData() == null) {
+            replaceSurfaceData();
+        }
     }
 
     // Just a helper method
@@ -213,49 +217,28 @@
     }
 
     @Override
-    public void setVisible(final boolean visible) {
-        if (getSurfaceData() == null) {
-            replaceSurfaceData();
-        }
+    protected void setVisibleImpl(final boolean visible) {
+        super.setVisibleImpl(visible);
+        // TODO: update graphicsConfig, see 4868278
+        platformWindow.setVisible(visible);
+        if (isSimpleWindow()) {
+            LWKeyboardFocusManagerPeer manager = LWKeyboardFocusManagerPeer.
+                getInstance(getAppContext());
 
-        if (isVisible() == visible) {
-            return;
-        }
-        super.setVisible(visible);
-
-        // TODO: update graphicsConfig, see 4868278
-        // TODO: don't notify the delegate if our visibility is unchanged
-
-        // it is important to call this method on EDT
-        // to prevent the deadlocks during the painting of the lightweight delegates
-        //TODO: WHY? This is a native-system related call. Perhaps NOT calling
-        // the painting procedure right from the setVisible(), but rather relying
-        // on the native Expose event (or, scheduling the repainting asynchronously)
-        // is better?
-        SwingUtilities.invokeLater(new Runnable() {
-            @Override
-            public void run() {
-                platformWindow.setVisible(visible);
-                if (isSimpleWindow()) {
-                    LWKeyboardFocusManagerPeer manager = LWKeyboardFocusManagerPeer.
-                        getInstance(getAppContext());
-
-                    if (visible) {
-                        if (!getTarget().isAutoRequestFocus()) {
-                            return;
-                        } else {
-                            requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
-                        }
-                    } else if (manager.getCurrentFocusedWindow() == getTarget()) {
-                        // Transfer focus to the owner.
-                        LWWindowPeer owner = getOwnerFrameDialog(LWWindowPeer.this);
-                        if (owner != null) {
-                            owner.requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
-                        }
-                    }
+            if (visible) {
+                if (!getTarget().isAutoRequestFocus()) {
+                    return;
+                } else {
+                    requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
+                }
+            } else if (manager.getCurrentFocusedWindow() == getTarget()) {
+                // Transfer focus to the owner.
+                LWWindowPeer owner = getOwnerFrameDialog(LWWindowPeer.this);
+                if (owner != null) {
+                    owner.requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
                 }
             }
-        });
+        }
     }
 
     @Override
@@ -689,39 +672,42 @@
             }
         } else {
             if (targetPeer != lastMouseEventPeer) {
-                // lastMouseEventPeer may be null if mouse was out of Java windows
-                if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
-                    // Sometimes, MOUSE_EXITED is not sent by delegate (or is sent a bit
-                    // later), in which case lastWindowPeer is another window
-                    if (lastWindowPeer != this) {
-                        Point oldp = lastMouseEventPeer.windowToLocal(x, y, lastWindowPeer);
-                        // Additionally translate from this to lastWindowPeer coordinates
-                        Rectangle lr = lastWindowPeer.getBounds();
-                        oldp.x += r.x - lr.x;
-                        oldp.y += r.y - lr.y;
-                        postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
-                                                 MouseEvent.MOUSE_EXITED,
+
+                if (id != MouseEvent.MOUSE_DRAGGED || lastMouseEventPeer == null) {
+                    // lastMouseEventPeer may be null if mouse was out of Java windows
+                    if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
+                        // Sometimes, MOUSE_EXITED is not sent by delegate (or is sent a bit
+                        // later), in which case lastWindowPeer is another window
+                        if (lastWindowPeer != this) {
+                            Point oldp = lastMouseEventPeer.windowToLocal(x, y, lastWindowPeer);
+                            // Additionally translate from this to lastWindowPeer coordinates
+                            Rectangle lr = lastWindowPeer.getBounds();
+                            oldp.x += r.x - lr.x;
+                            oldp.y += r.y - lr.y;
+                            postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
+                                                     MouseEvent.MOUSE_EXITED,
+                                                     when, modifiers,
+                                                     oldp.x, oldp.y, screenX, screenY,
+                                                     clickCount, popupTrigger, button));
+                        } else {
+                            Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
+                            postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
+                                                     MouseEvent.MOUSE_EXITED,
+                                                     when, modifiers,
+                                                     oldp.x, oldp.y, screenX, screenY,
+                                                     clickCount, popupTrigger, button));
+                        }
+                    }
+                    if (targetPeer != null && targetPeer.isEnabled() && id != MouseEvent.MOUSE_ENTERED) {
+                        Point newp = targetPeer.windowToLocal(x, y, curWindowPeer);
+                        postEvent(new MouseEvent(targetPeer.getTarget(),
+                                                 MouseEvent.MOUSE_ENTERED,
                                                  when, modifiers,
-                                                 oldp.x, oldp.y, screenX, screenY,
-                                                 clickCount, popupTrigger, button));
-                    } else {
-                        Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
-                        postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
-                                                 MouseEvent.MOUSE_EXITED,
-                                                 when, modifiers,
-                                                 oldp.x, oldp.y, screenX, screenY,
+                                                 newp.x, newp.y, screenX, screenY,
                                                  clickCount, popupTrigger, button));
                     }
                 }
                 lastMouseEventPeer = targetPeer;
-                if (targetPeer != null && targetPeer.isEnabled() && id != MouseEvent.MOUSE_ENTERED) {
-                    Point newp = targetPeer.windowToLocal(x, y, curWindowPeer);
-                    postEvent(new MouseEvent(targetPeer.getTarget(),
-                                             MouseEvent.MOUSE_ENTERED,
-                                             when, modifiers,
-                                             newp.x, newp.y, screenX, screenY,
-                                             clickCount, popupTrigger, button));
-                }
             }
             // TODO: fill "bdata" member of AWTEvent
 
@@ -804,9 +790,8 @@
                 }
                 mouseClickButtons &= ~eventButtonMask;
             }
-
-            notifyUpdateCursor();
         }
+        notifyUpdateCursor();
     }
 
     public void dispatchMouseWheelEvent(long when, int x, int y, int modifiers,
@@ -1002,6 +987,9 @@
                 try {
                     Rectangle r = getBounds();
                     g.setColor(getBackground());
+                    if (g instanceof Graphics2D) {
+                        ((Graphics2D) g).setComposite(AlphaComposite.Src);
+                    }
                     g.fillRect(0, 0, r.width, r.height);
                     if (oldBB != null) {
                         // Draw the old back buffer to the new one
@@ -1067,6 +1055,10 @@
         return lastMouseEventPeer != null ? lastMouseEventPeer.getWindowPeerOrSelf() : null;
     }
 
+    public static LWComponentPeer<?, ?> getPeerUnderCursor() {
+        return lastMouseEventPeer;
+    }
+
     /*
      * Requests platform to set native focus on a frame/dialog.
      * In case of a simple window, triggers appropriate java focus change.
--- a/src/macosx/classes/sun/lwawt/macosx/CCursorManager.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CCursorManager.java	Thu Jun 28 14:11:05 2012 -0700
@@ -25,12 +25,14 @@
 
 package sun.lwawt.macosx;
 
-import java.awt.*;
+import sun.lwawt.LWCursorManager;
+
+import java.awt.Cursor;
+import java.awt.Point;
 import java.awt.geom.Point2D;
 
-import sun.lwawt.*;
+final class CCursorManager extends LWCursorManager {
 
-public class CCursorManager extends LWCursorManager {
     private static native Point2D nativeGetCursorPosition();
     private static native void nativeSetBuiltInCursor(final int type, final String name);
     private static native void nativeSetCustomCursor(final long imgPtr, final double x, final double y);
@@ -38,12 +40,12 @@
 
     private static final int NAMED_CURSOR = -1;
 
-    private final static CCursorManager theInstance = new CCursorManager();
+    private static final CCursorManager theInstance = new CCursorManager();
     public static CCursorManager getInstance() {
         return theInstance;
     }
 
-    Cursor currentCursor;
+    private volatile Cursor currentCursor;
 
     private CCursorManager() { }
 
@@ -63,8 +65,11 @@
     }
 
     @Override
-    protected void setCursor(final LWWindowPeer windowUnderCursor, final Cursor cursor) {
-        if (cursor == currentCursor) return;
+    protected void setCursor(final Cursor cursor) {
+        if (cursor == currentCursor) {
+            return;
+        }
+        currentCursor = cursor;
 
         if (cursor == null) {
             nativeSetBuiltInCursor(Cursor.DEFAULT_CURSOR, null);
@@ -72,10 +77,12 @@
         }
 
         if (cursor instanceof CCustomCursor) {
-            final CCustomCursor customCursor = ((CCustomCursor)cursor);
+            final CCustomCursor customCursor = (CCustomCursor) cursor;
             final long imagePtr = customCursor.getImageData();
-            final Point hotSpot = customCursor.getHotSpot();
-            if(imagePtr != 0L) nativeSetCustomCursor(imagePtr, hotSpot.x, hotSpot.y);
+            if (imagePtr != 0L) {
+                final Point hotSpot = customCursor.getHotSpot();
+                nativeSetCustomCursor(imagePtr, hotSpot.x, hotSpot.y);
+            }
             return;
         }
 
@@ -95,13 +102,6 @@
         throw new RuntimeException("Unimplemented");
     }
 
-    static long getNativeWindow(final LWWindowPeer window) {
-        if (window == null) return 0;
-        final CPlatformWindow platformWindow = (CPlatformWindow)window.getPlatformWindow();
-        if (platformWindow == null) return 0;
-        return platformWindow.getNSWindowPtr();
-    }
-
     // package private methods to handle cursor change during drag-and-drop
     private boolean isDragging = false;
     private Point dragPos = null;
@@ -110,9 +110,7 @@
         if (isDragging) {
             throw new RuntimeException("Invalid Drag state in CCursorManager!");
         }
-
         isDragging = true;
-
         dragPos = new Point(x, y);
     }
 
--- a/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Thu Jun 28 14:11:05 2012 -0700
@@ -56,12 +56,13 @@
     private static native void nativePushNSWindowToBack(long nsWindowPtr);
     private static native void nativePushNSWindowToFront(long nsWindowPtr);
     private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
-    private static native void nativeSetNSWindowAlpha(long nsWindowPtr, float alpha);
     private static native void nativeRevalidateNSWindowShadow(long nsWindowPtr);
     private static native void nativeSetNSWindowMinimizedIcon(long nsWindowPtr, long nsImage);
     private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
     private static native void nativeSetNSWindowSecurityWarningPositioning(long nsWindowPtr, double x, double y, float biasX, float biasY);
     private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
+    private static native void nativeSynthesizeMouseEnteredExitedEvents(long nsWindowPtr);
+    private static native void nativeDispose(long nsWindowPtr);
 
     private static native int nativeGetNSWindowDisplayID_AppKitThread(long nsWindowPtr);
 
@@ -242,17 +243,6 @@
         // TODO: implement on top of JObjC bridged class
     //    NSWindow window = JObjC.getInstance().AppKit().NSWindow().getInstance(nativeWindowPtr, JObjCRuntime.getInstance());
 
-        // Since JDK7 we have standard way to set opacity, so we should not pick
-        // background's alpha.
-        // TODO: set appropriate opacity value
-        //        this.opacity = target.getOpacity();
-        //        this.setOpacity(this.opacity);
-
-        final float windowAlpha = target.getOpacity();
-        if (windowAlpha != 1.0f) {
-            nativeSetNSWindowAlpha(nativeWindowPtr, windowAlpha);
-        }
-
         if (target instanceof javax.swing.RootPaneContainer) {
             final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
             if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
@@ -417,14 +407,9 @@
         if (owner != null) {
             CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
         }
-        // Make sure window is ordered out before it is disposed, we could order it out right here or
-        // we could postpone the disposal, I think postponing is probably better.
-        EventQueue.invokeLater(new Runnable() {
-            public void run() {
-                contentView.dispose();
-                CPlatformWindow.super.dispose();
-            }
-        });
+        contentView.dispose();
+        nativeDispose(getNSWindowPtr());
+        CPlatformWindow.super.dispose();
     }
 
     @Override // PlatformWindow
@@ -594,6 +579,8 @@
             }
         }
 
+        nativeSynthesizeMouseEnteredExitedEvents(nsWindowPtr);
+
         // 6. Configure stuff #2
         updateFocusabilityForAutoRequestFocus(true);
 
@@ -803,6 +790,8 @@
                 throw new RuntimeException("Unknown window state: " + windowState);
         }
 
+        nativeSynthesizeMouseEnteredExitedEvents(nsWindowPtr);
+
         // NOTE: the SWP.windowState field gets updated to the newWindowState
         //       value when the native notification comes to us
     }
--- a/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Thu Jun 28 14:11:05 2012 -0700
@@ -225,7 +225,6 @@
     @Override
     public SystemTrayPeer createSystemTray(SystemTray target) {
         SystemTrayPeer peer = new CSystemTray();
-        targetCreatedPeer(target, peer);
         return peer;
     }
 
@@ -368,9 +367,11 @@
             CWrapper.NSObject.release(screen);
         }
         // Convert between Cocoa's coordinate system and Java.
-        return new Insets(fullScreen.height - workArea.height - workArea.y,
-                          workArea.x, workArea.y,
-                          fullScreen.width - workArea.width - workArea.x);
+        int bottom = workArea.y - fullScreen.y;
+        int top = fullScreen.height - workArea.height - bottom;
+        int left = workArea.x - fullScreen.x;
+        int right = fullScreen.width - workArea.width - left;
+        return  new Insets(top, left, bottom, right);
     }
 
     @Override
--- a/src/macosx/native/sun/awt/AWTView.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/awt/AWTView.h	Thu Jun 28 14:11:05 2012 -0700
@@ -52,9 +52,12 @@
     BOOL fPAHNeedsToSelect;
 
     id cglLayer; // is a sublayer of view.layer
+
+    BOOL mouseIsOver;
 }
 
 @property (nonatomic, retain) id cglLayer;
+@property (nonatomic) BOOL mouseIsOver;
 
 - (id) initWithRect:(NSRect) rect platformView:(jobject)cPlatformView windowLayer:(CALayer*)windowLayer;
 - (void) deliverJavaMouseEvent: (NSEvent *) event;
--- a/src/macosx/native/sun/awt/AWTView.m	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/awt/AWTView.m	Thu Jun 28 14:11:05 2012 -0700
@@ -60,6 +60,7 @@
 @synthesize _dropTarget;
 @synthesize _dragSource;
 @synthesize cglLayer;
+@synthesize mouseIsOver;
 
 // Note: Must be called on main (AppKit) thread only
 - (id) initWithRect: (NSRect) rect
@@ -80,6 +81,8 @@
     fInPressAndHold = NO;
     fPAHNeedsToSelect = NO;
 
+    mouseIsOver = NO;
+
     if (windowLayer != nil) {
         self.cglLayer = windowLayer;
         [self setWantsLayer: YES];
@@ -185,7 +188,9 @@
 #endif
         }
     } else {
+#if IM_DEBUG
         NSLog(@"-> IM does not want to handle event");
+#endif
         [self deliverJavaMouseEvent: event];
     }
 }
@@ -308,6 +313,16 @@
         return;
     }
 
+    NSEventType type = [event type];
+
+    // check synthesized mouse entered/exited events
+    if ((type == NSMouseEntered && mouseIsOver) || (type == NSMouseExited && !mouseIsOver)) {
+        return;
+    }else if ((type == NSMouseEntered && !mouseIsOver) || (type == NSMouseExited && mouseIsOver)) {
+        mouseIsOver = !mouseIsOver;
+    }
+
+
     [AWTToolkit eventCountPlusPlus];
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
@@ -315,7 +330,6 @@
     NSPoint eventLocation = [event locationInWindow];
     NSPoint localPoint = [self convertPoint: eventLocation fromView: nil];
     NSPoint absP = [NSEvent mouseLocation];
-    NSEventType type = [event type];
 
     // Convert global numbers between Cocoa's coordinate system and Java.
     // TODO: need consitent way for doing that both with global as well as with local coordinates.
--- a/src/macosx/native/sun/awt/AWTWindow.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/awt/AWTWindow.h	Thu Jun 28 14:11:05 2012 -0700
@@ -64,6 +64,7 @@
                   contentView:(NSView *)contentView;
 
 - (void) adjustGrowBoxWindow;
+- (BOOL) isTopmostWindowUnderMouse;
 
 // NSWindow overrides delegate methods
 - (BOOL) canBecomeKeyWindow;
--- a/src/macosx/native/sun/awt/AWTWindow.m	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/awt/AWTWindow.m	Thu Jun 28 14:11:05 2012 -0700
@@ -266,6 +266,7 @@
     }
 
     if (self.nsWindow == nil) return nil; // no hope either
+    [self.nsWindow release]; // the property retains the object already
 
     self.isEnabled = YES;
     self.javaPlatformWindow = platformWindow;
@@ -297,6 +298,66 @@
     return self;
 }
 
+// checks that this window is under the mouse cursor and this point is not overlapped by others windows
+- (BOOL) isTopmostWindowUnderMouse {
+
+    int currentWinID = [self.nsWindow windowNumber];
+
+    NSRect screenRect = [[NSScreen mainScreen] frame];
+    NSPoint nsMouseLocation = [NSEvent mouseLocation];
+    CGPoint cgMouseLocation = CGPointMake(nsMouseLocation.x, screenRect.size.height - nsMouseLocation.y);
+
+    NSMutableArray *windows = (NSMutableArray *)CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
+
+
+    for (NSDictionary *window in windows) {
+        int layer = [[window objectForKey:(id)kCGWindowLayer] intValue];
+        if (layer == 0) {
+            int winID = [[window objectForKey:(id)kCGWindowNumber] intValue];
+            CGRect rect;
+            CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[window objectForKey:(id)kCGWindowBounds], &rect);
+            if (CGRectContainsPoint(rect, cgMouseLocation)) {
+                return currentWinID == winID;
+            } else if (currentWinID == winID) {
+                return NO;
+            }
+        }
+    }
+    return NO;
+}
+
+- (void) synthesizeMouseEnteredExitedEvents {
+
+    int eventType = 0;
+    BOOL isUnderMouse = [self isTopmostWindowUnderMouse];
+    BOOL mouseIsOver = [[self.nsWindow contentView] mouseIsOver];
+
+    if (isUnderMouse && !mouseIsOver) {
+        eventType = NSMouseEntered;
+    } else if (!isUnderMouse && mouseIsOver) {
+        eventType = NSMouseExited;
+    } else {
+        return;
+    }
+
+    NSPoint screenLocation = [NSEvent mouseLocation];
+    NSPoint windowLocation = [self.nsWindow convertScreenToBase: screenLocation];
+    int modifierFlags = (eventType == NSMouseEntered) ? NSMouseEnteredMask : NSMouseExitedMask;
+
+    NSEvent *mouseEvent = [NSEvent enterExitEventWithType: eventType
+                                                 location: windowLocation
+                                            modifierFlags: modifierFlags
+                                                timestamp: 0
+                                             windowNumber: [self.nsWindow windowNumber]
+                                                  context: nil
+                                              eventNumber: 0
+                                           trackingNumber: 0
+                                                 userData: nil
+                           ];
+
+    [[self.nsWindow contentView] deliverJavaMouseEvent: mouseEvent];
+}
+
 - (void) dealloc {
 AWT_ASSERT_APPKIT_THREAD;
 
@@ -693,9 +754,9 @@
                                                   styleBits:styleBits
                                                   frameRect:frameRect
                                                 contentView:contentView];
+        // the window is released is CPlatformWindow.nativeDispose()
 
-        if (window) CFRetain(window);
-        [window release]; // GC
+        if (window) CFRetain(window.nsWindow);
     }];
 
 JNF_COCOA_EXIT(env);
@@ -839,6 +900,8 @@
         // ensure we repaint the whole window after the resize operation
         // (this will also re-enable screen updates, which were disabled above)
         // TODO: send PaintEvent
+
+        [window synthesizeMouseEnteredExitedEvents];
     }];
 
 JNF_COCOA_EXIT(env);
@@ -947,29 +1010,6 @@
 
 /*
  * Class:     sun_lwawt_macosx_CPlatformWindow
- * Method:    nativeSetNSWindowAlpha
- * Signature: (JF)V
- */
-JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowAlpha
-(JNIEnv *env, jclass clazz, jlong windowPtr, jfloat alpha)
-{
-JNF_COCOA_ENTER(env);
-AWT_ASSERT_NOT_APPKIT_THREAD;
-
-    NSWindow *nsWindow = OBJC(windowPtr);
-    [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^(){
-        AWT_ASSERT_APPKIT_THREAD;
-
-        AWTWindow *window = (AWTWindow*)[nsWindow delegate];
-        [nsWindow setAlphaValue:alpha];
-        [window.growBoxWindow setAlphaValue:alpha];
-    }];
-
-JNF_COCOA_EXIT(env);
-}
-
-/*
- * Class:     sun_lwawt_macosx_CPlatformWindow
  * Method:    nativeRevalidateNSWindowShadow
  * Signature: (J)V
  */
@@ -1073,6 +1113,28 @@
 
 /*
  * Class:     sun_lwawt_macosx_CPlatformWindow
+ * Method:    nativeSynthesizeMouseEnteredExitedEvents
+ * Signature: (J)V
+ */
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents
+(JNIEnv *env, jclass clazz, jlong windowPtr)
+{
+    JNF_COCOA_ENTER(env);
+    AWT_ASSERT_NOT_APPKIT_THREAD;
+
+    NSWindow *nsWindow = OBJC(windowPtr);
+    [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^(){
+        AWT_ASSERT_APPKIT_THREAD;
+        AWTWindow *window = (AWTWindow*)[nsWindow delegate];
+
+        [window synthesizeMouseEnteredExitedEvents];
+    }];
+
+    JNF_COCOA_EXIT(env);
+}
+
+/*
+ * Class:     sun_lwawt_macosx_CPlatformWindow
  * Method:    nativeGetDisplayID_AppKitThread
  * Signature: (J)I
  */
@@ -1153,3 +1215,24 @@
 JNF_COCOA_EXIT(env);
 }
 
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeDispose
+(JNIEnv *env, jclass clazz, jlong windowPtr)
+{
+JNF_COCOA_ENTER(env);
+
+    NSWindow *nsWindow = OBJC(windowPtr);
+    [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^(){
+        AWTWindow *window = (AWTWindow*)[nsWindow delegate];
+
+        // AWTWindow holds a reference to the NSWindow in its nsWindow
+        // property. Unsetting the delegate allows it to be deallocated
+        // which releases the reference. This, in turn, allows the window
+        // itself be deallocated.
+        [nsWindow setDelegate: nil];
+
+        [window release];
+    }];
+
+JNF_COCOA_EXIT(env);
+}
+
--- a/src/macosx/native/sun/awt/CGraphicsDevice.m	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/awt/CGraphicsDevice.m	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 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,6 +26,84 @@
 #include "LWCToolkit.h"
 
 /*
+ * Convert the mode string to the more convinient bits per pixel value
+ */
+static int getBPPFromModeString(CFStringRef mode) 
+{
+    if ((CFStringCompare(mode, CFSTR(kIO30BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)) {
+        // This is a strange mode, where we using 10 bits per RGB component and pack it into 32 bits
+        // Java is not ready to work with this mode but we have to specify it as supported
+        return 30;
+    }
+    else if (CFStringCompare(mode, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
+        return 32;
+    }
+    else if (CFStringCompare(mode, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
+        return 16;
+    }
+    else if (CFStringCompare(mode, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
+        return 8;
+    }
+    
+    return 0;
+}
+
+/*
+ * Find the best possible match in the list of display modes that we can switch to based on
+ * the provided parameters.
+ */
+static CGDisplayModeRef getBestModeForParameters(CFArrayRef allModes, int w, int h, int bpp, int refrate) {
+    CGDisplayModeRef bestGuess = NULL;
+    CFIndex numModes = CFArrayGetCount(allModes), n;
+    int thisBpp = 0;
+    for(n = 0; n < numModes; n++ ) {
+        CGDisplayModeRef cRef = (CGDisplayModeRef) CFArrayGetValueAtIndex(allModes, n);
+        if(cRef == NULL) {
+            continue;
+        }
+        CFStringRef modeString = CGDisplayModeCopyPixelEncoding(cRef);
+        thisBpp = getBPPFromModeString(modeString);
+        CFRelease(modeString);
+        if (thisBpp != bpp || (int)CGDisplayModeGetHeight(cRef) != h || (int)CGDisplayModeGetWidth(cRef) != w) {
+            // One of the key parameters does not match
+            continue;
+        }
+        // Refresh rate might be 0 in display mode and we ask for specific display rate
+        // but if we do not find exact match then 0 refresh rate might be just Ok
+        if (CGDisplayModeGetRefreshRate(cRef) == refrate) {
+            // Exact match
+            return cRef;
+        }
+        if (CGDisplayModeGetRefreshRate(cRef) == 0) {
+            // Not exactly what was asked for, but may fit our needs if we don't find an exact match
+            bestGuess = cRef;
+        }
+    }
+    return bestGuess;
+}
+
+/*
+ * Create a new java.awt.DisplayMode instance based on provided CGDisplayModeRef
+ */
+static jobject createJavaDisplayMode(CGDisplayModeRef mode, JNIEnv *env, jint displayID) {
+    jobject ret = NULL;
+    jint h, w, bpp, refrate;
+    JNF_COCOA_ENTER(env);
+    CFStringRef currentBPP = CGDisplayModeCopyPixelEncoding(mode);
+    bpp = getBPPFromModeString(currentBPP);
+    refrate = CGDisplayModeGetRefreshRate(mode);
+    h = CGDisplayModeGetHeight(mode);
+    w = CGDisplayModeGetWidth(mode);
+    CFRelease(currentBPP);
+    static JNF_CLASS_CACHE(jc_DisplayMode, "java/awt/DisplayMode");
+    static JNF_CTOR_CACHE(jc_DisplayMode_ctor, jc_DisplayMode, "(IIII)V");
+    ret = JNFNewObject(env, jc_DisplayMode_ctor, w, h, bpp, refrate);
+    JNF_COCOA_EXIT(env);
+    return ret;
+}
+
+
+/*
  * Class:     sun_awt_CGraphicsDevice
  * Method:    nativeGetXResolution
  * Signature: (I)D
@@ -62,3 +140,89 @@
     jfloat dpi = rect.size.height / inches;
     return dpi;
 }
+
+/*
+ * Class:     sun_awt_CGraphicsDevice
+ * Method:    nativeSetDisplayMode
+ * Signature: (IIIII)V
+ */
+JNIEXPORT void JNICALL
+Java_sun_awt_CGraphicsDevice_nativeSetDisplayMode
+(JNIEnv *env, jclass class, jint displayID, jint w, jint h, jint bpp, jint refrate)
+{
+    JNF_COCOA_ENTER(env);
+    CFArrayRef allModes = CGDisplayCopyAllDisplayModes(displayID, NULL);
+    CGDisplayModeRef closestMatch = getBestModeForParameters(allModes, (int)w, (int)h, (int)bpp, (int)refrate);
+    if (closestMatch != NULL) {
+        [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
+            CGDisplayConfigRef config;
+            CGError retCode = CGBeginDisplayConfiguration(&config);
+            if (retCode == kCGErrorSuccess) {
+                CGConfigureDisplayWithDisplayMode(config, displayID, closestMatch, NULL);
+                CGCompleteDisplayConfiguration(config, kCGConfigureForAppOnly);
+                if (config != NULL) {
+                    CFRelease(config);
+                }
+            }
+        }];
+    }
+    CFRelease(allModes);
+    JNF_COCOA_EXIT(env);
+}
+
+/*
+ * Class:     sun_awt_CGraphicsDevice
+ * Method:    nativeGetDisplayMode
+ * Signature: (I)Ljava/awt/DisplayMode
+ */
+JNIEXPORT jobject JNICALL
+Java_sun_awt_CGraphicsDevice_nativeGetDisplayMode
+(JNIEnv *env, jclass class, jint displayID)
+{
+    jobject ret = NULL;
+    CGDisplayModeRef currentMode = CGDisplayCopyDisplayMode(displayID);
+    ret = createJavaDisplayMode(currentMode, env, displayID);
+    CGDisplayModeRelease(currentMode);
+    return ret;
+}
+
+/*
+ * Class:     sun_awt_CGraphicsDevice
+ * Method:    nativeGetDisplayMode
+ * Signature: (I)[Ljava/awt/DisplayModes
+ */
+JNIEXPORT jobjectArray JNICALL
+Java_sun_awt_CGraphicsDevice_nativeGetDisplayModes
+(JNIEnv *env, jclass class, jint displayID)
+{
+    jobjectArray jreturnArray = NULL;
+    JNF_COCOA_ENTER(env);
+    CFArrayRef allModes = CGDisplayCopyAllDisplayModes(displayID, NULL);
+    CFIndex numModes = CFArrayGetCount(allModes);
+    static JNF_CLASS_CACHE(jc_DisplayMode, "java/awt/DisplayMode");
+
+    jreturnArray = JNFNewObjectArray(env, &jc_DisplayMode, (jsize) numModes);
+    if (!jreturnArray) {
+        NSLog(@"CGraphicsDevice can't create java array of DisplayMode objects");
+        return nil;
+    }
+
+    CFIndex n;
+    for (n=0; n < numModes; n++) {
+        CGDisplayModeRef cRef = (CGDisplayModeRef) CFArrayGetValueAtIndex(allModes, n);
+        if (cRef != NULL) {
+            jobject oneMode = createJavaDisplayMode(cRef, env, displayID);
+            (*env)->SetObjectArrayElement(env, jreturnArray, n, oneMode);
+            if ((*env)->ExceptionOccurred(env)) {
+                (*env)->ExceptionDescribe(env);
+                (*env)->ExceptionClear(env);
+                continue;
+            }
+            (*env)->DeleteLocalRef(env, oneMode);
+        }
+    }
+    CFRelease(allModes);
+    JNF_COCOA_EXIT(env);
+
+    return jreturnArray;
+}
--- a/src/macosx/native/sun/awt/LWCToolkit.m	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/awt/LWCToolkit.m	Thu Jun 28 14:11:05 2012 -0700
@@ -33,6 +33,7 @@
 #import "ThreadUtilities.h"
 #import "AWT_debug.h"
 #import "CSystemColors.h"
+#import  "NSApplicationAWT.h"
 
 #import "sun_lwawt_macosx_LWCToolkit.h"
 
@@ -47,7 +48,7 @@
     return eventCount;
 }
 
-+ (void) eventCountPlusPlus{
++ (void) eventCountPlusPlus{    
     eventCount++;
 }
 
@@ -79,7 +80,6 @@
 
 @end
 
-
 /*
  * Class:     sun_lwawt_macosx_LWCToolkit
  * Method:    nativeSyncQueue
@@ -90,12 +90,22 @@
 {
     int currentEventNum = [AWTToolkit getEventCount];
 
-    [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){}];
-
+    NSApplication* sharedApp = [NSApplication sharedApplication];
+    if ([sharedApp isKindOfClass:[NSApplicationAWT class]]) {
+        NSApplicationAWT* theApp = (NSApplicationAWT*)sharedApp;
+        [theApp postDummyEvent];
+        [theApp waitForDummyEvent];
+    } else {
+        // could happen if we are embedded inside SWT application,
+        // in this case just spin a single empty block through 
+        // the event loop to give it a chance to process pending events
+        [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){}];
+    }
+    
     if (([AWTToolkit getEventCount] - currentEventNum) != 0) {
         return JNI_TRUE;
     }
-
+        
     return JNI_FALSE;
 }
 
--- a/src/macosx/native/sun/awt/awt.m	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/awt/awt.m	Thu Jun 28 14:11:05 2012 -0700
@@ -70,33 +70,35 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
 
-    // Add CFRunLoopObservers to call into AWT so that AWT knows that the
-    //  AWT thread (which is the AppKit main thread) is alive. This way AWT
-    //  will not automatically shutdown.
-    busyObserver = CFRunLoopObserverCreate(
-                        NULL,                        // CFAllocator
-                        kCFRunLoopAfterWaiting,      // CFOptionFlags
-                        true,                        // repeats
-                        NSIntegerMax,                // order
-                        &BusyObserver,               // CFRunLoopObserverCallBack
-                        NULL);                       // CFRunLoopObserverContext
+    if (!headless) {
+        // Add CFRunLoopObservers to call into AWT so that AWT knows that the
+        //  AWT thread (which is the AppKit main thread) is alive. This way AWT
+        //  will not automatically shutdown.
+        busyObserver = CFRunLoopObserverCreate(
+                NULL,                        // CFAllocator
+                kCFRunLoopAfterWaiting,      // CFOptionFlags
+                true,                        // repeats
+                NSIntegerMax,                // order
+                &BusyObserver,               // CFRunLoopObserverCallBack
+                NULL);                       // CFRunLoopObserverContext
 
-    notBusyObserver = CFRunLoopObserverCreate(
-                        NULL,                        // CFAllocator
-                        kCFRunLoopBeforeWaiting,     // CFOptionFlags
-                        true,                        // repeats
-                        NSIntegerMin,                // order
-                        &NotBusyObserver,            // CFRunLoopObserverCallBack
-                        NULL);                       // CFRunLoopObserverContext
+        notBusyObserver = CFRunLoopObserverCreate(
+                NULL,                        // CFAllocator
+                kCFRunLoopBeforeWaiting,     // CFOptionFlags
+                true,                        // repeats
+                NSIntegerMin,                // order
+                &NotBusyObserver,            // CFRunLoopObserverCallBack
+                NULL);                       // CFRunLoopObserverContext
 
-    CFRunLoopRef runLoop = [[NSRunLoop currentRunLoop] getCFRunLoop];
-    CFRunLoopAddObserver(runLoop, busyObserver, kCFRunLoopDefaultMode);
-    CFRunLoopAddObserver(runLoop, notBusyObserver, kCFRunLoopDefaultMode);
+        CFRunLoopRef runLoop = [[NSRunLoop currentRunLoop] getCFRunLoop];
+        CFRunLoopAddObserver(runLoop, busyObserver, kCFRunLoopDefaultMode);
+        CFRunLoopAddObserver(runLoop, notBusyObserver, kCFRunLoopDefaultMode);
 
-    CFRelease(busyObserver);
-    CFRelease(notBusyObserver);
+        CFRelease(busyObserver);
+        CFRelease(notBusyObserver);
 
-    if (!headless) setBusy(YES);
+        setBusy(YES);
+    }
 
     // Set the java name of the AppKit main thread appropriately.
     jclass threadClass = NULL;
--- a/src/macosx/native/sun/osxapp/NSApplicationAWT.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/osxapp/NSApplicationAWT.h	Thu Jun 28 14:11:05 2012 -0700
@@ -28,13 +28,16 @@
 
 @interface NSApplicationAWT : NSApplication {
     NSString *fApplicationName;
-    BOOL fUseDefaultIcon;
     NSWindow *eventTransparentWindow;
+    NSTimeInterval dummyEventTimestamp;
+    NSConditionLock* seenDummyEventLock;
 }
 
 - (void) finishLaunching;
 - (void) registerWithProcessManager;
 - (void) setDockIconWithEnv:(JNIEnv *)env;
+- (void) postDummyEvent;
+- (void) waitForDummyEvent;
 
 + (void) runAWTLoopWithApp:(NSApplication*)app;
 
--- a/src/macosx/native/sun/osxapp/NSApplicationAWT.m	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/osxapp/NSApplicationAWT.m	Thu Jun 28 14:11:05 2012 -0700
@@ -31,7 +31,7 @@
 #import "PropertiesUtilities.h"
 #import "ThreadUtilities.h"
 #import "QueuingApplicationDelegate.h"
-
+#import "AWTIconData.h"
 
 static BOOL sUsingDefaultNIB = YES;
 static NSString *SHARED_FRAMEWORK_BUNDLE = @"/System/Library/Frameworks/JavaVM.framework";
@@ -52,7 +52,8 @@
 
 AWT_ASSERT_APPKIT_THREAD;
     fApplicationName = nil;
-    fUseDefaultIcon = NO;
+    dummyEventTimestamp = 0.0;
+    seenDummyEventLock = nil;
 
     // NSApplication will call _RegisterApplication with the application's bundle, but there may not be one.
     // So, we need to call it ourselves to ensure the app is set up properly.
@@ -147,10 +148,6 @@
     if (appName != NULL) {
         fApplicationName = [NSString stringWithUTF8String:appName];
         unsetenv(envVar);
-
-        // If this environment variable was set we were launched from the command line, so we
-        // should use a generic app icon if one wasn't set.
-        fUseDefaultIcon = YES;
     }
 
     // If it wasn't specified as an argument, see if it was specified as a system property.
@@ -163,6 +160,7 @@
         char mainClassEnvVar[80];
         snprintf(mainClassEnvVar, sizeof(mainClassEnvVar), "JAVA_MAIN_CLASS_%d", getpid());
         char *mainClass = getenv(mainClassEnvVar);
+
         if (mainClass != NULL) {
             fApplicationName = [NSString stringWithUTF8String:mainClass];
             unsetenv(mainClassEnvVar);
@@ -171,9 +169,6 @@
             if (lastPeriod.location != NSNotFound) {
                 fApplicationName = [fApplicationName substringFromIndex:lastPeriod.location + 1];
             }
-            // If this environment variable was set we were launched from the command line, so we
-            // should use a generic app icon if one wasn't set.
-            fUseDefaultIcon = YES;
         }
     }
 
@@ -263,22 +258,26 @@
         theIconPath = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.icon" withEnv:env];
     }
 
-    // If the icon file wasn't specified as an argument and we need to get an icon
-    // we'll use the generic java app icon.
-    NSString *defaultIconPath = [NSString stringWithFormat:@"%@%@", SHARED_FRAMEWORK_BUNDLE, @"/Resources/GenericApp.icns"];
-    if (fUseDefaultIcon && (theIconPath == nil)) {
-        theIconPath = defaultIconPath;
+    // Use the path specified to get the icon image
+    NSImage* iconImage = nil;
+    if (theIconPath != nil) {
+        iconImage = [[NSImage alloc] initWithContentsOfFile:theIconPath];
+    } 
+
+    // If no icon file was specified or we failed to get the icon image
+    // and we need to get an icon, then use the default icon
+    if (iconImage == nil) {
+        NSString* bundleIcon = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIconFile"];
+        if (bundleIcon == nil) {
+            NSData* iconData;
+            iconData = [[NSData alloc] initWithBytesNoCopy: sAWTIconData length: sizeof(sAWTIconData) freeWhenDone: NO];
+            iconImage = [[NSImage alloc] initWithData: iconData];
+            [iconData release];
+        }
     }
 
-    // Set up the dock icon if we have an icon name.
-    if (theIconPath != nil) {
-        NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile:theIconPath];
-
-        // If we failed for some reason fall back to the default icon.
-        if (iconImage == nil) {
-            iconImage = [[NSImage alloc] initWithContentsOfFile:defaultIconPath];
-        }
-
+    // Set up the dock icon if we have an icon image.
+    if (iconImage != nil) {
         [NSApp setApplicationIconImage:iconImage];
         [iconImage release];
     }
@@ -333,6 +332,45 @@
     return event;
 }
 
+// NSTimeInterval has microseconds precision
+#define TS_EQUAL(ts1, ts2) (fabs((ts1) - (ts2)) < 1e-6)
+
+- (void)sendEvent:(NSEvent *)event
+{
+    if ([event type] == NSApplicationDefined && TS_EQUAL([event timestamp], dummyEventTimestamp)) {
+        [seenDummyEventLock lockWhenCondition:NO];
+        [seenDummyEventLock unlockWithCondition:YES];
+    } else {
+        [super sendEvent:event];
+    }
+}
+
+- (void)postDummyEvent {
+    seenDummyEventLock = [[NSConditionLock alloc] initWithCondition:NO];
+    dummyEventTimestamp = [NSProcessInfo processInfo].systemUptime;
+    
+    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    
+    NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined
+                                        location: NSMakePoint(0,0)
+                                   modifierFlags: 0
+                                       timestamp: dummyEventTimestamp
+                                    windowNumber: 0
+                                         context: nil
+                                         subtype: 0
+                                           data1: 0
+                                           data2: 0];
+    [NSApp postEvent: event atStart: NO];
+    [pool drain];
+}
+
+- (void)waitForDummyEvent {
+    [seenDummyEventLock lockWhenCondition:YES];
+    [seenDummyEventLock unlock];
+    [seenDummyEventLock release];
+
+    seenDummyEventLock = nil;
+}
+
 @end
 
 
--- a/src/macosx/native/sun/osxapp/QueuingApplicationDelegate.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/osxapp/QueuingApplicationDelegate.h	Thu Jun 28 14:11:05 2012 -0700
@@ -30,6 +30,8 @@
     BOOL fHandlesDocumentTypes;
     BOOL fHandlesURLTypes;
 
+    id <NSApplicationDelegate> realDelegate;
+
     NSMutableArray* queue;
 }
 
@@ -40,5 +42,9 @@
 
 - (void)processQueuedEventsWithTargetDelegate:(id <NSApplicationDelegate>)delegate;
 
+@property(retain) id <NSApplicationDelegate> realDelegate;
+
+@property(retain) NSMutableArray* queue;
+
 @end
 
--- a/src/macosx/native/sun/osxapp/QueuingApplicationDelegate.m	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/macosx/native/sun/osxapp/QueuingApplicationDelegate.m	Thu Jun 28 14:11:05 2012 -0700
@@ -27,8 +27,6 @@
 
 #import "QueuingApplicationDelegate.h"
 
-static id <NSApplicationDelegate> realDelegate = nil;
-
 @interface NSBundle (EAWTOverrides)
 - (BOOL)_hasEAWTOverride:(NSString *)key;
 @end
@@ -44,6 +42,9 @@
 
 @implementation QueuingApplicationDelegate
 
+@synthesize realDelegate;
+@synthesize queue;
+
 + (QueuingApplicationDelegate*) sharedDelegate
 {
     static QueuingApplicationDelegate * qad = nil;
@@ -62,7 +63,7 @@
         return self;
     }
 
-    self->queue = [[NSMutableArray arrayWithCapacity: 0] retain];
+    self.queue = [NSMutableArray arrayWithCapacity: 0];
 
     // If the java application has a bundle with an Info.plist file with
     //  a CFBundleDocumentTypes entry, then it is set up to handle Open Doc
@@ -100,8 +101,8 @@
     Class clz = [QueuingApplicationDelegate class];
     [ctr removeObserver:clz];
 
-    [self->queue release];
-    self->queue = nil;
+    self.queue = nil;
+    self.realDelegate = nil;
 
     [super dealloc];
 }
@@ -109,16 +110,16 @@
 
 - (void)_handleOpenURLEvent:(NSAppleEventDescriptor *)openURLEvent withReplyEvent:(NSAppleEventDescriptor *)replyEvent
 {
-    [self->queue addObject:^(){
-        [realDelegate _handleOpenURLEvent:openURLEvent withReplyEvent:replyEvent];
-    }];
+    [self.queue addObject:[^(){
+        [self.realDelegate _handleOpenURLEvent:openURLEvent withReplyEvent:replyEvent];
+    } copy]];
 }
 
 - (void)application:(NSApplication *)theApplication openFiles:(NSArray *)fileNames
 {
-    [self->queue addObject:^(){
-        [realDelegate application:theApplication openFiles:fileNames];
-    }];
+    [self.queue addObject:[^(){
+        [self.realDelegate application:theApplication openFiles:fileNames];
+    } copy]];
 }
 
 - (NSApplicationPrintReply)application:(NSApplication *)application printFiles:(NSArray *)fileNames withSettings:(NSDictionary *)printSettings showPrintPanels:(BOOL)showPrintPanels
@@ -127,9 +128,9 @@
         return NSPrintingCancelled;
     }
 
-    [self->queue addObject:^(){
-        [realDelegate application:application printFiles:fileNames withSettings:printSettings showPrintPanels:showPrintPanels];
-    }];
+    [self.queue addObject:[^(){
+        [self.realDelegate application:application printFiles:fileNames withSettings:printSettings showPrintPanels:showPrintPanels];
+    } copy]];
 
     // well, a bit premature, but what else can we do?..
     return NSPrintingSuccess;
@@ -137,76 +138,76 @@
 
 - (void)_willFinishLaunching
 {
-    QueuingApplicationDelegate * q = self;
-    [self->queue addObject:^(){
-        [[realDelegate class] _willFinishLaunching];
-    }];
+    [self.queue addObject:[^(){
+        [[self.realDelegate class] _willFinishLaunching];
+    } copy]];
 }
 
 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
 {
-    [self->queue addObject:^(){
-        [realDelegate applicationShouldHandleReopen:theApplication hasVisibleWindows:flag];
-    }];
+    [self.queue addObject:[^(){
+        [self.realDelegate applicationShouldHandleReopen:theApplication hasVisibleWindows:flag];
+    } copy]];
     return YES;
 }
 
 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)app
 {
-    [self->queue addObject:^(){
-        [realDelegate applicationShouldTerminate:app];
-    }];
+    [self.queue addObject:[^(){
+        [self.realDelegate applicationShouldTerminate:app];
+    } copy]];
     return NSTerminateLater;
 }
 
 - (void)_systemWillPowerOff
 {
-    [self->queue addObject:^(){
-        [[realDelegate class] _systemWillPowerOff];
-    }];
+    [self.queue addObject:[^(){
+        [[self.realDelegate class] _systemWillPowerOff];
+    } copy]];
 }
 
 - (void)_appDidActivate
 {
-    [self->queue addObject:^(){
-        [[realDelegate class] _appDidActivate];
-    }];
+    [self.queue addObject:[^(){
+        [[self.realDelegate class] _appDidActivate];
+    } copy]];
 }
 
 - (void)_appDidDeactivate
 {
-    [self->queue addObject:^(){
-        [[realDelegate class] _appDidDeactivate];
-    }];
+    [self.queue addObject:[^(){
+        [[self.realDelegate class] _appDidDeactivate];
+    } copy]];
 }
 
 - (void)_appDidHide
 {
-    [self->queue addObject:^(){
-        [[realDelegate class] _appDidHide];
-    }];
+    [self.queue addObject:[^(){
+        [[self.realDelegate class] _appDidHide];
+    } copy]];
 }
 
 - (void)_appDidUnhide
 {
-    [self->queue addObject:^(){
-        [[realDelegate class] _appDidUnhide];
-    }];
+    [self.queue addObject:[^(){
+        [[self.realDelegate class] _appDidUnhide];
+    } copy]];
 }
 
 - (void)processQueuedEventsWithTargetDelegate:(id <NSApplicationDelegate>)delegate
 {
+    self.realDelegate = delegate;
+
     NSUInteger i;
-    NSUInteger count = [self->queue count];
-
-    realDelegate = delegate;
+    NSUInteger count = [self.queue count];
 
     for (i = 0; i < count; i++) {
-        void (^event)() = (void (^)())[self->queue objectAtIndex: i];
+        void (^event)() = (void (^)())[self.queue objectAtIndex: i];
         event();
+        [event release];
     }
 
-    [self->queue removeAllObjects];
+    [self.queue removeAllObjects];
 }
 
 @end
Binary file src/macosx/native/sun/osxapp/resource/icons/JavaApp.icns has changed
--- a/src/share/classes/com/sun/beans/TypeResolver.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/beans/TypeResolver.java	Thu Jun 28 14:11:05 2012 -0700
@@ -154,7 +154,7 @@
      * @see #resolve(Type)
      */
     public static Type resolve(Type actual, Type formal) {
-        return new TypeResolver(actual).resolve(formal);
+        return getTypeResolver(actual).resolve(formal);
     }
 
     /**
@@ -169,7 +169,7 @@
      * @see #resolve(Type[])
      */
     public static Type[] resolve(Type actual, Type[] formals) {
-        return new TypeResolver(actual).resolve(formals);
+        return getTypeResolver(actual).resolve(formals);
     }
 
     /**
@@ -228,9 +228,20 @@
         return classes;
     }
 
+    public static TypeResolver getTypeResolver(Type type) {
+        synchronized (CACHE) {
+            TypeResolver resolver = CACHE.get(type);
+            if (resolver == null) {
+                resolver = new TypeResolver(type);
+                CACHE.put(type, resolver);
+            }
+            return resolver;
+        }
+    }
 
-    private final Map<TypeVariable<?>, Type> map
-        = new HashMap<TypeVariable<?>, Type>();
+    private static final WeakCache<Type, TypeResolver> CACHE = new WeakCache<>();
+
+    private final Map<TypeVariable<?>, Type> map = new HashMap<>();
 
     /**
      * Constructs the type resolver for the given actual type.
--- a/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, 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
@@ -644,6 +644,9 @@
                    "released SPACE", "released"
                  }),
 
+            "Caret.width",
+                  new DesktopProperty("win.caret.width", null),
+
             "CheckBox.font", ControlFont,
             "CheckBox.interiorBackground", WindowBackgroundColor,
             "CheckBox.background", ControlBackgroundColor,
--- a/src/share/classes/com/sun/jndi/cosnaming/CNCtx.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/jndi/cosnaming/CNCtx.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2012, 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
@@ -59,8 +59,22 @@
 
     private final static boolean debug = false;
 
+    /*
+     * Implement one shared ORB among all CNCtx.  However, there is a public constructor
+     * accepting an ORB, so we need the option of using a given ORB.
+     */
+    private static ORB _defaultOrb;
     ORB _orb;                   // used by ExceptionMapper and RMI/IIOP factory
     public NamingContext _nc;   // public for accessing underlying NamingContext
+
+    private synchronized static ORB getDefaultOrb() {
+        if (_defaultOrb == null) {
+            _defaultOrb = CorbaUtils.getOrb(null, -1,
+               new Hashtable<String, java.lang.Object>());
+        }
+        return _defaultOrb;
+    }
+
     private NameComponent[] _name = null;
 
     Hashtable _env; // used by ExceptionMapper
@@ -113,8 +127,9 @@
         // rest is the INS name
         // Return the parsed form to prevent subsequent lookup
         // from parsing the string as a composite name
-        // The caller should be aware that a toString() of the name
-        // will yield its INS syntax, rather than a composite syntax
+        // The caller should be aware that a toString() of the name,
+        // which came from the environment will yield its INS syntax,
+        // rather than a composite syntax
         return new ResolveResult(ctx, parser.parse(rest));
     }
 
@@ -134,10 +149,10 @@
             if (orb == null || nctx == null)
                 throw new ConfigurationException(
                     "Must supply ORB or NamingContext");
-            _orb = orb;
-            orbTracker = tracker;
-            if (orbTracker != null) {
-                orbTracker.incRefCount();
+            if (orb != null) {
+                _orb = orb;
+            } else {
+                _orb = getDefaultOrb();
             }
             _nc = nctx;
             _env = env;
@@ -211,10 +226,13 @@
         org.omg.CORBA.ORB inOrb = null;
         String ncIor = null;
 
-        if (env != null) {
+        if (inOrb == null && env != null) {
             inOrb = (org.omg.CORBA.ORB) env.get("java.naming.corba.orb");
         }
 
+        if (inOrb == null)
+            inOrb = getDefaultOrb(); // will create a default ORB if none exists
+
         // Extract PROVIDER_URL from environment
         String provUrl = null;
         if (env != null) {
@@ -225,13 +243,6 @@
             // Initialize the root naming context by using the IOR supplied
             // in the PROVIDER_URL
             ncIor = getStringifiedIor(provUrl);
-
-            if (inOrb == null) {
-
-                // no ORB instance specified; create one using env and defaults
-                inOrb = CorbaUtils.getOrb(null, -1, env);
-                orbTracker = new OrbReuseTracker(inOrb);
-            }
             setOrbAndRootContext(inOrb, ncIor);
         } else if (provUrl != null) {
             // Initialize the root naming context by using the URL supplied
@@ -257,14 +268,8 @@
             }
         } else {
             // No PROVIDER_URL supplied; initialize using defaults
-            if (inOrb == null) {
-
-                // No ORB instance specified; create one using env and defaults
-                inOrb = CorbaUtils.getOrb(null, -1, env);
-                orbTracker = new OrbReuseTracker(inOrb);
-                if (debug) {
-                    System.err.println("Getting default ORB: " + inOrb + env);
-                }
+            if (debug) {
+                System.err.println("Getting default ORB: " + inOrb + env);
             }
             setOrbAndRootContext(inOrb, (String)null);
         }
@@ -285,6 +290,10 @@
      */
     private String initUsingIiopUrl(ORB defOrb, String url, Hashtable env)
         throws NamingException {
+
+        if (defOrb == null)
+            defOrb = getDefaultOrb();
+
         try {
             IiopUrl parsedUrl = new IiopUrl(url);
 
@@ -296,19 +305,17 @@
                 addr = (IiopUrl.Address)addrs.elementAt(i);
 
                 try {
-                    if (defOrb != null) {
-                        try {
-                            String tmpUrl = "corbaloc:iiop:" + addr.host
-                                + ":" + addr.port + "/NameService";
-                            if (debug) {
-                                System.err.println("Using url: " + tmpUrl);
-                            }
-                            org.omg.CORBA.Object rootCtx =
-                                defOrb.string_to_object(tmpUrl);
-                            setOrbAndRootContext(defOrb, rootCtx);
-                            return parsedUrl.getStringName();
-                        } catch (Exception e) {} // keep going
-                    }
+                    try {
+                        String tmpUrl = "corbaloc:iiop:" + addr.host
+                            + ":" + addr.port + "/NameService";
+                        if (debug) {
+                            System.err.println("Using url: " + tmpUrl);
+                        }
+                        org.omg.CORBA.Object rootCtx =
+                            defOrb.string_to_object(tmpUrl);
+                        setOrbAndRootContext(defOrb, rootCtx);
+                        return parsedUrl.getStringName();
+                    } catch (Exception e) {} // keep going
 
                     // Get ORB
                     if (debug) {
@@ -316,12 +323,8 @@
                             + " and port " + addr.port);
                     }
 
-                    // Get ORB
-                    ORB orb = CorbaUtils.getOrb(addr.host, addr.port, env);
-                    orbTracker = new OrbReuseTracker(orb);
-
                     // Assign to fields
-                    setOrbAndRootContext(orb, (String)null);
+                    setOrbAndRootContext(defOrb, (String)null);
                     return parsedUrl.getStringName();
 
                 } catch (NamingException ne) {
@@ -343,18 +346,16 @@
      */
     private String initUsingCorbanameUrl(ORB orb, String url, Hashtable env)
         throws NamingException {
+
+        if (orb == null)
+                orb = getDefaultOrb();
+
         try {
             CorbanameUrl parsedUrl = new CorbanameUrl(url);
 
             String corbaloc = parsedUrl.getLocation();
             String cosName = parsedUrl.getStringName();
 
-            if (orb == null) {
-
-                // No ORB instance specified; create one using env and defaults
-                orb = CorbaUtils.getOrb(null, -1, env);
-                orbTracker = new OrbReuseTracker(orb);
-            }
             setOrbAndRootContext(orb, corbaloc);
 
             return parsedUrl.getStringName();
@@ -1115,9 +1116,6 @@
     }
 
     synchronized public void incEnumCount() {
-        if (orbTracker == null) {
-            return;
-        }
         enumCount++;
         if (debug) {
             System.out.println("incEnumCount, new count:" + enumCount);
@@ -1126,9 +1124,6 @@
 
     synchronized public void decEnumCount()
             throws NamingException {
-        if (orbTracker == null) {
-            return;
-        }
         enumCount--;
         if (debug) {
             System.out.println("decEnumCount, new count:" + enumCount +
@@ -1140,14 +1135,15 @@
     }
 
     synchronized public void close() throws NamingException {
-        if (orbTracker == null) {
-            return;
-        }
+
         if (enumCount > 0) {
             isCloseCalled = true;
             return;
         }
-        orbTracker.decRefCount();
+
+        // Never destroy an orb in CNCtx.
+        // The orb we have is either the shared/default orb, or one passed in to a constructor
+        // from elsewhere, so that orb is somebody else's reponsibility.
     }
 
     protected void finalize() {
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=Type
 FileChooser.fileDateHeader.textAndMnemonic=Modified
 FileChooser.fileAttrHeader.textAndMnemonic=Attributes
+FileChooser.saveButton.textAndMnemonic=Save
+FileChooser.openButton.textAndMnemonic=Open
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=&Restore
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_de.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_de.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=Typ
 FileChooser.fileDateHeader.textAndMnemonic=Ge\u00E4ndert
 FileChooser.fileAttrHeader.textAndMnemonic=Attribute
+FileChooser.saveButton.textAndMnemonic=Speichern
+FileChooser.openButton.textAndMnemonic=\u00D6ffnen
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=&Wiederherstellen
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_es.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_es.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=Tipo
 FileChooser.fileDateHeader.textAndMnemonic=Modificado
 FileChooser.fileAttrHeader.textAndMnemonic=Atributos
+FileChooser.saveButton.textAndMnemonic=Guardar
+FileChooser.openButton.textAndMnemonic=Abrir
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=&Restaurar
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_fr.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_fr.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=Type
 FileChooser.fileDateHeader.textAndMnemonic=Modifi\u00E9
 FileChooser.fileAttrHeader.textAndMnemonic=Attributs
+FileChooser.saveButton.textAndMnemonic=Enregistrer
+FileChooser.openButton.textAndMnemonic=Ouvrir
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=&Restaurer
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_it.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_it.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=Tipo
 FileChooser.fileDateHeader.textAndMnemonic=Modificato
 FileChooser.fileAttrHeader.textAndMnemonic=Attributi
+FileChooser.saveButton.textAndMnemonic=Salva
+FileChooser.openButton.textAndMnemonic=Apri
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=&Ripristina
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_ja.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_ja.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=\u30BF\u30A4\u30D7
 FileChooser.fileDateHeader.textAndMnemonic=\u4FEE\u6B63\u65E5
 FileChooser.fileAttrHeader.textAndMnemonic=\u5C5E\u6027
+FileChooser.saveButton.textAndMnemonic=\u4FDD\u5B58
+FileChooser.openButton.textAndMnemonic=\u958B\u304F
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=\u5FA9\u5143(&R)
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_ko.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_ko.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=\uC720\uD615
 FileChooser.fileDateHeader.textAndMnemonic=\uC218\uC815 \uB0A0\uC9DC
 FileChooser.fileAttrHeader.textAndMnemonic=\uC18D\uC131
+FileChooser.saveButton.textAndMnemonic=\uC800\uC7A5
+FileChooser.openButton.textAndMnemonic=\uC5F4\uAE30
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=\uBCF5\uC6D0(&R)
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_pt_BR.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_pt_BR.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=Tipo
 FileChooser.fileDateHeader.textAndMnemonic=Modificado
 FileChooser.fileAttrHeader.textAndMnemonic=Atributos
+FileChooser.saveButton.textAndMnemonic=Salvar
+FileChooser.openButton.textAndMnemonic=Abrir
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=&Restaurar
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_sv.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_sv.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=Typ
 FileChooser.fileDateHeader.textAndMnemonic=\u00C4ndrad
 FileChooser.fileAttrHeader.textAndMnemonic=Attribut
+FileChooser.saveButton.textAndMnemonic=Spara
+FileChooser.openButton.textAndMnemonic=\u00D6ppna
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=&\u00C5terst\u00E4ll
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_zh_CN.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_zh_CN.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=\u7C7B\u578B
 FileChooser.fileDateHeader.textAndMnemonic=\u4FEE\u6539\u65E5\u671F
 FileChooser.fileAttrHeader.textAndMnemonic=\u5C5E\u6027
+FileChooser.saveButton.textAndMnemonic=\u4FDD\u5B58
+FileChooser.openButton.textAndMnemonic=\u6253\u5F00
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=\u8FD8\u539F(&R)
--- a/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_zh_TW.properties	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/com/sun/swing/internal/plaf/metal/resources/metal_zh_TW.properties	Thu Jun 28 14:11:05 2012 -0700
@@ -43,6 +43,8 @@
 FileChooser.fileTypeHeader.textAndMnemonic=\u985E\u578B
 FileChooser.fileDateHeader.textAndMnemonic=\u4FEE\u6539\u65E5\u671F
 FileChooser.fileAttrHeader.textAndMnemonic=\u5C6C\u6027
+FileChooser.saveButton.textAndMnemonic=\u5132\u5B58
+FileChooser.openButton.textAndMnemonic=\u958B\u555F
 
 ############ Used by MetalTitlePane if rendering window decorations############
 MetalTitlePane.restore.titleAndMnemonic=\u56DE\u5FA9(&R)
--- a/src/share/classes/java/awt/Dialog.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/java/awt/Dialog.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1037,7 +1037,7 @@
                 predictedFocusOwner = getMostRecentFocusOwner();
                 if (conditionalShow(predictedFocusOwner, time)) {
                     modalFilter = ModalEventFilter.createFilterForDialog(this);
-                    Conditional cond = new Conditional() {
+                    final Conditional cond = new Conditional() {
                         @Override
                         public boolean evaluate() {
                             return windowClosingException == null;
@@ -1067,7 +1067,12 @@
 
                     modalityPushed();
                     try {
-                        EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
+                        final EventQueue eventQueue = AccessController.doPrivileged(
+                            new PrivilegedAction<EventQueue>() {
+                                public EventQueue run() {
+                                    return Toolkit.getDefaultToolkit().getSystemEventQueue();
+                                }
+                        });
                         secondaryLoop = eventQueue.createSecondaryLoop(cond, modalFilter, 0);
                         if (!secondaryLoop.enter()) {
                             secondaryLoop = null;
--- a/src/share/classes/java/io/SerialCallbackContext.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/java/io/SerialCallbackContext.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,54 +1,74 @@
-  /*
-   * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
-   * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
-   */
+/*
+ * Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
 
-  package java.io;
+package java.io;
 
-  /**
-   * Context during upcalls from object stream to class-defined
-   * readObject/writeObject methods.
-   * Holds object currently being deserialized and descriptor for current class.
-   *
-   * This context keeps track of the thread it was constructed on, and allows
-   * only a single call of defaultReadObject, readFields, defaultWriteObject
-   * or writeFields which must be invoked on the same thread before the class's
-   * readObject/writeObject method has returned.
-   * If not set to the current thread, the getObj method throws NotActiveException.
-   */
-  final class SerialCallbackContext {
-      private final Object obj;
-      private final ObjectStreamClass desc;
-      /**
-       * Thread this context is in use by.
-       * As this only works in one thread, we do not need to worry about thread-safety.
-       */
-      private Thread thread;
+/**
+ * Context during upcalls from object stream to class-defined
+ * readObject/writeObject methods.
+ * Holds object currently being deserialized and descriptor for current class.
+ *
+ * This context keeps track of the thread it was constructed on, and allows
+ * only a single call of defaultReadObject, readFields, defaultWriteObject
+ * or writeFields which must be invoked on the same thread before the class's
+ * readObject/writeObject method has returned.
+ * If not set to the current thread, the getObj method throws NotActiveException.
+ */
+final class SerialCallbackContext {
+    private final Object obj;
+    private final ObjectStreamClass desc;
+    /**
+     * Thread this context is in use by.
+     * As this only works in one thread, we do not need to worry about thread-safety.
+     */
+    private Thread thread;
 
-      public SerialCallbackContext(Object obj, ObjectStreamClass desc) {
-          this.obj = obj;
-          this.desc = desc;
-          this.thread = Thread.currentThread();
-      }
+    public SerialCallbackContext(Object obj, ObjectStreamClass desc) {
+        this.obj = obj;
+        this.desc = desc;
+        this.thread = Thread.currentThread();
+    }
 
-      public Object getObj() throws NotActiveException {
-          checkAndSetUsed();
-          return obj;
-      }
+    public Object getObj() throws NotActiveException {
+        checkAndSetUsed();
+        return obj;
+    }
 
-      public ObjectStreamClass getDesc() {
-          return desc;
-      }
+    public ObjectStreamClass getDesc() {
+        return desc;
+    }
 
-      private void checkAndSetUsed() throws NotActiveException {
-          if (thread != Thread.currentThread()) {
-               throw new NotActiveException(
-                "not in readObject invocation or fields already read");
-          }
-          thread = null;
-      }
+    private void checkAndSetUsed() throws NotActiveException {
+        if (thread != Thread.currentThread()) {
+             throw new NotActiveException(
+              "not in readObject invocation or fields already read");
+        }
+        thread = null;
+    }
 
-      public void setUsed() {
-          thread = null;
-      }
-  }
+    public void setUsed() {
+        thread = null;
+    }
+}
--- a/src/share/classes/java/util/HashMap.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/java/util/HashMap.java	Thu Jun 28 14:11:05 2012 -0700
@@ -176,17 +176,16 @@
     transient int modCount;
 
     /**
-     * The default threshold of capacity above which alternate hashing is used.
-     * Alternative hashing reduces the incidence of collisions due to weak hash
-     * code calculation.
+     * The default threshold of map capacity above which alternative hashing is
+     * used for String keys. Alternative hashing reduces the incidence of
+     * collisions due to weak hash code calculation for String keys.
      * <p/>
      * This value may be overridden by defining the system property
-     * {@code java.util.althashing.threshold}. A property value of {@code 1}
+     * {@code jdk.map.althashing.threshold}. A property value of {@code 1}
      * forces alternative hashing to be used at all times whereas
-     * {@code 2147483648 } ({@code Integer.MAX_VALUE}) value ensures that
-     * alternative hashing is never used.
+     * {@code -1} value ensures that alternative hashing is never used.
      */
-    static final int ALTERNATE_HASHING_THRESHOLD_DEFAULT = 512;
+    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
 
     /**
      * holds values which can't be initialized until after VM is booted.
@@ -195,20 +194,19 @@
 
             // Unsafe mechanics
         /**
-         *
+         * Unsafe utilities
          */
         static final sun.misc.Unsafe UNSAFE;
 
         /**
-         * Offset of "final" hashmask field we must set in
-         * readObject() method.
+         * Offset of "final" hashSeed field we must set in readObject() method.
          */
         static final long HASHSEED_OFFSET;
 
         /**
-         * Table capacity above which to switch to use alternate hashing.
+         * Table capacity above which to switch to use alternative hashing.
          */
-        static final int ALTERNATE_HASHING_THRESHOLD;
+        static final int ALTERNATIVE_HASHING_THRESHOLD;
 
         static {
             String altThreshold = java.security.AccessController.doPrivileged(
@@ -219,19 +217,20 @@
             try {
                 threshold = (null != altThreshold)
                         ? Integer.parseInt(altThreshold)
-                        : ALTERNATE_HASHING_THRESHOLD_DEFAULT;
+                        : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
 
-                if(threshold == -1) {
+                // disable alternative hashing if -1
+                if (threshold == -1) {
                     threshold = Integer.MAX_VALUE;
                 }
 
-                if(threshold < 0) {
+                if (threshold < 0) {
                     throw new IllegalArgumentException("value must be positive integer.");
                 }
             } catch(IllegalArgumentException failed) {
                 throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
             }
-            ALTERNATE_HASHING_THRESHOLD = threshold;
+            ALTERNATIVE_HASHING_THRESHOLD = threshold;
 
             try {
                 UNSAFE = sun.misc.Unsafe.getUnsafe();
@@ -244,8 +243,8 @@
     }
 
     /**
-     * If {@code true} then perform alternate hashing to reduce the incidence of
-     * collisions due to weak hash code calculation.
+     * If {@code true} then perform alternative hashing of String keys to reduce
+     * the incidence of collisions due to weak hash code calculation.
      */
     transient boolean useAltHashing;
 
@@ -283,7 +282,7 @@
         threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
         table = new Entry[capacity];
         useAltHashing = sun.misc.VM.isBooted() &&
-                (capacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
+                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
         init();
     }
 
@@ -560,7 +559,7 @@
         Entry[] newTable = new Entry[newCapacity];
         boolean oldAltHashing = useAltHashing;
         useAltHashing |= sun.misc.VM.isBooted() &&
-                (newCapacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
+                (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
         boolean rehash = oldAltHashing ^ useAltHashing;
         transfer(newTable, rehash);
         table = newTable;
@@ -575,7 +574,7 @@
         for (Entry<K,V> e : table) {
             while(null != e) {
                 Entry<K,V> next = e.next;
-                if(rehash) {
+                if (rehash) {
                     e.hash = null == e.key ? 0 : hash(e.key);
                 }
                 int i = indexFor(e.hash, newCapacity);
@@ -1146,7 +1145,7 @@
         table = new Entry[capacity];
         threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
         useAltHashing = sun.misc.VM.isBooted() &&
-                (capacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
+                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
 
         init();  // Give subclass a chance to do its thing.
 
--- a/src/share/classes/java/util/Hashtable.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/java/util/Hashtable.java	Thu Jun 28 14:11:05 2012 -0700
@@ -164,17 +164,16 @@
     private static final long serialVersionUID = 1421746759512286392L;
 
     /**
-     * The default threshold of capacity above which alternate hashing is used.
-     * Alternative hashing reduces the incidence of collisions due to weak hash
-     * code calculation.
+     * The default threshold of map capacity above which alternative hashing is
+     * used for String keys. Alternative hashing reduces the incidence of
+     * collisions due to weak hash code calculation for String keys.
      * <p/>
      * This value may be overridden by defining the system property
-     * {@code java.util.althashing.threshold}. A property value of {@code 1}
+     * {@code jdk.map.althashing.threshold}. A property value of {@code 1}
      * forces alternative hashing to be used at all times whereas
-     * {@code 2147483648 } ({@code Integer.MAX_VALUE}) value ensures that
-     * alternative hashing is never used.
+     * {@code -1} value ensures that alternative hashing is never used.
      */
-    static final int ALTERNATE_HASHING_THRESHOLD_DEFAULT = 512;
+    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = 512;
 
     /**
      * holds values which can't be initialized until after VM is booted.
@@ -182,9 +181,9 @@
     private static class Holder {
 
         /**
-         * Table capacity above which to switch to use alternate hashing.
+         * Table capacity above which to switch to use alternative hashing.
          */
-        static final int ALTERNATE_HASHING_THRESHOLD;
+        static final int ALTERNATIVE_HASHING_THRESHOLD;
 
         static {
             String altThreshold = java.security.AccessController.doPrivileged(
@@ -195,31 +194,39 @@
             try {
                 threshold = (null != altThreshold)
                         ? Integer.parseInt(altThreshold)
-                        : 1;
+                        : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
 
-                if(threshold == -1) {
+                // disable alternative hashing if -1
+                if (threshold == -1) {
                     threshold = Integer.MAX_VALUE;
                 }
 
-                if(threshold < 0) {
+                if (threshold < 0) {
                     throw new IllegalArgumentException("value must be positive integer.");
                 }
             } catch(IllegalArgumentException failed) {
                 throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
             }
 
-            ALTERNATE_HASHING_THRESHOLD = threshold;
+            ALTERNATIVE_HASHING_THRESHOLD = threshold;
         }
     }
 
     /**
-     * If {@code true} then perform alternate hashing to reduce the incidence of
-     * collisions due to weak hash code calculation.
+     * If {@code true} then perform alternative hashing of String keys to reduce
+     * the incidence of collisions due to weak hash code calculation.
      */
     transient boolean useAltHashing;
 
     // Unsafe mechanics
+    /**
+    * Unsafe utilities
+    */
     private static final sun.misc.Unsafe UNSAFE;
+
+    /**
+    * Offset of "final" hashSeed field we must set in readObject() method.
+    */
     private static final long HASHSEED_OFFSET;
 
      static {
@@ -278,7 +285,7 @@
         table = new Entry[initialCapacity];
         threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
         useAltHashing = sun.misc.VM.isBooted() &&
-                (initialCapacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
+                (initialCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
     }
 
     /**
@@ -492,7 +499,7 @@
         threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
         boolean currentAltHashing = useAltHashing;
         useAltHashing = sun.misc.VM.isBooted() &&
-                (newCapacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
+                (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
         boolean rehash = currentAltHashing ^ useAltHashing;
 
         table = newMap;
@@ -502,7 +509,7 @@
                 Entry<K,V> e = old;
                 old = old.next;
 
-                if(rehash) {
+                if (rehash) {
                     e.hash = hash(e.key);
                 }
                 int index = (e.hash & 0x7FFFFFFF) % newCapacity;
@@ -1014,7 +1021,7 @@
         threshold = (int) Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1);
         count = 0;
         useAltHashing = sun.misc.VM.isBooted() &&
-                (length >= Holder.ALTERNATE_HASHING_THRESHOLD);
+                (length >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
 
         // Read the number of elements and then all the key/value objects
         for (; elements > 0; elements--) {
--- a/src/share/classes/java/util/WeakHashMap.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/java/util/WeakHashMap.java	Thu Jun 28 14:11:05 2012 -0700
@@ -185,17 +185,16 @@
     int modCount;
 
     /**
-    * The default threshold of capacity above which alternate hashing is
-    * used. Alternative hashing reduces the incidence of collisions due to
-    * weak hash code calculation.
-    * <p/>
-    * This value may be overridden by defining the system property
-    * {@code java.util.althashing.threshold} to an integer value. A property
-    * value of {@code 1} forces alternative hashing to be used at all times
-    * whereas {@code 2147483648 } ({@code Integer.MAX_VALUE}) value ensures
-    * that alternative hashing is never used.
-    */
-    static final int ALTERNATE_HASHING_THRESHOLD_DEFAULT = 512;
+     * The default threshold of map capacity above which alternative hashing is
+     * used for String keys. Alternative hashing reduces the incidence of
+     * collisions due to weak hash code calculation for String keys.
+     * <p/>
+     * This value may be overridden by defining the system property
+     * {@code jdk.map.althashing.threshold}. A property value of {@code 1}
+     * forces alternative hashing to be used at all times whereas
+     * {@code -1} value ensures that alternative hashing is never used.
+     */
+    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
 
     /**
      * holds values which can't be initialized until after VM is booted.
@@ -203,9 +202,9 @@
     private static class Holder {
 
         /**
-         * Table capacity above which to switch to use alternate hashing.
+         * Table capacity above which to switch to use alternative hashing.
          */
-        static final int ALTERNATE_HASHING_THRESHOLD;
+        static final int ALTERNATIVE_HASHING_THRESHOLD;
 
         static {
             String altThreshold = java.security.AccessController.doPrivileged(
@@ -216,19 +215,20 @@
             try {
                 threshold = (null != altThreshold)
                         ? Integer.parseInt(altThreshold)
-                        : ALTERNATE_HASHING_THRESHOLD_DEFAULT;
+                        : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
 
-                if(threshold == -1) {
+                // disable alternative hashing if -1
+                if (threshold == -1) {
                     threshold = Integer.MAX_VALUE;
                 }
 
-                if(threshold < 0) {
+                if (threshold < 0) {
                     throw new IllegalArgumentException("value must be positive integer.");
                 }
             } catch(IllegalArgumentException failed) {
                 throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
             }
-            ALTERNATE_HASHING_THRESHOLD = threshold;
+            ALTERNATIVE_HASHING_THRESHOLD = threshold;
         }
     }
 
@@ -275,7 +275,7 @@
         this.loadFactor = loadFactor;
         threshold = (int)(capacity * loadFactor);
         useAltHashing = sun.misc.VM.isBooted() &&
-                (capacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
+                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
     }
 
     /**
@@ -356,7 +356,7 @@
         if (useAltHashing) {
             h = hashSeed;
             if (k instanceof String) {
-                return h ^ sun.misc.Hashing.stringHash32((String) k);
+                return sun.misc.Hashing.stringHash32((String) k);
             } else {
                 h ^= k.hashCode();
             }
@@ -559,7 +559,7 @@
         Entry<K,V>[] newTable = newTable(newCapacity);
         boolean oldAltHashing = useAltHashing;
         useAltHashing |= sun.misc.VM.isBooted() &&
-                (newCapacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
+                (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
         boolean rehash = oldAltHashing ^ useAltHashing;
         transfer(oldTable, newTable, rehash);
         table = newTable;
@@ -591,7 +591,7 @@
                     e.value = null; //  "   "
                     size--;
                 } else {
-                    if(rehash) {
+                    if (rehash) {
                         e.hash = hash(key);
                     }
                     int i = indexFor(e.hash, dest.length);
--- a/src/share/classes/java/util/concurrent/ConcurrentHashMap.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentHashMap.java	Thu Jun 28 14:11:05 2012 -0700
@@ -183,11 +183,18 @@
     private static class Holder {
 
         /**
-        * Enable alternate hashing?
+        * Enable alternative hashing of String keys?
+        *
+        * <p>Unlike the other hash map implementations we do not implement a
+        * threshold for regulating whether alternative hashing is used for
+        * String keys. Alternative hashing is either enabled for all instances
+        * or disabled for all instances.
         */
-        static final boolean ALTERNATE_HASHING;
+        static final boolean ALTERNATIVE_HASHING;
 
         static {
+            // Use the "threshold" system property even though our threshold
+            // behaviour is "ON" or "OFF".
             String altThreshold = java.security.AccessController.doPrivileged(
                 new sun.security.action.GetPropertyAction(
                     "jdk.map.althashing.threshold"));
@@ -196,19 +203,20 @@
             try {
                 threshold = (null != altThreshold)
                         ? Integer.parseInt(altThreshold)
-                        : 1;
+                        : Integer.MAX_VALUE;
 
-                if(threshold == -1) {
+                // disable alternative hashing if -1
+                if (threshold == -1) {
                     threshold = Integer.MAX_VALUE;
                 }
 
-                if(threshold < 0) {
+                if (threshold < 0) {
                     throw new IllegalArgumentException("value must be positive integer.");
                 }
             } catch(IllegalArgumentException failed) {
                 throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
             }
-            ALTERNATE_HASHING = threshold <= MAXIMUM_CAPACITY;
+            ALTERNATIVE_HASHING = threshold <= MAXIMUM_CAPACITY;
         }
     }
 
@@ -219,7 +227,7 @@
     private transient final int hashSeed = randomHashSeed(this);
 
     private static int randomHashSeed(ConcurrentHashMap instance) {
-        if (sun.misc.VM.isBooted() && Holder.ALTERNATE_HASHING) {
+        if (sun.misc.VM.isBooted() && Holder.ALTERNATIVE_HASHING) {
             return sun.misc.Hashing.randomHashSeed(instance);
         }
 
--- a/src/share/classes/javax/swing/text/DefaultCaret.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/javax/swing/text/DefaultCaret.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, 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
@@ -1499,9 +1499,14 @@
 
         if (caretWidth > -1) {
             return caretWidth;
+        } else {
+            Object property = UIManager.get("Caret.width");
+            if (property instanceof Integer) {
+                return ((Integer) property).intValue();
+            } else {
+                return 1;
+            }
         }
-
-        return 1;
     }
 
     // --- serialization ---------------------------------------------
--- a/src/share/classes/javax/swing/text/html/parser/Parser.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/javax/swing/text/html/parser/Parser.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1986,8 +1986,6 @@
             if (i == SCRIPT_END_TAG.length) {
 
                 /*  '</script>' tag detected */
-                /* Here, ch == '>' */
-                ch = readCh();
                 /* Here, ch == the first character after </script> */
                 return;
             } else {
@@ -2060,6 +2058,8 @@
                 handleComment(str.toCharArray());
                 endTag(false);
                 lastBlockStartPos = currentPosition;
+
+                continue;
             } else {
                 switch (c) {
                   case '<':
--- a/src/share/classes/sun/font/SunLayoutEngine.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/font/SunLayoutEngine.java	Thu Jun 28 14:11:05 2012 -0700
@@ -33,7 +33,7 @@
 import sun.font.GlyphLayout.*;
 import java.awt.geom.Point2D;
 import java.lang.ref.SoftReference;
-import java.util.HashMap;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.Locale;
 
 /*
@@ -129,9 +129,9 @@
 
   // !!! don't need this unless we have more than one sun layout engine...
     public LayoutEngine getEngine(LayoutEngineKey key) {
-        HashMap cache = (HashMap)cacheref.get();
+        ConcurrentHashMap cache = (ConcurrentHashMap)cacheref.get();
         if (cache == null) {
-            cache = new HashMap();
+            cache = new ConcurrentHashMap();
             cacheref = new SoftReference(cache);
         }
 
--- a/src/share/classes/sun/net/spi/DefaultProxySelector.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/net/spi/DefaultProxySelector.java	Thu Jun 28 14:11:05 2012 -0700
@@ -111,7 +111,7 @@
     static class NonProxyInfo {
         // Default value for nonProxyHosts, this provides backward compatibility
         // by excluding localhost and its litteral notations.
-        static final String defStringVal = "localhost|127.*|[::1]";
+        static final String defStringVal = "localhost|127.*|[::1]|0.0.0.0|[::0]";
 
         String hostsSource;
         RegexpPool hostsPool;
--- a/src/share/classes/sun/nio/cs/ext/SJIS_0213.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/nio/cs/ext/SJIS_0213.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2012, 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
@@ -31,6 +31,8 @@
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.CharsetDecoder;
 import java.nio.charset.CoderResult;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.Arrays;
 import sun.nio.cs.CharsetMapping;
 
@@ -73,8 +75,12 @@
         return new Encoder(this);
     }
 
-    static CharsetMapping mapping =
-        CharsetMapping.get(SJIS_0213.class.getResourceAsStream("sjis0213.dat"));
+    static CharsetMapping mapping = AccessController.doPrivileged(
+        new PrivilegedAction<CharsetMapping>() {
+            public CharsetMapping run() {
+                return CharsetMapping.get(SJIS_0213.class.getResourceAsStream("sjis0213.dat"));
+            }
+        });
 
     protected static class Decoder extends CharsetDecoder {
         protected static final char UNMAPPABLE = CharsetMapping.UNMAPPABLE_DECODING;
--- a/src/share/classes/sun/print/ServiceDialog.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/print/ServiceDialog.java	Thu Jun 28 14:11:05 2012 -0700
@@ -429,6 +429,7 @@
         ValidatingFileChooser jfc = new ValidatingFileChooser();
         jfc.setApproveButtonText(getMsg("button.ok"));
         jfc.setDialogTitle(getMsg("dialog.printtofile"));
+        jfc.setDialogType(JFileChooser.SAVE_DIALOG);
         jfc.setSelectedFile(fileDest);
 
         int returnVal = jfc.showDialog(this, null);
--- a/src/share/classes/sun/security/provider/certpath/OCSP.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/OCSP.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2012, 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
@@ -84,7 +84,7 @@
      */
     public static RevocationStatus check(X509Certificate cert,
         X509Certificate issuerCert)
-        throws IOException, CertPathValidatorException {
+            throws IOException, CertPathValidatorException {
         CertId certId = null;
         URI responderURI = null;
         try {
@@ -103,7 +103,7 @@
                 ("Exception while encoding OCSPRequest", ioe);
         }
         OCSPResponse ocspResponse = check(Collections.singletonList(certId),
-            responderURI, issuerCert, null);
+            responderURI, Collections.singletonList(issuerCert), null);
         return (RevocationStatus) ocspResponse.getSingleResponse(certId);
     }
 
@@ -123,9 +123,34 @@
      *    encoding the OCSP Request or validating the OCSP Response
      */
     public static RevocationStatus check(X509Certificate cert,
-        X509Certificate issuerCert, URI responderURI, X509Certificate
-        responderCert, Date date)
-        throws IOException, CertPathValidatorException {
+        X509Certificate issuerCert, URI responderURI,
+        X509Certificate responderCert, Date date)
+            throws IOException, CertPathValidatorException {
+
+        return check(cert, issuerCert, responderURI,
+            Collections.singletonList(responderCert), date);
+    }
+
+    /**
+     * Obtains the revocation status of a certificate using OCSP.
+     *
+     * @param cert the certificate to be checked
+     * @param issuerCert the issuer certificate
+     * @param responderURI the URI of the OCSP responder
+     * @param responderCerts the OCSP responder's certificates
+     * @param date the time the validity of the OCSP responder's certificate
+     *    should be checked against. If null, the current time is used.
+     * @return the RevocationStatus
+     * @throws IOException if there is an exception connecting to or
+     *    communicating with the OCSP responder
+     * @throws CertPathValidatorException if an exception occurs while
+     *    encoding the OCSP Request or validating the OCSP Response
+     */
+    public static RevocationStatus check(X509Certificate cert,
+        X509Certificate issuerCert, URI responderURI,
+        List<X509Certificate> responderCerts, Date date)
+            throws IOException, CertPathValidatorException {
+
         CertId certId = null;
         try {
             X509CertImpl certImpl = X509CertImpl.toImpl(cert);
@@ -138,7 +163,7 @@
                 ("Exception while encoding OCSPRequest", ioe);
         }
         OCSPResponse ocspResponse = check(Collections.singletonList(certId),
-            responderURI, responderCert, date);
+            responderURI, responderCerts, date);
         return (RevocationStatus) ocspResponse.getSingleResponse(certId);
     }
 
@@ -147,7 +172,7 @@
      *
      * @param certs the CertIds to be checked
      * @param responderURI the URI of the OCSP responder
-     * @param responderCert the OCSP responder's certificate
+     * @param responderCerts the OCSP responder's certificates
      * @param date the time the validity of the OCSP responder's certificate
      *    should be checked against. If null, the current time is used.
      * @return the OCSPResponse
@@ -157,8 +182,8 @@
      *    encoding the OCSP Request or validating the OCSP Response
      */
     static OCSPResponse check(List<CertId> certIds, URI responderURI,
-        X509Certificate responderCert, Date date)
-        throws IOException, CertPathValidatorException {
+        List<X509Certificate> responderCerts, Date date)
+            throws IOException, CertPathValidatorException {
 
         byte[] bytes = null;
         try {
@@ -233,7 +258,7 @@
 
         OCSPResponse ocspResponse = null;
         try {
-            ocspResponse = new OCSPResponse(response, date, responderCert);
+            ocspResponse = new OCSPResponse(response, date, responderCerts);
         } catch (IOException ioe) {
             // response decoding exception
             throw new CertPathValidatorException(ioe);
@@ -291,7 +316,7 @@
 
         List<AccessDescription> descriptions = aia.getAccessDescriptions();
         for (AccessDescription description : descriptions) {
-            if (description.getAccessMethod().equals(
+            if (description.getAccessMethod().equals((Object)
                 AccessDescription.Ad_OCSP_Id)) {
 
                 GeneralName generalName = description.getAccessLocation();
--- a/src/share/classes/sun/security/provider/certpath/OCSPChecker.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/OCSPChecker.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2012, 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,6 +25,7 @@
 
 package sun.security.provider.certpath;
 
+import java.io.IOException;
 import java.math.BigInteger;
 import java.util.*;
 import java.security.AccessController;
@@ -190,7 +191,8 @@
         // (unless we're processing the final cert).
         X509Certificate issuerCert = null;
         boolean seekIssuerCert = true;
-        X509Certificate responderCert = null;
+        List<X509Certificate> responderCerts = new ArrayList<X509Certificate>();
+
         if (remainingCerts < certs.length) {
             issuerCert = certs[remainingCerts];
             seekIssuerCert = false; // done
@@ -198,7 +200,7 @@
             // By default, the OCSP responder's cert is the same as the
             // issuer of the cert being validated.
             if (!seekResponderCert) {
-                responderCert = issuerCert;
+                responderCerts.add(issuerCert);
                 if (DEBUG != null) {
                     DEBUG.println("Responder's certificate is the same " +
                         "as the issuer of the certificate being validated");
@@ -212,8 +214,8 @@
         if (seekIssuerCert || seekResponderCert) {
 
             if (DEBUG != null && seekResponderCert) {
-                DEBUG.println("Searching trust anchors for responder's " +
-                    "certificate");
+                DEBUG.println("Searching trust anchors for issuer or " +
+                    "responder certificate");
             }
 
             // Extract the anchor certs
@@ -226,6 +228,8 @@
 
             X500Principal certIssuerName =
                 currCertImpl.getIssuerX500Principal();
+            byte[] certIssuerKeyId = null;
+
             while (anchors.hasNext() && (seekIssuerCert || seekResponderCert)) {
 
                 TrustAnchor anchor = anchors.next();
@@ -242,13 +246,38 @@
                 if (seekIssuerCert &&
                     certIssuerName.equals(anchorSubjectName)) {
 
+                    // Retrieve the issuer's key identifier
+                    if (certIssuerKeyId == null) {
+                        certIssuerKeyId = currCertImpl.getIssuerKeyIdentifier();
+                        if (certIssuerKeyId == null) {
+                            if (DEBUG != null) {
+                                DEBUG.println("No issuer key identifier (AKID) "
+                                    + "in the certificate being validated");
+                            }
+                        }
+                    }
+
+                    // Check that the key identifiers match
+                    if (certIssuerKeyId != null &&
+                        !Arrays.equals(certIssuerKeyId, getKeyId(anchorCert))) {
+
+                        continue; // try next cert
+                    }
+
+                    if (DEBUG != null && certIssuerKeyId != null) {
+                        DEBUG.println("Issuer certificate key ID: " +
+                            String.format("0x%0" +
+                                (certIssuerKeyId.length * 2) + "x",
+                                    new BigInteger(1, certIssuerKeyId)));
+                    }
+
                     issuerCert = anchorCert;
                     seekIssuerCert = false; // done
 
                     // By default, the OCSP responder's cert is the same as
                     // the issuer of the cert being validated.
-                    if (!seekResponderCert && responderCert == null) {
-                        responderCert = anchorCert;
+                    if (!seekResponderCert && responderCerts.isEmpty()) {
+                        responderCerts.add(anchorCert);
                         if (DEBUG != null) {
                             DEBUG.println("Responder's certificate is the" +
                                 " same as the issuer of the certificate " +
@@ -271,8 +300,7 @@
                          responderSerialNumber.equals(
                          anchorCert.getSerialNumber()))) {
 
-                        responderCert = anchorCert;
-                        seekResponderCert = false; // done
+                        responderCerts.add(anchorCert);
                     }
                 }
             }
@@ -300,9 +328,10 @@
                 if (filter != null) {
                     List<CertStore> certStores = pkixParams.getCertStores();
                     for (CertStore certStore : certStores) {
-                        Iterator i = null;
                         try {
-                            i = certStore.getCertificates(filter).iterator();
+                            responderCerts.addAll(
+                                (Collection<X509Certificate>)
+                                    certStore.getCertificates(filter));
                         } catch (CertStoreException cse) {
                             // ignore and try next certStore
                             if (DEBUG != null) {
@@ -310,23 +339,23 @@
                             }
                             continue;
                         }
-                        if (i.hasNext()) {
-                            responderCert = (X509Certificate) i.next();
-                            seekResponderCert = false; // done
-                            break;
-                        }
                     }
                 }
             }
         }
 
         // Could not find the certificate identified in the OCSP properties
-        if (seekResponderCert) {
+        if (seekResponderCert && responderCerts.isEmpty()) {
             throw new CertPathValidatorException(
                 "Cannot find the responder's certificate " +
                 "(set using the OCSP security properties).");
         }
 
+        if (DEBUG != null) {
+            DEBUG.println("Located " + responderCerts.size() +
+                " trusted responder certificate(s)");
+        }
+
         // The algorithm constraints of the OCSP trusted responder certificate
         // does not need to be checked in this code. The constraints will be
         // checked when the responder's certificate is validated.
@@ -337,7 +366,7 @@
             certId = new CertId
                 (issuerCert, currCertImpl.getSerialNumberObject());
             response = OCSP.check(Collections.singletonList(certId), uri,
-                responderCert, pkixParams.getDate());
+                responderCerts, pkixParams.getDate());
         } catch (Exception e) {
             if (e instanceof CertPathValidatorException) {
                 throw (CertPathValidatorException) e;
@@ -353,14 +382,15 @@
         if (certStatus == RevocationStatus.CertStatus.REVOKED) {
             Throwable t = new CertificateRevokedException(
                 rs.getRevocationTime(), rs.getRevocationReason(),
-                responderCert.getSubjectX500Principal(),
+                responderCerts.get(0).getSubjectX500Principal(),
                 rs.getSingleExtensions());
             throw new CertPathValidatorException(t.getMessage(), t,
                 null, -1, BasicReason.REVOKED);
         } else if (certStatus == RevocationStatus.CertStatus.UNKNOWN) {
             throw new CertPathValidatorException(
                 "Certificate's revocation status is unknown", null, cp,
-                remainingCerts, BasicReason.UNDETERMINED_REVOCATION_STATUS);
+                (remainingCerts - 1),
+                BasicReason.UNDETERMINED_REVOCATION_STATUS);
         }
     }
 
@@ -392,7 +422,7 @@
 
         List<AccessDescription> descriptions = aia.getAccessDescriptions();
         for (AccessDescription description : descriptions) {
-            if (description.getAccessMethod().equals(
+            if (description.getAccessMethod().equals((Object)
                 AccessDescription.Ad_OCSP_Id)) {
 
                 GeneralName generalName = description.getAccessLocation();
@@ -443,4 +473,34 @@
         }
         return hexNumber.toString();
     }
+
+    /*
+     * Returns the subject key identifier for the supplied certificate, or null
+     */
+    static byte[] getKeyId(X509Certificate cert) {
+        X509CertImpl certImpl = null;
+        byte[] certSubjectKeyId = null;
+
+        try {
+            certImpl = X509CertImpl.toImpl(cert);
+            certSubjectKeyId = certImpl.getSubjectKeyIdentifier();
+
+            if (certSubjectKeyId == null) {
+                if (DEBUG != null) {
+                    DEBUG.println("No subject key identifier (SKID) in the " +
+                        "certificate (Subject: " +
+                        cert.getSubjectX500Principal() + ")");
+                }
+            }
+
+        } catch (CertificateException e) {
+            // Ignore certificate
+            if (DEBUG != null) {
+                DEBUG.println("Error parsing X.509 certificate (Subject: " +
+                    cert.getSubjectX500Principal() + ") " + e);
+            }
+        }
+
+        return certSubjectKeyId;
+    }
 }
--- a/src/share/classes/sun/security/provider/certpath/OCSPRequest.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/OCSPRequest.java	Thu Jun 28 14:11:05 2012 -0700
@@ -75,7 +75,7 @@
 class OCSPRequest {
 
     private static final Debug debug = Debug.getInstance("certpath");
-    private static final boolean dump = false;
+    private static final boolean dump = debug.isOn("ocsp");
 
     // List of request CertIds
     private final List<CertId> certIds;
@@ -116,8 +116,8 @@
 
         if (dump) {
             HexDumpEncoder hexEnc = new HexDumpEncoder();
-            System.out.println("OCSPRequest bytes are... ");
-            System.out.println(hexEnc.encode(bytes));
+            debug.println("\nOCSPRequest bytes... ");
+            debug.println(hexEnc.encode(bytes) + "\n");
         }
 
         return bytes;
--- a/src/share/classes/sun/security/provider/certpath/OCSPResponse.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/security/provider/certpath/OCSPResponse.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2012, 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
@@ -34,6 +34,7 @@
 import java.security.cert.CRLReason;
 import java.security.cert.TrustAnchor;
 import java.security.cert.X509Certificate;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
@@ -127,7 +128,7 @@
     private static ResponseStatus[] rsvalues = ResponseStatus.values();
 
     private static final Debug DEBUG = Debug.getInstance("certpath");
-    private static final boolean dump = false;
+    private static final boolean dump = DEBUG.isOn("ocsp");
     private static final ObjectIdentifier OCSP_BASIC_RESPONSE_OID =
         ObjectIdentifier.newInternal(new int[] { 1, 3, 6, 1, 5, 5, 7, 48, 1, 1});
     private static final ObjectIdentifier OCSP_NONCE_EXTENSION_OID =
@@ -158,14 +159,14 @@
      * Create an OCSP response from its ASN.1 DER encoding.
      */
     OCSPResponse(byte[] bytes, Date dateCheckedAgainst,
-        X509Certificate responderCert)
+        List<X509Certificate> responderCerts)
         throws IOException, CertPathValidatorException {
 
         // OCSPResponse
         if (dump) {
             HexDumpEncoder hexEnc = new HexDumpEncoder();
-            System.out.println("OCSPResponse bytes are...");
-            System.out.println(hexEnc.encode(bytes));
+            DEBUG.println("\nOCSPResponse bytes...");
+            DEBUG.println(hexEnc.encode(bytes) + "\n");
         }
         DerValue der = new DerValue(bytes);
         if (der.tag != DerValue.tag_Sequence) {
@@ -206,7 +207,7 @@
         // responseType
         derIn = tmp.data;
         ObjectIdentifier responseType = derIn.getOID();
-        if (responseType.equals(OCSP_BASIC_RESPONSE_OID)) {
+        if (responseType.equals((Object)OCSP_BASIC_RESPONSE_OID)) {
             if (DEBUG != null) {
                 DEBUG.println("OCSP response type: basic");
             }
@@ -263,10 +264,16 @@
                 DEBUG.println("OCSP Responder name: " + responderName);
             }
         } else if (tag == KEY_TAG) {
-            // Ignore, for now
+            if (DEBUG != null) {
+                byte[] responderKeyId = seq.getOctetString();
+                DEBUG.println("OCSP Responder key ID: " +
+                    String.format("0x%0" +
+                        (responderKeyId.length * 2) + "x",
+                            new BigInteger(1, responderKeyId)));
+            }
         } else {
             throw new IOException("Bad encoding in responderID element of " +
-                "OCSP response: expected ASN.1 context specific tag 0 or 1");
+                "OCSP response: expected ASN.1 context specific tag 1 or 2");
         }
 
         // producedAt
@@ -301,7 +308,7 @@
                     if (DEBUG != null) {
                         DEBUG.println("OCSP extension: " + responseExtension);
                     }
-                    if (responseExtension.getExtensionId().equals(
+                    if (responseExtension.getExtensionId().equals((Object)
                         OCSP_NONCE_EXTENSION_OID)) {
                         /*
                         ocspNonce =
@@ -342,99 +349,147 @@
             }
         }
 
-        // Check whether the cert returned by the responder is trusted
+        X509Certificate trustedResponderCert = null;
+
+        // Check whether the signer cert returned by the responder is trusted
         if (x509Certs != null && x509Certs[0] != null) {
-            X509CertImpl cert = x509Certs[0];
+            X509CertImpl signerCert = x509Certs[0];
 
-            // First check if the cert matches the responder cert which
-            // was set locally.
-            if (cert.equals(responderCert)) {
-                // cert is trusted, now verify the signed response
+            if (DEBUG != null) {
+                DEBUG.println("Signer certificate name: " +
+                    signerCert.getSubjectX500Principal());
 
-            // Next check if the cert was issued by the responder cert
-            // which was set locally.
-            } else if (cert.getIssuerX500Principal().equals(
-                responderCert.getSubjectX500Principal())) {
+                byte[] signerKeyId = signerCert.getSubjectKeyIdentifier();
+                if (signerKeyId != null) {
+                    DEBUG.println("Signer certificate key ID: " +
+                        String.format("0x%0" + (signerKeyId.length * 2) + "x",
+                                new BigInteger(1, signerKeyId)));
+                }
+            }
 
-                // Check for the OCSPSigning key purpose
-                try {
-                    List<String> keyPurposes = cert.getExtendedKeyUsage();
-                    if (keyPurposes == null ||
-                        !keyPurposes.contains(KP_OCSP_SIGNING_OID)) {
-                        throw new CertPathValidatorException(
-                            "Responder's certificate not valid for signing " +
-                            "OCSP responses");
+            byte[] certIssuerKeyId = null;
+
+            for (X509Certificate responderCert : responderCerts) {
+
+                // First check if signer cert matches a trusted responder cert
+                if (signerCert.equals(responderCert)) {
+
+                    // signer cert is trusted, now verify the signed response
+                    trustedResponderCert = responderCert;
+                    if (DEBUG != null) {
+                        DEBUG.println("Signer certificate is a trusted " +
+                            "responder");
                     }
-                } catch (CertificateParsingException cpe) {
-                    // assume cert is not valid for signing
-                    throw new CertPathValidatorException(
-                        "Responder's certificate not valid for signing " +
-                        "OCSP responses", cpe);
+                    break;
+
+                // Next check if signer cert was issued by a trusted responder
+                // cert
+                } else if (signerCert.getIssuerX500Principal().equals(
+                    responderCert.getSubjectX500Principal())) {
+
+                    // Retrieve the issuer's key identifier
+                    if (certIssuerKeyId == null) {
+                        certIssuerKeyId = signerCert.getIssuerKeyIdentifier();
+                    }
+
+                    // Check that the key identifiers match
+                    if (certIssuerKeyId == null ||
+                        !Arrays.equals(certIssuerKeyId,
+                            OCSPChecker.getKeyId(responderCert))) {
+
+                        continue; // try next cert
+                    }
+
+                    if (DEBUG != null) {
+                        DEBUG.println("Issuer certificate key ID: " +
+                            String.format("0x%0" +
+                                (certIssuerKeyId.length * 2) + "x",
+                                    new BigInteger(1, certIssuerKeyId)));
+                    }
+
+                    // Check for the OCSPSigning key purpose
+                    try {
+                        List<String> keyPurposes =
+                            signerCert.getExtendedKeyUsage();
+                        if (keyPurposes == null ||
+                            !keyPurposes.contains(KP_OCSP_SIGNING_OID)) {
+
+                            continue; // try next cert
+                        }
+                    } catch (CertificateParsingException cpe) {
+
+                        continue; // try next cert
+                    }
+
+                    // Check algorithm constraints specified in security
+                    // property "jdk.certpath.disabledAlgorithms".
+                    AlgorithmChecker algChecker = new AlgorithmChecker(
+                                        new TrustAnchor(responderCert, null));
+                    algChecker.init(false);
+                    algChecker.check(signerCert,
+                        Collections.<String>emptySet());
+
+                    // Check the date validity
+                    try {
+                        if (dateCheckedAgainst == null) {
+                            signerCert.checkValidity();
+                        } else {
+                            signerCert.checkValidity(dateCheckedAgainst);
+                        }
+                    } catch (GeneralSecurityException e) {
+                        if (DEBUG != null) {
+                            DEBUG.println("Responder's certificate not within" +
+                            " the validity period" + e);
+                        }
+                        continue; // try next cert
+                    }
+
+                    // Check for revocation
+                    //
+                    // A CA may specify that an OCSP client can trust a
+                    // responder for the lifetime of the responder's
+                    // certificate. The CA does so by including the
+                    // extension id-pkix-ocsp-nocheck.
+                    //
+                    Extension noCheck =
+                        signerCert.getExtension(PKIXExtensions.OCSPNoCheck_Id);
+                    if (noCheck != null) {
+                        if (DEBUG != null) {
+                            DEBUG.println("Responder's certificate includes " +
+                                "the extension id-pkix-ocsp-nocheck.");
+                        }
+                    } else {
+                        // we should do the revocation checking of the
+                        // authorized responder in a future update.
+                    }
+
+                    // Verify the signature
+                    try {
+                        signerCert.verify(responderCert.getPublicKey());
+                        trustedResponderCert = signerCert;
+                        // cert is trusted, now verify the signed response
+                        if (DEBUG != null) {
+                            DEBUG.println("Signer certificate was issued by " +
+                                "a trusted responder");
+                        }
+                        break;
+
+                    } catch (GeneralSecurityException e) {
+                        trustedResponderCert = null;
+                    }
                 }
-
-                // Check algorithm constraints specified in security property
-                // "jdk.certpath.disabledAlgorithms".
-                AlgorithmChecker algChecker = new AlgorithmChecker(
-                                    new TrustAnchor(responderCert, null));
-                algChecker.init(false);
-                algChecker.check(cert, Collections.<String>emptySet());
-
-                // check the validity
-                try {
-                    if (dateCheckedAgainst == null) {
-                        cert.checkValidity();
-                    } else {
-                        cert.checkValidity(dateCheckedAgainst);
-                    }
-                } catch (GeneralSecurityException e) {
-                    throw new CertPathValidatorException(
-                        "Responder's certificate not within the " +
-                        "validity period", e);
-                }
-
-                // check for revocation
-                //
-                // A CA may specify that an OCSP client can trust a
-                // responder for the lifetime of the responder's
-                // certificate. The CA does so by including the
-                // extension id-pkix-ocsp-nocheck.
-                //
-                Extension noCheck =
-                    cert.getExtension(PKIXExtensions.OCSPNoCheck_Id);
-                if (noCheck != null) {
-                    if (DEBUG != null) {
-                        DEBUG.println("Responder's certificate includes " +
-                            "the extension id-pkix-ocsp-nocheck.");
-                    }
-                } else {
-                    // we should do the revocation checking of the
-                    // authorized responder in a future update.
-                }
-
-                // verify the signature
-                try {
-                    cert.verify(responderCert.getPublicKey());
-                    responderCert = cert;
-                    // cert is trusted, now verify the signed response
-
-                } catch (GeneralSecurityException e) {
-                    responderCert = null;
-                }
-            } else {
-                throw new CertPathValidatorException(
-                    "Responder's certificate is not authorized to sign " +
-                    "OCSP responses");
             }
         }
 
         // Confirm that the signed response was generated using the public
         // key from the trusted responder cert
-        if (responderCert != null) {
+        if (trustedResponderCert != null) {
             // Check algorithm constraints specified in security property
             // "jdk.certpath.disabledAlgorithms".
-            AlgorithmChecker.check(responderCert.getPublicKey(), sigAlgId);
+            AlgorithmChecker.check(trustedResponderCert.getPublicKey(),
+                sigAlgId);
 
-            if (!verifyResponse(responseDataDer, responderCert,
+            if (!verifyResponse(responseDataDer, trustedResponderCert,
                 sigAlgId, signature)) {
                 throw new CertPathValidatorException(
                     "Error verifying OCSP Responder's signature");
@@ -442,7 +497,8 @@
         } else {
             // Need responder's cert in order to verify the signature
             throw new CertPathValidatorException(
-                "Unable to verify OCSP Responder's signature");
+                "Responder's certificate is not trusted for signing " +
+                "OCSP responses");
         }
     }
 
--- a/src/share/classes/sun/security/x509/X509CertImpl.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/classes/sun/security/x509/X509CertImpl.java	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, 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
@@ -174,6 +174,12 @@
      */
     private boolean verificationResult;
 
+    // Cached SKID
+    private byte[] subjectKeyId = null;
+
+    // Cached AKID
+    private byte[] issuerKeyId = null;
+
     /**
      * Default constructor.
      */
@@ -196,10 +202,7 @@
             parse(new DerValue(certData));
         } catch (IOException e) {
             signedCert = null;
-            CertificateException ce = new
-                CertificateException("Unable to initialize, " + e);
-            ce.initCause(e);
-            throw ce;
+            throw new CertificateException("Unable to initialize, " + e, e);
         }
     }
 
@@ -231,25 +234,19 @@
                 inBuffered.reset();
                 der = new DerValue(inBuffered);
             } catch (IOException ioe1) {
-                CertificateException ce = new
-                    CertificateException("Input stream must be " +
-                                         "either DER-encoded bytes " +
-                                         "or RFC1421 hex-encoded " +
-                                         "DER-encoded bytes: " +
-                                         ioe1.getMessage());
-                ce.initCause(ioe1);
-                throw ce;
+                throw new CertificateException("Input stream must be " +
+                                               "either DER-encoded bytes " +
+                                               "or RFC1421 hex-encoded " +
+                                               "DER-encoded bytes: " +
+                                               ioe1.getMessage(), ioe1);
             }
         }
         try {
             parse(der);
         } catch (IOException ioe) {
             signedCert = null;
-            CertificateException ce = new
-                CertificateException("Unable to parse DER value of " +
-                                     "certificate, " + ioe);
-            ce.initCause(ioe);
-            throw ce;
+            throw new CertificateException("Unable to parse DER value of " +
+                                           "certificate, " + ioe, ioe);
         }
     }
 
@@ -320,10 +317,7 @@
             parse(derVal);
         } catch (IOException e) {
             signedCert = null;
-            CertificateException ce = new
-                CertificateException("Unable to initialize, " + e);
-            ce.initCause(e);
-            throw ce;
+            throw new CertificateException("Unable to initialize, " + e, e);
         }
     }
 
@@ -1070,6 +1064,32 @@
     }
 
     /**
+     * Return the issuing authority's key identifier bytes, or null
+     */
+    public byte[] getIssuerKeyIdentifier()
+    {
+        if (issuerKeyId == null) {
+            AuthorityKeyIdentifierExtension aki =
+                getAuthorityKeyIdentifierExtension();
+            if (aki != null) {
+
+                try {
+                    issuerKeyId = ((KeyIdentifier)
+                        aki.get(AuthorityKeyIdentifierExtension.KEY_ID))
+                            .getIdentifier();
+                } catch (IOException e) {
+                    // should never happen (because KEY_ID attr is supported)
+                }
+
+            } else {
+                issuerKeyId = new byte[0]; // no AKID present
+            }
+        }
+
+        return issuerKeyId.length != 0 ? issuerKeyId : null;
+    }
+
+    /**
      * Get BasicConstraints extension
      * @return BasicConstraints object or null (if no such object in
      * certificate)
@@ -1169,6 +1189,32 @@
     }
 
     /**
+     * Returns the subject's key identifier bytes, or null
+     */
+    public byte[] getSubjectKeyIdentifier()
+    {
+        if (subjectKeyId == null) {
+            SubjectKeyIdentifierExtension ski =
+                getSubjectKeyIdentifierExtension();
+            if (ski != null) {
+
+                try {
+                    subjectKeyId = ((KeyIdentifier)
+                        ski.get(SubjectKeyIdentifierExtension.KEY_ID))
+                            .getIdentifier();
+                } catch (IOException e) {
+                    // should never happen (because KEY_ID attr is supported)
+                }
+
+            } else {
+                subjectKeyId = new byte[0]; // no SKID present
+            }
+        }
+
+        return subjectKeyId.length != 0 ? subjectKeyId : null;
+    }
+
+    /**
      * Get CRLDistributionPoints extension
      * @return CRLDistributionPoints object or null (if no such object in
      * certificate)
@@ -1339,7 +1385,7 @@
 
                 for (Extension ex : exts.getAllExtensions()) {
                     ObjectIdentifier inCertOID = ex.getExtensionId();
-                    if (inCertOID.equals(findOID)) {
+                    if (inCertOID.equals((Object)findOID)) {
                         certExt = ex;
                         break;
                     }
@@ -1438,10 +1484,7 @@
                 new ExtendedKeyUsageExtension(Boolean.FALSE, data);
             return Collections.unmodifiableList(ekuExt.getExtendedKeyUsage());
         } catch (IOException ioe) {
-            CertificateParsingException cpe =
-                new CertificateParsingException();
-            cpe.initCause(ioe);
-            throw cpe;
+            throw new CertificateParsingException(ioe);
         }
     }
 
@@ -1582,8 +1625,8 @@
         }
         GeneralNames names;
         try {
-            names = (GeneralNames) subjectAltNameExt.get
-                (SubjectAlternativeNameExtension.SUBJECT_NAME);
+            names = (GeneralNames) subjectAltNameExt.get(
+                    SubjectAlternativeNameExtension.SUBJECT_NAME);
         } catch (IOException ioe) {
             // should not occur
             return Collections.<List<?>>emptySet();
@@ -1614,18 +1657,15 @@
 
             GeneralNames names;
             try {
-                names = (GeneralNames) subjectAltNameExt.get
-                    (SubjectAlternativeNameExtension.SUBJECT_NAME);
+                names = (GeneralNames) subjectAltNameExt.get(
+                        SubjectAlternativeNameExtension.SUBJECT_NAME);
             }  catch (IOException ioe) {
                 // should not occur
                 return Collections.<List<?>>emptySet();
             }
             return makeAltNames(names);
         } catch (IOException ioe) {
-            CertificateParsingException cpe =
-                new CertificateParsingException();
-            cpe.initCause(ioe);
-            throw cpe;
+            throw new CertificateParsingException(ioe);
         }
     }
 
@@ -1648,8 +1688,8 @@
         }
         GeneralNames names;
         try {
-            names = (GeneralNames) issuerAltNameExt.get
-                (IssuerAlternativeNameExtension.ISSUER_NAME);
+            names = (GeneralNames) issuerAltNameExt.get(
+                    IssuerAlternativeNameExtension.ISSUER_NAME);
         } catch (IOException ioe) {
             // should not occur
             return Collections.<List<?>>emptySet();
@@ -1680,18 +1720,15 @@
                                                     data);
             GeneralNames names;
             try {
-                names = (GeneralNames) issuerAltNameExt.get
-                    (IssuerAlternativeNameExtension.ISSUER_NAME);
+                names = (GeneralNames) issuerAltNameExt.get(
+                        IssuerAlternativeNameExtension.ISSUER_NAME);
             }  catch (IOException ioe) {
                 // should not occur
                 return Collections.<List<?>>emptySet();
             }
             return makeAltNames(names);
         } catch (IOException ioe) {
-            CertificateParsingException cpe =
-                new CertificateParsingException();
-            cpe.initCause(ioe);
-            throw cpe;
+            throw new CertificateParsingException(ioe);
         }
     }
 
--- a/src/share/native/sun/awt/image/jpeg/jpegdecoder.c	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/share/native/sun/awt/image/jpeg/jpegdecoder.c	Thu Jun 28 14:11:05 2012 -0700
@@ -337,7 +337,7 @@
     /* Save the data currently in the buffer */
     offset = src->pub.bytes_in_buffer;
     if (src->pub.next_input_byte > src->inbuf) {
-        memcpy(src->inbuf, src->pub.next_input_byte, offset);
+        memmove(src->inbuf, src->pub.next_input_byte, offset);
     }
     RELEASE_ARRAYS(env, src);
     buflen = (*env)->GetArrayLength(env, src->hInputBuffer) - offset;
--- a/src/solaris/classes/sun/print/CUPSPrinter.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/solaris/classes/sun/print/CUPSPrinter.java	Thu Jun 28 14:11:05 2012 -0700
@@ -273,14 +273,26 @@
                                          is);
                     is.close();
 
-                    if (responseMap.length > 0) {
+                    if (responseMap != null && responseMap.length > 0) {
                         defaultMap = responseMap[0];
                     }
 
                     if (defaultMap == null) {
                         os.close();
                         urlConnection.disconnect();
-                        return null;
+
+                        /* CUPS on OS X, as initially configured, considers the
+                         * default printer to be the last one used that's
+                         * presently available. So if no default was
+                         * reported, exec lpstat -d which has all the Apple
+                         * special behaviour for this built in.
+                         */
+                         if (UnixPrintServiceLookup.isMac()) {
+                             return UnixPrintServiceLookup.
+                                                   getDefaultPrinterNameSysV();
+                         } else {
+                             return null;
+                         }
                     }
 
                     AttributeClass attribClass = (AttributeClass)
--- a/src/solaris/classes/sun/print/UnixPrintServiceLookup.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/solaris/classes/sun/print/UnixPrintServiceLookup.java	Thu Jun 28 14:11:05 2012 -0700
@@ -115,6 +115,10 @@
             new sun.security.action.GetPropertyAction("os.name"));
     }
 
+    static boolean isMac() {
+        return osname.contains("OS X");
+    }
+
     static boolean isSysV() {
         return osname.equals("SunOS");
     }
@@ -213,7 +217,7 @@
                 }
             }
         } else {
-            if (isSysV()) {
+            if (isMac() || isSysV()) {
                 printers = getAllPrinterNamesSysV();
             } else { //BSD
                 printers = getAllPrinterNamesBSD();
@@ -362,7 +366,7 @@
         if (name == null || name.equals("") || !checkPrinterName(name)) {
             return null;
         }
-        if (isSysV()) {
+        if (isMac() || isSysV()) {
             printer = getNamedPrinterNameSysV(name);
         } else {
             printer = getNamedPrinterNameBSD(name);
@@ -524,7 +528,7 @@
         if (CUPSPrinter.isCupsRunning()) {
             defaultPrinter = CUPSPrinter.getDefaultPrinter();
         } else {
-            if (isSysV()) {
+            if (isMac() || isSysV()) {
                 defaultPrinter = getDefaultPrinterNameSysV();
             } else {
                 defaultPrinter = getDefaultPrinterNameBSD();
@@ -645,7 +649,7 @@
         return names;
     }
 
-    private String getDefaultPrinterNameSysV() {
+    static String getDefaultPrinterNameSysV() {
         String defaultPrinter = "lp";
         String command = "/usr/bin/lpstat -d";
 
--- a/src/solaris/native/sun/awt/awt_LoadLibrary.c	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/solaris/native/sun/awt/awt_LoadLibrary.c	Thu Jun 28 14:11:05 2012 -0700
@@ -110,7 +110,7 @@
     /* Check if toolkit is specified in env variable */
 #ifdef MACOSX
     envvar = getenv("AWT_TOOLKIT");
-    if ((envvar && strstr(envvar, "XToolkit")) || AWTIsHeadless()) {
+    if (envvar && strstr(envvar, "XToolkit")) {
 #endif
         fmanager = (*env)->NewStringUTF(env, "sun.awt.X11FontManager");
         tk = "/xawt/libmawt";
@@ -127,11 +127,15 @@
     }
 
     /* Calculate library name to load */
+#ifndef MACOSX
     if (AWTIsHeadless()) {
         strcpy(p, "/headless/libmawt");
     } else if (tk) {
+#endif
         strcpy(p, tk);
+#ifndef MACOSX
     }
+#endif
 
 #ifdef MACOSX
     strcat(p, ".dylib");
--- a/src/solaris/native/sun/awt/swing_GTKEngine.c	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/solaris/native/sun/awt/swing_GTKEngine.c	Thu Jun 28 14:11:05 2012 -0700
@@ -323,9 +323,8 @@
 JNIEXPORT void JNICALL Java_com_sun_java_swing_plaf_gtk_GTKEngine_native_1switch_1theme(
         JNIEnv *env, jobject this)
 {
-    fp_gdk_threads_enter();
+    // Note that flush_gtk_event_loop takes care of locks (7053002)
     flush_gtk_event_loop();
-    fp_gdk_threads_leave();
 }
 
 /*
--- a/src/windows/native/java/lang/java_props_md.c	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/java/lang/java_props_md.c	Thu Jun 28 14:11:05 2012 -0700
@@ -390,6 +390,7 @@
          * Windows 7                    6               1  (VER_NT_WORKSTATION)
          * Windows Server 2008 R2       6               1  (!VER_NT_WORKSTATION)
          * Windows 8                    6               2  (VER_NT_WORKSTATION)
+         * Windows Server 2012          6               2  (!VER_NT_WORKSTATION)
          *
          * This mapping will presumably be augmented as new Windows
          * versions are released.
@@ -453,6 +454,7 @@
                     switch (ver.dwMinorVersion) {
                     case  0: sprops.os_name = "Windows Server 2008";    break;
                     case  1: sprops.os_name = "Windows Server 2008 R2"; break;
+                    case  2: sprops.os_name = "Windows Server 2012";    break;
                     default: sprops.os_name = "Windows NT (unknown)";
                     }
                 }
--- a/src/windows/native/sun/net/www/protocol/http/ntlm/NTLMAuthSequence.c	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/net/www/protocol/http/ntlm/NTLMAuthSequence.c	Thu Jun 28 14:11:05 2012 -0700
@@ -151,7 +151,7 @@
 
     VOID        *pInput = 0;
     DWORD            inputLen;
-    CHAR         buffOut[512];
+    CHAR         buffOut[1024];
     jboolean         isCopy;
     SECURITY_STATUS      ss;
     SecBufferDesc        OutBuffDesc;
@@ -178,7 +178,7 @@
     OutBuffDesc.cBuffers  = 1;
     OutBuffDesc.pBuffers  = &OutSecBuff;
 
-    OutSecBuff.cbBuffer   = 512;
+    OutSecBuff.cbBuffer   = 1024;
     OutSecBuff.BufferType = SECBUFFER_TOKEN;
     OutSecBuff.pvBuffer   = buffOut;
 
--- a/src/windows/native/sun/nio/ch/SocketDispatcher.c	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/nio/ch/SocketDispatcher.c	Thu Jun 28 14:11:05 2012 -0700
@@ -141,41 +141,54 @@
 
 JNIEXPORT jint JNICALL
 Java_sun_nio_ch_SocketDispatcher_write0(JNIEnv *env, jclass clazz, jobject fdo,
-                                       jlong address, jint len)
+                                       jlong address, jint total)
 {
     /* set up */
     int i = 0;
     DWORD written = 0;
+    jint count = 0;
     jint fd = fdval(env, fdo);
     WSABUF buf;
 
-    /* limit size */
-    if (len > MAX_BUFFER_SIZE)
-        len = MAX_BUFFER_SIZE;
+    do {
+        /* limit size */
+        jint len = total - count;
+        if (len > MAX_BUFFER_SIZE)
+            len = MAX_BUFFER_SIZE;
 
-    /* copy iovec into WSABUF */
-    buf.buf = (char *)address;
-    buf.len = (u_long)len;
+        /* copy iovec into WSABUF */
+        buf.buf = (char *)address;
+        buf.len = (u_long)len;
 
-    /* read into the buffers */
-    i = WSASend((SOCKET)fd, /* Socket */
-            &buf,           /* pointers to the buffers */
-            (DWORD)1,       /* number of buffers to process */
-            &written,       /* receives number of bytes written */
-            0,              /* no flags */
-            0,              /* no overlapped sockets */
-            0);             /* no completion routine */
+        /* write from the buffer */
+        i = WSASend((SOCKET)fd,     /* Socket */
+                    &buf,           /* pointers to the buffers */
+                    (DWORD)1,       /* number of buffers to process */
+                    &written,       /* receives number of bytes written */
+                    0,              /* no flags */
+                    0,              /* no overlapped sockets */
+                    0);             /* no completion routine */
 
-    if (i == SOCKET_ERROR) {
-        int theErr = (jint)WSAGetLastError();
-        if (theErr == WSAEWOULDBLOCK) {
-            return IOS_UNAVAILABLE;
+        if (i == SOCKET_ERROR) {
+            if (count > 0) {
+                /* can't throw exception when some bytes have been written */
+                break;
+            } else {
+               int theErr = (jint)WSAGetLastError();
+               if (theErr == WSAEWOULDBLOCK) {
+                   return IOS_UNAVAILABLE;
+               }
+               JNU_ThrowIOExceptionWithLastError(env, "Write failed");
+               return IOS_THROWN;
+            }
         }
-        JNU_ThrowIOExceptionWithLastError(env, "Write failed");
-        return IOS_THROWN;
-    }
 
-    return convertReturnVal(env, (jint)written, JNI_FALSE);
+        count += written;
+        address += written;
+
+    } while ((count < total) && (written == MAX_BUFFER_SIZE));
+
+    return count;
 }
 
 JNIEXPORT jlong JNICALL
--- a/src/windows/native/sun/windows/awt_Component.cpp	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_Component.cpp	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, 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
@@ -1472,9 +1472,7 @@
           ::GetClientRect( GetHWnd(), &r );
           mr = WmSize(static_cast<UINT>(wParam), r.right - r.left, r.bottom - r.top);
           //mr = WmSize(wParam, LOWORD(lParam), HIWORD(lParam));
-          if (ImmGetContext() != NULL) {
-              SetCompositionWindow(r);
-          }
+          SetCompositionWindow(r);
           break;
       }
       case WM_SIZING:
@@ -1533,7 +1531,10 @@
               // When the window is deactivated, send WM_IME_ENDCOMPOSITION
               // message to deactivate the composition window so that
               // it won't receive keyboard input focus.
-              if (ImmGetContext() != NULL) {
+              HIMC hIMC;
+              HWND hwnd = ImmGetHWnd();
+              if ((hIMC = ImmGetContext(hwnd)) != NULL) {
+                  ImmReleaseContext(hwnd, hIMC);
                   DefWindowProc(WM_IME_ENDCOMPOSITION, 0, 0);
               }
           }
@@ -1716,11 +1717,9 @@
       case WM_IME_SETCONTEXT:
           // lParam is passed as pointer and it can be modified.
           mr = WmImeSetContext(static_cast<BOOL>(wParam), &lParam);
-          CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
           break;
       case WM_IME_NOTIFY:
           mr = WmImeNotify(wParam, lParam);
-          CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
           break;
       case WM_IME_STARTCOMPOSITION:
           mr = WmImeStartComposition();
@@ -3721,12 +3720,14 @@
 // support IME Composition messages
 void AwtComponent::SetCompositionWindow(RECT& r)
 {
-    HIMC hIMC = ImmGetContext();
+    HWND hwnd = ImmGetHWnd();
+    HIMC hIMC = ImmGetContext(hwnd);
     if (hIMC == NULL) {
         return;
     }
     COMPOSITIONFORM cf = {CFS_DEFAULT, {0, 0}, {0, 0, 0, 0}};
     ImmSetCompositionWindow(hIMC, &cf);
+    ImmReleaseContext(hwnd, hIMC);
 }
 
 void AwtComponent::OpenCandidateWindow(int x, int y)
@@ -3740,16 +3741,16 @@
             SetCandidateWindow(iCandType, x-rc.left, y-rc.top);
     }
     if (m_bitsCandType != 0) {
-        HWND proxy = GetProxyFocusOwner();
         // REMIND: is there any chance GetProxyFocusOwner() returns NULL here?
-        ::DefWindowProc((proxy != NULL) ? proxy : GetHWnd(),
+        ::DefWindowProc(ImmGetHWnd(),
                         WM_IME_NOTIFY, IMN_OPENCANDIDATE, m_bitsCandType);
     }
 }
 
 void AwtComponent::SetCandidateWindow(int iCandType, int x, int y)
 {
-    HIMC hIMC = ImmGetContext();
+    HWND hwnd = ImmGetHWnd();
+    HIMC hIMC = ImmGetContext(hwnd);
     CANDIDATEFORM cf;
     cf.dwIndex = iCandType;
     cf.dwStyle = CFS_CANDIDATEPOS;
@@ -3757,17 +3758,20 @@
     cf.ptCurrentPos.y = y;
 
     ImmSetCandidateWindow(hIMC, &cf);
+    ImmReleaseContext(hwnd, hIMC);
 }
 
 MsgRouting AwtComponent::WmImeSetContext(BOOL fSet, LPARAM *lplParam)
 {
     // If the Windows input context is disabled, do not let Windows
     // display any UIs.
-    HIMC hIMC = ImmGetContext();
+    HWND hwnd = ImmGetHWnd();
+    HIMC hIMC = ImmGetContext(hwnd);
     if (hIMC == NULL) {
         *lplParam = 0;
         return mrDoDefault;
     }
+    ImmReleaseContext(hwnd, hIMC);
 
     if (fSet) {
         LPARAM lParam = *lplParam;
@@ -3822,11 +3826,13 @@
     AwtInputTextInfor* textInfor = NULL;
 
     try {
-        HIMC hIMC = ImmGetContext();
+        HWND hwnd = ImmGetHWnd();
+        HIMC hIMC = ImmGetContext(hwnd);
         DASSERT(hIMC!=0);
 
         textInfor = new AwtInputTextInfor;
         textInfor->GetContextData(hIMC, flags);
+        ImmReleaseContext(hwnd, hIMC);
 
         jstring jtextString = textInfor->GetText();
         /* The conditions to send the input method event to AWT EDT are:
@@ -4010,16 +4016,15 @@
     DASSERT(!safe_ExceptionOccurred(env));
 }
 
-HIMC AwtComponent::ImmGetContext()
+HWND AwtComponent::ImmGetHWnd()
 {
     HWND proxy = GetProxyFocusOwner();
-    return ::ImmGetContext((proxy != NULL) ? proxy : GetHWnd());
+    return (proxy != NULL) ? proxy : GetHWnd();
 }
 
 HIMC AwtComponent::ImmAssociateContext(HIMC himc)
 {
-    HWND proxy = GetProxyFocusOwner();
-    return ::ImmAssociateContext((proxy != NULL) ? proxy : GetHWnd(), himc);
+    return ::ImmAssociateContext(ImmGetHWnd(), himc);
 }
 
 HWND AwtComponent::GetProxyFocusOwner()
--- a/src/windows/native/sun/windows/awt_Component.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_Component.h	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, 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
@@ -464,7 +464,7 @@
                               int caretPos, int visiblePos);
     void InquireCandidatePosition();
     INLINE LPARAM GetCandidateType() { return m_bitsCandType; }
-    HIMC ImmGetContext();
+    HWND ImmGetHWnd();
     HIMC ImmAssociateContext(HIMC himc);
     HWND GetProxyFocusOwner();
 
--- a/src/windows/native/sun/windows/awt_DesktopProperties.cpp	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_DesktopProperties.cpp	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2012, 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
@@ -70,6 +70,7 @@
     GetNonClientParameters();
     GetIconParameters();
     GetColorParameters();
+    GetCaretParameters();
     GetOtherParameters();
     GetSoundEvents();
     GetSystemProperties();
@@ -636,6 +637,10 @@
     SetSoundProperty(TEXT("win.sound.start"), TEXT("SystemStart"));
 }
 
+void AwtDesktopProperties::GetCaretParameters() {
+    SetIntegerProperty(TEXT("win.caret.width"), GetIntegerParameter(SPI_GETCARETWIDTH));
+}
+
 BOOL AwtDesktopProperties::GetBooleanParameter(UINT spi) {
     BOOL        flag;
     SystemParametersInfo(spi, 0, &flag, 0);
--- a/src/windows/native/sun/windows/awt_DesktopProperties.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_DesktopProperties.h	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2012, 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
@@ -64,6 +64,7 @@
         void GetColorParameters();
         void GetOtherParameters();
         void GetSoundEvents();
+        void GetCaretParameters();
 
         static BOOL GetBooleanParameter(UINT spi);
         static UINT GetIntegerParameter(UINT spi);
--- a/src/windows/native/sun/windows/awt_FileDialog.cpp	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_FileDialog.cpp	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, 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
@@ -156,6 +156,7 @@
             HIMC hIMC = ::ImmGetContext(hdlg);
             if (hIMC != NULL) {
                 ::ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
+                ::ImmReleaseContext(hdlg, hIMC);
             }
 
             WNDPROC lpfnWndProc = (WNDPROC)(::GetProp(parent, NativeDialogWndProcProp));
--- a/src/windows/native/sun/windows/awt_Frame.cpp	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_Frame.cpp	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, 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
@@ -319,8 +319,6 @@
         case WM_IME_STARTCOMPOSITION:
         case WM_IME_ENDCOMPOSITION:
         case WM_IME_COMPOSITION:
-        case WM_IME_SETCONTEXT:
-        case WM_IME_NOTIFY:
         case WM_IME_CONTROL:
         case WM_IME_COMPOSITIONFULL:
         case WM_IME_SELECT:
--- a/src/windows/native/sun/windows/awt_TextArea.cpp	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_TextArea.cpp	Thu Jun 28 14:11:05 2012 -0700
@@ -74,135 +74,10 @@
     AwtTextComponent::Dispose();
 }
 
-LPCTSTR AwtTextArea::GetClassName() {
-    static BOOL richedLibraryLoaded = FALSE;
-    if (!richedLibraryLoaded) {
-        JDK_LoadSystemLibrary("RICHED20.DLL");
-        richedLibraryLoaded = TRUE;
-    }
-    return RICHEDIT_CLASS;
-}
-
 /* Create a new AwtTextArea object and window.   */
 AwtTextArea* AwtTextArea::Create(jobject peer, jobject parent)
 {
-    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-
-    jobject target = NULL;
-    AwtTextArea* c = NULL;
-
-    try {
-        if (env->EnsureLocalCapacity(1) < 0) {
-            return NULL;
-        }
-
-        PDATA pData;
-        AwtCanvas* awtParent;
-        JNI_CHECK_PEER_GOTO(parent, done);
-
-        awtParent = (AwtCanvas*)pData;
-        JNI_CHECK_NULL_GOTO(awtParent, "null awtParent", done);
-
-        target = env->GetObjectField(peer, AwtObject::targetID);
-        JNI_CHECK_NULL_GOTO(target, "null target", done);
-
-        c = new AwtTextArea();
-
-        {
-            /* Adjust style for scrollbar visibility and word wrap  */
-          DWORD scroll_style;
-          jint scrollbarVisibility =
-              env->GetIntField(target, AwtTextArea::scrollbarVisibilityID);
-
-          switch (scrollbarVisibility) {
-            case java_awt_TextArea_SCROLLBARS_NONE:
-              scroll_style = ES_AUTOVSCROLL;
-              break;
-            case java_awt_TextArea_SCROLLBARS_VERTICAL_ONLY:
-              scroll_style = WS_VSCROLL | ES_AUTOVSCROLL;
-              break;
-            case java_awt_TextArea_SCROLLBARS_HORIZONTAL_ONLY:
-              scroll_style = WS_HSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL;
-              break;
-            case java_awt_TextArea_SCROLLBARS_BOTH:
-              scroll_style = WS_VSCROLL | WS_HSCROLL |
-                  ES_AUTOVSCROLL | ES_AUTOHSCROLL;
-              break;
-          }
-
-          /*
-           * Specify ES_DISABLENOSCROLL - RichEdit control style to disable
-           * scrollbars instead of hiding them when not needed.
-           */
-          DWORD style = WS_CHILD | WS_CLIPSIBLINGS | ES_LEFT | ES_MULTILINE |
-              ES_WANTRETURN | scroll_style | ES_DISABLENOSCROLL;
-          DWORD exStyle = WS_EX_CLIENTEDGE;
-          if (GetRTL()) {
-              exStyle |= WS_EX_RIGHT | WS_EX_LEFTSCROLLBAR;
-              if (GetRTLReadingOrder())
-                  exStyle |= WS_EX_RTLREADING;
-          }
-
-          jint x = env->GetIntField(target, AwtComponent::xID);
-          jint y = env->GetIntField(target, AwtComponent::yID);
-          jint width = env->GetIntField(target, AwtComponent::widthID);
-          jint height = env->GetIntField(target, AwtComponent::heightID);
-
-          c->CreateHWnd(env, L"", style, exStyle,
-                        x, y, width, height,
-                        awtParent->GetHWnd(),
-                        reinterpret_cast<HMENU>(static_cast<INT_PTR>(
-                awtParent->CreateControlID())),
-                        ::GetSysColor(COLOR_WINDOWTEXT),
-                        ::GetSysColor(COLOR_WINDOW),
-                        peer);
-
-          // Fix for 4753116.
-          // If it is not win95 (we are using Richedit 2.0)
-          // we set plain text mode, in which the control is
-          // similar to a standard edit control:
-          //  - The text in a plain text control can have only
-          //    one format.
-          //  - The user cannot paste rich text formats, such as RTF
-          //    or embedded objects into a plain text control.
-          //  - Rich text mode controls always have a default
-          //    end-of-document marker or carriage return,
-          //    to format paragraphs.
-          // kdm@sparc.spb.su
-          c->SendMessage(EM_SETTEXTMODE, TM_PLAINTEXT, 0);
-
-          c->m_backgroundColorSet = TRUE;
-          /* suppress inheriting parent's color. */
-          c->UpdateBackground(env, target);
-          c->SendMessage(EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN,
-                         MAKELPARAM(1, 1));
-          /*
-           * Fix for BugTraq Id 4260109.
-           * Set the text limit to the maximum.
-           * Use EM_EXLIMITTEXT for RichEdit controls.
-           * For some reason RichEdit 1.0 becomes read-only if the
-           * specified limit is greater than 0x7FFFFFFD.
-           */
-          c->SendMessage(EM_EXLIMITTEXT, 0, 0x7FFFFFFD);
-
-          /* Unregister RichEdit built-in drop target. */
-          VERIFY(::RevokeDragDrop(c->GetHWnd()) != DRAGDROP_E_INVALIDHWND);
-
-          /* To enforce CF_TEXT format for paste operations. */
-          VERIFY(c->SendMessage(EM_SETOLECALLBACK, 0,
-                                (LPARAM)&GetOleCallback()));
-
-          c->SendMessage(EM_SETEVENTMASK, 0, ENM_CHANGE);
-        }
-    } catch (...) {
-        env->DeleteLocalRef(target);
-        throw;
-    }
-
-done:
-    env->DeleteLocalRef(target);
-
-    return c;
+    return (AwtTextArea*) AwtTextComponent::Create(peer, parent, true);
 }
 
 void AwtTextArea::EditSetSel(CHARRANGE &cr) {
@@ -220,11 +95,6 @@
     SendMessage(EM_EXGETSEL, 0, reinterpret_cast<LPARAM>(&cr));
 }
 
-LONG AwtTextArea::EditGetCharFromPos(POINT& pt) {
-    return static_cast<LONG>(SendMessage(EM_CHARFROMPOS, 0,
-            reinterpret_cast<LPARAM>(&pt)));
-}
-
 /* Count how many '\n's are there in jStr */
 size_t AwtTextArea::CountNewLines(JNIEnv *env, jstring jStr, size_t maxlen)
 {
@@ -253,34 +123,6 @@
 
 BOOL AwtTextArea::InheritsNativeMouseWheelBehavior() {return true;}
 
-MsgRouting
-AwtTextArea::PreProcessMsg(MSG& msg)
-{
-    MsgRouting mr = mrPassAlong;
-    static BOOL bPassAlongWmLButtonUp = TRUE;
-
-    if (msg.message == WM_LBUTTONDBLCLK) {
-        bPassAlongWmLButtonUp = FALSE;
-    }
-
-    /*
-     * For some reason RichEdit 1.0 filters out WM_LBUTTONUP after
-     * WM_LBUTTONDBLCLK. To work around this "feature" we send WM_LBUTTONUP
-     * directly to the window procedure and consume instead of passing it
-     * to the next hook.
-     */
-    if (msg.message == WM_LBUTTONUP && bPassAlongWmLButtonUp == FALSE) {
-        SendMessage(WM_LBUTTONUP, msg.wParam, msg.lParam);
-        bPassAlongWmLButtonUp = TRUE;
-        mr = mrConsume;
-    }
-
-    if (mr == mrPassAlong) {
-        mr = AwtComponent::PreProcessMsg(msg);
-    }
-
-    return mr;
-}
 
 LRESULT
 AwtTextArea::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) {
@@ -800,54 +642,6 @@
     return returnVal;
 }
 
-/*
- * WM_CTLCOLOR is not sent by rich edit controls.
- * Use EM_SETCHARFORMAT and EM_SETBKGNDCOLOR to set
- * respectively foreground and background color.
- */
-void AwtTextArea::SetColor(COLORREF c) {
-    AwtComponent::SetColor(c);
-
-    CHARFORMAT cf;
-    memset(&cf, 0, sizeof(cf));
-    cf.cbSize = sizeof(cf);
-    cf.dwMask = CFM_COLOR;
-
-    cf.crTextColor = ::IsWindowEnabled(GetHWnd()) ? GetColor() : ::GetSysColor(COLOR_3DSHADOW);
-
-    /*
-     * The documentation for EM_GETCHARFORMAT is not exactly
-     * correct. It appears that wParam has the same meaning
-     * as for EM_SETCHARFORMAT. Our task is to secure that
-     * all the characters in the control have the required
-     * formatting. That's why we use SCF_ALL.
-     */
-    VERIFY(SendMessage(EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf));
-    VERIFY(SendMessage(EM_SETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cf));
-}
-
-/*
- * In responce to EM_SETBKGNDCOLOR rich edit changes
- * its bg color and repaints itself so we don't need
- * to force repaint.
- */
-void AwtTextArea::SetBackgroundColor(COLORREF c) {
-    AwtComponent::SetBackgroundColor(c);
-    SendMessage(EM_SETBKGNDCOLOR, (WPARAM)FALSE, (LPARAM)GetBackgroundColor());
-}
-
-/*
- * Disabled edit control has grayed foreground.
- * Disabled RichEdit 1.0 control has original foreground.
- * Thus we have to set grayed foreground manually.
- */
-void AwtTextArea::Enable(BOOL bEnable)
-{
-    AwtComponent::Enable(bEnable);
-
-    SetColor(GetColor());
-}
-
 
 /* Fix for 4776535, 4648702
  * If width is 0 or 1 Windows hides the horizontal scroll bar even
@@ -1048,133 +842,3 @@
 } /* extern "C" */
 
 
-AwtTextArea::OleCallback AwtTextArea::sm_oleCallback;
-
-/************************************************************************
- * Inner class OleCallback definition.
- */
-
-AwtTextArea::OleCallback::OleCallback() {
-    m_refs = 0;
-    AddRef();
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::QueryInterface(REFIID riid, LPVOID * ppvObj) {
-
-    TRY;
-
-    if (::IsEqualIID(riid, IID_IUnknown)) {
-        *ppvObj = (void __RPC_FAR *__RPC_FAR)(IUnknown*)this;
-        AddRef();
-        return S_OK;
-    } else if (::IsEqualIID(riid, IID_IRichEditOleCallback)) {
-        *ppvObj = (void __RPC_FAR *__RPC_FAR)(IRichEditOleCallback*)this;
-        AddRef();
-        return S_OK;
-    } else {
-        *ppvObj = NULL;
-        return E_NOINTERFACE;
-    }
-
-    CATCH_BAD_ALLOC_RET(E_OUTOFMEMORY);
-}
-
-STDMETHODIMP_(ULONG)
-AwtTextArea::OleCallback::AddRef() {
-    return ++m_refs;
-}
-
-STDMETHODIMP_(ULONG)
-AwtTextArea::OleCallback::Release() {
-    int refs;
-
-    if ((refs = --m_refs) == 0) delete this;
-
-    return (ULONG)refs;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::GetNewStorage(LPSTORAGE FAR * ppstg) {
-    return E_NOTIMPL;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::GetInPlaceContext(LPOLEINPLACEFRAME FAR * ppipframe,
-                                                 LPOLEINPLACEUIWINDOW FAR* ppipuiDoc,
-                                                 LPOLEINPLACEFRAMEINFO pipfinfo)
-{
-    return E_NOTIMPL;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::ShowContainerUI(BOOL fShow) {
-    return E_NOTIMPL;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::QueryInsertObject(LPCLSID pclsid,
-                                                 LPSTORAGE pstg,
-                                                 LONG cp) {
-    return NOERROR;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::DeleteObject(LPOLEOBJECT poleobj) {
-    return NOERROR;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::QueryAcceptData(LPDATAOBJECT pdataobj,
-                                               CLIPFORMAT *pcfFormat,
-                                               DWORD reco,
-                                               BOOL fReally,
-                                               HGLOBAL hMetaPict) {
-    if (reco == RECO_PASTE) {
-        // If CF_TEXT format is available edit controls will select it,
-        // otherwise if it is CF_UNICODETEXT is available it will be
-        // selected, otherwise if CF_OEMTEXT is available it will be selected.
-        if (::IsClipboardFormatAvailable(CF_TEXT)) {
-            *pcfFormat = CF_TEXT;
-        } else if (::IsClipboardFormatAvailable(CF_UNICODETEXT)) {
-            *pcfFormat = CF_UNICODETEXT;
-        } else if (::IsClipboardFormatAvailable(CF_OEMTEXT)) {
-            *pcfFormat = CF_OEMTEXT;
-        } else {
-            // Don't allow rich edit to paste clipboard data
-            // in other formats.
-            *pcfFormat = CF_TEXT;
-        }
-    }
-
-    return NOERROR;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::ContextSensitiveHelp(BOOL fEnterMode) {
-    return NOERROR;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::GetClipboardData(CHARRANGE *pchrg,
-                                                DWORD reco,
-                                                LPDATAOBJECT *ppdataobj) {
-    return E_NOTIMPL;
-}
-
-STDMETHODIMP
-AwtTextArea::OleCallback::GetDragDropEffect(BOOL fDrag,
-                                                 DWORD grfKeyState,
-                                                 LPDWORD pdwEffect) {
-
-    return E_NOTIMPL;
-}
-
-
-STDMETHODIMP
-AwtTextArea::OleCallback::GetContextMenu(WORD seltype,
-                                              LPOLEOBJECT lpoleobj,
-                                              CHARRANGE FAR * lpchrg,
-                                              HMENU FAR * lphmenu) {
-    return E_NOTIMPL;
-}
--- a/src/windows/native/sun/windows/awt_TextArea.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_TextArea.h	Thu Jun 28 14:11:05 2012 -0700
@@ -51,15 +51,11 @@
 
     virtual void Dispose();
 
-    LPCTSTR GetClassName();
-
     static AwtTextArea* Create(jobject self, jobject parent);
 
     static size_t CountNewLines(JNIEnv *env, jstring jStr, size_t maxlen);
     static size_t GetALength(JNIEnv* env, jstring jStr, size_t maxlen);
 
-    MsgRouting PreProcessMsg(MSG& msg);
-
     LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
     static LRESULT CALLBACK EditProc(HWND hWnd, UINT message,
                                      WPARAM wParam, LPARAM lParam);
@@ -72,9 +68,6 @@
 
     INLINE void SetIgnoreEnChange(BOOL b) { m_bIgnoreEnChange = b; }
 
-    virtual void SetColor(COLORREF c);
-    virtual void SetBackgroundColor(COLORREF c);
-    virtual void Enable(BOOL bEnable);
     virtual BOOL InheritsNativeMouseWheelBehavior();
     virtual void Reshape(int x, int y, int w, int h);
 
@@ -87,40 +80,8 @@
 
 protected:
 
-    /*****************************************************************
-     * Inner class OleCallback declaration.
-     */
-    class OleCallback : public IRichEditOleCallback {
-    public:
-        OleCallback();
-
-        STDMETHODIMP QueryInterface(REFIID riid, LPVOID * ppvObj);
-        STDMETHODIMP_(ULONG) AddRef();
-        STDMETHODIMP_(ULONG) Release();
-        STDMETHODIMP GetNewStorage(LPSTORAGE FAR * ppstg);
-        STDMETHODIMP GetInPlaceContext(LPOLEINPLACEFRAME FAR * ppipframe,
-                                       LPOLEINPLACEUIWINDOW FAR* ppipuiDoc,
-                                       LPOLEINPLACEFRAMEINFO pipfinfo);
-        STDMETHODIMP ShowContainerUI(BOOL fShow);
-        STDMETHODIMP QueryInsertObject(LPCLSID pclsid, LPSTORAGE pstg, LONG cp);
-        STDMETHODIMP DeleteObject(LPOLEOBJECT poleobj);
-        STDMETHODIMP QueryAcceptData(LPDATAOBJECT pdataobj, CLIPFORMAT *pcfFormat,
-                                     DWORD reco, BOOL fReally, HGLOBAL hMetaPict);
-        STDMETHODIMP ContextSensitiveHelp(BOOL fEnterMode);
-        STDMETHODIMP GetClipboardData(CHARRANGE *pchrg, DWORD reco,
-                                      LPDATAOBJECT *ppdataobj);
-        STDMETHODIMP GetDragDropEffect(BOOL fDrag, DWORD grfKeyState,
-                                       LPDWORD pdwEffect);
-        STDMETHODIMP GetContextMenu(WORD seltype, LPOLEOBJECT poleobj,
-                                    CHARRANGE FAR * pchrg, HMENU FAR * phmenu);
-    private:
-        ULONG             m_refs; // Reference count
-    };//OleCallback class
-
-    INLINE static OleCallback& GetOleCallback() { return sm_oleCallback; }
     void EditSetSel(CHARRANGE &cr);
     void EditGetSel(CHARRANGE &cr);
-    LONG EditGetCharFromPos(POINT& pt);
   private:
     // RichEdit 1.0 control generates EN_CHANGE notifications not only
     // on text changes, but also on any character formatting change.
@@ -140,8 +101,6 @@
     LONG    m_lVDeltaAccum;
 
 
-    static OleCallback sm_oleCallback;
-
 };
 
 #endif /* AWT_TEXTAREA_H */
--- a/src/windows/native/sun/windows/awt_TextComponent.cpp	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_TextComponent.cpp	Thu Jun 28 14:11:05 2012 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, 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,6 +25,8 @@
 
 #include "awt_Toolkit.h"
 #include "awt_TextComponent.h"
+#include "awt_TextArea.h"
+#include "awt_TextField.h"
 #include "awt_Canvas.h"
 
 #include "jni.h"
@@ -70,7 +72,152 @@
 }
 
 LPCTSTR AwtTextComponent::GetClassName() {
-    return TEXT("EDIT");  /* System provided edit control class */
+    static BOOL richedLibraryLoaded = FALSE;
+    if (!richedLibraryLoaded) {
+        JDK_LoadSystemLibrary("RICHED20.DLL");
+        richedLibraryLoaded = TRUE;
+    }
+    return RICHEDIT_CLASS;
+}
+
+/* Create a new AwtTextArea or AwtTextField object and window.   */
+AwtTextComponent* AwtTextComponent::Create(jobject peer, jobject parent, BOOL isMultiline)
+{
+    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
+
+    jobject target = NULL;
+    AwtTextComponent* c = NULL;
+
+    try {
+        if (env->EnsureLocalCapacity(1) < 0) {
+            return NULL;
+        }
+
+        PDATA pData;
+        AwtCanvas* awtParent;
+        JNI_CHECK_PEER_GOTO(parent, done);
+
+        awtParent = (AwtCanvas*)pData;
+        JNI_CHECK_NULL_GOTO(awtParent, "null awtParent", done);
+
+        target = env->GetObjectField(peer, AwtObject::targetID);
+        JNI_CHECK_NULL_GOTO(target, "null target", done);
+
+        if(isMultiline){
+            c = new AwtTextArea();
+        }else{
+            c = new AwtTextField();
+        }
+
+        {
+            /* Adjust style for scrollbar visibility and word wrap  */
+            DWORD scroll_style;
+
+            if(isMultiline){
+
+                 jint scrollbarVisibility =
+                     env->GetIntField(target, AwtTextArea::scrollbarVisibilityID);
+
+                 switch (scrollbarVisibility) {
+                     case java_awt_TextArea_SCROLLBARS_NONE:
+                         scroll_style = ES_AUTOVSCROLL;
+                         break;
+                     case java_awt_TextArea_SCROLLBARS_VERTICAL_ONLY:
+                         scroll_style = WS_VSCROLL | ES_AUTOVSCROLL;
+                         break;
+                     case java_awt_TextArea_SCROLLBARS_HORIZONTAL_ONLY:
+                         scroll_style = WS_HSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL;
+                         break;
+                     case java_awt_TextArea_SCROLLBARS_BOTH:
+                         scroll_style = WS_VSCROLL | WS_HSCROLL |
+                             ES_AUTOVSCROLL | ES_AUTOHSCROLL;
+                         break;
+                }
+            }
+
+          DWORD style = WS_CHILD | WS_CLIPSIBLINGS | ES_LEFT;
+
+          /*
+           * Specify ES_DISABLENOSCROLL - RichEdit control style to disable
+           * scrollbars instead of hiding them when not needed.
+           */
+          style |= isMultiline ?  ES_MULTILINE | ES_WANTRETURN | scroll_style
+              | ES_DISABLENOSCROLL : ES_AUTOHSCROLL;
+
+
+          DWORD exStyle = WS_EX_CLIENTEDGE;
+          if (GetRTL()) {
+              exStyle |= WS_EX_RIGHT | WS_EX_LEFTSCROLLBAR;
+              if (GetRTLReadingOrder())
+                  exStyle |= WS_EX_RTLREADING;
+          }
+
+
+          jint x = env->GetIntField(target, AwtComponent::xID);
+          jint y = env->GetIntField(target, AwtComponent::yID);
+          jint width = env->GetIntField(target, AwtComponent::widthID);
+          jint height = env->GetIntField(target, AwtComponent::heightID);
+
+          c->CreateHWnd(env, L"", style, exStyle,
+                        x, y, width, height,
+                        awtParent->GetHWnd(),
+                        reinterpret_cast<HMENU>(static_cast<INT_PTR>(
+                awtParent->CreateControlID())),
+                        ::GetSysColor(COLOR_WINDOWTEXT),
+                        ::GetSysColor(COLOR_WINDOW),
+                        peer);
+
+          // Fix for 4753116.
+          // If it is not win95 (we are using Richedit 2.0)
+          // we set plain text mode, in which the control is
+          // similar to a standard edit control:
+          //  - The text in a plain text control can have only
+          //    one format.
+          //  - The user cannot paste rich text formats, such as RTF
+          //    or embedded objects into a plain text control.
+          //  - Rich text mode controls always have a default
+          //    end-of-document marker or carriage return,
+          //    to format paragraphs.
+          // kdm@sparc.spb.su
+          c->SendMessage(EM_SETTEXTMODE, TM_PLAINTEXT, 0);
+
+          c->m_backgroundColorSet = TRUE;
+          /* suppress inheriting parent's color. */
+          c->UpdateBackground(env, target);
+          c->SendMessage(EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN,
+                         MAKELPARAM(1, 1));
+          /*
+           * Fix for BugTraq Id 4260109.
+           * Set the text limit to the maximum.
+           * Use EM_EXLIMITTEXT for RichEdit controls.
+           * For some reason RichEdit 1.0 becomes read-only if the
+           * specified limit is greater than 0x7FFFFFFD.
+           */
+          c->SendMessage(EM_EXLIMITTEXT, 0, 0x7FFFFFFD);
+
+          /* Unregister RichEdit built-in drop target. */
+          VERIFY(::RevokeDragDrop(c->GetHWnd()) != DRAGDROP_E_INVALIDHWND);
+
+          /* To enforce CF_TEXT format for paste operations. */
+          VERIFY(c->SendMessage(EM_SETOLECALLBACK, 0,
+                                (LPARAM)&GetOleCallback()));
+
+          c->SendMessage(EM_SETEVENTMASK, 0, ENM_CHANGE);
+        }
+    } catch (...) {
+        env->DeleteLocalRef(target);
+        throw;
+    }
+
+done:
+    env->DeleteLocalRef(target);
+
+    return c;
+}
+
+LONG AwtTextComponent::EditGetCharFromPos(POINT& pt) {
+    return static_cast<LONG>(SendMessage(EM_CHARFROMPOS, 0,
+            reinterpret_cast<LPARAM>(&pt)));
 }
 
 /* Set a suitable font to IME against the component font. */
@@ -189,7 +336,8 @@
 //im --- override to over the spot composition
 void AwtTextComponent::SetCompositionWindow(RECT& rc)
 {
-    HIMC hIMC = ImmGetContext();
+    HWND hwnd = ImmGetHWnd();
+    HIMC hIMC = ImmGetContext(hwnd);
     // rc is not used for text component.
     COMPOSITIONFORM cf = { CFS_FORCE_POSITION, {0,0}, {0,0,0,0} };
     GetCaretPos(&(cf.ptCurrentPos));
@@ -201,6 +349,7 @@
     LOGFONT lf;
     GetObject(m_hFont, sizeof(LOGFONT), &lf);
     ImmSetCompositionFont(hIMC, &lf);
+    ImmReleaseContext(hwnd, hIMC);
 }
 //im --- end
 
@@ -463,6 +612,54 @@
     delete ees;
 }
 
+/*
+ * Disabled edit control has grayed foreground.
+ * Disabled RichEdit 1.0 control has original foreground.
+ * Thus we have to set grayed foreground manually.
+ */
+void AwtTextComponent::Enable(BOOL bEnable)
+{
+    AwtComponent::Enable(bEnable);
+    SetColor(GetColor());
+}
+
+
+/*
+ * WM_CTLCOLOR is not sent by rich edit controls.
+ * Use EM_SETCHARFORMAT and EM_SETBKGNDCOLOR to set
+ * respectively foreground and background color.
+ */
+void AwtTextComponent::SetColor(COLORREF c) {
+    AwtComponent::SetColor(c);
+
+    CHARFORMAT cf;
+    memset(&cf, 0, sizeof(cf));
+    cf.cbSize = sizeof(cf);
+    cf.dwMask = CFM_COLOR;
+
+    cf.crTextColor = ::IsWindowEnabled(GetHWnd()) ? GetColor() : ::GetSysColor(COLOR_3DSHADOW);
+
+    /*
+     * The documentation for EM_GETCHARFORMAT is not exactly
+     * correct. It appears that wParam has the same meaning
+     * as for EM_SETCHARFORMAT. Our task is to secure that
+     * all the characters in the control have the required
+     * formatting. That's why we use SCF_ALL.
+     */
+    VERIFY(SendMessage(EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf));
+    VERIFY(SendMessage(EM_SETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cf));
+}
+
+/*
+ * In responce to EM_SETBKGNDCOLOR rich edit changes
+ * its bg color and repaints itself so we don't need
+ * to force repaint.
+ */
+void AwtTextComponent::SetBackgroundColor(COLORREF c) {
+    AwtComponent::SetBackgroundColor(c);
+    SendMessage(EM_SETBKGNDCOLOR, (WPARAM)FALSE, (LPARAM)GetBackgroundColor());
+}
+
 
 /************************************************************************
  * WTextComponentPeer native methods
@@ -623,6 +820,127 @@
     CATCH_BAD_ALLOC;
 }
 
+
+AwtTextComponent::OleCallback AwtTextComponent::sm_oleCallback;
+
+/************************************************************************
+ * Inner class OleCallback definition.
+ */
+
+AwtTextComponent::OleCallback::OleCallback() {
+    m_refs = 0;
+    AddRef();
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::QueryInterface(REFIID riid, LPVOID * ppvObj) {
+     if (::IsEqualIID(riid, IID_IUnknown) ||::IsEqualIID(riid, IID_IRichEditOleCallback)  ) {
+         *ppvObj = static_cast<IRichEditOleCallback*>(this);
+         AddRef();
+         return S_OK;
+     }
+     *ppvObj = NULL;
+     return E_NOINTERFACE;
+}
+
+
+STDMETHODIMP_(ULONG)
+AwtTextComponent::OleCallback::AddRef() {
+    return ++m_refs;
+}
+
+STDMETHODIMP_(ULONG)
+AwtTextComponent::OleCallback::Release() {
+    return (ULONG)--m_refs;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::GetNewStorage(LPSTORAGE FAR * ppstg) {
+    return E_NOTIMPL;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::GetInPlaceContext(LPOLEINPLACEFRAME FAR * ppipframe,
+                                                 LPOLEINPLACEUIWINDOW FAR* ppipuiDoc,
+                                                 LPOLEINPLACEFRAMEINFO pipfinfo)
+{
+    return E_NOTIMPL;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::ShowContainerUI(BOOL fShow) {
+    return E_NOTIMPL;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::QueryInsertObject(LPCLSID pclsid,
+                                                 LPSTORAGE pstg,
+                                                 LONG cp) {
+    return S_OK;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::DeleteObject(LPOLEOBJECT poleobj) {
+    return S_OK;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::QueryAcceptData(LPDATAOBJECT pdataobj,
+                                               CLIPFORMAT *pcfFormat,
+                                               DWORD reco,
+                                               BOOL fReally,
+                                               HGLOBAL hMetaPict) {
+    if (reco == RECO_PASTE) {
+        // If CF_TEXT format is available edit controls will select it,
+        // otherwise if it is CF_UNICODETEXT is available it will be
+        // selected, otherwise if CF_OEMTEXT is available it will be selected.
+        if (::IsClipboardFormatAvailable(CF_TEXT)) {
+            *pcfFormat = CF_TEXT;
+        } else if (::IsClipboardFormatAvailable(CF_UNICODETEXT)) {
+            *pcfFormat = CF_UNICODETEXT;
+        } else if (::IsClipboardFormatAvailable(CF_OEMTEXT)) {
+            *pcfFormat = CF_OEMTEXT;
+        } else {
+            // Don't allow rich edit to paste clipboard data
+            // in other formats.
+            *pcfFormat = CF_TEXT;
+        }
+    }
+
+    return S_OK;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::ContextSensitiveHelp(BOOL fEnterMode) {
+    return S_OK;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::GetClipboardData(CHARRANGE *pchrg,
+                                                DWORD reco,
+                                                LPDATAOBJECT *ppdataobj) {
+    return E_NOTIMPL;
+}
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::GetDragDropEffect(BOOL fDrag,
+                                                 DWORD grfKeyState,
+                                                 LPDWORD pdwEffect) {
+
+    return E_NOTIMPL;
+}
+
+
+STDMETHODIMP
+AwtTextComponent::OleCallback::GetContextMenu(WORD seltype,
+                                              LPOLEOBJECT lpoleobj,
+                                              CHARRANGE FAR * lpchrg,
+                                              HMENU FAR * lphmenu) {
+    return E_NOTIMPL;
+}
+
+
+
 //
 // Accessibility support
 //
--- a/src/windows/native/sun/windows/awt_TextComponent.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_TextComponent.h	Thu Jun 28 14:11:05 2012 -0700
@@ -47,6 +47,8 @@
 
     AwtTextComponent();
 
+    static AwtTextComponent* Create(jobject self, jobject parent, BOOL isMultiline);
+
     virtual LPCTSTR GetClassName();
 
     int RemoveCR(WCHAR *pStr);
@@ -71,6 +73,10 @@
 
     void SetFont(AwtFont* font);
 
+    virtual void Enable(BOOL bEnable);
+    virtual void SetColor(COLORREF c);
+    virtual void SetBackgroundColor(COLORREF c);
+
     /*
      * Windows message handler functions
      */
@@ -113,7 +119,40 @@
     // Used to prevent untrusted code from synthesizing a WM_PASTE message
     // by posting a <CTRL>-V KeyEvent
     BOOL    m_synthetic;
-    virtual LONG EditGetCharFromPos(POINT& pt) = 0;
+    LONG EditGetCharFromPos(POINT& pt);
+
+    /*****************************************************************
+     * Inner class OleCallback declaration.
+     */
+    class OleCallback : public IRichEditOleCallback {
+    public:
+        OleCallback();
+
+        STDMETHODIMP QueryInterface(REFIID riid, LPVOID * ppvObj);
+        STDMETHODIMP_(ULONG) AddRef();
+        STDMETHODIMP_(ULONG) Release();
+        STDMETHODIMP GetNewStorage(LPSTORAGE FAR * ppstg);
+        STDMETHODIMP GetInPlaceContext(LPOLEINPLACEFRAME FAR * ppipframe,
+                                       LPOLEINPLACEUIWINDOW FAR* ppipuiDoc,
+                                       LPOLEINPLACEFRAMEINFO pipfinfo);
+        STDMETHODIMP ShowContainerUI(BOOL fShow);
+        STDMETHODIMP QueryInsertObject(LPCLSID pclsid, LPSTORAGE pstg, LONG cp);
+        STDMETHODIMP DeleteObject(LPOLEOBJECT poleobj);
+        STDMETHODIMP QueryAcceptData(LPDATAOBJECT pdataobj, CLIPFORMAT *pcfFormat,
+                                     DWORD reco, BOOL fReally, HGLOBAL hMetaPict);
+        STDMETHODIMP ContextSensitiveHelp(BOOL fEnterMode);
+        STDMETHODIMP GetClipboardData(CHARRANGE *pchrg, DWORD reco,
+                                      LPDATAOBJECT *ppdataobj);
+        STDMETHODIMP GetDragDropEffect(BOOL fDrag, DWORD grfKeyState,
+                                       LPDWORD pdwEffect);
+        STDMETHODIMP GetContextMenu(WORD seltype, LPOLEOBJECT poleobj,
+                                    CHARRANGE FAR * pchrg, HMENU FAR * phmenu);
+    private:
+        ULONG             m_refs; // Reference count
+    };//OleCallback class
+
+    INLINE static OleCallback& GetOleCallback() { return sm_oleCallback; }
+
 
 private:
 
@@ -126,6 +165,7 @@
     HFONT m_hFont;
     //im --- end
 
+    static OleCallback sm_oleCallback;
 
     //
     // Accessibility support
--- a/src/windows/native/sun/windows/awt_TextField.cpp	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_TextField.cpp	Thu Jun 28 14:11:05 2012 -0700
@@ -42,84 +42,23 @@
  */
 
 AwtTextField::AwtTextField()
-    : m_initialRescrollFlag( true )
 {
 }
 
 /* Create a new AwtTextField object and window.   */
 AwtTextField* AwtTextField::Create(jobject peer, jobject parent)
 {
-    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-
-    jobject target = NULL;
-    AwtTextField* c = NULL;
-
-    try {
-        PDATA pData;
-        AwtCanvas* awtParent;
-        JNI_CHECK_PEER_GOTO(parent, done);
-        awtParent = (AwtCanvas*)pData;
-
-        JNI_CHECK_NULL_GOTO(awtParent, "null awtParent", done);
-
-        target = env->GetObjectField(peer, AwtObject::targetID);
-        JNI_CHECK_NULL_GOTO(target, "null target", done);
-
-        c = new AwtTextField();
-
-        {
-            DWORD style = WS_CHILD | WS_CLIPSIBLINGS |
-                ES_LEFT | ES_AUTOHSCROLL;
-            DWORD exStyle = WS_EX_CLIENTEDGE;
-            if (GetRTL()) {
-                exStyle |= WS_EX_RIGHT | WS_EX_LEFTSCROLLBAR;
-                if (GetRTLReadingOrder())
-                    exStyle |= WS_EX_RTLREADING;
-            }
-
-            jint x = env->GetIntField(target, AwtComponent::xID);
-            jint y = env->GetIntField(target, AwtComponent::yID);
-            jint width = env->GetIntField(target, AwtComponent::widthID);
-            jint height = env->GetIntField(target, AwtComponent::heightID);
-
-            c->CreateHWnd(env, L"", style, exStyle,
-                          x, y, width, height,
-                          awtParent->GetHWnd(),
-                          reinterpret_cast<HMENU>(static_cast<INT_PTR>(
-                awtParent->CreateControlID())),
-                          ::GetSysColor(COLOR_WINDOWTEXT),
-                          ::GetSysColor(COLOR_WINDOW),
-                          peer);
-
-            c->m_backgroundColorSet = TRUE;
-            /* suppress inheriting parent's color. */
-            c->UpdateBackground(env, target);
-            c->SendMessage(EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN,
-                           MAKELPARAM(1, 1));
-            /*
-             * Fix for BugTraq Id 4260109.
-             * Set the text limit to the maximum.
-             */
-            c->SendMessage(EM_SETLIMITTEXT);
-
-        }
-    } catch (...) {
-        env->DeleteLocalRef(target);
-        throw;
-    }
-
-done:
-    env->DeleteLocalRef(target);
-
-    return c;
+    return (AwtTextField*) AwtTextComponent::Create(peer, parent, false);
 }
 
 void AwtTextField::EditSetSel(CHARRANGE &cr) {
-    SendMessage(EM_SETSEL, cr.cpMin, cr.cpMax);
-}
+    SendMessage(EM_EXSETSEL, 0, reinterpret_cast<LPARAM>(&cr));
 
-LONG AwtTextField::EditGetCharFromPos(POINT& pt) {
-    return static_cast<LONG>(SendMessage(EM_CHARFROMPOS, 0, MAKELPARAM(pt.x, pt.y)));
+    // 6417581: force expected drawing
+    if (IS_WINVISTA && cr.cpMin == cr.cpMax) {
+        ::InvalidateRect(GetHWnd(), NULL, TRUE);
+    }
+
 }
 
 LRESULT AwtTextField::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
@@ -162,10 +101,18 @@
          * to allow dnd of the current selection.
          */
         if (msg->message == WM_LBUTTONDBLCLK) {
-            SetStartSelectionPos(static_cast<LONG>(SendMessage(
-                EM_FINDWORDBREAK, WB_MOVEWORDLEFT, lCurPos)));
-            SetEndSelectionPos(static_cast<LONG>(SendMessage(
-                EM_FINDWORDBREAK, WB_MOVEWORDRIGHT, lCurPos)));
+            jchar echo = SendMessage(EM_GETPASSWORDCHAR);
+
+            if(echo == 0){
+              SetStartSelectionPos(static_cast<LONG>(SendMessage(
+                  EM_FINDWORDBREAK, WB_MOVEWORDLEFT, lCurPos)));
+              SetEndSelectionPos(static_cast<LONG>(SendMessage(
+                  EM_FINDWORDBREAK, WB_MOVEWORDRIGHT, lCurPos)));
+            }else{
+              SetStartSelectionPos(0);
+              SetEndSelectionPos(GetTextLength());
+            }
+
         } else {
             SetStartSelectionPos(lCurPos);
             SetEndSelectionPos(lCurPos);
@@ -307,46 +254,6 @@
     delete secs;
 }
 
-void AwtTextField::Reshape(int x, int y, int w, int h)
-{
-    AwtTextComponent::Reshape( x, y, w, h );
-
-    // Another option would be to call this
-    // after WM_SIZE notification is handled
-    initialRescroll();
-}
-
-
-// Windows' Edit control features:
-// (i) if text selection is set while control's width or height is 0,
-//   text is scrolled oddly.
-// (ii) if control's size is changed, text seems never be automatically
-//   rescrolled.
-//
-// This method is designed for the following scenario: AWT spawns Edit
-// control with 0x0 dimensions, then sets text selection, then resizes the
-// control (couple of times). This might cause text appear undesirably scrolled.
-// So we reset/set selection again to rescroll text. (see also CR 6480547)
-void AwtTextField::initialRescroll()
-{
-    if( ! m_initialRescrollFlag ) {
-        return;
-    }
-
-    ::RECT r;
-    BOOL ok = ::GetClientRect( GetHWnd(), &r );
-    if( ! ok || r.right==0 || r.bottom==0 ) {
-        return;
-    }
-
-    m_initialRescrollFlag = false;
-
-    DWORD start, end;
-    SendMessage( EM_GETSEL, (WPARAM)&start, (LPARAM)&end );
-    SendMessage( EM_SETSEL, (WPARAM)0, (LPARAM)0 );
-    SendMessage( EM_SETSEL, (WPARAM)start, (LPARAM)end );
-}
-
 
 /************************************************************************
  * WTextFieldPeer native methods
--- a/src/windows/native/sun/windows/awt_TextField.h	Wed Jun 27 17:19:47 2012 -0700
+++ b/src/windows/native/sun/windows/awt_TextField.h	Thu Jun 28 14:11:05 2012 -0700
@@ -54,15 +54,11 @@
     // invoked on Toolkit thread
     static void _SetEchoChar(void *param);
 
-  protected:
-    LONG EditGetCharFromPos(POINT& pt);
-    virtual void Reshape(int x, int y, int w, int h);
+protected:
 
 private:
     void EditSetSel(CHARRANGE &cr);
-    void initialRescroll();
 
-    bool m_initialRescrollFlag;
 };
 
 #endif /* AWT_TEXTFIELD_H */
--- a/test/Makefile	Wed Jun 27 17:19:47 2012 -0700
+++ b/test/Makefile	Thu Jun 28 14:11:05 2012 -0700
@@ -472,6 +472,16 @@
 jdk_io: $(call TestDirs, java/io)
 	$(call RunAgentvmBatch)
 
+# Stable othervm testruns (minus items from PROBLEM_LIST)
+#   Using agentvm has serious problems with these tests
+ifdef OPENJDK
+jdk_jfr:
+else
+JDK_ALL_TARGETS += jdk_jfr
+jdk_jfr: $(call TestDirs, com/oracle/jfr)
+	$(call RunOthervmBatch)
+endif
+
 # Stable agentvm testruns (minus items from PROBLEM_LIST)
 JDK_ALL_TARGETS += jdk_lang
 jdk_lang: $(call TestDirs, java/lang)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Dialog/ModalDialogPermission/ModalDialogPermission.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2012, 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.Dialog;
+import java.awt.Frame;
+import java.util.Timer;
+import java.util.TimerTask;
+
+/*
+  @test
+  @bug 7080109
+  @summary Dialog.show() lacks doPrivileged() to access system event queue.
+  @author sergey.bylokhov@oracle.com: area=awt.dialog
+  @run main/othervm/policy=java.policy -Djava.security.manager ModalDialogPermission
+*/
+public final class ModalDialogPermission {
+
+    public static void main(final String[] args) {
+        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
+            @Override
+            public void uncaughtException(final Thread t, final Throwable e) {
+                throw new RuntimeException(e);
+            }
+        });
+        final Frame frame = new Frame();
+        final Dialog dialog = new Dialog(frame, "ModalDialog", true);
+        final Timer t = new Timer();
+        t.schedule(new TimerTask() {
+
+            @Override
+            public void run() {
+                dialog.setVisible(false);
+                dialog.dispose();
+            }
+        }, 3000L);
+        dialog.show();
+        frame.dispose();
+        t.cancel();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Dialog/ModalDialogPermission/java.policy	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,3 @@
+grant {
+    permission java.lang.RuntimePermission "setDefaultUncaughtExceptionHandler";
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Frame/7024749/bug7024749.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2012, 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 7024749
+ * @summary JDK7 b131---a crash in: Java_sun_awt_windows_ThemeReader_isGetThemeTransitionDurationDefined+0x75
+ * @library ../../../regtesthelpers
+ * @build Util
+ * @author Oleg Pekhovskiy: area=awt.toplevel
+   @run main bug7024749
+ */
+
+import java.awt.*;
+import test.java.awt.regtesthelpers.Util;
+
+public class bug7024749 {
+    public static void main(String[] args) {
+        final Frame f = new Frame("F");
+        f.setBounds(0,0,200,200);
+        f.setEnabled(false); // <- disable the top-level
+        f.setVisible(true);
+
+        Window w = new Window(f);
+        w.setBounds(300,300,300,300);
+        w.add(new TextField(20));
+        w.setVisible(true);
+
+        Robot robot = Util.createRobot();
+        robot.setAutoDelay(1000);
+        Util.waitForIdle(robot);
+        robot.delay(1000);
+        Util.clickOnTitle(f, robot);
+        Util.waitForIdle(robot);
+
+        f.dispose();
+        System.out.println("Test passed!");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Mouse/EnterExitEvents/DragWindowOutOfFrameTest.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,267 @@
+/*
+ * Copyright (c) 2005, 2006, 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 7154048
+ * @summary Window created under a mouse does not receive mouse enter event.
+ *     Mouse Entered/Exited events should be generated during dragging the window
+ *     out of the frame and to the frame.
+ * @library ../../regtesthelpers
+ * @build Util
+ * @author alexandr.scherbatiy area=awt.event
+ * @run main DragWindowOutOfFrameTest
+ */
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+
+import java.util.concurrent.*;
+import sun.awt.SunToolkit;
+
+import test.java.awt.regtesthelpers.Util;
+
+public class DragWindowOutOfFrameTest {
+
+    private static volatile int dragWindowMouseEnteredCount = 0;
+    private static volatile int dragWindowMouseExitedCount = 0;
+    private static volatile int dragWindowMouseReleasedCount = 0;
+    private static volatile int buttonMouseEnteredCount = 0;
+    private static volatile int buttonMouseExitedCount = 0;
+    private static volatile int labelMouseEnteredCount = 0;
+    private static volatile int labelMouseExitedCount = 0;
+    private static volatile int labelMouseReleasedCount = 0;
+    private static MyDragWindow dragWindow;
+    private static JLabel label;
+    private static JButton button;
+
+    public static void main(String[] args) throws Exception {
+
+        SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+        Robot robot = new Robot();
+        robot.setAutoDelay(50);
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                createAndShowGUI();
+            }
+        });
+
+        toolkit.realSync();
+
+        Point pointToClick = Util.invokeOnEDT(new Callable<Point>() {
+
+            @Override
+            public Point call() throws Exception {
+                return getCenterPoint(label);
+            }
+        });
+
+
+        robot.mouseMove(pointToClick.x, pointToClick.y);
+        robot.mousePress(InputEvent.BUTTON1_MASK);
+        toolkit.realSync();
+
+        if (dragWindowMouseEnteredCount != 1 && dragWindowMouseExitedCount != 0) {
+            throw new RuntimeException(
+                    "Wrong number mouse Entered/Exited events on Drag Window!");
+        }
+
+        Point pointToDrag = Util.invokeOnEDT(new Callable<Point>() {
+
+            @Override
+            public Point call() throws Exception {
+                label.addMouseListener(new LabelMouseListener());
+                button.addMouseListener(new ButtonMouseListener());
+                return getCenterPoint(button);
+            }
+        });
+
+        robot.mouseMove(450, pointToClick.y);
+        toolkit.realSync();
+
+        if (labelMouseEnteredCount != 0 && labelMouseExitedCount != 1) {
+            throw new RuntimeException(
+                    "Wrong number Mouse Entered/Exited events on label!");
+        }
+
+        robot.mouseMove(450, pointToDrag.y);
+        toolkit.realSync();
+
+        if (labelMouseEnteredCount != 0 && labelMouseExitedCount != 1) {
+            throw new RuntimeException(
+                    "Wrong number Mouse Entered/Exited events on label!");
+        }
+
+        if (buttonMouseEnteredCount != 0 && buttonMouseExitedCount != 0) {
+            throw new RuntimeException(
+                    "Wrong number Mouse Entered/Exited events on button!");
+        }
+
+        robot.mouseMove(pointToDrag.y, pointToDrag.y);
+        toolkit.realSync();
+
+        if (buttonMouseEnteredCount != 1 && buttonMouseExitedCount != 0) {
+            throw new RuntimeException(
+                    "Wrong number Mouse Entered/Exited events on button!");
+        }
+
+        robot.mouseRelease(InputEvent.BUTTON1_MASK);
+        toolkit.realSync();
+
+        if (labelMouseReleasedCount != 1) {
+            throw new RuntimeException("No MouseReleased event on label!");
+        }
+    }
+
+    private static Point getCenterPoint(Component comp) {
+        Point p = comp.getLocationOnScreen();
+        Rectangle rect = comp.getBounds();
+        return new Point(p.x + rect.width / 2, p.y + rect.height / 2);
+    }
+
+    private static void createAndShowGUI() {
+
+        JFrame frame = new JFrame("Main Frame");
+        frame.setLocation(100, 100);
+        frame.setSize(300, 200);
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+        label = new JLabel("Label");
+
+        DragWindowCreationMouseListener listener = new DragWindowCreationMouseListener(frame);
+        label.addMouseListener(listener);
+        label.addMouseMotionListener(listener);
+
+        button = new JButton("Button");
+        Panel panel = new Panel(new BorderLayout());
+
+        panel.add(label, BorderLayout.NORTH);
+        panel.add(button, BorderLayout.CENTER);
+
+        frame.getContentPane().add(panel);
+        frame.setVisible(true);
+
+    }
+
+    private static Point getAbsoluteLocation(MouseEvent e) {
+        return new Point(e.getXOnScreen(), e.getYOnScreen());
+    }
+
+    static class MyDragWindow extends Window {
+
+        public MyDragWindow(Window parent, Point location) {
+            super(parent);
+            setSize(500, 300);
+            setVisible(true);
+            JPanel panel = new JPanel();
+            add(panel);
+            setLocation(location.x - 250, location.y - 150);
+            addMouseListener(new DragWindowMouseListener());
+        }
+
+        void dragTo(Point point) {
+            setLocation(point.x - 250, point.y - 150);
+        }
+    }
+
+    static class DragWindowCreationMouseListener extends MouseAdapter {
+
+        Point origin;
+        Window parent;
+
+        public DragWindowCreationMouseListener(Window parent) {
+            this.parent = parent;
+        }
+
+        @Override
+        public void mousePressed(MouseEvent e) {
+            if (dragWindow == null) {
+                dragWindow = new MyDragWindow(parent, getAbsoluteLocation(e));
+            } else {
+                dragWindow.setVisible(true);
+                dragWindow.dragTo(getAbsoluteLocation(e));
+            }
+        }
+
+        @Override
+        public void mouseReleased(MouseEvent e) {
+            labelMouseReleasedCount++;
+            if (dragWindow != null) {
+                dragWindow.setVisible(false);
+            }
+        }
+
+        public void mouseDragged(MouseEvent e) {
+            if (dragWindow != null) {
+                dragWindow.dragTo(getAbsoluteLocation(e));
+            }
+        }
+    }
+
+    static class DragWindowMouseListener extends MouseAdapter {
+
+        @Override
+        public void mouseEntered(MouseEvent e) {
+            dragWindowMouseEnteredCount++;
+        }
+
+        @Override
+        public void mouseExited(MouseEvent e) {
+            dragWindowMouseExitedCount++;
+        }
+
+        @Override
+        public void mouseReleased(MouseEvent e) {
+            dragWindowMouseReleasedCount++;
+        }
+    }
+
+    static class LabelMouseListener extends MouseAdapter {
+
+        @Override
+        public void mouseEntered(MouseEvent e) {
+            labelMouseEnteredCount++;
+        }
+
+        @Override
+        public void mouseExited(MouseEvent e) {
+            labelMouseExitedCount++;
+        }
+    }
+
+    static class ButtonMouseListener extends MouseAdapter {
+
+        @Override
+        public void mouseEntered(MouseEvent e) {
+            buttonMouseEnteredCount++;
+        }
+
+        @Override
+        public void mouseExited(MouseEvent e) {
+            buttonMouseExitedCount++;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Mouse/EnterExitEvents/DragWindowTest.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,219 @@
+/*
+ * Copyright (c) 2005, 2006, 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 7154048
+ * @summary Window created under a mouse does not receive mouse enter event.
+ *     Mouse Entered/Exited events are wrongly generated during dragging the window
+ *     from one component to another
+ * @library ../../regtesthelpers
+ * @build Util
+ * @author alexandr.scherbatiy area=awt.event
+ * @run main DragWindowTest
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+
+import java.util.concurrent.*;
+import sun.awt.SunToolkit;
+
+import test.java.awt.regtesthelpers.Util;
+
+public class DragWindowTest {
+
+    private static volatile int dragWindowMouseEnteredCount = 0;
+    private static volatile int dragWindowMouseReleasedCount = 0;
+    private static volatile int buttonMouseEnteredCount = 0;
+    private static volatile int labelMouseReleasedCount = 0;
+    private static MyDragWindow dragWindow;
+    private static JLabel label;
+    private static JButton button;
+
+    public static void main(String[] args) throws Exception {
+
+        SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+        Robot robot = new Robot();
+        robot.setAutoDelay(50);
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                createAndShowGUI();
+            }
+        });
+
+        toolkit.realSync();
+
+        Point pointToClick = Util.invokeOnEDT(new Callable<Point>() {
+
+            @Override
+            public Point call() throws Exception {
+                return getCenterPoint(label);
+            }
+        });
+
+
+        robot.mouseMove(pointToClick.x, pointToClick.y);
+        robot.mousePress(InputEvent.BUTTON1_MASK);
+        toolkit.realSync();
+
+        if (dragWindowMouseEnteredCount != 1) {
+            throw new RuntimeException("No MouseEntered event on Drag Window!");
+        }
+
+        Point pointToDrag = Util.invokeOnEDT(new Callable<Point>() {
+
+            @Override
+            public Point call() throws Exception {
+                button.addMouseListener(new ButtonMouseListener());
+                return getCenterPoint(button);
+            }
+        });
+
+        robot.mouseMove(pointToDrag.x, pointToDrag.y);
+        toolkit.realSync();
+
+        if (buttonMouseEnteredCount != 0) {
+            throw new RuntimeException("Extra MouseEntered event on button!");
+        }
+
+        robot.mouseRelease(InputEvent.BUTTON1_MASK);
+        toolkit.realSync();
+
+        if (labelMouseReleasedCount != 1) {
+            throw new RuntimeException("No MouseReleased event on label!");
+        }
+
+    }
+
+    private static Point getCenterPoint(Component comp) {
+        Point p = comp.getLocationOnScreen();
+        Rectangle rect = comp.getBounds();
+        return new Point(p.x + rect.width / 2, p.y + rect.height / 2);
+    }
+
+    private static void createAndShowGUI() {
+
+        JFrame frame = new JFrame("Main Frame");
+        frame.setSize(300, 200);
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+        label = new JLabel("Label");
+
+        LabelMouseListener listener = new LabelMouseListener(frame);
+        label.addMouseListener(listener);
+        label.addMouseMotionListener(listener);
+
+        button = new JButton("Button");
+        Panel panel = new Panel(new BorderLayout());
+
+        panel.add(label, BorderLayout.NORTH);
+        panel.add(button, BorderLayout.CENTER);
+
+        frame.getContentPane().add(panel);
+        frame.setVisible(true);
+
+    }
+
+    private static Point getAbsoluteLocation(MouseEvent e) {
+        return new Point(e.getXOnScreen(), e.getYOnScreen());
+    }
+
+    static class MyDragWindow extends Window {
+
+        static int d = 30;
+
+        public MyDragWindow(Window parent, Point location) {
+            super(parent);
+            setSize(150, 150);
+            setVisible(true);
+            JPanel panel = new JPanel();
+            add(panel);
+            setLocation(location.x - d, location.y - d);
+            addMouseListener(new DragWindowMouseListener());
+        }
+
+        void dragTo(Point point) {
+            setLocation(point.x - d, point.y - d);
+        }
+    }
+
+    static class LabelMouseListener extends MouseAdapter {
+
+        Point origin;
+        Window parent;
+
+        public LabelMouseListener(Window parent) {
+            this.parent = parent;
+        }
+
+        @Override
+        public void mousePressed(MouseEvent e) {
+            if (dragWindow == null) {
+                dragWindow = new MyDragWindow(parent, getAbsoluteLocation(e));
+            } else {
+                dragWindow.setVisible(true);
+                dragWindow.dragTo(getAbsoluteLocation(e));
+            }
+        }
+
+        @Override
+        public void mouseReleased(MouseEvent e) {
+            labelMouseReleasedCount++;
+            if (dragWindow != null) {
+                dragWindow.setVisible(false);
+            }
+        }
+
+        public void mouseDragged(MouseEvent e) {
+            if (dragWindow != null) {
+                dragWindow.dragTo(getAbsoluteLocation(e));
+            }
+        }
+    }
+
+    static class DragWindowMouseListener extends MouseAdapter {
+
+        @Override
+        public void mouseEntered(MouseEvent e) {
+            dragWindowMouseEnteredCount++;
+        }
+
+        @Override
+        public void mouseReleased(MouseEvent e) {
+            dragWindowMouseReleasedCount++;
+        }
+    }
+
+    static class ButtonMouseListener extends MouseAdapter {
+
+        @Override
+        public void mouseEntered(MouseEvent e) {
+            buttonMouseEnteredCount++;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2005, 2006, 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 7154048
+ * @summary Programmatically resized  window does not receive mouse entered/exited events
+ * @author  alexandr.scherbatiy area=awt.event
+ * @run main ResizingFrameTest
+ */
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+import sun.awt.SunToolkit;
+
+public class ResizingFrameTest {
+
+    private static volatile int mouseEnteredCount = 0;
+    private static volatile int mouseExitedCount = 0;
+    private static JFrame frame;
+
+    public static void main(String[] args) throws Exception {
+
+        SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+        Robot robot = new Robot();
+        robot.setAutoDelay(50);
+        robot.mouseMove(100, 100);
+
+        // create a frame under the mouse cursor
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                createAndShowGUI();
+            }
+        });
+
+
+        toolkit.realSync();
+
+        if (mouseEnteredCount != 1 || mouseExitedCount != 0) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+
+        // iconify frame
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                frame.setExtendedState(Frame.ICONIFIED);
+            }
+        });
+
+        toolkit.realSync();
+        robot.delay(200);
+
+        if (mouseEnteredCount != 1 || mouseExitedCount != 1) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+
+        // deiconify frame
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                frame.setExtendedState(Frame.NORMAL);
+            }
+        });
+
+        toolkit.realSync();
+        robot.delay(200);
+
+        if (mouseEnteredCount != 2 || mouseExitedCount != 1) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+
+        // move the mouse out of the frame
+        robot.mouseMove(500, 500);
+        toolkit.realSync();
+        robot.delay(200);
+
+        if (mouseEnteredCount != 2 || mouseExitedCount != 2) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+
+        // maximize the frame
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                frame.setExtendedState(Frame.MAXIMIZED_BOTH);
+            }
+        });
+
+        toolkit.realSync();
+        robot.delay(200);
+
+        if (mouseEnteredCount != 3 || mouseExitedCount != 2) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+
+
+        // demaximize the frame
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                frame.setExtendedState(Frame.NORMAL);
+            }
+        });
+
+        toolkit.realSync();
+        robot.delay(200);
+
+        if (mouseEnteredCount != 3 || mouseExitedCount != 3) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+
+        }
+
+        // move the frame under the mouse
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                frame.setLocation(400, 400);
+            }
+        });
+
+        toolkit.realSync();
+        robot.delay(200);
+
+        if (mouseEnteredCount != 4 || mouseExitedCount != 3) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+
+        // move the frame out of the mouse
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                frame.setLocation(100, 100);
+            }
+        });
+
+        toolkit.realSync();
+        robot.delay(400);
+
+        if (mouseEnteredCount != 4 || mouseExitedCount != 4) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+
+        // enlarge the frame bounds
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                frame.setBounds(100, 100, 800, 800);
+            }
+        });
+
+        toolkit.realSync();
+        robot.delay(200);
+
+        if (mouseEnteredCount != 5 || mouseExitedCount != 4) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+
+        // make the frame bounds smaller
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                frame.setBounds(100, 100, 200, 300);
+            }
+        });
+
+        toolkit.realSync();
+        robot.delay(400);
+
+
+        if (mouseEnteredCount != 5 || mouseExitedCount != 5) {
+            throw new RuntimeException("No Mouse Entered/Exited events!");
+        }
+    }
+
+    private static void createAndShowGUI() {
+
+        frame = new JFrame("Main Frame");
+        frame.setSize(300, 200);
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+        frame.addMouseListener(new MouseAdapter() {
+
+            @Override
+            public void mouseEntered(MouseEvent e) {
+                mouseEnteredCount++;
+            }
+
+            @Override
+            public void mouseExited(MouseEvent e) {
+                mouseExitedCount++;
+            }
+        });
+
+        frame.setVisible(true);
+    }
+}
\ No newline at end of file
--- a/test/java/awt/regtesthelpers/Util.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/test/java/awt/regtesthelpers/Util.java	Thu Jun 28 14:11:05 2012 -0700
@@ -607,4 +607,34 @@
                                 time, printEvent);
 
     }
+
+
+    /**
+     * Invokes the <code>task</code> on the EDT thread.
+     *
+     * @return result of the <code>task</code>
+     */
+    public static <T> T invokeOnEDT(final java.util.concurrent.Callable<T> task) throws Exception {
+        final java.util.List<T> result = new java.util.ArrayList<T>(1);
+        final Exception[] exception = new Exception[1];
+
+        javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                try {
+                    result.add(task.call());
+                } catch (Exception e) {
+                    exception[0] = e;
+                }
+            }
+        });
+
+        if (exception[0] != null) {
+            throw exception[0];
+        }
+
+        return result.get(0);
+    }
+
 }
--- a/test/java/nio/channels/AsyncCloseAndInterrupt.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/test/java/nio/channels/AsyncCloseAndInterrupt.java	Thu Jun 28 14:11:05 2012 -0700
@@ -644,9 +644,9 @@
         initPipes();
         initFile();
 
-        if (TestUtil.onME()) {
+        if (TestUtil.onWindows()) {
             log.println("WARNING: Cannot test FileChannel transfer operations"
-                        + " on Windows 95/98/ME");
+                        + " on Windows");
         } else {
             test(diskFileChannelFactory, TRANSFER_TO);
             test(diskFileChannelFactory, TRANSFER_FROM);
--- a/test/java/nio/channels/SocketChannel/AdaptSocket.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/test/java/nio/channels/SocketChannel/AdaptSocket.java	Thu Jun 28 14:11:05 2012 -0700
@@ -28,9 +28,7 @@
 
 import java.io.*;
 import java.net.*;
-import java.nio.*;
 import java.nio.channels.*;
-import java.nio.charset.*;
 
 
 public class AdaptSocket {
@@ -136,9 +134,8 @@
         out.println("timeout: " + so.getSoTimeout());
 
         testRead(so, shouldTimeout);
-        if (!TestUtil.onME())
-            for (int i = 0; i < 4; i++)
-                testRead(so, shouldTimeout);
+        for (int i = 0; i < 4; i++)
+            testRead(so, shouldTimeout);
 
         sc.close();
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/nio/channels/SocketChannel/CloseDuringWrite.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2012, 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
+ * @summary Test asynchronous close during a blocking write
+ */
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import java.net.*;
+import java.util.concurrent.*;
+import java.util.Random;
+
+public class CloseDuringWrite {
+
+    static final Random rand = new Random();
+
+    /**
+     * A task that closes a Closeable
+     */
+    static class Closer implements Callable<Void> {
+        final Closeable c;
+        Closer(Closeable c) {
+            this.c = c;
+        }
+        public Void call() throws IOException {
+            c.close();
+            return null;
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
+        try {
+            try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
+                ssc.bind(new InetSocketAddress(0));
+                InetAddress lh = InetAddress.getLocalHost();
+                int port = ssc.socket().getLocalPort();
+                SocketAddress sa = new InetSocketAddress(lh, port);
+
+                ByteBuffer bb = ByteBuffer.allocate(2*1024*1024);
+
+                for (int i=0; i<20; i++) {
+                    try (SocketChannel source = SocketChannel.open(sa);
+                         SocketChannel sink = ssc.accept())
+                    {
+                        // schedule channel to be closed
+                        Closer c = new Closer(source);
+                        int when = 1000 + rand.nextInt(2000);
+                        Future<Void> result = pool.schedule(c, when, TimeUnit.MILLISECONDS);
+
+                        // the write should either succeed or else throw a
+                        // ClosedChannelException (more likely an
+                        // AsynchronousCloseException)
+                        try {
+                            for (;;) {
+                                int limit = rand.nextInt(bb.capacity());
+                                bb.position(0);
+                                bb.limit(limit);
+                                int n = source.write(bb);
+                                System.out.format("wrote %d, expected %d%n", n, limit);
+                            }
+                        } catch (ClosedChannelException expected) {
+                            System.out.println(expected + " (expected)");
+                        } finally {
+                            result.get();
+                        }
+                    }
+                }
+            }
+        } finally {
+            pool.shutdown();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/nio/channels/SocketChannel/ShortWrite.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2012, 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 7176630
+ * @summary Check for short writes on SocketChannels configured in blocking mode
+ */
+
+import java.net.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import java.util.concurrent.*;
+import java.util.Random;
+import java.util.zip.CRC32;
+
+public class ShortWrite {
+
+    static final Random rand = new Random();
+
+    /**
+     * Returns a checksum on the remaining bytes in the given buffer.
+     */
+    static long computeChecksum(ByteBuffer bb) {
+        CRC32 crc32 = new CRC32();
+        crc32.update(bb.array());
+        return crc32.getValue();
+    }
+
+    /**
+     * A task that reads the expected number of bytes and returns the CRC32
+     * of those bytes.
+     */
+    static class Reader implements Callable<Long> {
+        final SocketChannel sc;
+        final ByteBuffer buf;
+
+        Reader(SocketChannel sc, int expectedSize) {
+            this.sc = sc;
+            this.buf = ByteBuffer.allocate(expectedSize);
+        }
+
+        public Long call() throws Exception {
+            while (buf.hasRemaining()) {
+                int n = sc.read(buf);
+                if (n == -1)
+                    throw new RuntimeException("Premature EOF encountered");
+            }
+            buf.flip();
+            return computeChecksum(buf);
+        }
+    }
+
+    /**
+     * Run test with a write of the given number of bytes.
+     */
+    static void test(ExecutorService pool,
+                     SocketChannel source,
+                     SocketChannel sink,
+                     int size)
+        throws Exception
+    {
+        System.out.println(size);
+
+        // random bytes in the buffer
+        ByteBuffer buf = ByteBuffer.allocate(size);
+        rand.nextBytes(buf.array());
+
+        // submit task to read the bytes
+        Future<Long> result = pool.submit(new Reader(sink, size));
+
+        // write the bytes
+        int n = source.write(buf);
+        if (n != size)
+            throw new RuntimeException("Short write detected");
+
+        // check the bytes that were received match
+        buf.rewind();
+        long expected = computeChecksum(buf);
+        long actual = result.get();
+        if (actual != expected)
+            throw new RuntimeException("Checksum did not match");
+    }
+
+
+    public static void main(String[] args) throws Exception {
+        ExecutorService pool = Executors.newSingleThreadExecutor();
+        try {
+            try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
+                ssc.bind(new InetSocketAddress(0));
+                InetAddress lh = InetAddress.getLocalHost();
+                int port = ssc.socket().getLocalPort();
+                SocketAddress sa = new InetSocketAddress(lh, port);
+
+                try (SocketChannel source = SocketChannel.open(sa);
+                     SocketChannel sink = ssc.accept())
+                {
+                    // run tests on sizes around 128k as that is the problem
+                    // area on Windows.
+                    int BOUNDARY = 128 * 1024;
+                    for (int size=(BOUNDARY-2); size<=(BOUNDARY+2); size++) {
+                        test(pool, source, sink, size);
+                    }
+
+                    // run tests on random sizes
+                    for (int i=0; i<20; i++) {
+                        int size = rand.nextInt(1024*1024);
+                        test(pool, source, sink, size);
+                    }
+                }
+            }
+
+        } finally {
+            pool.shutdown();
+        }
+    }
+}
--- a/test/java/nio/channels/TestUtil.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/test/java/nio/channels/TestUtil.java	Thu Jun 28 14:11:05 2012 -0700
@@ -81,20 +81,6 @@
 
     private static String osName = System.getProperty("os.name");
 
-    // Examines os.name property to determine if running on 95/98/ME.
-    //
-    // Returns true if running on windows95/98/ME.
-    //
-    static boolean onME() {
-        if (osName.startsWith("Windows")) {
-            if (osName.indexOf("9") > 0)
-                return true;
-            if (osName.indexOf("M") > 0)
-                return true;
-        }
-        return false;
-    }
-
     static boolean onSolaris() {
         return osName.startsWith("SunOS");
     }
--- a/test/java/nio/file/WatchService/Basic.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/test/java/nio/file/WatchService/Basic.java	Thu Jun 28 14:11:05 2012 -0700
@@ -25,7 +25,7 @@
  * @bug 4313887 6838333 7017446
  * @summary Unit test for java.nio.file.WatchService
  * @library ..
- * @run main/timeout=120 Basic
+ * @run main Basic
  */
 
 import java.nio.file.*;
@@ -281,11 +281,11 @@
 
             System.out.println("poll with timeout...");
             try {
-                long start = System.currentTimeMillis();
+                long start = System.nanoTime();
                 key = watcher.poll(3000, TimeUnit.MILLISECONDS);
                 if (key != null)
                     throw new RuntimeException("no keys registered");
-                long waited = System.currentTimeMillis() - start;
+                long waited = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
                 if (waited < 2900)
                     throw new RuntimeException("poll was too short");
             } catch (InterruptedException x) {
@@ -358,14 +358,14 @@
         }
 
         // assume that poll throws exception immediately
-        long start = System.currentTimeMillis();
+        long start = System.nanoTime();
         try {
             watcher.poll(10000, TimeUnit.MILLISECONDS);
             throw new RuntimeException("ClosedWatchServiceException not thrown");
         } catch (InterruptedException x) {
             throw new RuntimeException(x);
         } catch (ClosedWatchServiceException  x) {
-            long waited = System.currentTimeMillis() - start;
+            long waited = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
             if (waited > 5000)
                 throw new RuntimeException("poll was too long");
         }
--- a/test/java/nio/file/WatchService/SensitivityModifier.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/test/java/nio/file/WatchService/SensitivityModifier.java	Thu Jun 28 14:11:05 2012 -0700
@@ -23,9 +23,9 @@
 
 /* @test
  * @bug 4313887
- * @summary Sanity test for Sun-specific sensitivyt level watch event modifier
+ * @summary Sanity test for Sun-specific sensitivity level watch event modifier
  * @library ..
- * @run main/timeout=330 Basic
+ * @run main/timeout=240 SensitivityModifier
  */
 
 import java.nio.file.*;
@@ -96,6 +96,7 @@
 
             // drain events (to avoid interference)
             do {
+                key.pollEvents();
                 key.reset();
                 key = watcher.poll(1, TimeUnit.SECONDS);
             } while (key != null);
--- a/test/java/util/Map/Collisions.java	Wed Jun 27 17:19:47 2012 -0700
+++ b/test/java/util/Map/Collisions.java	Thu Jun 28 14:11:05 2012 -0700
@@ -68,7 +68,7 @@
             return Integer.toString(value);
         }
     }
-    private static final int ITEMS = 10000;
+    private static final int ITEMS = 5000;
     private static final Object KEYS[][];
 
     static {
@@ -133,7 +133,7 @@
 
     private static void realMain(String[] args) throws Throwable {
         for (Object[] keys_desc : KEYS) {
-            Map<Object, Boolean>[] MAPS = (Map<Object, Boolean>[]) new Map[]{
+            Map<Object, Object>[] MAPS = (Map<Object, Object>[]) new Map[]{
                         new Hashtable<>(),
                         new HashMap<>(),
                         new IdentityHashMap<>(),
@@ -144,51 +144,69 @@
                         new ConcurrentSkipListMap<>()
                     };
 
-            for (Map<Object, Boolean> map : MAPS) {
+            for (Map<Object, Object> map : MAPS) {
                 String desc = (String) keys_desc[0];
                 Object[] keys = (Object[]) keys_desc[1];
+                try {
                 testMap(map, desc, keys);
+                } catch(Exception all) {
+                    unexpected("Failed for " + map.getClass().getName() + " with " + desc, all);
+                }
             }
         }
     }
 
-    private static <T> void testMap(Map<T, Boolean> map, String keys_desc, T[] keys) {
-        System.err.println(map.getClass() + " : " + keys_desc);
+    private static <T> void testMap(Map<T, T> map, String keys_desc, T[] keys) {
+        System.out.println(map.getClass() + " : " + keys_desc);
+        System.out.flush();
         testInsertion(map, keys_desc, keys);
 
         if (keys[0] instanceof HashableInteger) {
-            testIntegerIteration((Map<HashableInteger, Boolean>) map, (HashableInteger[]) keys);
+            testIntegerIteration((Map<HashableInteger, HashableInteger>) map, (HashableInteger[]) keys);
         } else {
-            testStringIteration((Map<String, Boolean>) map, (String[]) keys);
+            testStringIteration((Map<String, String>) map, (String[]) keys);
         }
 
         testContainsKey(map, keys_desc, keys);
 
         testRemove(map, keys_desc, keys);
 
+        map.clear();
+        testInsertion(map, keys_desc, keys);
+        testKeysIteratorRemove(map, keys_desc, keys);
+
+        map.clear();
+        testInsertion(map, keys_desc, keys);
+        testValuesIteratorRemove(map, keys_desc, keys);
+
+        map.clear();
+        testInsertion(map, keys_desc, keys);
+        testEntriesIteratorRemove(map, keys_desc, keys);
+
         check(map.isEmpty());
     }
 
-    private static <T> void testInsertion(Map<T, Boolean> map, String keys_desc, T[] keys) {
+    private static <T> void testInsertion(Map<T, T> map, String keys_desc, T[] keys) {
         check("map empty", (map.size() == 0) && map.isEmpty());
 
         for (int i = 0; i < keys.length; i++) {
             check(String.format("insertion: map expected size m%d != i%d", map.size(), i),
                     map.size() == i);
-            check(String.format("insertion: put(%s[%d])", keys_desc, i), null == map.put(keys[i], true));
+            check(String.format("insertion: put(%s[%d])", keys_desc, i), null == map.put(keys[i], keys[i]));
             check(String.format("insertion: containsKey(%s[%d])", keys_desc, i), map.containsKey(keys[i]));
+            check(String.format("insertion: containsValue(%s[%d])", keys_desc, i), map.containsValue(keys[i]));
         }
 
         check(String.format("map expected size m%d != k%d", map.size(), keys.length),
                 map.size() == keys.length);
     }
 
-    private static void testIntegerIteration(Map<HashableInteger, Boolean> map, HashableInteger[] keys) {
+    private static void testIntegerIteration(Map<HashableInteger, HashableInteger> map, HashableInteger[] keys) {
         check(String.format("map expected size m%d != k%d", map.size(), keys.length),
                 map.size() == keys.length);
 
         BitSet all = new BitSet(keys.length);
-        for (Map.Entry<HashableInteger, Boolean> each : map.entrySet()) {
+        for (Map.Entry<HashableInteger, HashableInteger> each : map.entrySet()) {
             check("Iteration: key already seen", !all.get(each.getKey().value));
             all.set(each.getKey().value);
         }
@@ -205,7 +223,7 @@
         check("Iteration: some keys not visited", all.isEmpty());
 
         int count = 0;
-        for (Boolean each : map.values()) {
+        for (HashableInteger each : map.values()) {
             count++;
         }
 
@@ -213,12 +231,12 @@
                 map.size() == count);
     }
 
-    private static void testStringIteration(Map<String, Boolean> map, String[] keys) {
+    private static void testStringIteration(Map<String, String> map, String[] keys) {
         check(String.format("map expected size m%d != k%d", map.size(), keys.length),
                 map.size() == keys.length);
 
         BitSet all = new BitSet(keys.length);
-        for (Map.Entry<String, Boolean> each : map.entrySet()) {
+        for (Map.Entry<String, String> each : map.entrySet()) {
             String key = each.getKey();
             boolean longKey = key.length() > 5;
             int index = key.hashCode() + (longKey ? keys.length / 2 : 0);
@@ -240,7 +258,7 @@
         check("some keys not visited", all.isEmpty());
 
         int count = 0;
-        for (Boolean each : map.values()) {
+        for (String each : map.values()) {
             count++;
         }
 
@@ -248,14 +266,14 @@
                 map.size() == keys.length);
     }
 
-    private static <T> void testContainsKey(Map<T, Boolean> map, String keys_desc, T[] keys) {
+    private static <T> void testContainsKey(Map<T, T> map, String keys_desc, T[] keys) {
         for (int i = 0; i < keys.length; i++) {
             T each = keys[i];
             check("containsKey: " + keys_desc + "[" + i + "]" + each, map.containsKey(each));
         }
     }
 
-    private static <T> void testRemove(Map<T, Boolean> map, String keys_desc, T[] keys) {
+    private static <T> void testRemove(Map<T, T> map, String keys_desc, T[] keys) {
         check(String.format("remove: map expected size m%d != k%d", map.size(), keys.length),
                 map.size() == keys.length);
 
@@ -267,6 +285,56 @@
         check(String.format("remove: map empty. size=%d", map.size()),
                 (map.size() == 0) && map.isEmpty());
     }
+
+    private static <T> void testKeysIteratorRemove(Map<T, T> map, String keys_desc, T[] keys) {
+        check(String.format("remove: map expected size m%d != k%d", map.size(), keys.length),
+                map.size() == keys.length);
+
+        Iterator<T> each = map.keySet().iterator();
+        while (each.hasNext()) {
+            T t = each.next();
+            each.remove();
+            check("not removed: " + each, !map.containsKey(t) );
+        }
+
+        check(String.format("remove: map empty. size=%d", map.size()),
+                (map.size() == 0) && map.isEmpty());
+    }
+
+    private static <T> void testValuesIteratorRemove(Map<T, T> map, String keys_desc, T[] keys) {
+        check(String.format("remove: map expected size m%d != k%d", map.size(), keys.length),
+                map.size() == keys.length);
+
+        Iterator<T> each = map.values().iterator();
+        while (each.hasNext()) {
+            T t = each.next();
+            each.remove();
+            check("not removed: " + each, !map.containsValue(t) );
+        }
+
+        check(String.format("remove: map empty. size=%d", map.size()),
+                (map.size() == 0) && map.isEmpty());
+    }
+
+    private static <T> void testEntriesIteratorRemove(Map<T, T> map, String keys_desc, T[] keys) {
+        check(String.format("remove: map expected size m%d != k%d", map.size(), keys.length),
+                map.size() == keys.length);
+
+        Iterator<Map.Entry<T,T>> each = map.entrySet().iterator();
+        while (each.hasNext()) {
+            Map.Entry<T,T> t = each.next();
+            T key = t.getKey();
+            T value = t.getValue();
+            each.remove();
+            check("not removed: " + each, (map instanceof IdentityHashMap) || !map.entrySet().contains(t) );
+            check("not removed: " + each, !map.containsKey(key) );
+            check("not removed: " + each, !map.containsValue(value));
+        }
+
+        check(String.format("remove: map empty. size=%d", map.size()),
+                (map.size() == 0) && map.isEmpty());
+    }
+
     //--------------------- Infrastructure ---------------------------
     static volatile int passed = 0, failed = 0;
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/swing/text/html/parser/Parser/7165725/bug7165725.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,305 @@
+/*
+ * Copyright (c) 2012, 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 7165725
+   @summary  Tests if HTML parser can handle successive script tags in a line
+             and it does not call false text callback after script tags.
+   @run main bug7165725
+*/
+
+import sun.awt.SunToolkit;
+
+import java.awt.BorderLayout;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import javax.swing.*;
+import javax.swing.text.AbstractDocument.AbstractElement;
+import javax.swing.text.AbstractDocument;
+import javax.swing.text.Document;
+import javax.swing.text.MutableAttributeSet;
+import javax.swing.text.html.HTML;
+import javax.swing.text.html.HTMLDocument;
+import javax.swing.text.html.HTMLEditorKit;
+import javax.swing.text.html.parser.ParserDelegator;
+
+public class bug7165725 extends JFrame {
+    private static class GoldenElement {
+
+        private String goldenName;
+        private List<GoldenElement> goldenChildren;
+
+        GoldenElement(String goldenName, GoldenElement... goldenChildren){
+            this.goldenName = goldenName;
+            if (goldenChildren != null) {
+                this.goldenChildren = Arrays.asList(goldenChildren);
+            } else {
+                this.goldenChildren = new ArrayList<>();
+            }
+        }
+
+        // throws RuntimeException if not ok
+        public void checkStructureEquivalence(AbstractDocument.AbstractElement elem) {
+            String name = elem.getName();
+            if (!goldenName.equals(name)) {
+                throw new RuntimeException("Bad structure: expected element name is '" + goldenName + "' but the actual name was '" + name + "'.");
+            }
+            int goldenChildCount = goldenChildren.size();
+            int childCount = elem.getChildCount();
+            if (childCount != goldenChildCount) {
+                System.out.print("D: children: ");
+                for (int i = 0; i < childCount; i++) {
+                    System.out.print(" " + elem.getElement(i).getName());
+                }
+                System.out.println("");
+                System.out.print("D: goldenChildren: ");
+                for (GoldenElement ge : goldenChildren) {
+                    System.out.print(" " + ge.goldenName);
+                }
+                System.out.println("");
+
+                throw new RuntimeException("Bad structure: expected child count of element '" + goldenName + "' is '" + goldenChildCount + "' but the actual count was '" + childCount + "'.");
+            }
+            for (int i = 0; i < childCount; i++) {
+                AbstractDocument.AbstractElement nextElem = (AbstractDocument.AbstractElement) elem.getElement(i);
+                GoldenElement goldenElement = goldenChildren.get(i);
+                goldenElement.checkStructureEquivalence(nextElem);
+            }
+        }
+    }
+
+    private JEditorPane editorPane;
+    public void execute(final String urlStr, final GoldenElement goldenElement) throws Exception {
+        System.out.println();
+        System.out.println("***** TEST: " + urlStr + " *****");
+        System.out.println();
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                try {
+                    editorPane = new JEditorPane();
+                    editorPane.setEditorKit(new HTMLEditorKit() {
+                        public Document createDefaultDocument() {
+                            AbstractDocument doc =
+                                    (AbstractDocument) super.createDefaultDocument();
+                            doc.setAsynchronousLoadPriority(-1);
+                            return doc;
+                        }
+                    });
+                    editorPane.setPage(new URL(urlStr));
+                } catch (IOException ex) {
+                    throw new RuntimeException("Test failed", ex);
+                }
+                editorPane.setEditable(false);
+                JScrollPane scroller = new JScrollPane();
+                JViewport vp = scroller.getViewport();
+                vp.add(editorPane);
+                add(scroller, BorderLayout.CENTER);
+                setDefaultCloseOperation(EXIT_ON_CLOSE);
+                setSize(400, 400);
+                setLocationRelativeTo(null);
+                setVisible(true);
+            }
+        });
+
+        ((SunToolkit) SunToolkit.getDefaultToolkit()).realSync();
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
+                doc.dump(System.out);
+                goldenElement.checkStructureEquivalence((AbstractElement) doc.getDefaultRootElement());
+                dispose();
+            }
+        });
+
+        System.out.println();
+        System.out.println("*********************************");
+        System.out.println();
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        String dirURL = getDirURL();
+
+        System.out.println("dirURL = " + dirURL);
+
+        new bug7165725().execute(dirURL + "successive-script-tag.html", createSuccessiveScriptTags());
+        new bug7165725().execute(dirURL + "false-text-after-script.html", createFalseTextAfterScript());
+
+        checkByCallbackForSuccessiveScript();
+        checkByCallbackForFalseTextAfterScript();
+
+        System.out.println();
+        System.out.println();
+        System.out.println("Test passed.");
+    }
+
+    static String getDirURL() {
+        return "file:///" +
+                new File(System.getProperty("test.src", ".")).getAbsolutePath() +
+                File.separator;
+    }
+
+    static String getParsedContentOneLine(String path) throws Exception {
+        File f = new File(path);
+        FileReader fr = new FileReader(f);
+        ParserDelegator pd = new ParserDelegator();
+        SBParserCallback sbcallback = new SBParserCallback();
+        pd.parse(fr, sbcallback, true);
+        fr.close();
+        return sbcallback.getStringOneLine();
+    }
+
+    static String getParsedContentOneLine(URL url) throws Exception {
+        return getParsedContentOneLine(url.getPath());
+    }
+
+    static void checkByCallbackForSuccessiveScript() throws Exception {
+        String content = getParsedContentOneLine(new URL(getDirURL() + "successive-script-tag.html"));
+        if (!content.matches(".*<script .*/js/js1\\.js.*<script .*/js/js2\\.js.*<script .*/js/js3\\.js.*"))
+            throw new RuntimeException("Failed to lookup script tags/attributes.");
+        if (!content.matches(".*<style .*stylesheets/base\\.css.*<style .*stylesheets/adv\\.css.*"))
+            throw new RuntimeException("Failed to lookup style tags.");
+    }
+
+    static void checkByCallbackForFalseTextAfterScript() throws Exception {
+        String content = getParsedContentOneLine(new URL(getDirURL() + "false-text-after-script.html"));
+        final int bodyIdx = content.indexOf("<body ");
+        if (bodyIdx > 0) {
+            String sbody = content.substring(bodyIdx);
+            // There should be no Text(...) in this html
+            if (sbody.indexOf("Text(") >= 0)
+                throw new RuntimeException("Unexpected text found.");
+        } else {
+            throw new RuntimeException("Failed to find body tag.");
+        }
+    }
+
+    private static GoldenElement createSuccessiveScriptTags() {
+        return new GoldenElement("html",
+                new GoldenElement("head",
+                        new GoldenElement("p-implied",
+                                new GoldenElement("title"),
+                                new GoldenElement("title"),
+                                new GoldenElement("script"),
+                                new GoldenElement("comment"),
+                                new GoldenElement("script"),
+                                new GoldenElement("script"),
+                                new GoldenElement("comment"),
+                                new GoldenElement("script"),
+                                new GoldenElement("script"),
+                                new GoldenElement("comment"),
+                                new GoldenElement("script"),
+                                new GoldenElement("content"))),
+                new GoldenElement("body",
+                        new GoldenElement("p-implied",
+                                new GoldenElement("content"))));
+    }
+
+    private static GoldenElement createFalseTextAfterScript() {
+        return new GoldenElement("html",
+                new GoldenElement("head",
+                        new GoldenElement("p-implied",
+                                new GoldenElement("title"),
+                                new GoldenElement("title"),
+                                new GoldenElement("content"))),
+                new GoldenElement("body",
+                        new GoldenElement("form",
+                                new GoldenElement("p-implied",
+                                        new GoldenElement("input"),
+                                        new GoldenElement("input"),
+                                        new GoldenElement("content"))),
+                        new GoldenElement("p-implied",
+                                new GoldenElement("script"),
+                                new GoldenElement("comment"),
+                                new GoldenElement("script"),
+                                new GoldenElement("script"),
+                                new GoldenElement("comment"),
+                                new GoldenElement("script"),
+                                new GoldenElement("content"))));
+    }
+
+    static class SBParserCallback extends HTMLEditorKit.ParserCallback
+    {
+        private int indentSize = 0;
+        private ArrayList<String> elist = new ArrayList<>();
+
+        public String getStringOneLine() {
+            StringBuilder sb = new StringBuilder();
+            for (String s : elist) sb.append(s);
+            return sb.toString();
+        }
+
+        public String toString() {
+            StringBuffer sb = new StringBuffer();
+            for (String s : elist) sb.append(s + "\n");
+            return sb.toString();
+        }
+
+        protected void indent() {
+            indentSize += 3;
+        }
+        protected void unIndent() {
+            indentSize -= 3; if (indentSize < 0) indentSize = 0;
+        }
+
+        protected String pIndent() {
+            StringBuilder sb = new StringBuilder();
+            for(int i = 0; i < indentSize; i++) sb.append(" ");
+            return sb.toString();
+        }
+
+        public void handleText(char[] data, int pos) {
+            elist.add(pIndent() + "Text(" + data.length + " chars) \"" + new String(data) + "\"");
+        }
+
+        public void handleComment(char[] data, int pos) {
+            elist.add(pIndent() + "Comment(" + data.length + " chars)");
+        }
+
+        public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
+            elist.add(pIndent() + "Tag start(<" + t.toString() + " " + a + ">, " +
+                    a.getAttributeCount() + " attrs)");
+            indent();
+        }
+
+        public void handleEndTag(HTML.Tag t, int pos) {
+            unIndent();
+            elist.add(pIndent() + "Tag end(</" + t.toString() + ">)");
+        }
+
+        public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
+            elist.add(pIndent() + "Tag(<" + t.toString() + ">, " +
+                    a.getAttributeCount() + " attrs)");
+        }
+
+        public void handleError(String errorMsg, int pos){
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/swing/text/html/parser/Parser/7165725/false-text-after-script.html	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,20 @@
+<html>
+<head> <title> Testing </title> </head>
+<body>
+<form>
+
+  <input type="text" name="text1" >
+  <input type="button" name="button1" value="button" onclick="test1(this.form)">
+
+</form>
+
+<SCRIPT LANGUAGE="JavaScript">
+  function test1(form) {
+  alert(form.text1.value);
+  }
+</SCRIPT>
+<SCRIPT>
+  history.forward();
+</SCRIPT>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/swing/text/html/parser/Parser/7165725/successive-script-tag.html	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,8 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head><title>my title</title>
+  <script src="../../js/js1.js" language="JavaScript"></script><script src="../../js/js2.js" language="JavaScript"></script><script src="../../js/js3.js" language="JavaScript"></script><style type="text/css" media="screen">@import "stylesheets/base.css";</style><style type="text/css" media="screen">@import "stylesheets/adv.css";</style>
+</head>
+<body>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/nio/cs/TestSJIS0213_SM.java	Thu Jun 28 14:11:05 2012 -0700
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2012, 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 7152690
+   @summary Initialize SJIS_0213 charset with SecurityManager enabled
+ */
+public class TestSJIS0213_SM {
+    public static void main(String[] args) throws Throwable {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm == null) {
+            System.setSecurityManager(new SecurityManager());
+        }
+        java.nio.charset.Charset.forName("SJIS_0213");
+    }
+}