From 83d661a615ac0a7ccddee369d75942563a4a81a7 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Fri, 16 May 2014 15:46:24 +0400 Subject: [PATCH 001/192] 8043151: KSS: javax.swing.plaf.nimbus.AbstractRegionPainter#getComponentColor Reviewed-by: alexsch, serb --- .../javax/swing/plaf/nimbus/AbstractRegionPainter.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java b/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java index f10dfd4298f..15a10fbf5f9 100644 --- a/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java +++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java @@ -31,6 +31,7 @@ import javax.swing.*; import javax.swing.plaf.UIResource; import javax.swing.Painter; import java.awt.print.PrinterGraphics; +import sun.reflect.misc.MethodUtil; /** * Convenient base class for defining Painter instances for rendering a @@ -445,8 +446,8 @@ public abstract class AbstractRegionPainter implements Painter { } else { String s = "get" + Character.toUpperCase(property.charAt(0)) + property.substring(1); try { - Method method = c.getClass().getMethod(s); - color = (Color) method.invoke(c); + Method method = MethodUtil.getMethod(c.getClass(), s, null); + color = (Color) MethodUtil.invoke(method, c, null); } catch (Exception e) { //don't do anything, it just didn't work, that's all. //This could be a normal occurance if you use a property From e01b173e5af5155e1c6c226180ae5baff878a31a Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Fri, 16 May 2014 15:51:57 +0400 Subject: [PATCH 002/192] 8043152: KSS: javax.swing.plaf.synth.SynthContext Reviewed-by: alexsch, serb --- jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java index 6d89a4a06c8..1730f25d35c 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java @@ -26,6 +26,7 @@ package javax.swing.plaf.synth; import javax.swing.*; import java.util.*; +import sun.reflect.misc.ReflectUtil; /** * An immutable transient object containing contextual information about @@ -70,7 +71,7 @@ public class SynthContext { } if (context == null) { try { - context = (SynthContext)type.newInstance(); + context = (SynthContext) ReflectUtil.newInstance(type); } catch (IllegalAccessException iae) { } catch (InstantiationException ie) { } From df3fb56e9e4d02231709845b0ccc1604721090c5 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Fri, 16 May 2014 15:57:06 +0400 Subject: [PATCH 003/192] 8043153: KSS: javax.swing.plaf.synth.SynthParser#startColor Reviewed-by: alexsch, serb --- jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java index ef38ae11387..a15bb509e78 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java @@ -67,6 +67,7 @@ import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import com.sun.beans.decoder.DocumentHandler; +import sun.reflect.misc.ReflectUtil; class SynthParser extends DefaultHandler { // @@ -648,7 +649,7 @@ class SynthParser extends DefaultHandler { } else { try { - typeClass = Class.forName(typeName.substring( + typeClass = ReflectUtil.forName(typeName.substring( 0, classIndex)); } catch (ClassNotFoundException cnfe) { throw new SAXException("Unknown class: " + From 86104df3c2a520277364baf54f747d2b8a72a0bc Mon Sep 17 00:00:00 2001 From: Anton Nashatyrev Date: Mon, 19 May 2014 16:48:41 +0400 Subject: [PATCH 004/192] 8038000: java.awt.image.RasterFormatException: Incorrect scanline stride Reviewed-by: bae, serb --- .../sun/awt/image/ByteBandedRaster.java | 20 ++- .../sun/awt/image/ByteComponentRaster.java | 20 ++- .../sun/awt/image/BytePackedRaster.java | 19 ++- .../sun/awt/image/IntegerComponentRaster.java | 20 ++- .../sun/awt/image/ShortBandedRaster.java | 19 ++- .../sun/awt/image/ShortComponentRaster.java | 20 ++- jdk/test/sun/awt/image/bug8038000.java | 153 ++++++++++++++++++ 7 files changed, 255 insertions(+), 16 deletions(-) create mode 100644 jdk/test/sun/awt/image/bug8038000.java diff --git a/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java b/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java index 78903979d6f..a0431baf4ac 100644 --- a/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java +++ b/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java @@ -755,10 +755,22 @@ public class ByteBandedRaster extends SunWritableRaster { + scanlineStride); } - for (int i = 0; i < data.length; i++) { - if (scanlineStride > data[i].length) { - throw new RasterFormatException("Incorrect scanline stride: " - + scanlineStride); + if ((long)minX - sampleModelTranslateX < 0 || + (long)minY - sampleModelTranslateY < 0) { + + throw new RasterFormatException("Incorrect origin/translate: (" + + minX + ", " + minY + ") / (" + + sampleModelTranslateX + ", " + sampleModelTranslateY + ")"); + } + + + if (height > 1 || minY - sampleModelTranslateY > 0) { + // buffer should contain at least one scanline + for (int i = 0; i < data.length; i++) { + if (scanlineStride > data[i].length) { + throw new RasterFormatException("Incorrect scanline stride: " + + scanlineStride); + } } } diff --git a/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java b/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java index 9695d3a0df8..b5f4f7095aa 100644 --- a/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java +++ b/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java @@ -885,15 +885,31 @@ public class ByteComponentRaster extends SunWritableRaster { } } + if ((long)minX - sampleModelTranslateX < 0 || + (long)minY - sampleModelTranslateY < 0) { + + throw new RasterFormatException("Incorrect origin/translate: (" + + minX + ", " + minY + ") / (" + + sampleModelTranslateX + ", " + sampleModelTranslateY + ")"); + } + // we can be sure that width and height are greater than 0 if (scanlineStride < 0 || - scanlineStride > (Integer.MAX_VALUE / height) || - scanlineStride > data.length) + scanlineStride > (Integer.MAX_VALUE / height)) { // integer overflow throw new RasterFormatException("Incorrect scanline stride: " + scanlineStride); } + + if (height > 1 || minY - sampleModelTranslateY > 0) { + // buffer should contain at least one scanline + if (scanlineStride > data.length) { + throw new RasterFormatException("Incorrect scanline stride: " + + scanlineStride); + } + } + int lastScanOffset = (height - 1) * scanlineStride; if (pixelStride < 0 || diff --git a/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java b/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java index da370a30c0d..bd3835d5184 100644 --- a/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java +++ b/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java @@ -1386,13 +1386,28 @@ public class BytePackedRaster extends SunWritableRaster { throw new RasterFormatException("Invalid raster dimension"); } + if ((long)minX - sampleModelTranslateX < 0 || + (long)minY - sampleModelTranslateY < 0) { + + throw new RasterFormatException("Incorrect origin/translate: (" + + minX + ", " + minY + ") / (" + + sampleModelTranslateX + ", " + sampleModelTranslateY + ")"); + } + if (scanlineStride < 0 || - scanlineStride > (Integer.MAX_VALUE / height) || - scanlineStride > data.length) + scanlineStride > (Integer.MAX_VALUE / height)) { throw new RasterFormatException("Invalid scanline stride"); } + if (height > 1 || minY - sampleModelTranslateY > 0) { + // buffer should contain at least one scanline + if (scanlineStride > data.length) { + throw new RasterFormatException("Incorrect scanline stride: " + + scanlineStride); + } + } + int lastbit = (dataBitOffset + (height-1) * scanlineStride * 8 + (width-1) * pixelBitStride diff --git a/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java b/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java index a95ce0d015d..f7e8bf37100 100644 --- a/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java +++ b/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java @@ -654,15 +654,31 @@ public class IntegerComponentRaster extends SunWritableRaster { ") must be >= 0"); } + if ((long)minX - sampleModelTranslateX < 0 || + (long)minY - sampleModelTranslateY < 0) { + + throw new RasterFormatException("Incorrect origin/translate: (" + + minX + ", " + minY + ") / (" + + sampleModelTranslateX + ", " + sampleModelTranslateY + ")"); + } + // we can be sure that width and height are greater than 0 if (scanlineStride < 0 || - scanlineStride > (Integer.MAX_VALUE / height) || - scanlineStride > data.length) + scanlineStride > (Integer.MAX_VALUE / height)) { // integer overflow throw new RasterFormatException("Incorrect scanline stride: " + scanlineStride); } + + if (height > 1 || minY - sampleModelTranslateY > 0) { + // buffer should contain at least one scanline + if (scanlineStride > data.length) { + throw new RasterFormatException("Incorrect scanline stride: " + + scanlineStride); + } + } + int lastScanOffset = (height - 1) * scanlineStride; if (pixelStride < 0 || diff --git a/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java b/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java index 45ef9eb21f3..ccf7740ad53 100644 --- a/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java +++ b/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java @@ -754,10 +754,21 @@ public class ShortBandedRaster extends SunWritableRaster { + scanlineStride); } - for (int i = 0; i < data.length; i++) { - if (scanlineStride > data[i].length) { - throw new RasterFormatException("Incorrect scanline stride: " - + scanlineStride); + if ((long)minX - sampleModelTranslateX < 0 || + (long)minY - sampleModelTranslateY < 0) { + + throw new RasterFormatException("Incorrect origin/translate: (" + + minX + ", " + minY + ") / (" + + sampleModelTranslateX + ", " + sampleModelTranslateY + ")"); + } + + if (height > 1 || minY - sampleModelTranslateY > 0) { + // buffer should contain at least one scanline + for (int i = 0; i < data.length; i++) { + if (scanlineStride > data[i].length) { + throw new RasterFormatException("Incorrect scanline stride: " + + scanlineStride); + } } } diff --git a/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java b/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java index 53f3ff3e3e6..14ffe5539cf 100644 --- a/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java +++ b/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java @@ -819,15 +819,31 @@ public class ShortComponentRaster extends SunWritableRaster { } } + if ((long)minX - sampleModelTranslateX < 0 || + (long)minY - sampleModelTranslateY < 0) { + + throw new RasterFormatException("Incorrect origin/translate: (" + + minX + ", " + minY + ") / (" + + sampleModelTranslateX + ", " + sampleModelTranslateY + ")"); + } + // we can be sure that width and height are greater than 0 if (scanlineStride < 0 || - scanlineStride > (Integer.MAX_VALUE / height) || - scanlineStride > data.length) + scanlineStride > (Integer.MAX_VALUE / height)) { // integer overflow throw new RasterFormatException("Incorrect scanline stride: " + scanlineStride); } + + if (height > 1 || minY - sampleModelTranslateY > 0) { + // buffer should contain at least one scanline + if (scanlineStride > data.length) { + throw new RasterFormatException("Incorrect scanline stride: " + + scanlineStride); + } + } + int lastScanOffset = (height - 1) * scanlineStride; if (pixelStride < 0 || diff --git a/jdk/test/sun/awt/image/bug8038000.java b/jdk/test/sun/awt/image/bug8038000.java new file mode 100644 index 00000000000..2bfdc27d2b7 --- /dev/null +++ b/jdk/test/sun/awt/image/bug8038000.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8038000 + * + * @summary Verifies that we could create different type of Rasters with height 1 + * and strideline which exceeds raster width. + * Also checks that a set of RasterOp work correctly with such kind of Rasters. + * + * @run main bug8038000 + */ + +import java.awt.*; +import java.awt.color.ColorSpace; +import java.awt.geom.AffineTransform; +import java.awt.image.*; +import java.util.Arrays; + +public class bug8038000 { + + public static void main(String[] args) throws Exception { + new bug8038000().checkOps(); + + // No exceptions - Passed + } + + private void checkOps() throws Exception { + + RasterOp[] ops = new RasterOp[] { + new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), + ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB), null), + new AffineTransformOp(AffineTransform.getScaleInstance(1, 1.1), null) + }; + + + for (RasterOp op: ops) { + // Banded rasters + checkOp(Raster.createBandedRaster(DataBuffer.TYPE_BYTE, 10, 1, 10, + new int[] {0, 1, 2}, new int[]{2,1,0}, null), + Raster.createBandedRaster(DataBuffer.TYPE_BYTE, 10, 1, 1001, + new int[] {0, 1, 2}, new int[]{2,1,0}, null), op); + checkOp(Raster.createBandedRaster(DataBuffer.TYPE_USHORT, 10, 1, 10, + new int[] {0, 1, 2}, new int[]{2,1,0}, null), + Raster.createBandedRaster(DataBuffer.TYPE_USHORT, 10, 1, 1001, + new int[] {0, 1, 2}, new int[]{2,1,0}, null), op); + checkOp(Raster.createBandedRaster(DataBuffer.TYPE_INT, 10, 1, 10, + new int[] {0, 1, 2}, new int[]{2,1,0}, null), + Raster.createBandedRaster(DataBuffer.TYPE_INT, 10, 1, 1001, + new int[] {0, 1, 2}, new int[]{2,1,0}, null), op); + + // Interleaved rasters + checkOp(Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, + 10, 1, 30, 3, new int[]{0, 1, 2}, null), + Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, + 10, 1, 1001, 3, new int[]{0, 1, 2}, null), + op); + + checkOp(Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, + 10, 1, 30, 3, new int[]{0, 1, 2}, null), + Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, + 10, 1, 1001, 3, new int[]{0, 1, 2}, null), + op); + + // Packed rasters + checkOp(Raster.createPackedRaster(new DataBufferByte(10), 10, 1, 10, + new int[] {0x01, 0x02, 0x04}, null), + Raster.createPackedRaster(new DataBufferByte(10), 10, 1, 2000, + new int[] {0x01, 0x02, 0x04}, null), + op); + checkOp(Raster.createPackedRaster(new DataBufferInt(10), 10, 1, 10, + new int[] {0xff0000, 0x00ff00, 0x0000ff}, null), + Raster.createPackedRaster(new DataBufferInt(10), 10, 1, 20, + new int[] {0xff0000, 0x00ff00, 0x0000ff}, null), + op); + + } + } + + /** + * Takes two identical rasters (identical with the exception of scanline stride) + * fills their pixels with identical data, applies the RasterOp to both rasters + * and checks that the result is the same + */ + private void checkOp(WritableRaster wr1, WritableRaster wr2, RasterOp op) { + System.out.println("Checking " + op + " with rasters: \n " + wr1 + + "\n " + wr2); + try { + WritableRaster r1 = op.filter(fillRaster(wr1), null); + WritableRaster r2 = op.filter(fillRaster(wr2), null); + compareRasters(r1, r2); + } catch (ImagingOpException e) { + System.out.println(" Skip: Op is not supported: " + e); + } + } + + private WritableRaster fillRaster(WritableRaster wr) { + int c = 0; + for(int x = wr.getMinX(); x < wr.getMinX() + wr.getWidth(); x++) { + for(int y = wr.getMinY(); y < wr.getMinY() + wr.getHeight(); y++) { + for (int b = 0; b < wr.getNumBands(); b++) { + wr.setSample(x, y, b, c++); + } + } + } + return wr; + } + + private void compareRasters(Raster r1, Raster r2) { + Rectangle bounds = r1.getBounds(); + if (!bounds.equals(r2.getBounds())) { + throw new RuntimeException("Bounds differ."); + } + + if (r1.getNumBands() != r2.getNumBands()) { + throw new RuntimeException("Bands differ."); + } + + int[] b1 = new int[r1.getNumBands()]; + int[] b2 = new int[r1.getNumBands()]; + + for (int x = (int) bounds.getX(); x < bounds.getMaxX(); x++) { + for (int y = (int) bounds.getY(); y < bounds.getMaxY(); y++) { + r1.getPixel(x,y, b1); + r2.getPixel(x,y, b2); + if (!Arrays.equals(b1, b2)) { + throw new RuntimeException("Pixels differ."); + } + } + } + } +} From ba597e32a7902750b50acb4ce34505e3862fcd15 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Mon, 19 May 2014 10:03:58 -0700 Subject: [PATCH 005/192] 8042871: Fix raw and unchecked warnings in sun.audio Reviewed-by: serb --- .../share/classes/sun/audio/AudioDevice.java | 20 +++++++------------ .../share/classes/sun/audio/AudioPlayer.java | 12 +++++------ .../sun/audio/AudioStreamSequence.java | 11 +++------- 3 files changed, 15 insertions(+), 28 deletions(-) diff --git a/jdk/src/share/classes/sun/audio/AudioDevice.java b/jdk/src/share/classes/sun/audio/AudioDevice.java index 05c180748f0..6e0804d8aad 100644 --- a/jdk/src/share/classes/sun/audio/AudioDevice.java +++ b/jdk/src/share/classes/sun/audio/AudioDevice.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,10 +58,7 @@ public final class AudioDevice { private boolean DEBUG = false /*true*/ ; - /** Hashtable of audio clips / input streams. */ - private Hashtable clipStreams; - - private Vector infos; + private Vector infos; /** Are we currently playing audio? */ private boolean playing = false; @@ -81,9 +78,7 @@ public final class AudioDevice { * Create an AudioDevice instance. */ private AudioDevice() { - - clipStreams = new Hashtable(); - infos = new Vector(); + infos = new Vector<>(); } @@ -161,7 +156,7 @@ public final class AudioDevice { // is this already playing? if so, then just return for(int i=0; i(); } /** diff --git a/jdk/src/share/classes/sun/audio/AudioPlayer.java b/jdk/src/share/classes/sun/audio/AudioPlayer.java index f6e9a30e9e8..58ae9105d4c 100644 --- a/jdk/src/share/classes/sun/audio/AudioPlayer.java +++ b/jdk/src/share/classes/sun/audio/AudioPlayer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -92,18 +92,16 @@ public final class AudioPlayer extends Thread { private static AudioPlayer getAudioPlayer() { if(DEBUG) { System.out.println("> AudioPlayer.getAudioPlayer()"); } - AudioPlayer audioPlayer; - PrivilegedAction action = new PrivilegedAction() { - public Object run() { - Thread t = new AudioPlayer(); + PrivilegedAction action = new PrivilegedAction() { + public AudioPlayer run() { + AudioPlayer t = new AudioPlayer(); t.setPriority(MAX_PRIORITY); t.setDaemon(true); t.start(); return t; } }; - audioPlayer = (AudioPlayer) AccessController.doPrivileged(action); - return audioPlayer; + return AccessController.doPrivileged(action); } /** diff --git a/jdk/src/share/classes/sun/audio/AudioStreamSequence.java b/jdk/src/share/classes/sun/audio/AudioStreamSequence.java index f948070c1ce..178764c1c3d 100644 --- a/jdk/src/share/classes/sun/audio/AudioStreamSequence.java +++ b/jdk/src/share/classes/sun/audio/AudioStreamSequence.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,16 +44,11 @@ import java.util.Enumeration; * @author Arthur van Hoff */ public final class AudioStreamSequence extends SequenceInputStream { - - Enumeration e; - InputStream in; - /** * Create an AudioStreamSequence given an * enumeration of streams. */ - public AudioStreamSequence(Enumeration e) { + public AudioStreamSequence(Enumeration e) { super(e); } - - } +} From bf464ca61b68443c9c95b0302eb0af3098c4bf76 Mon Sep 17 00:00:00 2001 From: David DeHaven Date: Mon, 19 May 2014 23:21:39 +0400 Subject: [PATCH 006/192] 8026385: [macosx] (awt) setjmp/longjmp changes the process signal mask on OS X Use _setjmp/_longjmp instead Reviewed-by: prr, anthony --- jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c | 6 ++++++ jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c | 6 ++++++ .../share/native/sun/awt/splashscreen/splashscreen_jpeg.c | 6 ++++++ .../share/native/sun/awt/splashscreen/splashscreen_png.c | 5 +++++ 4 files changed, 23 insertions(+) diff --git a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c index f108dde9f8b..5f7a0364866 100644 --- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c +++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c @@ -56,6 +56,12 @@ #undef MAX #define MAX(a,b) ((a) > (b) ? (a) : (b)) +#ifdef __APPLE__ +/* use setjmp/longjmp versions that do not save/restore the signal mask */ +#define setjmp _setjmp +#define longjmp _longjmp +#endif + /* Cached Java method ids */ static jmethodID JPEGImageReader_readInputDataID; static jmethodID JPEGImageReader_skipInputBytesID; diff --git a/jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c b/jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c index ba8405c86c3..37b743a0339 100644 --- a/jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c +++ b/jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c @@ -47,6 +47,12 @@ #include #include "jerror.h" +#ifdef __APPLE__ +/* use setjmp/longjmp versions that do not save/restore the signal mask */ +#define setjmp _setjmp +#define longjmp _longjmp +#endif + /* The method IDs we cache. Note that the last two belongs to the * java.io.InputStream class. */ diff --git a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c index 8d41c9207d8..e773fd4ee39 100644 --- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c +++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c @@ -30,6 +30,12 @@ #include +#ifdef __APPLE__ +/* use setjmp/longjmp versions that do not save/restore the signal mask */ +#define setjmp _setjmp +#define longjmp _longjmp +#endif + /* stream input handling */ typedef struct diff --git a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_png.c b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_png.c index ed6f012d950..aeddf868082 100644 --- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_png.c +++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_png.c @@ -71,7 +71,12 @@ SplashDecodePng(Splash * splash, png_rw_ptr read_func, void *io_ptr) goto done; } +#ifdef __APPLE__ + /* use setjmp/longjmp versions that do not save/restore the signal mask */ + if (_setjmp(png_set_longjmp_fn(png_ptr, _longjmp, sizeof(jmp_buf)))) { +#else if (setjmp(png_jmpbuf(png_ptr))) { +#endif goto done; } From 17612e8b46823f984eb204d26b36863abfe99031 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 20 May 2014 09:36:22 -0700 Subject: [PATCH 007/192] 8042864: Fix raw and unchecked warnings in javax.print Reviewed-by: prr, henryjen --- .../javax/print/AttributeException.java | 2 +- .../share/classes/javax/print/DocFlavor.java | 3 +- .../share/classes/javax/print/MimeType.java | 26 +++---- .../javax/print/PrintServiceLookup.java | 78 +++++++++---------- .../share/classes/javax/print/ServiceUI.java | 8 +- .../share/classes/javax/print/SimpleDoc.java | 2 +- .../print/StreamPrintServiceFactory.java | 30 ++++--- .../attribute/AttributeSetUtilities.java | 2 +- .../print/attribute/HashAttributeSet.java | 13 ++-- .../print/attribute/SetOfIntegerSyntax.java | 14 ++-- .../standard/DialogTypeSelection.java | 3 +- .../print/attribute/standard/MediaSize.java | 8 +- .../standard/PrinterStateReasons.java | 26 ++++--- 13 files changed, 106 insertions(+), 109 deletions(-) diff --git a/jdk/src/share/classes/javax/print/AttributeException.java b/jdk/src/share/classes/javax/print/AttributeException.java index f941e8109f3..136d3376810 100644 --- a/jdk/src/share/classes/javax/print/AttributeException.java +++ b/jdk/src/share/classes/javax/print/AttributeException.java @@ -52,7 +52,7 @@ public interface AttributeException { * * @return unsupported attribute classes */ - public Class[] getUnsupportedAttributes(); + public Class[] getUnsupportedAttributes(); /** * Returns the array of printing attributes for which the Print Service diff --git a/jdk/src/share/classes/javax/print/DocFlavor.java b/jdk/src/share/classes/javax/print/DocFlavor.java index d016cb7edb8..eac9d38954d 100644 --- a/jdk/src/share/classes/javax/print/DocFlavor.java +++ b/jdk/src/share/classes/javax/print/DocFlavor.java @@ -545,8 +545,7 @@ public class DocFlavor implements Serializable, Cloneable { * @exception NullPointerException if paramName is null. */ public String getParameter(String paramName) { - return - (String)myMimeType.getParameterMap().get(paramName.toLowerCase()); + return myMimeType.getParameterMap().get(paramName.toLowerCase()); } /** diff --git a/jdk/src/share/classes/javax/print/MimeType.java b/jdk/src/share/classes/javax/print/MimeType.java index 14251b59bda..8fe5eaf3366 100644 --- a/jdk/src/share/classes/javax/print/MimeType.java +++ b/jdk/src/share/classes/javax/print/MimeType.java @@ -117,18 +117,18 @@ class MimeType implements Serializable, Cloneable { /** * Parameter map entry. */ - private class ParameterMapEntry implements Map.Entry { + private class ParameterMapEntry implements Map.Entry { private int myIndex; public ParameterMapEntry(int theIndex) { myIndex = theIndex; } - public Object getKey(){ + public String getKey(){ return myPieces[myIndex]; } - public Object getValue(){ + public String getValue(){ return myPieces[myIndex+1]; } - public Object setValue (Object value) { + public String setValue (String value) { throw new UnsupportedOperationException(); } public boolean equals(Object o) { @@ -145,12 +145,12 @@ class MimeType implements Serializable, Cloneable { /** * Parameter map entry set iterator. */ - private class ParameterMapEntrySetIterator implements Iterator { + private class ParameterMapEntrySetIterator implements Iterator> { private int myIndex = 2; public boolean hasNext() { return myIndex < myPieces.length; } - public Object next() { + public Map.Entry next() { if (hasNext()) { ParameterMapEntry result = new ParameterMapEntry (myIndex); myIndex += 2; @@ -167,8 +167,8 @@ class MimeType implements Serializable, Cloneable { /** * Parameter map entry set. */ - private class ParameterMapEntrySet extends AbstractSet { - public Iterator iterator() { + private class ParameterMapEntrySet extends AbstractSet> { + public Iterator> iterator() { return new ParameterMapEntrySetIterator(); } public int size() { @@ -179,8 +179,8 @@ class MimeType implements Serializable, Cloneable { /** * Parameter map. */ - private class ParameterMap extends AbstractMap { - public Set entrySet() { + private class ParameterMap extends AbstractMap { + public Set> entrySet() { if (myEntrySet == null) { myEntrySet = new ParameterMapEntrySet(); } @@ -234,7 +234,7 @@ class MimeType implements Serializable, Cloneable { * * @return Parameter map for this MIME type object. */ - public Map getParameterMap() { + public Map getParameterMap() { if (myParameterMap == null) { myParameterMap = new ParameterMap(); } @@ -548,7 +548,7 @@ class MimeType implements Serializable, Cloneable { } LexicalAnalyzer theLexer = new LexicalAnalyzer (s); int theLexemeType; - Vector thePieces = new Vector(); + Vector thePieces = new Vector<>(); boolean mediaTypeIsText = false; boolean parameterNameIsCharset = false; @@ -623,7 +623,7 @@ class MimeType implements Serializable, Cloneable { // Save the pieces. Parameters are not in ascending order yet. int n = thePieces.size(); - myPieces = (String[]) thePieces.toArray (new String [n]); + myPieces = thePieces.toArray (new String [n]); // Sort the parameters into ascending order using an insertion sort. int i, j; diff --git a/jdk/src/share/classes/javax/print/PrintServiceLookup.java b/jdk/src/share/classes/javax/print/PrintServiceLookup.java index a466a8a4b38..aece5d1205a 100644 --- a/jdk/src/share/classes/javax/print/PrintServiceLookup.java +++ b/jdk/src/share/classes/javax/print/PrintServiceLookup.java @@ -69,8 +69,8 @@ import java.util.ServiceConfigurationError; public abstract class PrintServiceLookup { static class Services { - private ArrayList listOfLookupServices = null; - private ArrayList registeredServices = null; + private ArrayList listOfLookupServices = null; + private ArrayList registeredServices = null; } private static Services getServicesForContext() { @@ -83,23 +83,23 @@ public abstract class PrintServiceLookup { return services; } - private static ArrayList getListOfLookupServices() { + private static ArrayList getListOfLookupServices() { return getServicesForContext().listOfLookupServices; } - private static ArrayList initListOfLookupServices() { - ArrayList listOfLookupServices = new ArrayList(); + private static ArrayList initListOfLookupServices() { + ArrayList listOfLookupServices = new ArrayList<>(); getServicesForContext().listOfLookupServices = listOfLookupServices; return listOfLookupServices; } - private static ArrayList getRegisteredServices() { + private static ArrayList getRegisteredServices() { return getServicesForContext().registeredServices; } - private static ArrayList initRegisteredServices() { - ArrayList registeredServices = new ArrayList(); + private static ArrayList initRegisteredServices() { + ArrayList registeredServices = new ArrayList<>(); getServicesForContext().registeredServices = registeredServices; return registeredServices; } @@ -120,8 +120,8 @@ public abstract class PrintServiceLookup { public static final PrintService[] lookupPrintServices(DocFlavor flavor, AttributeSet attributes) { - ArrayList list = getServices(flavor, attributes); - return (PrintService[])(list.toArray(new PrintService[list.size()])); + ArrayList list = getServices(flavor, attributes); + return list.toArray(new PrintService[list.size()]); } @@ -148,9 +148,8 @@ public abstract class PrintServiceLookup { public static final MultiDocPrintService[] lookupMultiDocPrintServices(DocFlavor[] flavors, AttributeSet attributes) { - ArrayList list = getMultiDocServices(flavors, attributes); - return (MultiDocPrintService[]) - list.toArray(new MultiDocPrintService[list.size()]); + ArrayList list = getMultiDocServices(flavors, attributes); + return list.toArray(new MultiDocPrintService[list.size()]); } @@ -177,10 +176,10 @@ public abstract class PrintServiceLookup { public static final PrintService lookupDefaultPrintService() { - Iterator psIterator = getAllLookupServices().iterator(); + Iterator psIterator = getAllLookupServices().iterator(); while (psIterator.hasNext()) { try { - PrintServiceLookup lus = (PrintServiceLookup)psIterator.next(); + PrintServiceLookup lus = psIterator.next(); PrintService service = lus.getDefaultPrintService(); if (service != null) { return service; @@ -208,7 +207,8 @@ public abstract class PrintServiceLookup { */ public static boolean registerServiceProvider(PrintServiceLookup sp) { synchronized (PrintServiceLookup.class) { - Iterator psIterator = getAllLookupServices().iterator(); + Iterator psIterator = + getAllLookupServices().iterator(); while (psIterator.hasNext()) { try { Object lus = psIterator.next(); @@ -249,7 +249,7 @@ public abstract class PrintServiceLookup { if (service instanceof StreamPrintService) { return false; } - ArrayList registeredServices = getRegisteredServices(); + ArrayList registeredServices = getRegisteredServices(); if (registeredServices == null) { registeredServices = initRegisteredServices(); } @@ -326,9 +326,9 @@ public abstract class PrintServiceLookup { */ public abstract PrintService getDefaultPrintService(); - private static ArrayList getAllLookupServices() { + private static ArrayList getAllLookupServices() { synchronized (PrintServiceLookup.class) { - ArrayList listOfLookupServices = getListOfLookupServices(); + ArrayList listOfLookupServices = getListOfLookupServices(); if (listOfLookupServices != null) { return listOfLookupServices; } else { @@ -336,12 +336,12 @@ public abstract class PrintServiceLookup { } try { java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction() { public Object run() { Iterator iterator = ServiceLoader.load(PrintServiceLookup.class). iterator(); - ArrayList los = getListOfLookupServices(); + ArrayList los = getListOfLookupServices(); while (iterator.hasNext()) { try { los.add(iterator.next()); @@ -364,14 +364,14 @@ public abstract class PrintServiceLookup { } } - private static ArrayList getServices(DocFlavor flavor, - AttributeSet attributes) { + private static ArrayList getServices(DocFlavor flavor, + AttributeSet attributes) { - ArrayList listOfServices = new ArrayList(); - Iterator psIterator = getAllLookupServices().iterator(); + ArrayList listOfServices = new ArrayList<>(); + Iterator psIterator = getAllLookupServices().iterator(); while (psIterator.hasNext()) { try { - PrintServiceLookup lus = (PrintServiceLookup)psIterator.next(); + PrintServiceLookup lus = psIterator.next(); PrintService[] services=null; if (flavor == null && attributes == null) { try { @@ -391,7 +391,7 @@ public abstract class PrintServiceLookup { } } /* add any directly registered services */ - ArrayList registeredServices = null; + ArrayList registeredServices = null; try { SecurityManager security = System.getSecurityManager(); if (security != null) { @@ -401,8 +401,7 @@ public abstract class PrintServiceLookup { } catch (SecurityException se) { } if (registeredServices != null) { - PrintService[] services = (PrintService[]) - registeredServices.toArray( + PrintService[] services = registeredServices.toArray( new PrintService[registeredServices.size()]); for (int i=0; i getMultiDocServices(DocFlavor[] flavors, + AttributeSet attributes) { - ArrayList listOfServices = new ArrayList(); - Iterator psIterator = getAllLookupServices().iterator(); + ArrayList listOfServices = new ArrayList<>(); + Iterator psIterator = getAllLookupServices().iterator(); while (psIterator.hasNext()) { try { - PrintServiceLookup lus = (PrintServiceLookup)psIterator.next(); + PrintServiceLookup lus = psIterator.next(); MultiDocPrintService[] services = lus.getMultiDocPrintServices(flavors, attributes); if (services == null) { @@ -442,7 +441,7 @@ public abstract class PrintServiceLookup { } } /* add any directly registered services */ - ArrayList registeredServices = null; + ArrayList registeredServices = null; try { SecurityManager security = System.getSecurityManager(); if (security != null) { @@ -452,14 +451,13 @@ public abstract class PrintServiceLookup { } catch (Exception e) { } if (registeredServices != null) { - PrintService[] services = (PrintService[]) - registeredServices.toArray( - new PrintService[registeredServices.size()]); + PrintService[] services = + registeredServices.toArray(new PrintService[registeredServices.size()]); for (int i=0; i dstCategory = Destination.class; + Class amCategory = SunAlternateMedia.class; + Class fdCategory = Fidelity.class; if (attributes.containsKey(dstCategory) && !newas.containsKey(dstCategory)) @@ -315,7 +315,7 @@ public class ServiceUI { Attribute[] usAttrs = asUnsupported.toArray(); for (int i=0; i category = usAttrs[i].getCategory(); if (ps.isAttributeCategorySupported(category)) { Attribute attr = diff --git a/jdk/src/share/classes/javax/print/SimpleDoc.java b/jdk/src/share/classes/javax/print/SimpleDoc.java index 8bb812a66f4..3cf0d779086 100644 --- a/jdk/src/share/classes/javax/print/SimpleDoc.java +++ b/jdk/src/share/classes/javax/print/SimpleDoc.java @@ -89,7 +89,7 @@ public final class SimpleDoc implements Doc { throw new IllegalArgumentException("null argument(s)"); } - Class repClass = null; + Class repClass = null; try { String className = flavor.getRepresentationClassName(); sun.reflect.misc.ReflectUtil.checkPackageAccess(className); diff --git a/jdk/src/share/classes/javax/print/StreamPrintServiceFactory.java b/jdk/src/share/classes/javax/print/StreamPrintServiceFactory.java index 3199dac2985..dfa91a70fcb 100644 --- a/jdk/src/share/classes/javax/print/StreamPrintServiceFactory.java +++ b/jdk/src/share/classes/javax/print/StreamPrintServiceFactory.java @@ -59,7 +59,7 @@ import java.util.ServiceConfigurationError; public abstract class StreamPrintServiceFactory { static class Services { - private ArrayList listOfFactories = null; + private ArrayList listOfFactories = null; } private static Services getServices() { @@ -72,12 +72,12 @@ public abstract class StreamPrintServiceFactory { return services; } - private static ArrayList getListOfFactories() { + private static ArrayList getListOfFactories() { return getServices().listOfFactories; } - private static ArrayList initListOfFactories() { - ArrayList listOfFactories = new ArrayList(); + private static ArrayList initListOfFactories() { + ArrayList listOfFactories = new ArrayList<>(); getServices().listOfFactories = listOfFactories; return listOfFactories; } @@ -108,9 +108,8 @@ public abstract class StreamPrintServiceFactory { lookupStreamPrintServiceFactories(DocFlavor flavor, String outputMimeType) { - ArrayList list = getFactories(flavor, outputMimeType); - return (StreamPrintServiceFactory[]) - (list.toArray(new StreamPrintServiceFactory[list.size()])); + ArrayList list = getFactories(flavor, outputMimeType); + return list.toArray(new StreamPrintServiceFactory[list.size()]); } /** Queries the factory for the document format that is emitted @@ -162,10 +161,10 @@ public abstract class StreamPrintServiceFactory { public abstract StreamPrintService getPrintService(OutputStream out); - private static ArrayList getAllFactories() { + private static ArrayList getAllFactories() { synchronized (StreamPrintServiceFactory.class) { - ArrayList listOfFactories = getListOfFactories(); + ArrayList listOfFactories = getListOfFactories(); if (listOfFactories != null) { return listOfFactories; } else { @@ -174,12 +173,12 @@ public abstract class StreamPrintServiceFactory { try { java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction() { public Object run() { Iterator iterator = ServiceLoader.load (StreamPrintServiceFactory.class).iterator(); - ArrayList lof = getListOfFactories(); + ArrayList lof = getListOfFactories(); while (iterator.hasNext()) { try { lof.add(iterator.next()); @@ -210,17 +209,16 @@ public abstract class StreamPrintServiceFactory { return false; } - private static ArrayList getFactories(DocFlavor flavor, String outType) { + private static ArrayList getFactories(DocFlavor flavor, String outType) { if (flavor == null && outType == null) { return getAllFactories(); } - ArrayList list = new ArrayList(); - Iterator iterator = getAllFactories().iterator(); + ArrayList list = new ArrayList<>(); + Iterator iterator = getAllFactories().iterator(); while (iterator.hasNext()) { - StreamPrintServiceFactory factory = - (StreamPrintServiceFactory)iterator.next(); + StreamPrintServiceFactory factory = iterator.next(); if ((outType == null || outType.equalsIgnoreCase(factory.getOutputFormat())) && (flavor == null || diff --git a/jdk/src/share/classes/javax/print/attribute/AttributeSetUtilities.java b/jdk/src/share/classes/javax/print/attribute/AttributeSetUtilities.java index 42ebc1f512d..2c5896f633f 100644 --- a/jdk/src/share/classes/javax/print/attribute/AttributeSetUtilities.java +++ b/jdk/src/share/classes/javax/print/attribute/AttributeSetUtilities.java @@ -523,7 +523,7 @@ public final class AttributeSetUtilities { public static Class verifyAttributeCategory(Object object, Class interfaceName) { - Class result = (Class) object; + Class result = (Class) object; if (interfaceName.isAssignableFrom (result)) { return result; } diff --git a/jdk/src/share/classes/javax/print/attribute/HashAttributeSet.java b/jdk/src/share/classes/javax/print/attribute/HashAttributeSet.java index a1995014525..7956794d304 100644 --- a/jdk/src/share/classes/javax/print/attribute/HashAttributeSet.java +++ b/jdk/src/share/classes/javax/print/attribute/HashAttributeSet.java @@ -48,13 +48,13 @@ public class HashAttributeSet implements AttributeSet, Serializable { * or a subinterface thereof. * @serial */ - private Class myInterface; + private Class myInterface; /* * A HashMap used by the implementation. * The serialised form doesn't include this instance variable. */ - private transient HashMap attrMap = new HashMap(); + private transient HashMap, Attribute> attrMap = new HashMap<>(); /** * Write the instance to a stream (ie serialize the object) @@ -82,7 +82,7 @@ public class HashAttributeSet implements AttributeSet, Serializable { throws ClassNotFoundException, IOException { s.defaultReadObject(); - attrMap = new HashMap(); + attrMap = new HashMap<>(); int count = s.readInt(); Attribute attr; for (int i = 0; i < count; i++) { @@ -274,10 +274,9 @@ public class HashAttributeSet implements AttributeSet, Serializable { * Attribute Attribute}. */ public Attribute get(Class category) { - return (Attribute) - attrMap.get(AttributeSetUtilities. - verifyAttributeCategory(category, - Attribute.class)); + return attrMap.get(AttributeSetUtilities. + verifyAttributeCategory(category, + Attribute.class)); } /** diff --git a/jdk/src/share/classes/javax/print/attribute/SetOfIntegerSyntax.java b/jdk/src/share/classes/javax/print/attribute/SetOfIntegerSyntax.java index 344a5941294..67ff40c179c 100644 --- a/jdk/src/share/classes/javax/print/attribute/SetOfIntegerSyntax.java +++ b/jdk/src/share/classes/javax/print/attribute/SetOfIntegerSyntax.java @@ -112,7 +112,7 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { private static int[][] parse(String members) { // Create vector to hold int[] elements, each element being one range // parsed out of members. - Vector theRanges = new Vector(); + Vector theRanges = new Vector<>(); // Run state machine over members. int n = (members == null ? 0 : members.length()); @@ -243,7 +243,7 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { * Accumulate the given range (lb .. ub) into the canonical array form * into the given vector of int[] objects. */ - private static void accumulate(Vector ranges, int lb,int ub) { + private static void accumulate(Vector ranges, int lb,int ub) { // Make sure range is non-null. if (lb <= ub) { // Stick range at the back of the vector. @@ -253,10 +253,10 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { // with the existing ranges. for (int j = ranges.size()-2; j >= 0; -- j) { // Get lower and upper bounds of the two ranges being compared. - int[] rangea = (int[]) ranges.elementAt (j); + int[] rangea = ranges.elementAt (j); int lba = rangea[0]; int uba = rangea[1]; - int[] rangeb = (int[]) ranges.elementAt (j+1); + int[] rangeb = ranges.elementAt (j+1); int lbb = rangeb[0]; int ubb = rangeb[1]; @@ -293,8 +293,8 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { /** * Convert the given vector of int[] objects to canonical array form. */ - private static int[][] canonicalArrayForm(Vector ranges) { - return (int[][]) ranges.toArray (new int[ranges.size()][]); + private static int[][] canonicalArrayForm(Vector ranges) { + return ranges.toArray (new int[ranges.size()][]); } /** @@ -323,7 +323,7 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { private static int[][] parse(int[][] members) { // Create vector to hold int[] elements, each element being one range // parsed out of members. - Vector ranges = new Vector(); + Vector ranges = new Vector<>(); // Process all integer groups in members. int n = (members == null ? 0 : members.length); diff --git a/jdk/src/share/classes/javax/print/attribute/standard/DialogTypeSelection.java b/jdk/src/share/classes/javax/print/attribute/standard/DialogTypeSelection.java index 0a41fc23830..43cc15ee96a 100644 --- a/jdk/src/share/classes/javax/print/attribute/standard/DialogTypeSelection.java +++ b/jdk/src/share/classes/javax/print/attribute/standard/DialogTypeSelection.java @@ -26,6 +26,7 @@ package javax.print.attribute.standard; import javax.print.attribute.EnumSyntax; +import javax.print.attribute.Attribute; import javax.print.attribute.PrintRequestAttribute; /** @@ -110,7 +111,7 @@ public final class DialogTypeSelection extends EnumSyntax * @return Printing attribute class (category), an instance of class * {@link java.lang.Class java.lang.Class}. */ - public final Class getCategory() { + public final Class getCategory() { return DialogTypeSelection.class; } diff --git a/jdk/src/share/classes/javax/print/attribute/standard/MediaSize.java b/jdk/src/share/classes/javax/print/attribute/standard/MediaSize.java index e50960e5060..af173a8d6ea 100644 --- a/jdk/src/share/classes/javax/print/attribute/standard/MediaSize.java +++ b/jdk/src/share/classes/javax/print/attribute/standard/MediaSize.java @@ -56,9 +56,9 @@ public class MediaSize extends Size2DSyntax implements Attribute { private MediaSizeName mediaName; - private static HashMap mediaMap = new HashMap(100, 10); + private static HashMap mediaMap = new HashMap<>(100, 10); - private static Vector sizeVector = new Vector(100, 10); + private static Vector sizeVector = new Vector<>(100, 10); /** * Construct a new media size attribute from the given floating-point @@ -174,7 +174,7 @@ public class MediaSize extends Size2DSyntax implements Attribute { * with any size. */ public static MediaSize getMediaSizeForName(MediaSizeName media) { - return (MediaSize)mediaMap.get(media); + return mediaMap.get(media); } /** @@ -213,7 +213,7 @@ public class MediaSize extends Size2DSyntax implements Attribute { float diffy = y; for (int i=0; i < sizeVector.size() ; i++) { - MediaSize mediaSize = (MediaSize)sizeVector.elementAt(i); + MediaSize mediaSize = sizeVector.elementAt(i); dim = mediaSize.getSize(units); if (x == dim[0] && y == dim[1]) { match = mediaSize; diff --git a/jdk/src/share/classes/javax/print/attribute/standard/PrinterStateReasons.java b/jdk/src/share/classes/javax/print/attribute/standard/PrinterStateReasons.java index de695b78aa0..89b08f311ad 100644 --- a/jdk/src/share/classes/javax/print/attribute/standard/PrinterStateReasons.java +++ b/jdk/src/share/classes/javax/print/attribute/standard/PrinterStateReasons.java @@ -242,16 +242,18 @@ public final class PrinterStateReasons extends AbstractSet { private Severity mySeverity; - private Set myEntrySet; - public PrinterStateReasonSet(Severity severity, Set entrySet) { + private Set> myEntrySet; + + public PrinterStateReasonSet(Severity severity, + Set> entrySet) { mySeverity = severity; myEntrySet = entrySet; } public int size() { int result = 0; - Iterator iter = iterator(); + Iterator iter = iterator(); while (iter.hasNext()) { iter.next(); ++ result; @@ -259,19 +261,19 @@ public final class PrinterStateReasons return result; } - public Iterator iterator() { + public Iterator iterator() { return new PrinterStateReasonSetIterator(mySeverity, myEntrySet.iterator()); } } - private class PrinterStateReasonSetIterator implements Iterator { + private class PrinterStateReasonSetIterator implements Iterator { private Severity mySeverity; - private Iterator myIterator; - private Map.Entry myEntry; + private Iterator> myIterator; + private Map.Entry myEntry; public PrinterStateReasonSetIterator(Severity severity, - Iterator iterator) { + Iterator> iterator) { mySeverity = severity; myIterator = iterator; goToNext(); @@ -280,8 +282,8 @@ public final class PrinterStateReasons private void goToNext() { myEntry = null; while (myEntry == null && myIterator.hasNext()) { - myEntry = (Map.Entry) myIterator.next(); - if ((Severity) myEntry.getValue() != mySeverity) { + myEntry = myIterator.next(); + if (myEntry.getValue() != mySeverity) { myEntry = null; } } @@ -291,11 +293,11 @@ public final class PrinterStateReasons return myEntry != null; } - public Object next() { + public PrinterStateReason next() { if (myEntry == null) { throw new NoSuchElementException(); } - Object result = myEntry.getKey(); + PrinterStateReason result = myEntry.getKey(); goToNext(); return result; } From ad5b8ee3f0d1c9ff4b320dc266f80cdae3ce16de Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Wed, 21 May 2014 14:07:06 +0400 Subject: [PATCH 008/192] 8036110: In TextField can only select text visible or to the left of the cursor Reviewed-by: serb, pchelko --- .../native/sun/windows/awt_TextField.cpp | 3 + .../SelectionInvisibleTest.java | 85 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 jdk/test/java/awt/TextField/SelectionInvisibleTest/SelectionInvisibleTest.java diff --git a/jdk/src/windows/native/sun/windows/awt_TextField.cpp b/jdk/src/windows/native/sun/windows/awt_TextField.cpp index c6d3f21ae1d..b37b5c74596 100644 --- a/jdk/src/windows/native/sun/windows/awt_TextField.cpp +++ b/jdk/src/windows/native/sun/windows/awt_TextField.cpp @@ -200,7 +200,10 @@ AwtTextField::HandleEvent(MSG *msg, BOOL synthetic) si.cbSize = sizeof(si); si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; + SendMessage(EM_SHOWSCROLLBAR, SB_HORZ, TRUE); VERIFY(::GetScrollInfo(GetHWnd(), SB_HORZ, &si)); + SendMessage(EM_SHOWSCROLLBAR, SB_HORZ, FALSE); + if (bScrollLeft == TRUE) { si.nPos = si.nPos - si.nPage / 2; si.nPos = max(si.nMin, si.nPos); diff --git a/jdk/test/java/awt/TextField/SelectionInvisibleTest/SelectionInvisibleTest.java b/jdk/test/java/awt/TextField/SelectionInvisibleTest/SelectionInvisibleTest.java new file mode 100644 index 00000000000..be451285b97 --- /dev/null +++ b/jdk/test/java/awt/TextField/SelectionInvisibleTest/SelectionInvisibleTest.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Robot; +import java.awt.TextField; +import java.awt.Toolkit; +import java.awt.event.InputEvent; +import sun.awt.SunToolkit; + +/** + * @test + * @bug 8036110 + * @author Alexander Scherbatiy + * @summary In TextField can only select text visible or to the left + * @run main SelectionInvisibleTest + */ + +public class SelectionInvisibleTest { + + private static final String TEXT = "One Two Three Four Five Six Seven Eight Nine "; + private static final String LAST_WORD = "Ten"; + + public static void main(String[] args) throws Exception { + + Frame frame = new Frame(); + frame.setSize(300, 200); + TextField textField = new TextField(TEXT + LAST_WORD, 30); + Panel panel = new Panel(new FlowLayout()); + panel.add(textField); + frame.add(panel); + frame.setVisible(true); + + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + toolkit.realSync(); + + Robot robot = new Robot(); + robot.setAutoDelay(50); + + Point point = textField.getLocationOnScreen(); + int x = point.x + textField.getWidth() / 2; + int y = point.y + textField.getHeight() / 2; + robot.mouseMove(x, y); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + toolkit.realSync(); + + robot.mousePress(InputEvent.BUTTON1_MASK); + int N = 10; + int dx = textField.getWidth() / N; + for (int i = 0; i < N; i++) { + x += dx; + robot.mouseMove(x, y); + } + robot.mouseRelease(InputEvent.BUTTON1_MASK); + toolkit.realSync(); + + if (!textField.getSelectedText().endsWith(LAST_WORD)) { + throw new RuntimeException("Last word is not selected!"); + } + } +} From 74511c3cf51528951366d3292406c38373725c9d Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Wed, 21 May 2014 14:13:17 +0400 Subject: [PATCH 009/192] 8041561: Inconsistent opacity behaviour between JCheckBox and JRadioButton Reviewed-by: malenkov --- .../swing/plaf/metal/MetalIconFactory.java | 6 +- .../JRadioButton/8041561/bug8041561.java | 103 ++++++++++++++++++ 2 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 jdk/test/javax/swing/JRadioButton/8041561/bug8041561.java diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java index e74882523d0..4e0b3535208 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java @@ -1251,8 +1251,10 @@ public class MetalIconFactory implements Serializable { g.translate(x, y); // fill interior - g.setColor(interiorColor); - g.fillRect(2,2, 9,9); + if (c.isOpaque()) { + g.setColor(interiorColor); + g.fillRect(2, 2, 9, 9); + } // draw Dark Circle (start at top, go clockwise) g.setColor(darkCircle); diff --git a/jdk/test/javax/swing/JRadioButton/8041561/bug8041561.java b/jdk/test/javax/swing/JRadioButton/8041561/bug8041561.java new file mode 100644 index 00000000000..79f737ba248 --- /dev/null +++ b/jdk/test/javax/swing/JRadioButton/8041561/bug8041561.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.AWTException; +import java.awt.Color; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Toolkit; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalLookAndFeel; +import sun.awt.SunToolkit; + +/** + * @test + * @bug 8041561 + * @author Alexander Scherbatiy + * @summary Inconsistent opacity behaviour between JCheckBox and JRadioButton + * @run main bug8041561 + */ +public class bug8041561 { + + private static JRadioButton radioButton; + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + try { + MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); + UIManager.setLookAndFeel(new MetalLookAndFeel()); + createAndShowGUI(); + } catch (UnsupportedLookAndFeelException e) { + throw new RuntimeException(e); + } + } + }); + + ((SunToolkit) Toolkit.getDefaultToolkit()).realSync(); + Thread.sleep(500); + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + try { + Point point = radioButton.getLocationOnScreen(); + int x = (int) point.getX() + radioButton.getWidth() / 2; + int y = (int) point.getY() + radioButton.getHeight() / 2; + + Robot robot = new Robot(); + Color color = robot.getPixelColor(x, y); + if (!Color.BLUE.equals(color)) { + throw new RuntimeException("JRadioButton is opaque"); + } + } catch (AWTException e) { + throw new RuntimeException(e); + } + } + }); + + } + + private static void createAndShowGUI() { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setBackground(Color.BLUE); + radioButton = new JRadioButton(); + radioButton.setOpaque(false); + JPanel panel = new JPanel(); + panel.setBackground(Color.BLUE); + panel.add(radioButton); + frame.getContentPane().add(panel); + frame.pack(); + frame.setVisible(true); + } +} From dd0ba6cac3245153787ddeadd2e931416892b504 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 21 May 2014 16:48:04 +0400 Subject: [PATCH 010/192] 8043456: KSS: javax.swing.plaf.basic.BasicInternalFrameTitlePane#postClosingEvent Reviewed-by: alexsch, serb --- .../plaf/basic/BasicInternalFrameTitlePane.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java index 33b38623425..3c4338fdc76 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java @@ -380,15 +380,11 @@ public class BasicInternalFrameTitlePane extends JComponent InternalFrameEvent e = new InternalFrameEvent( frame, InternalFrameEvent.INTERNAL_FRAME_CLOSING); // Try posting event, unless there's a SecurityManager. - if (JInternalFrame.class.getClassLoader() == null) { - try { - Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(e); - return; - } catch (SecurityException se) { - // Use dispatchEvent instead. - } + try { + Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(e); + } catch (SecurityException se) { + frame.dispatchEvent(e); } - frame.dispatchEvent(e); } From a4fbee71455e8f06be1288a3886b17796ccd1f39 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 21 May 2014 10:50:14 -0700 Subject: [PATCH 011/192] 8016451: Scary messages emitted by build.tools.generatenimbus.PainterGenerator during build Reviewed-by: alexsch, anthony --- .../generatenimbus/PainterGenerator.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/jdk/make/src/classes/build/tools/generatenimbus/PainterGenerator.java b/jdk/make/src/classes/build/tools/generatenimbus/PainterGenerator.java index 07b016d75ff..265ab3c9e65 100644 --- a/jdk/make/src/classes/build/tools/generatenimbus/PainterGenerator.java +++ b/jdk/make/src/classes/build/tools/generatenimbus/PainterGenerator.java @@ -57,6 +57,9 @@ import java.util.Map; * @author Jasper Potts */ public class PainterGenerator { + + private static final boolean debug = false; + //a handful of counters, incremented whenever the associated object type is encounted. //These counters form the basis of the field and method suffixes. //These are all 1 based, because I felt like it :-) @@ -384,16 +387,24 @@ public class PainterGenerator { } if (Float.isNaN(r)) { - System.err.println("[Error] Encountered NaN: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + if (debug) { + System.err.println("[Error] Encountered NaN: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + } return 0; } else if (Float.isInfinite(r)) { - System.err.println("[Error] Encountered Infinity: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + if (debug) { + System.err.println("[Error] Encountered Infinity: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + } return 0; } else if (r < 0) { - System.err.println("[Error] encoded value was less than 0: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + if (debug) { + System.err.println("[Error] encoded value was less than 0: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + } return 0; } else if (r > 3) { - System.err.println("[Error] encoded value was greater than 3: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + if (debug) { + System.err.println("[Error] encoded value was greater than 3: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + } return 3; } else { return r; From ae470d197084728aec6db9baa739729761d0f3e3 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 21 May 2014 11:12:18 -0700 Subject: [PATCH 012/192] 8039394: Compiler warnings about C++ exceptions in windows printing code Reviewed-by: bae, jgodinez --- .../native/sun/windows/awt_PrintJob.cpp | 90 +++++++++---------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp b/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp index b9d818e0cfd..1b59e71203c 100644 --- a/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp +++ b/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp @@ -2541,8 +2541,21 @@ JNIEXPORT void JNICALL Java_sun_awt_windows_WPrinterJob_textOut * rounded advances will drift away from the true advance. */ if (glyphPos != NULL && strLen > 0) { - xadvances = (int*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, strLen, sizeof(int)); - xyadvances = (int*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, strLen, sizeof(int) * 2); + try { + xadvances = (int*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, + strLen, sizeof(int)); + xyadvances = (int*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, strLen, + sizeof(int) * 2); + } catch (std::bad_alloc&) { + if (xadvances != NULL) { + free(xadvances); + xadvances = NULL; + } + if (xyadvances != NULL) { + free(xyadvances); + xyadvances = NULL; + } + } } if (xadvances != NULL && xyadvances != NULL) { int *inxAdvances = xadvances; @@ -2752,8 +2765,12 @@ static jbyte* reverseDIB(jbyte* imageBits, long srcWidth, long srcHeight, if ((imgWidthByteSz % sizeof(DWORD)) != 0) padBytes = sizeof(DWORD) - (imgWidthByteSz % sizeof(DWORD)); - jbyte* alignedImage = (jbyte*) SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, + jbyte* alignedImage = NULL; + try { + alignedImage = (jbyte*) SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, imgWidthByteSz+padBytes, ROUND_TO_LONG(srcHeight)); + } catch (std::bad_alloc&) { + } long newImgSize = (imgWidthByteSz+padBytes) * ROUND_TO_LONG(srcHeight); if (alignedImage != NULL) { @@ -3355,36 +3372,6 @@ static void pageFormatToSetup(JNIEnv *env, jobject job, // Set page size here. } - -/** - * Return an array of POINTS describing the paper sizes supported - * by the driver identified by 'deviceName' and 'portName'. - * If there is an error, then NULL is returned. - */ -static POINT *getPaperSizeList(LPCTSTR deviceName, LPCTSTR portName) { - DWORD numPaperSizes; - POINT *paperSizes = NULL; - - SAVE_CONTROLWORD - numPaperSizes = DeviceCapabilities(deviceName, portName, - DC_PAPERSIZE, NULL, NULL); - - if (numPaperSizes > 0) { - paperSizes = (POINT *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(*paperSizes), numPaperSizes); - - DWORD result = DeviceCapabilities(deviceName, portName, - DC_PAPERSIZE, (LPTSTR) paperSizes, - NULL); - if (result == -1) { - free((char *) paperSizes); - paperSizes = NULL; - } - } - RESTORE_CONTROLWORD - - return paperSizes; -} - static WORD getOrientationFromDevMode2(HGLOBAL hDevMode) { WORD orient = DMORIENT_PORTRAIT; @@ -3989,20 +3976,33 @@ static void matchPaperSize(HDC printDC, HGLOBAL hDevMode, HGLOBAL hDevNames, numPaperSizes = (int)DeviceCapabilities(printer, port, DC_PAPERSIZE, NULL, NULL); if (numPaperSizes > 0) { - papers = (WORD*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(WORD), numPaperSizes); - paperSizes = (POINT *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(*paperSizes), numPaperSizes); + try { + papers = (WORD*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(WORD), numPaperSizes); + paperSizes = (POINT *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(*paperSizes), numPaperSizes); + } catch (std::bad_alloc&) { + if (papers != NULL) { + free((char*)papers); + papers = NULL; + } + if (paperSizes != NULL) { + free((char *)paperSizes); + paperSizes = NULL; + } + } - DWORD result1 = DeviceCapabilities(printer, port, - DC_PAPERS, (LPTSTR) papers, NULL); - DWORD result2 = DeviceCapabilities(printer, port, - DC_PAPERSIZE, (LPTSTR) paperSizes, - NULL); + if (papers != NULL && paperSizes != NULL) { + DWORD result1 = DeviceCapabilities(printer, port, + DC_PAPERS, (LPTSTR) papers, NULL); + DWORD result2 = DeviceCapabilities(printer, port, + DC_PAPERSIZE, (LPTSTR) paperSizes, + NULL); - if (result1 == -1 || result2 == -1 ) { - free((char *) papers); - papers = NULL; - free((char *) paperSizes); - paperSizes = NULL; + if (result1 == -1 || result2 == -1 ) { + free((char *) papers); + papers = NULL; + free((char *) paperSizes); + paperSizes = NULL; + } } } From 1d4a340a2ba621d78233a2298545bd897fd94d01 Mon Sep 17 00:00:00 2001 From: Petr Pchelko Date: Thu, 22 May 2014 15:46:50 +0400 Subject: [PATCH 013/192] 8043646: libosxapp.dylib fails to build on Mac OS 10.9 with clang Reviewed-by: anthony, serb --- jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m b/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m index c7dd0b78726..7deb34d0baa 100644 --- a/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m +++ b/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m @@ -36,7 +36,7 @@ static JNIEnv *appKitEnv = NULL; static jobject appkitThreadGroup = NULL; static BOOL awtEmbedded = NO; -inline void attachCurrentThread(void** env) { +static inline void attachCurrentThread(void** env) { if ([NSThread isMainThread]) { JavaVMAttachArgs args; args.version = JNI_VERSION_1_4; From 57d0476f97b58d3afb3cb478501258475ffe6d8f Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 22 May 2014 21:05:30 +0400 Subject: [PATCH 014/192] 8043627: NPE in SynthContext in plugin mode Reviewed-by: alexsch, serb, pchelko --- .../javax/swing/plaf/synth/SynthButtonUI.java | 4 +- .../swing/plaf/synth/SynthColorChooserUI.java | 3 +- .../swing/plaf/synth/SynthComboBoxUI.java | 3 +- .../javax/swing/plaf/synth/SynthContext.java | 47 ++++--------------- .../swing/plaf/synth/SynthDesktopIconUI.java | 4 +- .../swing/plaf/synth/SynthDesktopPaneUI.java | 3 +- .../swing/plaf/synth/SynthEditorPaneUI.java | 3 +- .../synth/SynthInternalFrameTitlePane.java | 3 +- .../plaf/synth/SynthInternalFrameUI.java | 3 +- .../javax/swing/plaf/synth/SynthLabelUI.java | 3 +- .../javax/swing/plaf/synth/SynthListUI.java | 3 +- .../swing/plaf/synth/SynthMenuBarUI.java | 3 +- .../swing/plaf/synth/SynthMenuItemUI.java | 6 +-- .../javax/swing/plaf/synth/SynthMenuUI.java | 7 +-- .../swing/plaf/synth/SynthOptionPaneUI.java | 3 +- .../javax/swing/plaf/synth/SynthPanelUI.java | 3 +- .../swing/plaf/synth/SynthPopupMenuUI.java | 3 +- .../swing/plaf/synth/SynthProgressBarUI.java | 3 +- .../swing/plaf/synth/SynthRootPaneUI.java | 3 +- .../swing/plaf/synth/SynthScrollBarUI.java | 6 +-- .../swing/plaf/synth/SynthScrollPaneUI.java | 3 +- .../swing/plaf/synth/SynthSeparatorUI.java | 3 +- .../javax/swing/plaf/synth/SynthSliderUI.java | 6 +-- .../swing/plaf/synth/SynthSpinnerUI.java | 3 +- .../swing/plaf/synth/SynthSplitPaneUI.java | 9 ++-- .../swing/plaf/synth/SynthTabbedPaneUI.java | 6 +-- .../swing/plaf/synth/SynthTableHeaderUI.java | 3 +- .../javax/swing/plaf/synth/SynthTableUI.java | 3 +- .../swing/plaf/synth/SynthTextAreaUI.java | 3 +- .../swing/plaf/synth/SynthTextFieldUI.java | 3 +- .../swing/plaf/synth/SynthToolBarUI.java | 8 ++-- .../swing/plaf/synth/SynthToolTipUI.java | 3 +- .../javax/swing/plaf/synth/SynthTreeUI.java | 6 +-- .../swing/plaf/synth/SynthViewportUI.java | 3 +- .../javax/swing/plaf/synth/Test8043627.java | 39 +++++++++++++++ 35 files changed, 92 insertions(+), 125 deletions(-) create mode 100644 jdk/test/javax/swing/plaf/synth/Test8043627.java diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java index 74e13aaa900..38900d04b43 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java @@ -138,9 +138,7 @@ public class SynthButtonUI extends BasicButtonUI implements } SynthContext getContext(JComponent c, int state) { - Region region = SynthLookAndFeel.getRegion(c); - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthColorChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthColorChooserUI.java index 92566845636..72ab2b09a16 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthColorChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthColorChooserUI.java @@ -128,8 +128,7 @@ public class SynthColorChooserUI extends BasicColorChooserUI implements } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java index b36b4cf4984..b50e0e4887d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java @@ -208,8 +208,7 @@ public class SynthComboBoxUI extends BasicComboBoxUI implements } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java index 1730f25d35c..64b6e536f79 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java @@ -24,9 +24,9 @@ */ package javax.swing.plaf.synth; -import javax.swing.*; -import java.util.*; -import sun.reflect.misc.ReflectUtil; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import javax.swing.JComponent; /** * An immutable transient object containing contextual information about @@ -40,59 +40,32 @@ import sun.reflect.misc.ReflectUtil; * @author Scott Violet */ public class SynthContext { - private static final Map> contextMap; + private static final Queue queue = new ConcurrentLinkedQueue<>(); private JComponent component; private Region region; private SynthStyle style; private int state; - - static { - contextMap = new HashMap>(); + static SynthContext getContext(JComponent c, SynthStyle style, int state) { + return getContext(c, SynthLookAndFeel.getRegion(c), style, state); } - - static SynthContext getContext(Class type, JComponent component, + static SynthContext getContext(JComponent component, Region region, SynthStyle style, int state) { - SynthContext context = null; - - synchronized(contextMap) { - List instances = contextMap.get(type); - - if (instances != null) { - int size = instances.size(); - - if (size > 0) { - context = instances.remove(size - 1); - } - } - } + SynthContext context = queue.poll(); if (context == null) { - try { - context = (SynthContext) ReflectUtil.newInstance(type); - } catch (IllegalAccessException iae) { - } catch (InstantiationException ie) { - } + context = new SynthContext(); } context.reset(component, region, style, state); return context; } static void releaseContext(SynthContext context) { - synchronized(contextMap) { - List instances = contextMap.get(context.getClass()); - - if (instances == null) { - instances = new ArrayList(5); - contextMap.put(context.getClass(), instances); - } - instances.add(context); - } + queue.offer(context); } - SynthContext() { } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java index e10014100d9..8da1fe0cf3b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java @@ -144,9 +144,7 @@ public class SynthDesktopIconUI extends BasicDesktopIconUI } private SynthContext getContext(JComponent c, int state) { - Region region = SynthLookAndFeel.getRegion(c); - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java index 40300565b9a..6259171317b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java @@ -432,8 +432,7 @@ public class SynthDesktopPaneUI extends BasicDesktopPaneUI implements } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java index 2ccf59268de..69489197d6a 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java @@ -139,8 +139,7 @@ public class SynthEditorPaneUI extends BasicEditorPaneUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java index abf490ce863..92ad059085d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java @@ -68,8 +68,7 @@ class SynthInternalFrameTitlePane extends BasicInternalFrameTitlePane } public SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private Region getRegion(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameUI.java index 34c94cdbc8f..c5c1ef7fdad 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameUI.java @@ -141,8 +141,7 @@ public class SynthInternalFrameUI extends BasicInternalFrameUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthLabelUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthLabelUI.java index 45031e99188..22e57e5e4a8 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthLabelUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthLabelUI.java @@ -91,8 +91,7 @@ public class SynthLabelUI extends BasicLabelUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java index 58a443acb44..6a36a58a14f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java @@ -188,8 +188,7 @@ public class SynthListUI extends BasicListUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuBarUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuBarUI.java index 9c1f9cba227..1f096646495 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuBarUI.java @@ -116,8 +116,7 @@ public class SynthMenuBarUI extends BasicMenuBarUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java index 19ac0a760b3..956f76f1fb3 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java @@ -170,8 +170,7 @@ public class SynthMenuItemUI extends BasicMenuItemUI implements } SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } SynthContext getContext(JComponent c, Region region) { @@ -179,8 +178,7 @@ public class SynthMenuItemUI extends BasicMenuItemUI implements } private SynthContext getContext(JComponent c, Region region, int state) { - return SynthContext.getContext(SynthContext.class, c, - region, accStyle, state); + return SynthContext.getContext(c, region, accStyle, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java index 3f53f461ecc..7bb66a25c93 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java @@ -170,9 +170,7 @@ public class SynthMenuUI extends BasicMenuUI } SynthContext getContext(JComponent c, int state) { - Region region = SynthLookAndFeel.getRegion(c); - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, style, state); } SynthContext getContext(JComponent c, Region region) { @@ -180,8 +178,7 @@ public class SynthMenuUI extends BasicMenuUI } private SynthContext getContext(JComponent c, Region region, int state) { - return SynthContext.getContext(SynthContext.class, c, - region, accStyle, state); + return SynthContext.getContext(c, region, accStyle, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthOptionPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthOptionPaneUI.java index 42d454cf8d9..de6f2a7135e 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthOptionPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthOptionPaneUI.java @@ -140,8 +140,7 @@ public class SynthOptionPaneUI extends BasicOptionPaneUI implements } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPanelUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPanelUI.java index ddfff5c1597..73f37ff530b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPanelUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPanelUI.java @@ -127,8 +127,7 @@ public class SynthPanelUI extends BasicPanelUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java index d228abab79a..cbb09f29212 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java @@ -123,8 +123,7 @@ public class SynthPopupMenuUI extends BasicPopupMenuUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthProgressBarUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthProgressBarUI.java index 1afc81bb1f4..c37ce490368 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthProgressBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthProgressBarUI.java @@ -138,8 +138,7 @@ public class SynthProgressBarUI extends BasicProgressBarUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthRootPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthRootPaneUI.java index 0d437de7613..1115fe35551 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthRootPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthRootPaneUI.java @@ -80,8 +80,7 @@ public class SynthRootPaneUI extends BasicRootPaneUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java index d3e948d899c..498d69e1e86 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java @@ -185,8 +185,7 @@ public class SynthScrollBarUI extends BasicScrollBarUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region region) { @@ -199,8 +198,7 @@ public class SynthScrollBarUI extends BasicScrollBarUI if (region == Region.SCROLL_BAR_THUMB) { style = thumbStyle; } - return SynthContext.getContext(SynthContext.class, c, region, style, - state); + return SynthContext.getContext(c, region, style, state); } private int getComponentState(JComponent c, Region region) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollPaneUI.java index 6b261546408..6b3e29602de 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollPaneUI.java @@ -211,8 +211,7 @@ public class SynthScrollPaneUI extends BasicScrollPaneUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSeparatorUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSeparatorUI.java index 7e759d4e3be..158e16bd5c9 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSeparatorUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSeparatorUI.java @@ -248,8 +248,7 @@ public class SynthSeparatorUI extends SeparatorUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } public void propertyChange(PropertyChangeEvent evt) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java index 65d461264dc..5cc7cd48606 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java @@ -722,8 +722,7 @@ public class SynthSliderUI extends BasicSliderUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region subregion) { @@ -732,14 +731,13 @@ public class SynthSliderUI extends BasicSliderUI private SynthContext getContext(JComponent c, Region subregion, int state) { SynthStyle style = null; - Class klass = SynthContext.class; if (subregion == Region.SLIDER_TRACK) { style = sliderTrackStyle; } else if (subregion == Region.SLIDER_THUMB) { style = sliderThumbStyle; } - return SynthContext.getContext(klass, c, subregion, style, state); + return SynthContext.getContext(c, subregion, style, state); } private int getComponentState(JComponent c, Region region) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSpinnerUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSpinnerUI.java index d8bc4feea52..a1293dfdadd 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSpinnerUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSpinnerUI.java @@ -278,8 +278,7 @@ public class SynthSpinnerUI extends BasicSpinnerUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java index 2c5031c03d6..f82ccb37fab 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java @@ -209,8 +209,7 @@ public class SynthSplitPaneUI extends BasicSplitPaneUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } SynthContext getContext(JComponent c, Region region) { @@ -219,11 +218,9 @@ public class SynthSplitPaneUI extends BasicSplitPaneUI private SynthContext getContext(JComponent c, Region region, int state) { if (region == Region.SPLIT_PANE_DIVIDER) { - return SynthContext.getContext(SynthContext.class, c, region, - dividerStyle, state); + return SynthContext.getContext(c, region, dividerStyle, state); } - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, region, style, state); } private int getComponentState(JComponent c, Region subregion) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java index df09ba5fcfa..211e8a2c331 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java @@ -235,13 +235,11 @@ public class SynthTabbedPaneUI extends BasicTabbedPaneUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c),style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region subregion, int state){ SynthStyle style = null; - Class klass = SynthContext.class; if (subregion == Region.TABBED_PANE_TAB) { style = tabStyle; @@ -252,7 +250,7 @@ public class SynthTabbedPaneUI extends BasicTabbedPaneUI else if (subregion == Region.TABBED_PANE_CONTENT) { style = tabContentStyle; } - return SynthContext.getContext(klass, c, subregion, style, state); + return SynthContext.getContext(c, subregion, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java index a988692a4aa..f09f86d6548 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java @@ -193,8 +193,7 @@ public class SynthTableHeaderUI extends BasicTableHeaderUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java index da49bddc4c2..194e9deee84 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java @@ -246,8 +246,7 @@ public class SynthTableUI extends BasicTableUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } // diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java index 441698ce0a9..33214dad926 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java @@ -119,8 +119,7 @@ public class SynthTextAreaUI extends BasicTextAreaUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java index 7028a5a5999..6adb7538e88 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java @@ -157,8 +157,7 @@ public class SynthTextFieldUI extends BasicTextFieldUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolBarUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolBarUI.java index f65fdd14dc1..51d2fefd17e 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolBarUI.java @@ -178,19 +178,17 @@ public class SynthToolBarUI extends BasicToolBarUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region region, SynthStyle style) { - return SynthContext.getContext(SynthContext.class, c, region, + return SynthContext.getContext(c, region, style, getComponentState(c, region)); } private SynthContext getContext(JComponent c, Region region, SynthStyle style, int state) { - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, region, style, state); } private int getComponentState(JComponent c, Region region) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolTipUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolTipUI.java index afd49f4a7e5..dc42debba7d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolTipUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolTipUI.java @@ -107,8 +107,7 @@ public class SynthToolTipUI extends BasicToolTipUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java index a214532ed56..d8107879254 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java @@ -173,8 +173,7 @@ public class SynthTreeUI extends BasicTreeUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region region) { @@ -182,8 +181,7 @@ public class SynthTreeUI extends BasicTreeUI } private SynthContext getContext(JComponent c, Region region, int state) { - return SynthContext.getContext(SynthContext.class, c, - region, cellStyle, state); + return SynthContext.getContext(c, region, cellStyle, state); } private int getComponentState(JComponent c, Region region) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthViewportUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthViewportUI.java index 4c5a9b0cd88..dc3e6c6e1a1 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthViewportUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthViewportUI.java @@ -141,8 +141,7 @@ public class SynthViewportUI extends ViewportUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private Region getRegion(JComponent c) { diff --git a/jdk/test/javax/swing/plaf/synth/Test8043627.java b/jdk/test/javax/swing/plaf/synth/Test8043627.java new file mode 100644 index 00000000000..2a36634a5fd --- /dev/null +++ b/jdk/test/javax/swing/plaf/synth/Test8043627.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.swing.JButton; +import javax.swing.plaf.synth.SynthButtonUI; + +/* + * @test + * @bug 8043627 + * @summary Tests that SynthContext can be created with SecurityManager installed + * @author Sergey Malenkov + */ + +public class Test8043627 { + public static void main(String[] args) { + System.setSecurityManager(new SecurityManager()); + new SynthButtonUI().getContext(new JButton()); + } +} From 6a4110296a1a4766e50df356a5f53d8fe7ed99fc Mon Sep 17 00:00:00 2001 From: Phil Race Date: Thu, 22 May 2014 13:54:08 -0700 Subject: [PATCH 015/192] 8042855: [parfait] Potential null pointer dereference in IndicLayoutEngine.cpp Reviewed-by: bae, srl --- jdk/src/share/native/sun/font/layout/IndicLayoutEngine.cpp | 2 +- jdk/src/share/native/sun/font/layout/IndicReordering.cpp | 6 +++++- jdk/src/share/native/sun/font/layout/IndicReordering.h | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/jdk/src/share/native/sun/font/layout/IndicLayoutEngine.cpp b/jdk/src/share/native/sun/font/layout/IndicLayoutEngine.cpp index d45ebb65985..c50fbae6157 100644 --- a/jdk/src/share/native/sun/font/layout/IndicLayoutEngine.cpp +++ b/jdk/src/share/native/sun/font/layout/IndicLayoutEngine.cpp @@ -151,7 +151,7 @@ le_int32 IndicOpenTypeLayoutEngine::characterProcessing(const LEUnicode chars[], le_int32 outCharCount; if (fVersion2) { _LETRACE("v2process"); - outCharCount = IndicReordering::v2process(&chars[offset], count, fScriptCode, outChars, glyphStorage); + outCharCount = IndicReordering::v2process(&chars[offset], count, fScriptCode, outChars, glyphStorage, success); } else { _LETRACE("reorder"); outCharCount = IndicReordering::reorder(&chars[offset], count, fScriptCode, outChars, glyphStorage, &fMPreFixups, success); diff --git a/jdk/src/share/native/sun/font/layout/IndicReordering.cpp b/jdk/src/share/native/sun/font/layout/IndicReordering.cpp index 7753e246535..22bbb7cf839 100644 --- a/jdk/src/share/native/sun/font/layout/IndicReordering.cpp +++ b/jdk/src/share/native/sun/font/layout/IndicReordering.cpp @@ -1096,9 +1096,13 @@ void IndicReordering::finalReordering(LEGlyphStorage &glyphStorage, le_int32 cou le_int32 IndicReordering::v2process(const LEUnicode *chars, le_int32 charCount, le_int32 scriptCode, - LEUnicode *outChars, LEGlyphStorage &glyphStorage) + LEUnicode *outChars, LEGlyphStorage &glyphStorage, LEErrorCode& success) { const IndicClassTable *classTable = IndicClassTable::getScriptClassTable(scriptCode); + if (classTable == NULL) { + success = LE_MEMORY_ALLOCATION_ERROR; + return 0; + } DynamicProperties dynProps[INDIC_BLOCK_SIZE]; IndicReordering::getDynamicProperties(dynProps,classTable); diff --git a/jdk/src/share/native/sun/font/layout/IndicReordering.h b/jdk/src/share/native/sun/font/layout/IndicReordering.h index f90bf1ba224..ca77fe0c64a 100644 --- a/jdk/src/share/native/sun/font/layout/IndicReordering.h +++ b/jdk/src/share/native/sun/font/layout/IndicReordering.h @@ -181,7 +181,7 @@ public: static void adjustMPres(MPreFixups *mpreFixups, LEGlyphStorage &glyphStorage, LEErrorCode& success); static le_int32 v2process(const LEUnicode *theChars, le_int32 charCount, le_int32 scriptCode, - LEUnicode *outChars, LEGlyphStorage &glyphStorage); + LEUnicode *outChars, LEGlyphStorage &glyphStorage, LEErrorCode& success); static const FeatureMap *getFeatureMap(le_int32 &count); From d09ff6959851a60c50ffab7c95386621ef509b5d Mon Sep 17 00:00:00 2001 From: Phil Race Date: Thu, 22 May 2014 13:54:52 -0700 Subject: [PATCH 016/192] 8042850: [parfait]: Extra unused entries in ICU ScriptCodes enum Reviewed-by: bae, srl --- jdk/src/share/native/sun/font/layout/LEScripts.h | 6 ------ 1 file changed, 6 deletions(-) diff --git a/jdk/src/share/native/sun/font/layout/LEScripts.h b/jdk/src/share/native/sun/font/layout/LEScripts.h index 5524ef31ae3..bb1b07e032f 100644 --- a/jdk/src/share/native/sun/font/layout/LEScripts.h +++ b/jdk/src/share/native/sun/font/layout/LEScripts.h @@ -262,12 +262,6 @@ enum ScriptCodes { khojScriptCode = 157, tirhScriptCode = 158, -/** - * @stable ICU 52 - */ - aghbScriptCode = 159, - mahjScriptCode = 160, - /** * @stable ICU 2.2 */ From 13b3a50623fde05825fa9e7991de08d43c22f095 Mon Sep 17 00:00:00 2001 From: Omair Majid Date: Fri, 23 May 2014 11:04:32 -0400 Subject: [PATCH 017/192] 8043805: Allow using a system-installed libjpeg Reviewed-by: andrew, anthony, prr --- common/autoconf/generated-configure.sh | 77 ++++++++++++++++++++------ common/autoconf/libraries.m4 | 35 ++++++++++-- 2 files changed, 91 insertions(+), 21 deletions(-) diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index a146145de81..676ed1e65a9 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -1081,6 +1081,7 @@ enable_freetype_bundling with_alsa with_alsa_include with_alsa_lib +with_libjpeg with_giflib with_lcms with_libpng @@ -1938,6 +1939,8 @@ Optional Packages: headers under PATH/include) --with-alsa-include specify directory for the alsa include files --with-alsa-lib specify directory for the alsa library + --with-libjpeg use libjpeg from build system or OpenJDK source + (system, bundled) [bundled] --with-giflib use giflib from build system or OpenJDK source (system, bundled) [bundled] --with-lcms use lcms2 from build system or OpenJDK source @@ -4253,7 +4256,7 @@ TOOLCHAIN_DESCRIPTION_xlc="IBM XL C/C++" #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1398861894 +DATE_WHEN_GENERATED=1400601642 ############################################################################### # @@ -47176,10 +47179,43 @@ done # Check for the jpeg library # - USE_EXTERNAL_LIBJPEG=true - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ljpeg" >&5 -$as_echo_n "checking for main in -ljpeg... " >&6; } -if ${ac_cv_lib_jpeg_main+:} false; then : + +# Check whether --with-libjpeg was given. +if test "${with_libjpeg+set}" = set; then : + withval=$with_libjpeg; +fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for which libjpeg to use" >&5 +$as_echo_n "checking for which libjpeg to use... " >&6; } + + # default is bundled + DEFAULT_LIBJPEG=bundled + + # + # if user didn't specify, use DEFAULT_LIBJPEG + # + if test "x${with_libjpeg}" = "x"; then + with_libjpeg=${DEFAULT_LIBJPEG} + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_libjpeg}" >&5 +$as_echo "${with_libjpeg}" >&6; } + + if test "x${with_libjpeg}" = "xbundled"; then + USE_EXTERNAL_LIBJPEG=false + elif test "x${with_libjpeg}" = "xsystem"; then + ac_fn_cxx_check_header_mongrel "$LINENO" "jpeglib.h" "ac_cv_header_jpeglib_h" "$ac_includes_default" +if test "x$ac_cv_header_jpeglib_h" = xyes; then : + +else + as_fn_error $? "--with-libjpeg=system specified, but jpeglib.h not found!" "$LINENO" 5 +fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for jpeg_CreateDecompress in -ljpeg" >&5 +$as_echo_n "checking for jpeg_CreateDecompress in -ljpeg... " >&6; } +if ${ac_cv_lib_jpeg_jpeg_CreateDecompress+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -47187,27 +47223,33 @@ LIBS="-ljpeg $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char jpeg_CreateDecompress (); int main () { -return main (); +return jpeg_CreateDecompress (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : - ac_cv_lib_jpeg_main=yes + ac_cv_lib_jpeg_jpeg_CreateDecompress=yes else - ac_cv_lib_jpeg_main=no + ac_cv_lib_jpeg_jpeg_CreateDecompress=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jpeg_main" >&5 -$as_echo "$ac_cv_lib_jpeg_main" >&6; } -if test "x$ac_cv_lib_jpeg_main" = xyes; then : +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jpeg_jpeg_CreateDecompress" >&5 +$as_echo "$ac_cv_lib_jpeg_jpeg_CreateDecompress" >&6; } +if test "x$ac_cv_lib_jpeg_jpeg_CreateDecompress" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBJPEG 1 _ACEOF @@ -47215,13 +47257,16 @@ _ACEOF LIBS="-ljpeg $LIBS" else - USE_EXTERNAL_LIBJPEG=false - { $as_echo "$as_me:${as_lineno-$LINENO}: Will use jpeg decoder bundled with the OpenJDK source" >&5 -$as_echo "$as_me: Will use jpeg decoder bundled with the OpenJDK source" >&6;} - + as_fn_error $? "--with-libjpeg=system specified, but no libjpeg found" "$LINENO" 5 fi + USE_EXTERNAL_LIBJPEG=true + else + as_fn_error $? "Invalid use of --with-libjpeg: ${with_libjpeg}, use 'system' or 'bundled'" "$LINENO" 5 + fi + + ############################################################################### # diff --git a/common/autoconf/libraries.m4 b/common/autoconf/libraries.m4 index 6ee3221ad96..5f9546f0770 100644 --- a/common/autoconf/libraries.m4 +++ b/common/autoconf/libraries.m4 @@ -620,11 +620,36 @@ AC_DEFUN_ONCE([LIB_SETUP_MISC_LIBS], # Check for the jpeg library # - USE_EXTERNAL_LIBJPEG=true - AC_CHECK_LIB(jpeg, main, [], - [ USE_EXTERNAL_LIBJPEG=false - AC_MSG_NOTICE([Will use jpeg decoder bundled with the OpenJDK source]) - ]) + AC_ARG_WITH(libjpeg, [AS_HELP_STRING([--with-libjpeg], + [use libjpeg from build system or OpenJDK source (system, bundled) @<:@bundled@:>@])]) + + AC_MSG_CHECKING([for which libjpeg to use]) + + # default is bundled + DEFAULT_LIBJPEG=bundled + + # + # if user didn't specify, use DEFAULT_LIBJPEG + # + if test "x${with_libjpeg}" = "x"; then + with_libjpeg=${DEFAULT_LIBJPEG} + fi + + AC_MSG_RESULT(${with_libjpeg}) + + if test "x${with_libjpeg}" = "xbundled"; then + USE_EXTERNAL_LIBJPEG=false + elif test "x${with_libjpeg}" = "xsystem"; then + AC_CHECK_HEADER(jpeglib.h, [], + [ AC_MSG_ERROR([--with-libjpeg=system specified, but jpeglib.h not found!])]) + AC_CHECK_LIB(jpeg, jpeg_CreateDecompress, [], + [ AC_MSG_ERROR([--with-libjpeg=system specified, but no libjpeg found])]) + + USE_EXTERNAL_LIBJPEG=true + else + AC_MSG_ERROR([Invalid use of --with-libjpeg: ${with_libjpeg}, use 'system' or 'bundled']) + fi + AC_SUBST(USE_EXTERNAL_LIBJPEG) ############################################################################### From e563c48360d58f0baca9bd0a77ed875808f31c30 Mon Sep 17 00:00:00 2001 From: Omair Majid Date: Fri, 23 May 2014 11:04:37 -0400 Subject: [PATCH 018/192] 8043805: Allow using a system-installed libjpeg Reviewed-by: andrew, anthony, prr --- jdk/make/lib/Awt2dLibraries.gmk | 67 +++++++++++++------ .../imageio/plugins/jpeg/JPEGImageReader.java | 2 +- .../imageio/plugins/jpeg/JPEGImageWriter.java | 2 +- .../sun/awt/image/JPEGImageDecoder.java | 2 +- .../native/sun/awt/image/jpeg/imageioJPEG.c | 2 +- 5 files changed, 49 insertions(+), 26 deletions(-) diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index 06a5672d00a..c473784f16e 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -709,21 +709,24 @@ $(BUILD_LIBLCMS): $(BUILD_LIBAWT) ########################################################################################## +BUILD_LIBJAVAJPEG_DIR := $(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg + ifdef OPENJDK - BUILD_LIBJPEG_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjpeg/mapfile-vers + BUILD_LIBJAVAJPEG_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjpeg/mapfile-vers else - BUILD_LIBJPEG_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjpeg/mapfile-vers-closed - BUILD_LIBJPEG_CLOSED_SRC := $(JDK_TOPDIR)/src/closed/share/native/sun/awt/image/jpeg - BUILD_LIBJPEG_CLOSED_INCLUDES := -I$(BUILD_LIBJPEG_CLOSED_SRC) + BUILD_LIBJAVAJPEG_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjpeg/mapfile-vers-closed + BUILD_LIBJAVAJPEG_CLOSED_SRC := $(JDK_TOPDIR)/src/closed/share/native/sun/awt/image/jpeg + BUILD_LIBJAVAJPEG_CLOSED_INCLUDES := -I$(BUILD_LIBJAVAJPEG_CLOSED_SRC) endif -BUILD_LIBJPEG_REORDER := +BUILD_LIBJAVAJPEG_REORDER := ifeq ($(OPENJDK_TARGET_OS), solaris) ifneq ($(OPENJDK_TARGET_CPU), x86_64) - BUILD_LIBJPEG_REORDER := $(JDK_TOPDIR)/make/mapfiles/libjpeg/reorder-$(OPENJDK_TARGET_CPU) + BUILD_LIBJAVAJPEG_REORDER := $(JDK_TOPDIR)/make/mapfiles/libjpeg/reorder-$(OPENJDK_TARGET_CPU) endif endif + # Suppress gcc warnings like "variable might be clobbered by 'longjmp' # or 'vfork'": this warning indicates that some variable is placed to # a register by optimized compiler and it's value might be lost on longjmp(). @@ -735,37 +738,50 @@ endif # $(shell $(EXPR) $(CC_MAJORVER) \> 4 \| \ # \( $(CC_MAJORVER) = 4 \& $(CC_MINORVER) \>= 3 \) ) # ifeq ($(CC_43_OR_NEWER), 1) -# BUILD_LIBJPEG_CFLAGS_linux += -Wno-clobbered +# BUILD_LIBJAVAJPEG_CFLAGS_linux += -Wno-clobbered # endif #endif -$(eval $(call SetupNativeCompilation,BUILD_LIBJPEG, \ - LIBRARY := jpeg, \ +ifeq ($(USE_EXTERNAL_LIBJPEG), true) + LIBJPEG_LIBS := -ljpeg + BUILD_LIBJAVAJPEG_INCLUDE_FILES := \ + imageIOJPEG.c \ + jpegdecoder.c + BUILD_LIBJAVAJPEG_HEADERS := +else + LIBJPEG_LIBS := + BUILD_LIBJAVAJPEG_INCLUDE_FILES := + BUILD_LIBJAVAJPEG_HEADERS := -I$(BUILD_LIBJAVAJPEG_DIR) +endif + +$(eval $(call SetupNativeCompilation,BUILD_LIBJAVAJPEG, \ + LIBRARY := javajpeg, \ OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \ - SRC := $(BUILD_LIBJPEG_CLOSED_SRC) \ - $(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg, \ + SRC := $(BUILD_LIBJAVAJPEG_CLOSED_SRC) \ + $(BUILD_LIBJAVAJPEG_DIR), \ + INCLUDE_FILES := $(BUILD_LIBJAVAJPEG_INCLUDE_FILES), \ LANG := C, \ OPTIMIZATION := HIGHEST, \ CFLAGS := $(CFLAGS_JDKLIB) \ - $(BUILD_LIBJPEG_CLOSED_INCLUDES) \ - -I$(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg, \ - MAPFILE := $(BUILD_LIBJPEG_MAPFILE), \ - LDFLAGS := $(LDFLAGS_JDKLIB) \ + $(BUILD_LIBJAVAJPEG_CLOSED_INCLUDES) \ + $(BUILD_LIBJAVAJPEG_HEADERS), \ + MAPFILE := $(BUILD_LIBJAVAJPEG_MAPFILE), \ + LDFLAGS := $(LDFLAGS_JDKLIB) $(LIBJPEG_LIBS) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_windows := $(WIN_JAVA_LIB) jvm.lib, \ LDFLAGS_SUFFIX := $(LDFLAGS_JDKLIB_SUFFIX), \ VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \ RC_FLAGS := $(RC_FLAGS) \ - -D "JDK_FNAME=jpeg.dll" \ - -D "JDK_INTERNAL_NAME=jpeg" \ + -D "JDK_FNAME=javajpeg.dll" \ + -D "JDK_INTERNAL_NAME=javajpeg" \ -D "JDK_FTYPE=0x2L", \ - REORDER := $(BUILD_LIBJPEG_REORDER), \ + REORDER := $(BUILD_LIBJAVAJPEG_REORDER), \ OBJECT_DIR := $(JDK_OUTPUTDIR)/objs/libjpeg, \ DEBUG_SYMBOLS := $(DEBUG_ALL_BINARIES))) -$(BUILD_LIBJPEG): $(BUILD_LIBJAVA) +$(BUILD_LIBJAVAJPEG): $(BUILD_LIBJAVA) -BUILD_LIBRARIES += $(BUILD_LIBJPEG) +BUILD_LIBRARIES += $(BUILD_LIBJAVAJPEG) ########################################################################################## @@ -1213,6 +1229,13 @@ ifndef BUILD_HEADLESS_ONLY GIFLIB_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/sun/awt/giflib endif + ifeq ($(USE_EXTERNAL_LIBJPEG), true) + LIBJPEG_LDFLAGS := -ljpeg + else + LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg + LIBJPEG_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg + endif + ifeq ($(USE_EXTERNAL_LIBPNG), false) LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/share/native/sun/awt/libpng LIBPNG_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/sun/awt/libpng @@ -1276,12 +1299,12 @@ ifndef BUILD_HEADLESS_ONLY LANG := C, \ OPTIMIZATION := LOW, \ CFLAGS := $(LIBSPLASHSCREEN_CFLAGS) $(CFLAGS_JDKLIB) \ - $(GIFLIB_CFLAGS) $(PNG_CFLAGS), \ + $(GIFLIB_CFLAGS) $(LIBJPEG_CFLAGS) $(PNG_CFLAGS), \ MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libsplashscreen/mapfile-vers, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_SUFFIX := $(LIBSPLASHSCREEN_LDFLAGS_SUFFIX) $(LIBZ) \ - $(GIFLIB_LDFLAGS) $(PNG_LIBS), \ + $(GIFLIB_LDFLAGS) $(LIBJPEG_LDFLAGS) $(PNG_LIBS), \ LDFLAGS_SUFFIX_solaris := -lc, \ VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \ RC_FLAGS := $(RC_FLAGS) \ diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java index 961255ce8c9..8b6cdcbce13 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java @@ -89,7 +89,7 @@ public class JPEGImageReader extends ImageReader { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Void run() { - System.loadLibrary("jpeg"); + System.loadLibrary("javajpeg"); return null; } }); diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java index 1913ef4641f..477e6738b5f 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java @@ -179,7 +179,7 @@ public class JPEGImageWriter extends ImageWriter { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Void run() { - System.loadLibrary("jpeg"); + System.loadLibrary("javajpeg"); return null; } }); diff --git a/jdk/src/share/classes/sun/awt/image/JPEGImageDecoder.java b/jdk/src/share/classes/sun/awt/image/JPEGImageDecoder.java index 70dacb195c3..b1fce632d1c 100644 --- a/jdk/src/share/classes/sun/awt/image/JPEGImageDecoder.java +++ b/jdk/src/share/classes/sun/awt/image/JPEGImageDecoder.java @@ -56,7 +56,7 @@ public class JPEGImageDecoder extends ImageDecoder { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Void run() { - System.loadLibrary("jpeg"); + System.loadLibrary("javajpeg"); return null; } }); diff --git a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c index 5f7a0364866..2fb507c0f66 100644 --- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c +++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c @@ -51,7 +51,7 @@ /* headers from the JPEG library */ #include -#include "jerror.h" +#include #undef MAX #define MAX(a,b) ((a) > (b) ? (a) : (b)) From d454bf5946dff6d32bb6ebf77cf83e61abc198f6 Mon Sep 17 00:00:00 2001 From: Petr Pchelko Date: Fri, 23 May 2014 19:43:14 +0400 Subject: [PATCH 019/192] 8043610: Sorting columns in JFileChooser fails with AppContext NPE Reviewed-by: anthony, alexsch --- .../com/sun/java/swing/SwingUtilities3.java | 6 +- jdk/src/share/classes/java/awt/Component.java | 2 +- .../share/classes/javax/swing/JComponent.java | 19 ++-- .../swing/JComponent/8043610/bug8043610.java | 100 ++++++++++++++++++ 4 files changed, 114 insertions(+), 13 deletions(-) create mode 100644 jdk/test/javax/swing/JComponent/8043610/bug8043610.java diff --git a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java index 1ca240dd743..b50fb2ae1b2 100644 --- a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -27,6 +27,8 @@ package com.sun.java.swing; import sun.awt.EventQueueDelegate; import sun.awt.AppContext; +import sun.awt.SunToolkit; + import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; @@ -117,8 +119,8 @@ public class SwingUtilities3 { public static RepaintManager getDelegateRepaintManager(Component component) { RepaintManager delegate = null; - if (Boolean.TRUE == AppContext.getAppContext().get( - DELEGATE_REPAINT_MANAGER_KEY)) { + if (Boolean.TRUE == SunToolkit.targetToAppContext(component) + .get(DELEGATE_REPAINT_MANAGER_KEY)) { while (delegate == null && component != null) { while (component != null && ! (component instanceof JComponent)) { diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index cd6ae69de1d..0fce6a51b49 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -3411,7 +3411,7 @@ public abstract class Component implements ImageObserver, MenuContainer, (width > 0) && (height > 0)) { PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE, new Rectangle(x, y, width, height)); - Toolkit.getEventQueue().postEvent(e); + SunToolkit.postEvent(SunToolkit.targetToAppContext(this), e); } } } diff --git a/jdk/src/share/classes/javax/swing/JComponent.java b/jdk/src/share/classes/javax/swing/JComponent.java index 2d2745957e7..4eb85b23a53 100644 --- a/jdk/src/share/classes/javax/swing/JComponent.java +++ b/jdk/src/share/classes/javax/swing/JComponent.java @@ -63,6 +63,7 @@ import javax.swing.plaf.*; import static javax.swing.ClientPropertyKey.*; import javax.accessibility.*; +import sun.awt.SunToolkit; import sun.swing.SwingUtilities2; import sun.swing.UIClientPropertyKey; @@ -4802,7 +4803,8 @@ public abstract class JComponent extends Container implements Serializable, * @see RepaintManager#addDirtyRegion */ public void repaint(long tm, int x, int y, int width, int height) { - RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height); + RepaintManager.currentManager(SunToolkit.targetToAppContext(this)) + .addDirtyRegion(this, x, y, width, height); } @@ -4856,7 +4858,7 @@ public abstract class JComponent extends Container implements Serializable, // which was causing some people grief. return; } - if (SwingUtilities.isEventDispatchThread()) { + if (SunToolkit.isDispatchThreadForAppContext(this)) { invalidate(); RepaintManager.currentManager(this).addInvalidComponent(this); } @@ -4870,15 +4872,12 @@ public abstract class JComponent extends Container implements Serializable, } setFlag(REVALIDATE_RUNNABLE_SCHEDULED, true); } - Runnable callRevalidate = new Runnable() { - public void run() { - synchronized(JComponent.this) { - setFlag(REVALIDATE_RUNNABLE_SCHEDULED, false); - } - revalidate(); + SunToolkit.executeOnEventHandlerThread(this, () -> { + synchronized(JComponent.this) { + setFlag(REVALIDATE_RUNNABLE_SCHEDULED, false); } - }; - SwingUtilities.invokeLater(callRevalidate); + revalidate(); + }); } } diff --git a/jdk/test/javax/swing/JComponent/8043610/bug8043610.java b/jdk/test/javax/swing/JComponent/8043610/bug8043610.java new file mode 100644 index 00000000000..b4fc89f0552 --- /dev/null +++ b/jdk/test/javax/swing/JComponent/8043610/bug8043610.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + @test + @bug 8043610 + @summary Tests that JComponent invalidate, revalidate and repaint methods could + be called from any thread + @author Petr Pchelko +*/ + +import sun.awt.SunToolkit; + +import javax.swing.*; +import java.awt.*; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; + +public class bug8043610 { + private static volatile JFrame frame; + private static volatile JComponent component; + + public static void main(String[] args) throws Exception { + ThreadGroup stubTG = new ThreadGroup(getRootThreadGroup(), "Stub Thread Group"); + ThreadGroup swingTG = new ThreadGroup(getRootThreadGroup(), "SwingTG"); + try { + Thread stubThread = new Thread(stubTG, SunToolkit::createNewAppContext); + stubThread.start(); + stubThread.join(); + + CountDownLatch startSwingLatch = new CountDownLatch(1); + new Thread(swingTG, () -> { + SunToolkit.createNewAppContext(); + SwingUtilities.invokeLater(() -> { + frame = new JFrame(); + component = new JLabel("Test Text"); + frame.add(component); + frame.setBounds(100, 100, 100, 100); + frame.setVisible(true); + startSwingLatch.countDown(); + }); + }).start(); + startSwingLatch.await(); + + AtomicReference caughtException = new AtomicReference<>(); + Thread checkThread = new Thread(getRootThreadGroup(), () -> { + try { + component.invalidate(); + component.revalidate(); + component.repaint(new Rectangle(0, 0, 0, 0)); + } catch (Exception e) { + caughtException.set(e); + } + }); + checkThread.start(); + checkThread.join(); + + if (caughtException.get() != null) { + throw new RuntimeException("Failed. Caught exception!", caughtException.get()); + } + } finally { + new Thread(swingTG, () -> SwingUtilities.invokeLater(() -> { + if (frame != null) { + frame.dispose(); + } + })).start(); + } + } + + private static ThreadGroup getRootThreadGroup() { + ThreadGroup currentTG = Thread.currentThread().getThreadGroup(); + ThreadGroup parentTG = currentTG.getParent(); + while (parentTG != null) { + currentTG = parentTG; + parentTG = currentTG.getParent(); + } + return currentTG; + } +} From e6130c49cd9f31c4de2387f97c6a94dfc4e22598 Mon Sep 17 00:00:00 2001 From: Petr Pchelko Date: Fri, 23 May 2014 19:48:25 +0400 Subject: [PATCH 020/192] 8031485: [macosx] Combo box consuming escape key events Reviewed-by: serb, alexsch --- .../classes/com/apple/laf/AquaComboBoxUI.java | 12 +-- .../ConsumedEscTest/ConsumedEscTest.java | 82 +++++++++++++++++++ 2 files changed, 89 insertions(+), 5 deletions(-) create mode 100644 jdk/test/javax/swing/JComboBox/ConsumedEscTest/ConsumedEscTest.java diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java index c38e108633b..75c7babb58a 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java @@ -522,15 +522,17 @@ public class AquaComboBoxUI extends BasicComboBoxUI implements Sizeable { }; @SuppressWarnings("serial") // anonymous class - private static Action hideAction = new AbstractAction() { + private final Action hideAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { final JComboBox comboBox = (JComboBox)e.getSource(); + comboBox.firePopupMenuCanceled(); + comboBox.setPopupVisible(false); + } - if (comboBox.isPopupVisible()) { - comboBox.firePopupMenuCanceled(); - comboBox.setPopupVisible(false); - } + @Override + public boolean isEnabled() { + return comboBox.isPopupVisible() && super.isEnabled(); } }; diff --git a/jdk/test/javax/swing/JComboBox/ConsumedEscTest/ConsumedEscTest.java b/jdk/test/javax/swing/JComboBox/ConsumedEscTest/ConsumedEscTest.java new file mode 100644 index 00000000000..2828d7af864 --- /dev/null +++ b/jdk/test/javax/swing/JComboBox/ConsumedEscTest/ConsumedEscTest.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.swing.*; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; + +/* + @test + @bug 8031485 + @summary Combo box consuming escape and enter key events + @author Petr Pchelko + @library ../../../../lib/testlibrary/ + @build ExtendedRobot + @run main ConsumedEscTest +*/ +public class ConsumedEscTest { + private static volatile JFrame frame; + private static volatile boolean passed = false; + + public static void main(String... args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + frame = new JFrame(); + JComboBox combo = new JComboBox<>(new String[]{"one", "two", "three"}); + JPanel panel = new JPanel(); + panel.add(combo); + combo.requestFocusInWindow(); + frame.setBounds(100, 150, 300, 100); + addAction(panel); + frame.add(panel); + frame.setVisible(true); + }); + + ExtendedRobot robot = new ExtendedRobot(); + robot.waitForIdle(); + robot.type(KeyEvent.VK_ESCAPE); + robot.waitForIdle(); + if (!passed) { + throw new RuntimeException("FAILED: ESC was consumed by combo box"); + } + } finally { + if (frame != null) { + frame.dispose(); + } + } + } + + private static void addAction(JComponent comp) { + KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); + Object actionKey = "cancel"; + comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(k, actionKey); + Action cancelAction = new AbstractAction() { + @Override + public void actionPerformed(ActionEvent ev) { + passed = true; + } + }; + comp.getActionMap().put(actionKey, cancelAction); + } + +} From 7a0d4ecc23de5539cf16209e000c5ebc7526b738 Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Mon, 26 May 2014 14:33:49 +0400 Subject: [PATCH 021/192] 8040291: [macosx] Http-Images are not fully loaded when using ImageIcon Reviewed-by: serb, pchelko --- .../share/classes/java/awt/MediaTracker.java | 9 +- jdk/src/share/classes/sun/awt/SunToolkit.java | 16 +- .../image/MultiResolutionToolkitImage.java | 13 ++ .../MultiResolutionToolkitImageTest.java | 158 ++++++++++++++++++ 4 files changed, 189 insertions(+), 7 deletions(-) create mode 100644 jdk/test/java/awt/image/multiresolution/MultiResolutionToolkitImageTest.java diff --git a/jdk/src/share/classes/java/awt/MediaTracker.java b/jdk/src/share/classes/java/awt/MediaTracker.java index 4dd0fb5abfe..a551fef73d4 100644 --- a/jdk/src/share/classes/java/awt/MediaTracker.java +++ b/jdk/src/share/classes/java/awt/MediaTracker.java @@ -226,7 +226,9 @@ public class MediaTracker implements java.io.Serializable { addImageImpl(image, id, w, h); Image rvImage = getResolutionVariant(image); if (rvImage != null) { - addImageImpl(rvImage, id, 2 * w, 2 * h); + addImageImpl(rvImage, id, + w == -1 ? -1 : 2 * w, + h == -1 ? -1 : 2 * h); } } @@ -810,8 +812,9 @@ public class MediaTracker implements java.io.Serializable { removeImageImpl(image, id, width, height); Image rvImage = getResolutionVariant(image); if (rvImage != null) { - removeImageImpl(rvImage, id, 2 * width, 2 * height); - + removeImageImpl(rvImage, id, + width == -1 ? -1 : 2 * width, + height == -1 ? -1 : 2 * height); } notifyAll(); // Notify in case remaining images are "done". } diff --git a/jdk/src/share/classes/sun/awt/SunToolkit.java b/jdk/src/share/classes/sun/awt/SunToolkit.java index 6739a603c5d..434115bfefb 100644 --- a/jdk/src/share/classes/sun/awt/SunToolkit.java +++ b/jdk/src/share/classes/sun/awt/SunToolkit.java @@ -850,22 +850,30 @@ public abstract class SunToolkit extends Toolkit private int checkResolutionVariant(Image img, int w, int h, ImageObserver o) { ToolkitImage rvImage = getResolutionVariant(img); + int rvw = getRVSize(w); + int rvh = getRVSize(h); // Ignore the resolution variant in case of error return (rvImage == null || rvImage.hasError()) ? 0xFFFF : - checkImage(rvImage, 2 * w, 2 * h, MultiResolutionToolkitImage. + checkImage(rvImage, rvw, rvh, MultiResolutionToolkitImage. getResolutionVariantObserver( - img, o, w, h, 2 * w, 2 * h)); + img, o, w, h, rvw, rvh, true)); } private boolean prepareResolutionVariant(Image img, int w, int h, ImageObserver o) { ToolkitImage rvImage = getResolutionVariant(img); + int rvw = getRVSize(w); + int rvh = getRVSize(h); // Ignore the resolution variant in case of error return rvImage == null || rvImage.hasError() || prepareImage( - rvImage, 2 * w, 2 * h, + rvImage, rvw, rvh, MultiResolutionToolkitImage.getResolutionVariantObserver( - img, o, w, h, 2 * w, 2 * h)); + img, o, w, h, rvw, rvh, true)); + } + + private static int getRVSize(int size){ + return size == -1 ? -1 : 2 * size; } private static ToolkitImage getResolutionVariant(Image image) { diff --git a/jdk/src/share/classes/sun/awt/image/MultiResolutionToolkitImage.java b/jdk/src/share/classes/sun/awt/image/MultiResolutionToolkitImage.java index a49c8a7f59c..bde59ab6275 100644 --- a/jdk/src/share/classes/sun/awt/image/MultiResolutionToolkitImage.java +++ b/jdk/src/share/classes/sun/awt/image/MultiResolutionToolkitImage.java @@ -66,6 +66,14 @@ public class MultiResolutionToolkitImage extends ToolkitImage implements MultiRe final Image image, final ImageObserver observer, final int imgWidth, final int imgHeight, final int rvWidth, final int rvHeight) { + return getResolutionVariantObserver(image, observer, + imgWidth, imgHeight, rvWidth, rvHeight, false); + } + + public static ImageObserver getResolutionVariantObserver( + final Image image, final ImageObserver observer, + final int imgWidth, final int imgHeight, + final int rvWidth, final int rvHeight, boolean concatenateInfo) { if (observer == null) { return null; @@ -92,6 +100,11 @@ public class MultiResolutionToolkitImage extends ToolkitImage implements MultiRe y /= 2; } + if(concatenateInfo){ + flags &= ((ToolkitImage) image). + getImageRep().check(null); + } + return observer.imageUpdate( image, flags, x, y, width, height); }; diff --git a/jdk/test/java/awt/image/multiresolution/MultiResolutionToolkitImageTest.java b/jdk/test/java/awt/image/multiresolution/MultiResolutionToolkitImageTest.java new file mode 100644 index 00000000000..57a54386f0c --- /dev/null +++ b/jdk/test/java/awt/image/multiresolution/MultiResolutionToolkitImageTest.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.Toolkit; +import java.awt.image.BufferedImage; +import java.awt.image.ImageObserver; +import static java.awt.image.ImageObserver.ALLBITS; +import java.io.File; +import javax.imageio.ImageIO; +import sun.awt.OSInfo; +import sun.awt.SunToolkit; +import sun.awt.image.MultiResolutionToolkitImage; + +/** + * @test + * @bug 8040291 + * @author Alexander Scherbatiy + * @summary [macosx] Http-Images are not fully loaded when using ImageIcon + * @run main MultiResolutionToolkitImageTest + */ +public class MultiResolutionToolkitImageTest { + + private static final int IMAGE_WIDTH = 300; + private static final int IMAGE_HEIGHT = 200; + private static final Color COLOR_1X = Color.GREEN; + private static final Color COLOR_2X = Color.BLUE; + private static final String IMAGE_NAME_1X = "image.png"; + private static final String IMAGE_NAME_2X = "image@2x.png"; + private static final int WAIT_TIME = 400; + private static volatile boolean isImageLoaded = false; + private static volatile boolean isRVObserverCalled = false; + + public static void main(String[] args) throws Exception { + + if (!checkOS()) { + return; + } + generateImages(); + testToolkitMultiResolutionImageLoad(); + } + + static void testToolkitMultiResolutionImageLoad() throws Exception { + File imageFile = new File(IMAGE_NAME_1X); + String fileName = imageFile.getAbsolutePath(); + Image image = Toolkit.getDefaultToolkit().getImage(fileName); + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + toolkit.prepareImage(image, -1, -1, new LoadImageObserver()); + + final long time = WAIT_TIME + System.currentTimeMillis(); + while ((!isImageLoaded || !isRVObserverCalled) + && System.currentTimeMillis() < time) { + Thread.sleep(50); + } + + if(!isImageLoaded){ + throw new RuntimeException("Image is not loaded!"); + } + + if(!isRVObserverCalled){ + throw new RuntimeException("Resolution Variant observer is not called!"); + } + } + + static void generateImages() throws Exception { + if (!new File(IMAGE_NAME_1X).exists()) { + generateImage(1); + } + + if (!new File(IMAGE_NAME_2X).exists()) { + generateImage(2); + } + } + + static void generateImage(int scale) throws Exception { + BufferedImage image = new BufferedImage(scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT, + BufferedImage.TYPE_INT_RGB); + Graphics g = image.getGraphics(); + g.setColor(scale == 1 ? COLOR_1X : COLOR_2X); + g.fillRect(0, 0, scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT); + File file = new File(scale == 1 ? IMAGE_NAME_1X : IMAGE_NAME_2X); + ImageIO.write(image, "png", file); + } + + static boolean checkOS() { + return OSInfo.getOSType() == OSInfo.OSType.MACOSX; + } + + static class LoadImageObserver implements ImageObserver { + + @Override + public boolean imageUpdate(Image img, int infoflags, int x, int y, + int width, int height) { + + if (isRVObserver()) { + isRVObserverCalled = true; + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + Image resolutionVariant = getResolutionVariant(img); + int rvFlags = toolkit.checkImage(resolutionVariant, width, height, + new IdleImageObserver()); + if (rvFlags < infoflags) { + throw new RuntimeException("Info flags are greater than" + + " resolution varint info flags"); + } + } else if ((infoflags & ALLBITS) != 0) { + isImageLoaded = true; + } + + return (infoflags & ALLBITS) == 0; + } + } + + static boolean isRVObserver() { + Exception e = new Exception(); + + for (StackTraceElement elem : e.getStackTrace()) { + if (elem.getClassName().endsWith("MultiResolutionToolkitImage")) { + return true; + } + } + return false; + } + + static class IdleImageObserver implements ImageObserver { + + @Override + public boolean imageUpdate(Image img, int infoflags, int x, int y, + int width, int height) { + return false; + } + } + + static Image getResolutionVariant(Image image) { + return ((MultiResolutionToolkitImage) image).getResolutionVariant(); + } +} From 8fab8231ab42fefd6567f1d62e29155b06c95187 Mon Sep 17 00:00:00 2001 From: Dmitriy Ermashov Date: Mon, 26 May 2014 15:50:10 +0400 Subject: [PATCH 022/192] 8041915: Move 8 awt tests to OpenJDK regression tests tree Reviewed-by: pchelko, alexsch --- .../InvocationEventTest.java | 203 +++++++++++ .../DecoratedExceptions.java | 81 +++++ .../ShapedAndTranslucentWindows/Common.java | 316 ++++++++++++++++++ .../FocusAWTTest.java | 225 +++++++++++++ .../ShapedAndTranslucentWindows/Shaped.java | 69 ++++ .../ShapedByAPI.java | 71 ++++ .../ShapedTranslucent.java | 70 ++++ .../StaticallyShaped.java | 68 ++++ .../Translucent.java | 71 ++++ jdk/test/lib/testlibrary/ExtendedRobot.java | 45 ++- 10 files changed, 1216 insertions(+), 3 deletions(-) create mode 100644 jdk/test/java/awt/EventQueue/InvocationEventTest/InvocationEventTest.java create mode 100644 jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java create mode 100644 jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Common.java create mode 100644 jdk/test/java/awt/Window/ShapedAndTranslucentWindows/FocusAWTTest.java create mode 100644 jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Shaped.java create mode 100644 jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedByAPI.java create mode 100644 jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucent.java create mode 100644 jdk/test/java/awt/Window/ShapedAndTranslucentWindows/StaticallyShaped.java create mode 100644 jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Translucent.java diff --git a/jdk/test/java/awt/EventQueue/InvocationEventTest/InvocationEventTest.java b/jdk/test/java/awt/EventQueue/InvocationEventTest/InvocationEventTest.java new file mode 100644 index 00000000000..a0d19940340 --- /dev/null +++ b/jdk/test/java/awt/EventQueue/InvocationEventTest/InvocationEventTest.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +import java.awt.*; +import java.awt.event.*; + +/* + * @test + * @summary To Test the following assertions in InvovationEvent. + * 1.InvocationEvent when dispatched, should invoke the + * run() method of the Runnable Interface. + * 2.If catchExceptions is false, Exception should be + * propagated up to the EventDispatchThread's dispatch loop. + * 3.If catchExceptions is true, InvocationEvent.getExceptions() + * should return the exception thrown inside thr run() method. + * 4.When InvocationEvent object is posted on to the EventQueue, + * InvocationEvent.dispatch() method should be invoked by the + * EventQueue. + * 5.If the notifier object is not null, notifyAll() of the + * notifier object should be invoked when the run() method returns. + * 6.To test whether the threads are invoked in the right order + * When InvocationEvents are nested. + * 7.The getWhen method should return timestamp which is less than + * current System time and greater than the time before it has + * actually happened + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main InvocationEventTest + */ + +public class InvocationEventTest { + EventQueue eventQ1 = new EventQueue(); + + Object lock = new Object(); + + static final int delay = 5000; + + public volatile boolean notifierStatus = false; + public Object notifierLock = new Object(); + + public volatile boolean threadStatus = false; + public volatile boolean childInvoked = false; + + public synchronized void doTest() throws Exception { + // Testing assertions 1, 2 and 7: + // 1.InvocationEvent when dispatched, should invoke the + // run() method of the Runnable Interface. + // 2.If catchExceptions is false, Exception should be + // propagated up to the EventDispatchThread's dispatch loop. + // 7.The getWhen method should return timestamp which is less than + // current System time and greater than the time before it has + // actually happened + + long timeBeforeInvoking = System.currentTimeMillis(); + + Thread.sleep(10); + + InvocationEvent invoc = new InvocationEvent(this, () -> { threadStatus = true; }, lock, false); + invoc.dispatch(); + + Thread.sleep(10); + + if (!threadStatus) { + synchronized (lock) { + lock.wait(delay); + } + } + + // testing getException() when no exception is thrown + if (invoc.getWhen() <= timeBeforeInvoking || + invoc.getWhen() >= System.currentTimeMillis()) { + throw new RuntimeException("getWhen method is not getting the time at which event occured"); + } + + if (invoc.getException() != null) { + throw new RuntimeException("InvocationEvent.getException() does not return null " + + "when catchException is false"); + } + + // testing the normal behaviour of InvocationEvent + if (!threadStatus) { + throw new RuntimeException("InvocationEvent when dispatched, did not" + + " invoke the run() of the Runnable interface "); + } + threadStatus = false; + + // Testing assertion 3: + // 3.If catchExceptions is true, InvocationEvent.getExceptions() + // should return the exception thrown inside the run() method. + RuntimeException sampleExn = new RuntimeException(" test exception"); + + invoc = new InvocationEvent(this, () -> { threadStatus = true; throw sampleExn; }, lock, true); + invoc.dispatch(); + if (!threadStatus) { + synchronized (lock) { + lock.wait(delay); + } + } + // testing getException() when exception is thrown + // Should return the same exception thrown inside the run() method + if (!invoc.getException().equals(sampleExn)) { + throw new RuntimeException("getException() does not return " + + "the same Exception thrown inside the run() method "); + } + threadStatus = false; + + // Testing assertions 4 and 5: + // 4.When InvocationEvent object is posted on to the EventQueue, + // InvocationEvent.dispatch() method should be invoked by the + // EventQueue. + // 5.If the notifier object is not null, notifyAll() of the + // notifier object should be invoked when the run() method returns. + + Thread notify = new Thread(){ + public void run() { + synchronized (this) { + try { wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } + } + notifierStatus = true; + synchronized (notifierLock) { + notifierLock.notifyAll(); + } + } + }; + notify.start(); + + while (notify.getState() != Thread.State.WAITING) + Thread.sleep(delay/5); + + InvocationEvent invocation = new InvocationEvent(this, () -> { }, (Object) notify, false); + eventQ1.postEvent(invocation); + + while(!invocation.isDispatched()) + synchronized (notifierLock) { + notifierLock.wait(delay); + } + + while (notify.getState() != Thread.State.TERMINATED) + Thread.sleep(delay/5); + + if (!notifierStatus) { + throw new RuntimeException("Notifier object did not get notified" + + " When the run method of the Runnable returns "); + } + + // Testing assertion 6: + // 6.To test whether the threads are invoked in the right order + // When InvocationEvents are nested. + Thread thread = new Thread(){ + public void run() { + InvocationEvent evt = new InvocationEvent(this, () -> { childInvoked = true; }, (Object) this, false); + new EventQueue().postEvent(evt); + synchronized (this) { + try { + wait(delay); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + threadStatus = true; + } + }; + + invocation = new InvocationEvent(this, thread, lock, false); + + eventQ1.postEvent(invocation); + + while (!invocation.isDispatched()) + synchronized (lock) { + lock.wait(delay); + } + + if (!threadStatus || !childInvoked) { + throw new RuntimeException("Nesting of InvocationEvents when dispatched," + + " did not invoke the run() of the Runnables properly "); + } + } + + public static void main(String[] args) throws Exception { + new InvocationEventTest().doTest(); + } +} + diff --git a/jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java b/jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java new file mode 100644 index 00000000000..b2a0ddc6fdc --- /dev/null +++ b/jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. + */ + +import java.awt.*; + +/* + * @test + * @summary An attempt to set non-trivial background, shape, or translucency + * to a decorated toplevel should end with an exception. + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary + * @build ExtendedRobot + * @run main DecoratedExceptions + */ +public class DecoratedExceptions { + public static void main(String args[]) throws Exception{ + ExtendedRobot robot = new ExtendedRobot(); + Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(() -> { + Frame frame = new Frame("Frame"); + frame.setBounds(50,50,400,200); + try { + frame.setOpacity(0.5f); + throw new RuntimeException("No exception when Opacity set to a decorated Frame"); + }catch(IllegalComponentStateException e) { + } + try { + frame.setShape(new Rectangle(50,50,400,200)); + throw new RuntimeException("No exception when Shape set to a decorated Frame"); + }catch(IllegalComponentStateException e) { + } + try { + frame.setBackground(new Color(50, 50, 50, 100)); + throw new RuntimeException("No exception when Alpha background set to a decorated Frame"); + }catch(IllegalComponentStateException e) { + } + frame.setVisible(true); + Dialog dialog = new Dialog( frame ); + try { + dialog.setOpacity(0.5f); + throw new RuntimeException("No exception when Opacity set to a decorated Dialog"); + }catch(IllegalComponentStateException e) { + } + try { + dialog.setShape(new Rectangle(50,50,400,200)); + throw new RuntimeException("No exception when Shape set to a decorated Dialog"); + }catch(IllegalComponentStateException e) { + } + try { + dialog.setBackground(new Color(50, 50, 50, 100)); + throw new RuntimeException("No exception when Alpha background set to a decorated Dialog"); + }catch(IllegalComponentStateException e) { + } + dialog.setVisible(true); + }); + robot.waitForIdle(1000); + } +} diff --git a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Common.java b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Common.java new file mode 100644 index 00000000000..8927642ecf8 --- /dev/null +++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Common.java @@ -0,0 +1,316 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.Area; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.security.SecureRandom; + + +/* + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + */ +public abstract class Common { + + ExtendedRobot robot; + Class windowClass; + Frame background; + BufferedImage foreground; + Window window; + Container componentsContainer; + + float opacity = 1.0f; + static final int STATIC_STEP = 30; + static final int STATIC_WIDTH = 25; + static final int STATIC_BLOCKS = 30; + static final Color BG_COLOR = Color.BLUE; + static final Color FG_COLOR = Color.RED; + static final int delay = 1000; + static final SecureRandom random = new SecureRandom(); + static final int dl = 100; + static final Class[] WINDOWS_TO_TEST = { Window.class, Frame.class, Dialog.class }; + + public Common(Class windowClass, float opacity) throws Exception{ + this.opacity = opacity; + robot = new ExtendedRobot(); + this.windowClass = windowClass; + EventQueue.invokeAndWait(this::initBackgroundFrame); + EventQueue.invokeAndWait(this::initGUI); + } + + public Common(Class windowClass) throws Exception{ + this(windowClass, 1.0f); + } + + public void doTest() throws Exception { + robot.waitForIdle(delay); + }; + + public void dispose() { + window.dispose(); + background.dispose(); + } + + public abstract void applyShape(); + + public void applyDynamicShape() { + final Area a = new Area(); + Dimension size = window.getSize(); + for (int x = 0; x < 3; x++) { + for (int y = 0; y < 3; y++) { + a.add(new Area(new Rectangle2D.Double( + x * size.getWidth() / 17*6, y * size.getHeight() / 17*6, + size.getWidth() / 17*5, size.getHeight() / 17*5))); + } + } + window.setShape(a); + } + + public void applyStaticShape() { + final Area a = new Area(); + for (int x = 0; x < STATIC_BLOCKS; x++) { + for (int y = 0; y < STATIC_BLOCKS; y++) { + a.add(new Area(new Rectangle2D.Float( + x*STATIC_STEP, y*STATIC_STEP, + STATIC_WIDTH, STATIC_WIDTH))); + } + } + window.setShape(a); + } + + public BufferedImage getForegroundWindow() throws Exception { + final BufferedImage f[] = new BufferedImage[1]; + EventQueue.invokeAndWait( () -> { + f[0] = new BufferedImage(window.getWidth(), + window.getHeight(), BufferedImage.TYPE_INT_RGB); + window.printAll(f[0].createGraphics()); + }); + robot.waitForIdle(delay); + return f[0]; + } + + public static boolean checkTranslucencyMode(GraphicsDevice.WindowTranslucency mode) { + + if (!GraphicsEnvironment + .getLocalGraphicsEnvironment() + .getDefaultScreenDevice() + .isWindowTranslucencySupported(mode)){ + System.out.println(mode+" translucency mode isn't supported"); + return false; + } else { + return true; + } + + } + + public void applyAppDragNResizeSupport() { + MouseAdapter m = new MouseAdapter() { + + private Point dragOrigin = null; + private Dimension origSize = null; + private Point origLoc = null; + private boolean left = false; + private boolean top = false; + private boolean bottom = false; + private boolean right = false; + + public void mousePressed(MouseEvent e) { + dragOrigin = e.getLocationOnScreen(); + origSize = window.getSize(); + origLoc = window.getLocationOnScreen(); + right = (origLoc.x + window.getWidth() - dragOrigin.x) < 5; + left = !right && dragOrigin.x - origLoc.x < 5; + bottom = (origLoc.y + window.getHeight() - dragOrigin.y) < 5; + top = !bottom && dragOrigin.y - origLoc.y < 5; + } + + public void mouseReleased(MouseEvent e) { resize(e); } + public void mouseDragged(MouseEvent e) { resize(e); } + + void resize(MouseEvent e) { + Point dragDelta = e.getLocationOnScreen(); + dragDelta.translate(-dragOrigin.x, -dragOrigin.y); + Point newLoc = new Point(origLoc); + newLoc.translate(dragDelta.x, dragDelta.y); + Dimension newSize = new Dimension(origSize); + if (left || right) { + newSize.width += right ? dragDelta.x : -dragDelta.x; + } + if (top || bottom) { + newSize.height += bottom ? dragDelta.y : -dragDelta.y; + } + if (right || (top || bottom) && !left) { + newLoc.x = origLoc.x; + } + if (bottom || (left || right) && !top) { + newLoc.y = origLoc.y; + } + window.setBounds(newLoc.x, newLoc.y, newSize.width, newSize.height); + } + }; + for (Component comp : window.getComponents()) { + comp.addMouseListener(m); + comp.addMouseMotionListener(m); + } + + window.addMouseListener(m); + window.addMouseMotionListener(m); + } + + public void checkTranslucentShape() throws Exception { + foreground = getForegroundWindow(); + Point[] points = new Point[4]; + + Dimension size = window.getSize(); + Point location = window.getLocationOnScreen(); + + points[0] = new Point(20, 20); + points[1] = new Point(20, size.height-20); + points[2] = new Point(size.width-20, 20); + points[3] = new Point(size.width-20, size.height-20); + + for (Point p : points){ + p.translate(location.x, location.y); + Color actual = robot.getPixelColor(p.x, p.y); + if (actual.equals(BG_COLOR)|| actual.equals(FG_COLOR)) + throw new RuntimeException("Error in point "+p+": "+actual+" equals to foreground or background color"); + else + System.out.println("OK with foreground point "+p); + } + } + + public void checkStaticShape() throws Exception { + Point[] points = new Point[4]; + + Dimension size = window.getSize(); + int xFactor = (int) Math.floor(size.getWidth()/STATIC_STEP)-1; + int yFactor = (int) Math.floor(size.getHeight()/STATIC_STEP)-1; + + // background + points[0] = new Point((STATIC_STEP+STATIC_WIDTH)/2, (STATIC_STEP+STATIC_WIDTH)/2); + points[1] = new Point(STATIC_STEP*xFactor+(STATIC_STEP+STATIC_WIDTH)/2, STATIC_STEP*yFactor+(STATIC_STEP+STATIC_WIDTH)/2); + points[2] = new Point((STATIC_STEP+STATIC_WIDTH)/2, STATIC_STEP*yFactor+(STATIC_STEP+STATIC_WIDTH)/2); + points[3] = new Point(STATIC_STEP*xFactor+(STATIC_STEP+STATIC_WIDTH)/2, (STATIC_STEP+STATIC_WIDTH)/2); + checkShape(points, true); + + // foreground + if (opacity < 1.0f){ + checkTranslucentShape(); + } else { + points[0] = new Point((STATIC_WIDTH) / 2, (STATIC_WIDTH) / 2); + points[1] = new Point(STATIC_STEP * xFactor + (STATIC_WIDTH) / 2, STATIC_STEP * yFactor + (STATIC_WIDTH) / 2); + points[2] = new Point((STATIC_WIDTH) / 2, STATIC_STEP * yFactor + (STATIC_WIDTH) / 2); + points[3] = new Point(STATIC_STEP * xFactor + (STATIC_WIDTH) / 2, (STATIC_WIDTH) / 2); + checkShape(points, false); + } + } + + public void checkDynamicShape() throws Exception { + Point[] points = new Point[4]; + + Dimension size = window.getSize(); + + int blockSizeX = (int) (size.getWidth() / 17); + int blockSizeY = (int) (size.getHeight() / 17); + + // background + points[0] = new Point((int) (blockSizeX * 5.5), (int) (blockSizeY * 5.5)); + points[1] = new Point((int) (size.getWidth() - blockSizeX * 5.5), (int) (size.getHeight() - blockSizeY * 5.5)); + points[2] = new Point((int) (blockSizeX * 5.5), (int) (size.getHeight() - blockSizeY * 5.5)); + points[3] = new Point((int) (size.getWidth() - blockSizeX * 5.5), (int) (blockSizeY * 5.5)); + checkShape(points, true); + + // foreground + if (opacity < 1.0f){ + checkTranslucentShape(); + } else { + points[0] = new Point(3 * blockSizeX, 3 * blockSizeY); + points[1] = new Point(14 * blockSizeX, 14 * blockSizeY); + points[2] = new Point(3 * blockSizeX, 14 * blockSizeY); + points[3] = new Point(14 * blockSizeX, 3 * blockSizeY); + checkShape(points, false); + } + } + + public void checkShape(Point[] points, boolean areBackgroundPoints) throws Exception { + + Point location = window.getLocationOnScreen(); + + for (Point p : points) { + p.translate(location.x, location.y); + if (areBackgroundPoints) { + if (!robot.getPixelColor(p.x, p.y).equals(BG_COLOR)) + throw new RuntimeException("Background point " + p + " color " + robot.getPixelColor(p.x, p.y) + + " does not equal to background color " + BG_COLOR); + else + System.out.println("OK with background point " + p); + } else { + if (robot.getPixelColor(p.x, p.y).equals(BG_COLOR)) + throw new RuntimeException("Foreground point " + p + + " equals to background color " + BG_COLOR); + else + System.out.println("OK with foreground point " + p); + } + } + } + + public void initBackgroundFrame() { + background = new Frame(); + background.setUndecorated(true); + background.setBackground(BG_COLOR); + background.setSize(500, 500); + background.setLocation(dl, dl); + background.setVisible(true); + } + + public void initGUI() { + if (windowClass.equals(Frame.class)) { + window = new Frame(); + ((Frame) window).setUndecorated(true); + } else if (windowClass.equals(Dialog.class)) { + window = new Dialog(background); + ((Dialog) window).setUndecorated(true); + } else { + window = new Window(background); + } + + window.setBackground(FG_COLOR); + componentsContainer = new Panel(); + window.add(componentsContainer, BorderLayout.CENTER); + window.setLocation(2 * dl, 2 * dl); + window.setSize(255, 255); + if (opacity < 1.0f) + window.setOpacity(opacity); + window.addComponentListener(new ComponentAdapter() { + public void componentResized(ComponentEvent e) { + applyShape(); + } + }); + applyShape(); + window.setVisible(true); + applyAppDragNResizeSupport(); + window.toFront(); + } +} diff --git a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/FocusAWTTest.java b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/FocusAWTTest.java new file mode 100644 index 00000000000..81f94f7839c --- /dev/null +++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/FocusAWTTest.java @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowFocusListener; +import java.awt.geom.Area; +import java.awt.geom.GeneralPath; +import java.awt.geom.Rectangle2D; +import java.util.HashMap; + +/* + * @test + * @bug 8013450 + * @summary Check if the window events (Focus and Activation) are triggered correctly + * when clicked on visible and clipped areas. + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary + * @build Common ExtendedRobot + * @run main FocusAWTTest + */ + +public class FocusAWTTest extends Common { + + ExtendedRobot robot; + int dx; + int dy; + static final int x = 20; + static final int y = 400; + + static volatile HashMap flags = new HashMap(); + static { + flags.put("backgroundWindowActivated", false); + flags.put("backgroundWindowDeactivated", false); + flags.put("backgroundWindowGotFocus", false); + flags.put("backgroundWindowLostFocus", false); + flags.put("foregroundWindowGotFocus", false); + flags.put("foregroundWindowLostFocus", false); + flags.put("foregroundWindowActivated", false); + flags.put("foregroundWindowDeactivated", false); + } + + public static void main(String[] ignored) throws Exception{ + if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) + for (Class windowClass: WINDOWS_TO_TEST) { + new FocusAWTTest(windowClass).doTest(); + } + } + + public FocusAWTTest(Class windowClass) throws Exception { + super(windowClass); + this.robot = new ExtendedRobot(); + robot.waitForIdle(); + EventQueue.invokeAndWait(() -> { + dx = background.getX() - x; + dy = background.getY() - y; + }); + robot.waitForIdle(); + } + + @Override + public void initBackgroundFrame() { + background = new Frame(); + background.setSize(300, 300); + background.setLocation(x, y); + background.setFocusable(true); + background.setFocusableWindowState(true); + + background.addWindowFocusListener(new WindowFocusListener() { + public void windowGainedFocus(WindowEvent e) { flags.put("backgroundWindowGotFocus", true); } + public void windowLostFocus(WindowEvent e) { flags.put("backgroundWindowLostFocus", true); } + }); + + background.addWindowListener(new WindowAdapter() { + public void windowActivated(WindowEvent e) { flags.put("backgroundWindowActivated", true); } + public void windowDeactivated(WindowEvent e) { flags.put("backgroundWindowDeactivated", true); } + }); + background.add(new TextArea()); + background.setVisible(true); + } + + @Override + public void initGUI() { + if (windowClass.equals(Frame.class)) { + window = new Frame() { + public void paint(Graphics g) { + g.setColor(Color.BLUE); + g.fillRect(0, 0, 200, 200); + } + }; + ((Frame) window).setUndecorated(true); + } else if (windowClass.equals(Dialog.class)) { + window = new Dialog(background) { + public void paint(Graphics g) { + g.setColor(Color.BLUE); + g.fillRect(0, 0, 200, 200); + } + }; + ((Dialog) window).setUndecorated(true); + } else { + window = new Window(background) { + public void paint(Graphics g) { + g.setColor(Color.BLUE); + g.fillRect(0, 0, 200, 200); + } + }; + window.setFocusable(true); + window.setFocusableWindowState(true); + } + + window.setPreferredSize(new Dimension(200, 200)); + window.setLocation(70 + dx, 450 + dy); + window.setLayout(new BorderLayout()); + + window.addWindowFocusListener(new WindowFocusListener() { + public void windowGainedFocus(WindowEvent e) { flags.put("foregroundWindowGotFocus", true); } + public void windowLostFocus(WindowEvent e) { flags.put("foregroundWindowLostFocus", true); } + }); + + window.addWindowListener(new WindowAdapter() { + public void windowActivated(WindowEvent e) { flags.put("foregroundWindowActivated", true); } + public void windowDeactivated(WindowEvent e) { flags.put("foregroundWindowDeactivated", true); } + }); + + applyShape(); + window.pack(); + window.setAlwaysOnTop(true); + window.setVisible(true); + } + + public void doTest() throws Exception { + super.doTest(); + final Point wls = new Point(); + final Dimension size = new Dimension(); + EventQueue.invokeAndWait(() -> { + window.requestFocus(); + wls.setLocation(window.getLocationOnScreen()); + window.getSize(size); + }); + + robot.waitForIdle(); + + check(wls.x + size.width - 5, wls.y + 5, wls.x + size.width / 3, wls.y + size.height / 3); + check(wls.x + size.width / 2, wls.y + size.height / 2, wls.x + size.width * 2 / 3, wls.y + size.height * 2 / 3); + + EventQueue.invokeAndWait(() -> { + background.dispose(); + window.dispose(); + }); + + robot.waitForIdle(); + } + + @Override + public void applyShape() { + Shape shape; + Area a = new Area(new Rectangle2D.Float(0, 0, 200, 200)); + GeneralPath gp; + gp = new GeneralPath(); + gp.moveTo(190, 0); + gp.lineTo(200, 0); + gp.lineTo(200, 10); + gp.lineTo(10, 200); + gp.lineTo(0, 200); + gp.lineTo(0, 190); + gp.closePath(); + a.subtract(new Area(gp)); + shape = a; + + window.setShape(shape); + } + + private void check(int xb, int yb, int xw, int yw) throws Exception { + checkClick(xb, yb, "backgroundWindowGotFocus"); + checkClick(xw, yw, "foregroundWindowGotFocus"); + checkClick(xb, yb, "foregroundWindowLostFocus"); + checkClick(xw, yw, "backgroundWindowLostFocus"); + + if (window instanceof Dialog || window instanceof Frame) { + checkClick(xb, yb, "backgroundWindowActivated"); + checkClick(xw, yw, "foregroundWindowActivated"); + checkClick(xb, yb, "foregroundWindowDeactivated"); + checkClick(xw, yw, "backgroundWindowDeactivated"); + } + + } + + private void checkClick(int x, int y, String flag) throws Exception { + System.out.println("Trying to click point " + x + ", " + y + ", looking for " + flag + " to trigger."); + + flags.put(flag, false); + + robot.mouseMove(x, y); + robot.click(); + int i = 0; + while (i < 5000 && !flags.get(flag)) { + robot.waitForIdle(50); + i += 50; + } + + if (!flags.get(flag)) + throw new RuntimeException(flag + " is not triggered for click on point " + x + ", " + y + " for " + windowClass + "!"); + } +} diff --git a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Shaped.java b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Shaped.java new file mode 100644 index 00000000000..8061465e51f --- /dev/null +++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Shaped.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; + + +/* + * @test + * @summary Check if dynamically shaped window is moved and resized + * by robot correctly + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary + * @build Common ExtendedRobot + * @run main Shaped + */ +public class Shaped extends Common{ + + public static void main(String[] args) throws Exception { + if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) + for (Class windowClass: WINDOWS_TO_TEST){ + new Shaped(windowClass).doTest(); + } + } + + public Shaped(Class windowClass) throws Exception{ + super(windowClass); + } + public void applyShape(){ applyDynamicShape(); } + + public void doTest() throws Exception{ + super.doTest(); + + checkDynamicShape(); + + // Drag + Point location = window.getLocationOnScreen(); + robot.dragAndDrop(location.x + dl, location.y + 5, location.x + dl + random.nextInt(dl), location.y + random.nextInt(dl)); + robot.waitForIdle(delay); + checkDynamicShape(); + + // Resize + location = window.getLocationOnScreen(); + robot.dragAndDrop(location.x + 4, location.y + 4, location.x + random.nextInt(2*dl)-dl, location.y + random.nextInt(2*dl)-dl); + robot.waitForIdle(delay); + checkDynamicShape(); + + dispose(); + } +} diff --git a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedByAPI.java b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedByAPI.java new file mode 100644 index 00000000000..00d5193740b --- /dev/null +++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedByAPI.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; + + +/* + * @test + * @summary Check if dynamically shaped window is moved and resized + * using API correctly + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary + * @run main ShapedByAPI + */ +public class ShapedByAPI extends Common { + + public static void main(String[] args) throws Exception { + if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) + for (Class windowClass: WINDOWS_TO_TEST){ + new ShapedByAPI(windowClass).doTest(); + } + } + + public ShapedByAPI(Class windowClass) throws Exception{ + super(windowClass); + } + public void applyShape(){ applyDynamicShape(); } + + public void doTest() throws Exception{ + super.doTest(); + + checkDynamicShape(); + + EventQueue.invokeAndWait(() -> { + Point location = window.getLocationOnScreen(); + location.translate(random.nextInt(dl), random.nextInt(dl)); + window.setLocation(location); + }); + robot.waitForIdle(delay); + checkDynamicShape(); + + EventQueue.invokeAndWait(() -> { + Dimension size = window.getSize(); + window.setSize(size.width+random.nextInt(2*dl)-dl, size.height+random.nextInt(2*dl)-dl); + }); + robot.waitForIdle(delay); + checkDynamicShape(); + + dispose(); + } +} diff --git a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucent.java b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucent.java new file mode 100644 index 00000000000..cb98c4450e2 --- /dev/null +++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucent.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; + +/* + * @test + * @summary Check if a translucent shaped window is dragged and + * resized correctly. + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary + * @build Common ExtendedRobot + * @run main ShapedTranslucent + */ +public class ShapedTranslucent extends Common { + + public static void main(String[] args) throws Exception { + if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.TRANSLUCENT) && + checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) + for (Class windowClass: WINDOWS_TO_TEST){ + new ShapedTranslucent(windowClass).doTest(); + } + } + + public ShapedTranslucent(Class windowClass) throws Exception{ + super(windowClass, 0.3f); + } + + public void applyShape(){ applyDynamicShape(); } + + public void doTest() throws Exception{ + super.doTest(); + + checkDynamicShape(); + + // Drag + Point location = window.getLocationOnScreen(); + robot.dragAndDrop(location.x + dl, location.y + 5, location.x + dl + random.nextInt(dl), location.y + random.nextInt(dl)); + robot.waitForIdle(delay); + checkDynamicShape(); + + // Resize + location = window.getLocationOnScreen(); + robot.dragAndDrop(location.x + 4, location.y + 4, location.x + random.nextInt(2*dl)-dl, location.y + random.nextInt(2*dl)-dl); + robot.waitForIdle(delay); + checkDynamicShape(); + + dispose(); + } +} diff --git a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/StaticallyShaped.java b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/StaticallyShaped.java new file mode 100644 index 00000000000..7d48847b682 --- /dev/null +++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/StaticallyShaped.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; + + +/* + * @test + * @summary Check if statically shaped window is dragged and resized + * correctly. + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary + * @build Common ExtendedRobot + * @run main StaticallyShaped + */ + +public class StaticallyShaped extends Common { + + public static void main(String[] args) throws Exception { + if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) + for (Class windowClass: WINDOWS_TO_TEST){ + new StaticallyShaped(windowClass).doTest(); + } + } + + public StaticallyShaped(Class windowClass) throws Exception{ super(windowClass); } + public void applyShape(){ applyStaticShape(); } + + public void doTest() throws Exception{ + super.doTest(); + + checkStaticShape(); + + // Drag + Point location = window.getLocationOnScreen(); + robot.dragAndDrop(location.x + dl, location.y + 5, location.x + dl + random.nextInt(dl), location.y + random.nextInt(dl)); + robot.waitForIdle(delay); + checkStaticShape(); + + // Resize + location = window.getLocationOnScreen(); + robot.dragAndDrop(location.x + 4, location.y + 4, location.x + random.nextInt(2*dl)-dl, location.y + random.nextInt(2*dl)-dl); + robot.waitForIdle(delay); + checkStaticShape(); + + dispose(); + } +} diff --git a/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Translucent.java b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Translucent.java new file mode 100644 index 00000000000..024885362c9 --- /dev/null +++ b/jdk/test/java/awt/Window/ShapedAndTranslucentWindows/Translucent.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; + +/* + * @test + * @summary Check if translucent window is dragged and resized + correctly. + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary + * @build Common ExtendedRobot + * @run main Translucent + */ +public class Translucent extends Common { + + public static void main(String[] args) throws Exception { + if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.TRANSLUCENT) && + checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) + for (Class windowClass: WINDOWS_TO_TEST){ + new Translucent(windowClass).doTest(); + } + } + + public Translucent(Class windowClass) throws Exception{ + super(windowClass, 0.3f); + } + + public void applyShape(){ } + + public void doTest() throws Exception{ + super.doTest(); + + checkTranslucentShape(); + + // Drag + Point location = window.getLocationOnScreen(); + robot.dragAndDrop(location.x + dl, location.y + 5, location.x + dl + random.nextInt(dl), location.y + random.nextInt(dl)); + robot.waitForIdle(delay); + checkTranslucentShape(); + + // Resize + location = window.getLocationOnScreen(); + robot.dragAndDrop(location.x + 4, location.y + 4, location.x + random.nextInt(2*dl)-dl, location.y + random.nextInt(2*dl)-dl); + robot.waitForIdle(delay); + checkTranslucentShape(); + + dispose(); + robot.waitForIdle(delay); + } +} diff --git a/jdk/test/lib/testlibrary/ExtendedRobot.java b/jdk/test/lib/testlibrary/ExtendedRobot.java index d28aca0f642..725bd82c7a8 100644 --- a/jdk/test/lib/testlibrary/ExtendedRobot.java +++ b/jdk/test/lib/testlibrary/ExtendedRobot.java @@ -25,7 +25,6 @@ import sun.awt.ExtendedKeyCodes; import sun.awt.SunToolkit; -import sun.security.action.GetIntegerAction; import java.awt.AWTException; import java.awt.Robot; @@ -34,8 +33,6 @@ import java.awt.Toolkit; import java.awt.Point; import java.awt.MouseInfo; import java.awt.event.InputEvent; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * ExtendedRobot is a subclass of {@link java.awt.Robot}. It provides some convenience methods that are @@ -312,6 +309,48 @@ public class ExtendedRobot extends Robot { mouseMove(position.x, position.y); } + + /** + * Emulate native drag and drop process using {@code InputEvent.BUTTON1_DOWN_MASK}. + * The method successively moves mouse cursor to point with coordinates + * ({@code fromX}, {@code fromY}), presses mouse button 1, drag mouse to + * point with coordinates ({@code toX}, {@code toY}) and releases mouse + * button 1 at last. + * + * @param fromX Source point x coordinate + * @param fromY Source point y coordinate + * @param toX Destination point x coordinate + * @param toY Destination point y coordinate + * + * @see #mousePress(int) + * @see #glide(int, int, int, int) + */ + public void dragAndDrop(int fromX, int fromY, int toX, int toY){ + mouseMove(fromX, fromY); + mousePress(InputEvent.BUTTON1_DOWN_MASK); + waitForIdle(); + glide(toX, toY); + mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + waitForIdle(); + } + + /** + * Emulate native drag and drop process using {@code InputEvent.BUTTON1_DOWN_MASK}. + * The method successively moves mouse cursor to point {@code from}, + * presses mouse button 1, drag mouse to point {@code to} and releases + * mouse button 1 at last. + * + * @param from Source point + * @param to Destination point + * + * @see #mousePress(int) + * @see #glide(int, int, int, int) + * @see #dragAndDrop(int, int, int, int) + */ + public void dragAndDrop(Point from, Point to){ + dragAndDrop(from.x, from.y, to.x, to.y); + } + /** * Successively presses and releases a given key. *

From 4239598cedeb7ad875077f6ffb7fb71ac27d6782 Mon Sep 17 00:00:00 2001 From: Peter Brunet Date: Mon, 26 May 2014 16:37:25 +0400 Subject: [PATCH 023/192] 8009883: REGRESSION: test/closed/javax/swing/AbstractButton/4246045/bug4246045.java fails Remove redundant focus handler that was causing a second focus event Reviewed-by: alexsch, pchelko --- jdk/src/share/classes/javax/swing/JComponent.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/JComponent.java b/jdk/src/share/classes/javax/swing/JComponent.java index 4eb85b23a53..c7bd205aac6 100644 --- a/jdk/src/share/classes/javax/swing/JComponent.java +++ b/jdk/src/share/classes/javax/swing/JComponent.java @@ -3679,8 +3679,8 @@ public abstract class JComponent extends Container implements Serializable, private volatile transient int propertyListenersCount = 0; /** - * This field duplicates the one in java.awt.Component.AccessibleAWTComponent, - * so it has been deprecated. + * This field duplicates the function of the accessibleAWTFocusHandler field + * in java.awt.Component.AccessibleAWTComponent, so it has been deprecated. */ @Deprecated protected FocusListener accessibleFocusHandler = null; @@ -3738,14 +3738,10 @@ public abstract class JComponent extends Container implements Serializable, * @param listener the PropertyChangeListener to be added */ public void addPropertyChangeListener(PropertyChangeListener listener) { - if (accessibleFocusHandler == null) { - accessibleFocusHandler = new AccessibleFocusHandler(); - } if (accessibleContainerHandler == null) { accessibleContainerHandler = new AccessibleContainerHandler(); } if (propertyListenersCount++ == 0) { - JComponent.this.addFocusListener(accessibleFocusHandler); JComponent.this.addContainerListener(accessibleContainerHandler); } super.addPropertyChangeListener(listener); @@ -3760,7 +3756,6 @@ public abstract class JComponent extends Container implements Serializable, */ public void removePropertyChangeListener(PropertyChangeListener listener) { if (--propertyListenersCount == 0) { - JComponent.this.removeFocusListener(accessibleFocusHandler); JComponent.this.removeContainerListener(accessibleContainerHandler); } super.removePropertyChangeListener(listener); From 13c62bc476fd73d92ebf279aeee06078d6ed084b Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Mon, 26 May 2014 18:01:59 +0400 Subject: [PATCH 024/192] 8019180: Use JComboBox as it's own ActionListener leads to unexpected behaviour Reviewed-by: alexsch, serb --- .../share/classes/javax/swing/JComboBox.java | 16 +++-- .../swing/JComboBox/8019180/Test8019180.java | 68 +++++++++++++++++++ 2 files changed, 77 insertions(+), 7 deletions(-) create mode 100644 jdk/test/javax/swing/JComboBox/8019180/Test8019180.java diff --git a/jdk/src/share/classes/javax/swing/JComboBox.java b/jdk/src/share/classes/javax/swing/JComboBox.java index ceec992b31d..febc6b8e576 100644 --- a/jdk/src/share/classes/javax/swing/JComboBox.java +++ b/jdk/src/share/classes/javax/swing/JComboBox.java @@ -1308,13 +1308,15 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { * do not call or override. */ public void actionPerformed(ActionEvent e) { - Object newItem = getEditor().getItem(); - setPopupVisible(false); - getModel().setSelectedItem(newItem); - String oldCommand = getActionCommand(); - setActionCommand("comboBoxEdited"); - fireActionEvent(); - setActionCommand(oldCommand); + ComboBoxEditor editor = getEditor(); + if ((editor != null) && (e != null) && (editor == e.getSource())) { + setPopupVisible(false); + getModel().setSelectedItem(editor.getItem()); + String oldCommand = getActionCommand(); + setActionCommand("comboBoxEdited"); + fireActionEvent(); + setActionCommand(oldCommand); + } } /** diff --git a/jdk/test/javax/swing/JComboBox/8019180/Test8019180.java b/jdk/test/javax/swing/JComboBox/8019180/Test8019180.java new file mode 100644 index 00000000000..d089f998eb3 --- /dev/null +++ b/jdk/test/javax/swing/JComboBox/8019180/Test8019180.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.util.concurrent.CountDownLatch; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +/* + * @test + * @bug 8019180 + * @summary Tests that combobox works if it is used as action listener + * @author Sergey Malenkov + */ + +public class Test8019180 implements Runnable { + private static final CountDownLatch LATCH = new CountDownLatch(1); + private static final String[] ITEMS = {"First", "Second", "Third", "Fourth"}; + + public static void main(String[] args) throws InterruptedException { + SwingUtilities.invokeLater(new Test8019180()); + LATCH.await(); + } + + private JComboBox test; + + @Override + public void run() { + if (this.test == null) { + this.test = new JComboBox<>(ITEMS); + this.test.addActionListener(this.test); + JFrame frame = new JFrame(); + frame.add(test); + frame.pack(); + frame.setVisible(true); + SwingUtilities.invokeLater(this); + } else { + int index = this.test.getSelectedIndex(); + this.test.setSelectedIndex(1 + index); + if (0 > this.test.getSelectedIndex()) { + System.err.println("ERROR: no selection"); + System.exit(8019180); + } + SwingUtilities.getWindowAncestor(this.test).dispose(); + LATCH.countDown(); + } + } +} From 2a52417897a5667233b09043a529a22a50163706 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Tue, 27 May 2014 12:50:51 -0700 Subject: [PATCH 025/192] 8035301: Eliminate dependency on sun.text from font code Reviewed-by: mchung, jgodinez --- jdk/src/share/classes/java/awt/font/StyledParagraph.java | 2 +- jdk/src/share/classes/java/awt/font/TextLayout.java | 2 +- jdk/src/share/classes/java/awt/font/TextLine.java | 2 +- jdk/src/share/classes/sun/{text => font}/CodePointIterator.java | 2 +- jdk/src/share/classes/sun/font/FontResolver.java | 1 - 5 files changed, 4 insertions(+), 5 deletions(-) rename jdk/src/share/classes/sun/{text => font}/CodePointIterator.java (99%) diff --git a/jdk/src/share/classes/java/awt/font/StyledParagraph.java b/jdk/src/share/classes/java/awt/font/StyledParagraph.java index 2087fa09455..380fa36e918 100644 --- a/jdk/src/share/classes/java/awt/font/StyledParagraph.java +++ b/jdk/src/share/classes/java/awt/font/StyledParagraph.java @@ -38,9 +38,9 @@ import java.text.AttributedCharacterIterator.Attribute; import java.util.Vector; import java.util.HashMap; import java.util.Map; +import sun.font.CodePointIterator; import sun.font.Decoration; import sun.font.FontResolver; -import sun.text.CodePointIterator; /** * This class stores Font, GraphicAttribute, and Decoration intervals diff --git a/jdk/src/share/classes/java/awt/font/TextLayout.java b/jdk/src/share/classes/java/awt/font/TextLayout.java index 08d779427a1..45da5af89c6 100644 --- a/jdk/src/share/classes/java/awt/font/TextLayout.java +++ b/jdk/src/share/classes/java/awt/font/TextLayout.java @@ -60,13 +60,13 @@ import java.util.Map; import java.util.HashMap; import java.util.Hashtable; import sun.font.AttributeValues; +import sun.font.CodePointIterator; import sun.font.CoreMetrics; import sun.font.Decoration; import sun.font.FontLineMetrics; import sun.font.FontResolver; import sun.font.GraphicComponent; import sun.font.LayoutPathImpl; -import sun.text.CodePointIterator; /** * diff --git a/jdk/src/share/classes/java/awt/font/TextLine.java b/jdk/src/share/classes/java/awt/font/TextLine.java index 9efcdc32de2..c1c4e899997 100644 --- a/jdk/src/share/classes/java/awt/font/TextLine.java +++ b/jdk/src/share/classes/java/awt/font/TextLine.java @@ -50,6 +50,7 @@ import java.util.Hashtable; import java.util.Map; import sun.font.AttributeValues; import sun.font.BidiUtils; +import sun.font.CodePointIterator; import sun.font.CoreMetrics; import sun.font.Decoration; import sun.font.FontLineMetrics; @@ -60,7 +61,6 @@ import sun.font.LayoutPathImpl.EmptyPath; import sun.font.LayoutPathImpl.SegmentPathBuilder; import sun.font.TextLabelFactory; import sun.font.TextLineComponent; -import sun.text.CodePointIterator; import java.awt.geom.Line2D; diff --git a/jdk/src/share/classes/sun/text/CodePointIterator.java b/jdk/src/share/classes/sun/font/CodePointIterator.java similarity index 99% rename from jdk/src/share/classes/sun/text/CodePointIterator.java rename to jdk/src/share/classes/sun/font/CodePointIterator.java index 519ad9e93b3..179e049db60 100644 --- a/jdk/src/share/classes/sun/text/CodePointIterator.java +++ b/jdk/src/share/classes/sun/font/CodePointIterator.java @@ -33,7 +33,7 @@ * patents. This notice and attribution to IBM may not be removed. */ -package sun.text; +package sun.font; import java.text.CharacterIterator; diff --git a/jdk/src/share/classes/sun/font/FontResolver.java b/jdk/src/share/classes/sun/font/FontResolver.java index b5d2fe9077d..607dc804cfa 100644 --- a/jdk/src/share/classes/sun/font/FontResolver.java +++ b/jdk/src/share/classes/sun/font/FontResolver.java @@ -36,7 +36,6 @@ import java.awt.font.TextAttribute; import java.text.AttributedCharacterIterator; import java.util.ArrayList; import java.util.Map; -import sun.text.CodePointIterator; /** * This class maps an individual character to a Font family which can From d674dee4f2676d684ceb6da3bea4cdc324d49bef Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Wed, 28 May 2014 15:36:10 +0400 Subject: [PATCH 026/192] 8043705: Can't exit color chooser dialog when running as an applet Reviewed-by: serb, pchelko --- .../classes/sun/awt/windows/WWindowPeer.java | 5 +- .../windows/native/sun/windows/awt_Dialog.cpp | 3 +- .../Dialog/CloseDialog/CloseDialogTest.java | 116 ++++++++++++++++++ 3 files changed, 121 insertions(+), 3 deletions(-) create mode 100644 jdk/test/java/awt/Dialog/CloseDialog/CloseDialogTest.java diff --git a/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java b/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java index 33f27ac5694..51bf8379408 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java @@ -450,8 +450,9 @@ public class WWindowPeer extends WPanelPeer implements WindowPeer, * active window is always at the end. */ @SuppressWarnings("unchecked") - public static long[] getActiveWindowHandles() { - AppContext appContext = AppContext.getAppContext(); + public static long[] getActiveWindowHandles(Component target) { + AppContext appContext = SunToolkit.targetToAppContext(target); + if (appContext == null) return null; synchronized (appContext) { List l = (List)appContext.get(ACTIVE_WINDOWS_KEY); if (l == null) { diff --git a/jdk/src/windows/native/sun/windows/awt_Dialog.cpp b/jdk/src/windows/native/sun/windows/awt_Dialog.cpp index cbba78e3b7b..7bb201b49af 100644 --- a/jdk/src/windows/native/sun/windows/awt_Dialog.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Dialog.cpp @@ -464,7 +464,8 @@ void AwtDialog::ModalActivateNextWindow(HWND dialogHWnd, &exc, "sun/awt/windows/WWindowPeer", "getActiveWindowHandles", - "()[J").l; + "(Ljava/awt/Component;)[J", + dialogTarget).l; if (exc == JNI_TRUE) { throw std::bad_alloc(); } diff --git a/jdk/test/java/awt/Dialog/CloseDialog/CloseDialogTest.java b/jdk/test/java/awt/Dialog/CloseDialog/CloseDialogTest.java new file mode 100644 index 00000000000..0a6288d896d --- /dev/null +++ b/jdk/test/java/awt/Dialog/CloseDialog/CloseDialogTest.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Dialog; +import java.awt.Frame; +import java.io.*; +import javax.swing.*; +import sun.awt.SunToolkit; +import java.util.concurrent.atomic.AtomicReference; + +/** + * @test + * @bug 8043705 + * @summary Can't exit color chooser dialog when running as an applet + * @run main CloseDialogTest + */ +public class CloseDialogTest { + + private static volatile Frame frame; + private static volatile Dialog dialog; + private static volatile InputStream testErrorStream; + private static final PrintStream systemErrStream = System.err; + private static final AtomicReference caughtException + = new AtomicReference<>(); + + public static void main(String[] args) throws Exception { + + // redirect System err + PipedOutputStream errorOutputStream = new PipedOutputStream(); + testErrorStream = new PipedInputStream(errorOutputStream); + System.setErr(new PrintStream(errorOutputStream)); + + ThreadGroup swingTG = new ThreadGroup(getRootThreadGroup(), "SwingTG"); + try { + new Thread(swingTG, () -> { + SunToolkit.createNewAppContext(); + SwingUtilities.invokeLater(() -> { + frame = new Frame(); + frame.setSize(300, 300); + frame.setVisible(true); + + dialog = new Dialog(frame); + dialog.setSize(200, 200); + dialog.setModal(true); + dialog.setVisible(true); + }); + }).start(); + + Thread.sleep(400); + + Thread disposeThread = new Thread(swingTG, () -> + SwingUtilities.invokeLater(() -> { + try { + while (dialog == null || !dialog.isVisible()) { + Thread.sleep(100); + } + dialog.setVisible(false); + dialog.dispose(); + frame.dispose(); + } catch (Exception e) { + caughtException.set(e); + } + })); + disposeThread.start(); + disposeThread.join(); + Thread.sleep(500); + + // read System err + final char[] buffer = new char[2048]; + System.err.print("END"); + System.setErr(systemErrStream); + try (Reader in = new InputStreamReader(testErrorStream, "UTF-8")) { + int size = in.read(buffer, 0, buffer.length); + String errorString = new String(buffer, 0, size); + if (!errorString.startsWith("END")) { + System.err.println(errorString. + substring(0, errorString.length() - 4)); + throw new RuntimeException("Error output is not empty!"); + } + } + } finally { + if (caughtException.get() != null) { + throw new RuntimeException("Failed. Caught exception!", + caughtException.get()); + } + } + } + + private static ThreadGroup getRootThreadGroup() { + ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); + while (threadGroup.getParent() != null) { + threadGroup = threadGroup.getParent(); + } + return threadGroup; + } +} From 86e0ce97e6364a898dbc575dcb184e69ae5a92e5 Mon Sep 17 00:00:00 2001 From: Anton Nashatyrev Date: Thu, 29 May 2014 17:31:41 +0400 Subject: [PATCH 027/192] 8028617: Dvorak keyboard mapping not honored when ctrl key pressed Reviewed-by: pchelko, anthony --- .../classes/sun/lwawt/macosx/CEmbeddedFrame.java | 3 ++- .../classes/sun/lwawt/macosx/CPlatformResponder.java | 7 +++++-- .../macosx/classes/sun/lwawt/macosx/CPlatformView.java | 2 +- jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java | 10 ++++++++-- jdk/src/macosx/native/sun/awt/AWTView.m | 7 +++++-- 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java index dd718c0ca0b..c241aae3cc0 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java @@ -97,7 +97,8 @@ public class CEmbeddedFrame extends EmbeddedFrame { public void handleKeyEvent(int eventType, int modifierFlags, String characters, String charsIgnoringMods, boolean isRepeat, short keyCode, boolean needsKeyTyped) { - responder.handleKeyEvent(eventType, modifierFlags, charsIgnoringMods, keyCode, needsKeyTyped, isRepeat); + responder.handleKeyEvent(eventType, modifierFlags, characters, charsIgnoringMods, + keyCode, needsKeyTyped, isRepeat); } public void handleInputEvent(String text) { diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java index d8d1555450c..591c16d2879 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java @@ -125,7 +125,7 @@ final class CPlatformResponder { /** * Handles key events. */ - void handleKeyEvent(int eventType, int modifierFlags, String chars, + void handleKeyEvent(int eventType, int modifierFlags, String chars, String charsIgnoringModifiers, short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) { boolean isFlagsChangedEvent = isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) : @@ -153,7 +153,10 @@ final class CPlatformResponder { testChar = chars.charAt(0); } - int[] in = new int[] {testChar, isDeadChar ? 1 : 0, modifierFlags, keyCode}; + char testCharIgnoringModifiers = charsIgnoringModifiers != null && charsIgnoringModifiers.length() > 0 ? + charsIgnoringModifiers.charAt(0) : KeyEvent.CHAR_UNDEFINED; + + int[] in = new int[] {testCharIgnoringModifiers, isDeadChar ? 1 : 0, modifierFlags, keyCode}; int[] out = new int[3]; // [jkeyCode, jkeyLocation, deadChar] postsTyped = NSEvent.nsToJavaKeyInfo(in, out); diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java index e81371b4751..3c2cd2325e4 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java @@ -200,7 +200,7 @@ public class CPlatformView extends CFRetainedResource { } private void deliverKeyEvent(NSEvent event) { - responder.handleKeyEvent(event.getType(), event.getModifierFlags(), + responder.handleKeyEvent(event.getType(), event.getModifierFlags(), event.getCharacters(), event.getCharactersIgnoringModifiers(), event.getKeyCode(), true, false); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java index ddb74d42b02..d30a39cdfb9 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java @@ -47,13 +47,15 @@ final class NSEvent { // Key event information private short keyCode; + private String characters; private String charactersIgnoringModifiers; // Called from native - NSEvent(int type, int modifierFlags, short keyCode, String charactersIgnoringModifiers) { + NSEvent(int type, int modifierFlags, short keyCode, String characters, String charactersIgnoringModifiers) { this.type = type; this.modifierFlags = modifierFlags; this.keyCode = keyCode; + this.characters = characters; this.charactersIgnoringModifiers = charactersIgnoringModifiers; } @@ -121,12 +123,16 @@ final class NSEvent { return charactersIgnoringModifiers; } + String getCharacters() { + return characters; + } + @Override public String toString() { return "NSEvent[" + getType() + " ," + getModifierFlags() + " ," + getClickCount() + " ," + getButtonNumber() + " ," + getX() + " ," + getY() + " ," + getAbsX() + " ," + getAbsY()+ " ," + getKeyCode() + " ," - + getCharactersIgnoringModifiers() + "]"; + + getCharacters() + " ," + getCharactersIgnoringModifiers() + "]"; } /* diff --git a/jdk/src/macosx/native/sun/awt/AWTView.m b/jdk/src/macosx/native/sun/awt/AWTView.m index 830fb77e82b..a59ff1a51ae 100644 --- a/jdk/src/macosx/native/sun/awt/AWTView.m +++ b/jdk/src/macosx/native/sun/awt/AWTView.m @@ -440,17 +440,20 @@ AWT_ASSERT_APPKIT_THREAD; JNIEnv *env = [ThreadUtilities getJNIEnv]; jstring characters = NULL; + jstring charactersIgnoringModifiers = NULL; if ([event type] != NSFlagsChanged) { characters = JNFNSToJavaString(env, [event characters]); + charactersIgnoringModifiers = JNFNSToJavaString(env, [event charactersIgnoringModifiers]); } static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent"); - static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;)V"); + static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;Ljava/lang/String;)V"); jobject jEvent = JNFNewObject(env, jctor_NSEvent, [event type], [event modifierFlags], [event keyCode], - characters); + characters, + charactersIgnoringModifiers); CHECK_NULL(jEvent); static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView"); From db6fa669549e17c09452df05972542f69970cbaa Mon Sep 17 00:00:00 2001 From: Anton Nashatyrev Date: Fri, 30 May 2014 11:20:03 +0400 Subject: [PATCH 028/192] 8032788: ImageIcon constructor throws an NPE and hangs when passed a null String parameter Reviewed-by: pchelko, serb --- .../sun/awt/image/FileImageSource.java | 4 ++ jdk/test/java/awt/image/ImageIconHang.java | 48 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 jdk/test/java/awt/image/ImageIconHang.java diff --git a/jdk/src/share/classes/sun/awt/image/FileImageSource.java b/jdk/src/share/classes/sun/awt/image/FileImageSource.java index f448b0723ce..8f75aa81b1c 100644 --- a/jdk/src/share/classes/sun/awt/image/FileImageSource.java +++ b/jdk/src/share/classes/sun/awt/image/FileImageSource.java @@ -48,6 +48,10 @@ public class FileImageSource extends InputStreamImageSource { } protected ImageDecoder getDecoder() { + if (imagefile == null) { + return null; + } + InputStream is; try { is = new BufferedInputStream(new FileInputStream(imagefile)); diff --git a/jdk/test/java/awt/image/ImageIconHang.java b/jdk/test/java/awt/image/ImageIconHang.java new file mode 100644 index 00000000000..25d6a219d39 --- /dev/null +++ b/jdk/test/java/awt/image/ImageIconHang.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; + +/* + * @test + * @bug 8032788 + * @summary Checks that null filename argument is processed correctly + * + * @run main ImageIconHang + */ +public class ImageIconHang { + public static void main(String[] args) throws Exception { + Image image = Toolkit.getDefaultToolkit().getImage((String) null); + MediaTracker mt = new MediaTracker(new Component() {}); + mt.addImage(image, 1); + mt.waitForID(1, 5000); + + int status = mt.statusID(1, false); + + System.out.println("Status: " + status); + + if (status != MediaTracker.ERRORED) { + throw new RuntimeException("MediaTracker.waitForID() hung."); + } + } +} From 7f80153eb206011d7b7b8294bfcd9fb47c9809a3 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Fri, 30 May 2014 14:06:50 +0400 Subject: [PATCH 029/192] 8040113: File not initialized in src/share/native/sun/awt/giflib/dgif_lib.c Reviewed-by: pchelko, prr --- jdk/src/share/native/sun/awt/giflib/dgif_lib.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/jdk/src/share/native/sun/awt/giflib/dgif_lib.c b/jdk/src/share/native/sun/awt/giflib/dgif_lib.c index 1a9e2cce125..d6d2a3ce448 100644 --- a/jdk/src/share/native/sun/awt/giflib/dgif_lib.c +++ b/jdk/src/share/native/sun/awt/giflib/dgif_lib.c @@ -195,6 +195,11 @@ DGifOpen(void *userData, GifFileType *GifFile; GifFilePrivateType *Private; + if (!readFunc) { + _GifError = D_GIF_ERR_READ_FAILED; + return NULL; + } + GifFile = (GifFileType *)malloc(sizeof(GifFileType)); if (GifFile == NULL) { _GifError = D_GIF_ERR_NOT_ENOUGH_MEM; From a666497db87eb504e772f29bcb419d932b068504 Mon Sep 17 00:00:00 2001 From: Yuri Nesterenko Date: Fri, 30 May 2014 14:23:25 +0400 Subject: [PATCH 030/192] 8044172: [TEST_BUG] Move regtests for 4523758 and AltPlusNumberKeyCombinationsTest to jdk Reviewed-by: pchelko --- .../AltPlusNumberKeyCombinationsTest.java | 307 ++++++++++++++++++ .../swing/JComboBox/4523758/bug4523758.java | 182 +++++++++++ 2 files changed, 489 insertions(+) create mode 100644 jdk/test/java/awt/keyboard/AltPlusNumberKeyCombinationsTest/AltPlusNumberKeyCombinationsTest.java create mode 100644 jdk/test/javax/swing/JComboBox/4523758/bug4523758.java diff --git a/jdk/test/java/awt/keyboard/AltPlusNumberKeyCombinationsTest/AltPlusNumberKeyCombinationsTest.java b/jdk/test/java/awt/keyboard/AltPlusNumberKeyCombinationsTest/AltPlusNumberKeyCombinationsTest.java new file mode 100644 index 00000000000..9088018e258 --- /dev/null +++ b/jdk/test/java/awt/keyboard/AltPlusNumberKeyCombinationsTest/AltPlusNumberKeyCombinationsTest.java @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; + +/** + * Test that it is possible to type "Alt code" on Windows. + * Windows-only test. + */ +/* +@test +@summary Test that it is possible to type "Alt code" on Windows. +@library ../../../../lib/testlibrary +@build ExtendedRobot +@run main AltPlusNumberKeyCombinationsTest +*/ +public class AltPlusNumberKeyCombinationsTest { + + private Frame frame; + private TextField tf; + private TextArea ta; + + private static int delay = 500; + private static String euroChar = "\u20AC"; + private static String accChar = "\u00E3"; + + private boolean passed = true; + private ExtendedRobot robot; + + public AltPlusNumberKeyCombinationsTest() { + try { + Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { + public void run() { + initializeGUI(); + } + }); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test failed;", e.getCause()); + } + } + + private void initializeGUI() { + frame = new Frame("AltPlusNumberKeyCombinationsTest"); + frame.setLayout(new FlowLayout()); + + tf = new TextField(15); + frame.add(tf); + + ta = new TextArea(8, 20); + frame.add(ta); + + frame.setSize(250,400); + frame.setVisible(true); + } + + + private void doTest() throws Exception { + robot = new ExtendedRobot(); + robot.setAutoDelay(100); + + robot.waitForIdle(delay); + + robot.mouseMove((int) ta.getLocationOnScreen().x + ta.getSize().width / 2, + (int) ta.getLocationOnScreen().y + ta.getSize().height / 2); + robot.waitForIdle(delay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_RIGHT); + robot.keyRelease(KeyEvent.VK_RIGHT); + robot.keyRelease(KeyEvent.VK_ALT); + + robot.waitForIdle(delay); + + if (! "".equals(ta.getText())) { + System.err.println("FAIL: Symbol typed in the text area when ALT + RIGHT ARROW keys typed"); + passed = false; + } + + try { + Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { + public void run() { + ta.setText(""); + } + }); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test failed;", e.getCause()); + } + + // getLockingKeyState works on Windows; + // Alt code only make sense on Windows; + // so don't check availability of this and just use it. + if( Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_NUM_LOCK) ) { + robot.keyPress(KeyEvent.VK_NUM_LOCK); + robot.keyRelease(KeyEvent.VK_NUM_LOCK); + } + + robot.mouseMove((int) tf.getLocationOnScreen().x + tf.getSize().width / 2, + (int) tf.getLocationOnScreen().y + tf.getSize().height / 2); + robot.waitForIdle(delay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_NUMPAD0); + robot.keyRelease(KeyEvent.VK_NUMPAD0); + robot.keyPress(KeyEvent.VK_NUMPAD1); + robot.keyRelease(KeyEvent.VK_NUMPAD1); + robot.keyPress(KeyEvent.VK_NUMPAD2); + robot.keyRelease(KeyEvent.VK_NUMPAD2); + robot.keyPress(KeyEvent.VK_NUMPAD8); + robot.keyRelease(KeyEvent.VK_NUMPAD8); + robot.keyRelease(KeyEvent.VK_ALT); + + robot.waitForIdle(delay); + + if (! euroChar.equals(tf.getText())) { + System.err.println("FAIL: Euro symbol not typed in the text field when " + + "ALT + NUMPAD 1,2,8 keys typed"); + passed = false; + } + + try { + Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { + public void run() { + tf.setText(""); + } + }); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test failed;", e.getCause()); + } + + robot.mouseMove((int) ta.getLocationOnScreen().x + ta.getSize().width / 2, + (int) ta.getLocationOnScreen().y + ta.getSize().height / 2); + robot.waitForIdle(delay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_NUMPAD0); + robot.keyRelease(KeyEvent.VK_NUMPAD0); + robot.keyPress(KeyEvent.VK_NUMPAD1); + robot.keyRelease(KeyEvent.VK_NUMPAD1); + robot.keyPress(KeyEvent.VK_NUMPAD2); + robot.keyRelease(KeyEvent.VK_NUMPAD2); + robot.keyPress(KeyEvent.VK_NUMPAD8); + robot.keyRelease(KeyEvent.VK_NUMPAD8); + robot.keyRelease(KeyEvent.VK_ALT); + + robot.waitForIdle(delay); + + if (! euroChar.equals(ta.getText())) { + System.err.println("FAIL: Euro symbol not typed in the text area when " + + "ALT + NUMPAD 1,2,8 keys typed"); + passed = false; + } + + try { + Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { + public void run() { + ta.setText(""); + } + }); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test failed;", e.getCause()); + } + + robot.mouseMove((int) tf.getLocationOnScreen().x + tf.getSize().width / 2, + (int) tf.getLocationOnScreen().y + tf.getSize().height / 2); + robot.waitForIdle(delay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_NUMPAD0); + robot.keyRelease(KeyEvent.VK_NUMPAD0); + robot.keyPress(KeyEvent.VK_NUMPAD2); + robot.keyRelease(KeyEvent.VK_NUMPAD2); + robot.keyPress(KeyEvent.VK_NUMPAD2); + robot.keyRelease(KeyEvent.VK_NUMPAD2); + robot.keyPress(KeyEvent.VK_NUMPAD7); + robot.keyRelease(KeyEvent.VK_NUMPAD7); + robot.keyRelease(KeyEvent.VK_ALT); + + robot.waitForIdle(delay); + + if (! accChar.equals(tf.getText())) { + System.err.println("FAIL: Symbol not typed in the text field when " + + "ALT + NUMPAD 2,2,7 keys typed"); + passed = false; + } + + try { + Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { + public void run() { + tf.setText(""); + } + }); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test failed;", e.getCause()); + } + + robot.mouseMove((int) ta.getLocationOnScreen().x + ta.getSize().width / 2, + (int) ta.getLocationOnScreen().y + ta.getSize().height / 2); + robot.waitForIdle(delay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_NUMPAD0); + robot.keyRelease(KeyEvent.VK_NUMPAD0); + robot.keyPress(KeyEvent.VK_NUMPAD2); + robot.keyRelease(KeyEvent.VK_NUMPAD2); + robot.keyPress(KeyEvent.VK_NUMPAD2); + robot.keyRelease(KeyEvent.VK_NUMPAD2); + robot.keyPress(KeyEvent.VK_NUMPAD7); + robot.keyRelease(KeyEvent.VK_NUMPAD7); + robot.keyRelease(KeyEvent.VK_ALT); + + robot.waitForIdle(delay); + + if (! accChar.equals(ta.getText())) { + System.err.println("FAIL: Symbol not typed in the text field when " + + "ALT + NUMPAD 2,2,7 keys typed"); + passed = false; + } + + try { + Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { + public void run() { + ta.setText(""); + } + }); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test failed;", e.getCause()); + } + + if (! passed) { + System.err.println("Test failed"); + captureScreenAndSave(); + throw new RuntimeException("Test failed"); + } else { + System.out.println("Test passed"); + } + } + + public static void main(String[] args) { + if (System.getProperty("os.name").indexOf("Win") == -1) { + System.out.println("This test is supposed to be run only on Windows! Marking as passed.."); + return; + } + try { + AltPlusNumberKeyCombinationsTest test = new AltPlusNumberKeyCombinationsTest(); + test.doTest(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Fail; "+e.getMessage()); + } + } + + /** + * Do screen capture and save it as image + */ + private static void captureScreenAndSave() { + + try { + Robot robot = new Robot(); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height); + System.out.println("About to screen capture - " + rectangle); + java.awt.image.BufferedImage image = robot.createScreenCapture(rectangle); + javax.imageio.ImageIO.write(image, "jpg", new java.io.File("ScreenImage.jpg")); + robot.delay(3000); + } catch (Throwable t) { + System.out.println("WARNING: Exception thrown while screen capture!"); + t.printStackTrace(); + } + } +} diff --git a/jdk/test/javax/swing/JComboBox/4523758/bug4523758.java b/jdk/test/javax/swing/JComboBox/4523758/bug4523758.java new file mode 100644 index 00000000000..423f89d8bff --- /dev/null +++ b/jdk/test/javax/swing/JComboBox/4523758/bug4523758.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4523758 + * @summary Directly check that torn-off combo works + * @library ../../../../lib/testlibrary + * @build ExtendedRobot + * @run main bug4523758 + */ +/* + * There is another regression test for this bug created by ssi with a + * fix. It is purely AWT and designed to verify the (absence of) underlying Component issue. + * This functional test does test, well, functionality of the swing control. + * + */ + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; + +public class bug4523758 { + + private JFrame frame; + private JToolBar tools; + private JComboBox combo; + + private boolean passed = true; + private boolean itemStateChanged = false; + private Object itemLock = new Object(); + + private static int delay = 500; + private static final int WAIT_EVENT_DELAY = 60000; + + public bug4523758() { + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + initializeGUI(); + } + }); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Failed to initialize GUI"); + } + } + + private void initializeGUI() { + frame = new JFrame("bug4523758"); + tools = new JToolBar(); + frame.getContentPane().add(tools, BorderLayout.NORTH); + combo = new JComboBox(new Object[] { "Red", "Orange", "Yellow", + "Green", "Blue", "Indigo", "Violet"}); + combo.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent event) { + itemStateChanged = true; + synchronized (itemLock) { + try { + itemLock.notifyAll(); + } catch (Exception e) { + } + } + } + }); + tools.add(combo); + frame.setSize(250,400); + frame.setLocation(700, 0); + frame.setVisible(true); + } + + private void doTest() throws Exception { + ExtendedRobot robot = new ExtendedRobot(); + robot.waitForIdle(1000); + + final Point cl = combo.getLocationOnScreen(); + final Dimension cs = combo.getSize(); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.dispose(); + } + }); + robot.waitForIdle(delay); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setSize((int) cl.x - 700 + cs.width, + (int) cl.y + cs.height - 5); + frame.setVisible(true); + } + }); + + robot.waitForIdle(delay*2); + Point comboLocation = combo.getLocationOnScreen(); + Dimension comboSize = combo.getSize(); + + robot.mouseMove((int) comboLocation.x + comboSize.width / 2, + (int) comboLocation.y + 5); + robot.waitForIdle(delay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(100); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(delay); + + robot.mouseMove((int) comboLocation.x + comboSize.width / 2, + (int) comboLocation.y + 60); + robot.waitForIdle(delay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(100); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(delay); + + if (! itemStateChanged) { + synchronized (itemLock) { + try { + itemLock.wait(WAIT_EVENT_DELAY); + } catch (Exception e) { + } + } + } + if (! itemStateChanged) { + System.err.println("FAIL: ItemEvent not triggered when mouse clicked on combo box drop down"); + passed = false; + } + + if (! passed) { + System.err.println("Test failed!"); + captureScreenAndSave(); + throw new RuntimeException("FAIL"); + } else { + System.out.println("Test passed!"); + } + } + + public static void main(String[] args) { + try { + bug4523758 test = new bug4523758(); + test.doTest(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("FAIL"); + } + } + + /** + * Do screen capture and save it as image + */ + private static void captureScreenAndSave() { + + try { + Robot robot = new Robot(); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height); + System.out.println("About to screen capture - " + rectangle); + java.awt.image.BufferedImage image = robot.createScreenCapture(rectangle); + javax.imageio.ImageIO.write(image, "jpg", new java.io.File("ScreenImage.jpg")); + robot.delay(3000); + } catch (Throwable t) { + System.out.println("WARNING: Exception thrown while screen capture!"); + t.printStackTrace(); + } + } +} From e0716258fc6b555bfa7033c58666f4d17ea5a687 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Fri, 30 May 2014 15:24:42 +0400 Subject: [PATCH 031/192] 8007563: When checking the default behaviour for a scroll tab layout and checking the 'opaque' checkbox, the area behind tabs is not red Reviewed-by: alexsch, serb --- .../swing/plaf/metal/MetalTabbedPaneUI.java | 5 +- .../JTabbedPane/8007563/Test8007563.java | 124 ++++++++++++++++++ 2 files changed, 126 insertions(+), 3 deletions(-) create mode 100644 jdk/test/javax/swing/JTabbedPane/8007563/Test8007563.java diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java index 75dc959ca3d..0a54a878534 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java @@ -806,9 +806,8 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { // Paint the background for the tab area if ( tabPane.isOpaque() ) { - Color bg = UIManager.getColor("TabbedPane.tabAreaBackground"); - if (bg != null) { - g.setColor(bg); + if (!c.isBackgroundSet() && (tabAreaBackground != null)) { + g.setColor(tabAreaBackground); } else { g.setColor( c.getBackground() ); diff --git a/jdk/test/javax/swing/JTabbedPane/8007563/Test8007563.java b/jdk/test/javax/swing/JTabbedPane/8007563/Test8007563.java new file mode 100644 index 00000000000..5f73173df34 --- /dev/null +++ b/jdk/test/javax/swing/JTabbedPane/8007563/Test8007563.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Point; +import java.awt.Robot; +import java.util.ArrayList; +import java.util.concurrent.CountDownLatch; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JTabbedPane; + +import static javax.swing.UIManager.*; +import static javax.swing.SwingUtilities.*; + +/* + * @test + * @bug 8007563 + * @summary Tests JTabbedPane background + * @author Sergey Malenkov + */ + +public class Test8007563 implements Runnable { + private static final ArrayList LIST = new ArrayList<>(); + private static final LookAndFeelInfo[] INFO = getInstalledLookAndFeels(); + private static final CountDownLatch LATCH = new CountDownLatch(INFO.length); + private static Robot ROBOT; + + public static void main(String[] args) throws Exception { + ROBOT = new Robot(); + invokeLater(new Test8007563()); + LATCH.await(); + if (!LIST.isEmpty()) { + throw new Error(LIST.toString()); + } + } + + private static void addOpaqueError(boolean opaque) { + LIST.add(getLookAndFeel().getName() + " opaque=" + opaque); + } + + private static boolean updateLookAndFeel() { + int index = (int) LATCH.getCount() - 1; + if (index >= 0) { + try { + LookAndFeelInfo info = INFO[index]; + System.err.println("L&F: " + info.getName()); + setLookAndFeel(info.getClassName()); + return true; + } catch (Exception exception) { + exception.printStackTrace(); + } + } + return false; + } + + private JFrame frame; + private JTabbedPane pane; + + public void run() { + if (this.frame == null) { + if (!updateLookAndFeel()) { + return; + } + this.pane = new JTabbedPane(); + this.pane.setOpaque(false); + this.pane.setBackground(Color.RED); + for (int i = 0; i < 3; i++) { + this.pane.addTab("Tab " + i, new JLabel("Content area " + i)); + } + this.frame = new JFrame(getClass().getSimpleName()); + this.frame.getContentPane().setBackground(Color.BLUE); + this.frame.add(this.pane); + this.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + this.frame.setSize(400, 200); + this.frame.setLocationRelativeTo(null); + this.frame.setVisible(true); + } else { + Point point = new Point(this.pane.getWidth() - 2, 2); + convertPointToScreen(point, this.pane); + Color actual = ROBOT.getPixelColor(point.x, point.y); + + boolean opaque = this.pane.isOpaque(); + Color expected = opaque + ? this.pane.getBackground() + : this.frame.getContentPane().getBackground(); + + if (!expected.equals(actual)){ + addOpaqueError(opaque); + } + if (!opaque) { + this.pane.setOpaque(true); + this.pane.repaint(); + } else { + this.frame.dispose(); + this.frame = null; + this.pane = null; + LATCH.countDown(); + } + + } + invokeLater(this); + } +} From 19759f801ccb580c9f4521eb576407c2db67f2cd Mon Sep 17 00:00:00 2001 From: Alexander Zvegintsev Date: Fri, 30 May 2014 13:16:51 +0400 Subject: [PATCH 032/192] 8031471: Test closed/java/awt/dnd/FileDialogDropTargetTest/FileDialogDropTargetTest.java fails on Solaris zones virtual hosts Reviewed-by: anthony, serb --- .../classes/sun/awt/X11/XErrorHandlerUtil.java | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java b/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java index 4bdf0ecb0dc..037b7329ecd 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -97,6 +97,7 @@ public final class XErrorHandlerUtil { * @param handler the synthetic error handler to set */ public static void WITH_XERROR_HANDLER(XErrorHandler handler) { + XSync(); saved_error = null; current_error_handler = handler; } @@ -105,15 +106,9 @@ public final class XErrorHandlerUtil { * Unsets a current synthetic error handler. Must be called with the acquired AWT lock. */ public static void RESTORE_XERROR_HANDLER() { - RESTORE_XERROR_HANDLER(true); - } - - private static void RESTORE_XERROR_HANDLER(boolean doXSync) { - if (doXSync) { - // Wait until all requests are processed by the X server - // and only then uninstall the error handler. - XSync(); - } + // Wait until all requests are processed by the X server + // and only then uninstall the error handler. + XSync(); current_error_handler = null; } From b57d6c9a4faa1af5c6bf6eb03ced32ae49c494e7 Mon Sep 17 00:00:00 2001 From: Dmitry Markov Date: Mon, 2 Jun 2014 14:20:02 +0400 Subject: [PATCH 033/192] 8042465: Applet menus not rendering when browser is full screen on Mac Reviewed-by: anthony, pchelko --- .../sun/lwawt/macosx/CPlatformWindow.java | 2 ++ jdk/src/macosx/native/sun/awt/AWTWindow.m | 6 ++++- .../classes/javax/swing/PopupFactory.java | 26 +++++++++++++++++-- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index edf25ddb313..190894934b9 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -119,6 +119,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo static final int NONACTIVATING = 1 << 24; static final int IS_DIALOG = 1 << 25; static final int IS_MODAL = 1 << 26; + static final int IS_POPUP = 1 << 27; static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE; @@ -318,6 +319,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo styleBits = SET(styleBits, TEXTURED, false); // Popups in applets don't activate applet's process styleBits = SET(styleBits, NONACTIVATING, true); + styleBits = SET(styleBits, IS_POPUP, true); } if (Window.Type.UTILITY.equals(target.getType())) { diff --git a/jdk/src/macosx/native/sun/awt/AWTWindow.m b/jdk/src/macosx/native/sun/awt/AWTWindow.m index 6a9c1166e84..5cb5621a159 100644 --- a/jdk/src/macosx/native/sun/awt/AWTWindow.m +++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -252,6 +252,10 @@ AWT_ASSERT_APPKIT_THREAD; self.ownerWindow = owner; [self setPropertiesForStyleBits:styleBits mask:MASK(_METHOD_PROP_BITMASK)]; + if (IS(self.styleBits, IS_POPUP)) { + [self.nsWindow setCollectionBehavior:(1 << 8) /*NSWindowCollectionBehaviorFullScreenAuxiliary*/]; + } + return self; } diff --git a/jdk/src/share/classes/javax/swing/PopupFactory.java b/jdk/src/share/classes/javax/swing/PopupFactory.java index 20b21c7a274..695ef2bb76b 100644 --- a/jdk/src/share/classes/javax/swing/PopupFactory.java +++ b/jdk/src/share/classes/javax/swing/PopupFactory.java @@ -25,10 +25,14 @@ package javax.swing; +import sun.awt.EmbeddedFrame; +import sun.awt.OSInfo; + import java.applet.Applet; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.security.AccessController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -226,7 +230,12 @@ public class PopupFactory { case MEDIUM_WEIGHT_POPUP: return getMediumWeightPopup(owner, contents, ownerX, ownerY); case HEAVY_WEIGHT_POPUP: - return getHeavyWeightPopup(owner, contents, ownerX, ownerY); + Popup popup = getHeavyWeightPopup(owner, contents, ownerX, ownerY); + if ((AccessController.doPrivileged(OSInfo.getOSTypeAction()) == + OSInfo.OSType.MACOSX) && (EmbeddedFrame.getAppletIfAncestorOf(owner) != null)) { + ((HeavyWeightPopup)popup).setCacheEnabled(false); + } + return popup; } return null; } @@ -294,6 +303,8 @@ public class PopupFactory { private static final Object heavyWeightPopupCacheKey = new StringBuffer("PopupFactory.heavyWeightPopupCache"); + private volatile boolean isCacheEnabled = true; + /** * Returns either a new or recycled Popup containing * the specified children. @@ -448,12 +459,23 @@ public class PopupFactory { } } + /** + * Enables or disables cache for current object. + */ + void setCacheEnabled(boolean enable) { + isCacheEnabled = enable; + } + // // Popup methods // public void hide() { super.hide(); - recycleHeavyWeightPopup(this); + if (isCacheEnabled) { + recycleHeavyWeightPopup(this); + } else { + this._dispose(); + } } /** From ffed33a4916ae264c6af8088d2e7ef0ee44fcc00 Mon Sep 17 00:00:00 2001 From: Petr Pchelko Date: Mon, 2 Jun 2014 15:25:43 +0400 Subject: [PATCH 034/192] 8043807: Incorrect StackTrace in IOException thrown from ClipboardTransferable Reviewed-by: anthony, serb --- .../classes/sun/awt/datatransfer/ClipboardTransferable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java b/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java index 6c3a4d18c06..f8c02601497 100644 --- a/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java +++ b/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java @@ -153,7 +153,7 @@ public class ClipboardTransferable implements Transferable { Object ret = flavorsToData.get(flavor); if (ret instanceof IOException) { // rethrow IOExceptions generated while fetching data - throw (IOException)ret; + throw new IOException("Exception fetching data: ", (IOException)ret); } else if (ret instanceof DataFactory) { // Now we can render the data DataFactory factory = (DataFactory)ret; From e563a70ab70083a5a7bbc2e6f58cf128d73c9fb9 Mon Sep 17 00:00:00 2001 From: Mikael Auno Date: Mon, 2 Jun 2014 17:21:15 +0200 Subject: [PATCH 035/192] 8044540: serviceability/sa/jmap-hashcode/Test8028623.java should be quarantined Reviewed-by: sla --- hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java b/hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java index 6f4b2fd689a..815b3f606ca 100644 --- a/hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java +++ b/hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java @@ -26,6 +26,7 @@ * @bug 8028623 * @summary Test hashing of extended characters in Serviceability Agent. * @library /testlibrary + * @ignore 8044416 * @build com.oracle.java.testlibrary.* * @compile -encoding utf8 Test8028623.java * @run main Test8028623 From 333b1ed5ba4a818196f0635839e6bfe0922f00fc Mon Sep 17 00:00:00 2001 From: Otavio Goncalves de Santana Date: Tue, 3 Jun 2014 11:18:03 -0400 Subject: [PATCH 036/192] 8044460: Cleanup new Boolean and single character strings Reviewed-by: pchelko, serb, rriggs --- .../share/classes/com/sun/java/swing/plaf/gtk/Metacity.java | 2 +- jdk/src/share/classes/javax/swing/JEditorPane.java | 2 +- .../share/classes/javax/swing/plaf/nimbus/NimbusStyle.java | 2 +- jdk/src/share/classes/sun/applet/AppletClassLoader.java | 4 ++-- jdk/src/share/classes/sun/awt/FontConfiguration.java | 4 ++-- jdk/src/share/classes/sun/font/SunFontManager.java | 3 +-- jdk/src/share/classes/sun/font/Type1Font.java | 6 +++--- 7 files changed, 11 insertions(+), 12 deletions(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java index 72167580a92..8c40e755d51 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java @@ -547,7 +547,7 @@ class Metacity implements SynthConstants { i = strLowerCase.indexOf("", i); if (i > 0) { i += "".length(); - int i2 = str.indexOf("<", i); + int i2 = str.indexOf('<', i); return str.substring(i, i2); } } diff --git a/jdk/src/share/classes/javax/swing/JEditorPane.java b/jdk/src/share/classes/javax/swing/JEditorPane.java index c1382125237..bc738185d20 100644 --- a/jdk/src/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/share/classes/javax/swing/JEditorPane.java @@ -965,7 +965,7 @@ public class JEditorPane extends JTextComponent { // The type could have optional info is part of it, // for example some charset info. We need to strip that // of and save it. - int parm = type.indexOf(";"); + int parm = type.indexOf(';'); if (parm > -1) { // Save the paramList. String paramList = type.substring(parm); diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java index e38a0789e3c..bcdae78da79 100644 --- a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java +++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java @@ -653,7 +653,7 @@ public final class NimbusStyle extends SynthStyle { // strip off the prefix, if there is one. String fullKey = key.toString(); - String partialKey = fullKey.substring(fullKey.indexOf(".") + 1); + String partialKey = fullKey.substring(fullKey.indexOf('.') + 1); Object obj = null; int xstate = getExtendedState(ctx, v); diff --git a/jdk/src/share/classes/sun/applet/AppletClassLoader.java b/jdk/src/share/classes/sun/applet/AppletClassLoader.java index f732ad22425..72358e80fa2 100644 --- a/jdk/src/share/classes/sun/applet/AppletClassLoader.java +++ b/jdk/src/share/classes/sun/applet/AppletClassLoader.java @@ -168,7 +168,7 @@ public class AppletClassLoader extends URLClassLoader { */ protected Class findClass(String name) throws ClassNotFoundException { - int index = name.indexOf(";"); + int index = name.indexOf(';'); String cookie = ""; if(index != -1) { cookie = name.substring(index, name.length()); @@ -608,7 +608,7 @@ public class AppletClassLoader extends URLClassLoader { // deal with URL rewriting String cookie = null; - int index = name.indexOf(";"); + int index = name.indexOf(';'); if(index != -1) { cookie = name.substring(index, name.length()); name = name.substring(0, index); diff --git a/jdk/src/share/classes/sun/awt/FontConfiguration.java b/jdk/src/share/classes/sun/awt/FontConfiguration.java index c234b534633..b4deecebc8a 100644 --- a/jdk/src/share/classes/sun/awt/FontConfiguration.java +++ b/jdk/src/share/classes/sun/awt/FontConfiguration.java @@ -272,9 +272,9 @@ public abstract class FontConfiguration { if (configFile != null) { return configFile; } - int decimalPointIndex = osVersion.indexOf("."); + int decimalPointIndex = osVersion.indexOf('.'); if (decimalPointIndex != -1) { - osMajorVersion = osVersion.substring(0, osVersion.indexOf(".")); + osMajorVersion = osVersion.substring(0, osVersion.indexOf('.')); configFile = findImpl(baseName + "." + osName + "." + osMajorVersion); if (configFile != null) { return configFile; diff --git a/jdk/src/share/classes/sun/font/SunFontManager.java b/jdk/src/share/classes/sun/font/SunFontManager.java index 998713b4494..3266268b315 100644 --- a/jdk/src/share/classes/sun/font/SunFontManager.java +++ b/jdk/src/share/classes/sun/font/SunFontManager.java @@ -2872,8 +2872,7 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { new java.security.PrivilegedAction() { public Object run() { SecurityManager sm = System.getSecurityManager(); - return new Boolean - (sm instanceof sun.applet.AppletSecurity); + return sm instanceof sun.applet.AppletSecurity; } }); return appletSM.booleanValue(); diff --git a/jdk/src/share/classes/sun/font/Type1Font.java b/jdk/src/share/classes/sun/font/Type1Font.java index fca68cbfea3..c738315d607 100644 --- a/jdk/src/share/classes/sun/font/Type1Font.java +++ b/jdk/src/share/classes/sun/font/Type1Font.java @@ -492,7 +492,7 @@ public class Type1Font extends FileFont { //Conversion: Expand abbreviations in style portion (everything after '-'), // replace '-' with space and insert missing spaces - pos = name.indexOf("-"); + pos = name.indexOf('-'); if (pos >= 0) { res = expandName(name.substring(0, pos), false); res += " " + expandName(name.substring(pos+1), true); @@ -513,8 +513,8 @@ public class Type1Font extends FileFont { //Conversion: Truncate style portion (everything after '-') // and insert missing spaces - if (tmp.indexOf("-") > 0) { - tmp = tmp.substring(0, tmp.indexOf("-")); + if (tmp.indexOf('-') > 0) { + tmp = tmp.substring(0, tmp.indexOf('-')); } return expandName(tmp, false); From faa3d72cb09d9f948f45aaceb28022b285f8cc59 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 3 Jun 2014 09:22:59 -0700 Subject: [PATCH 037/192] 8042860: Fix raw and unchecked warnings in java.beans Reviewed-by: malenkov, alanb, mduigou --- .../classes/java/beans/EventHandler.java | 4 +- .../java/beans/EventSetDescriptor.java | 4 +- .../java/beans/IndexedPropertyDescriptor.java | 6 +- .../classes/java/beans/Introspector.java | 8 +- .../share/classes/java/beans/MetaData.java | 4 +- .../java/beans/PropertyDescriptor.java | 4 +- .../BeanContextServiceAvailableEvent.java | 10 +- .../BeanContextServiceProvider.java | 6 +- .../BeanContextServiceRevokedEvent.java | 10 +- .../beancontext/BeanContextServices.java | 14 +- .../BeanContextServicesSupport.java | 154 +++++++++--------- .../beans/beancontext/BeanContextSupport.java | 53 +++--- 12 files changed, 142 insertions(+), 135 deletions(-) diff --git a/jdk/src/share/classes/java/beans/EventHandler.java b/jdk/src/share/classes/java/beans/EventHandler.java index 470991e11bd..dd41750f2f1 100644 --- a/jdk/src/share/classes/java/beans/EventHandler.java +++ b/jdk/src/share/classes/java/beans/EventHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -446,7 +446,7 @@ public class EventHandler implements InvocationHandler { } if (listenerMethodName == null || listenerMethodName.equals(methodName)) { - Class[] argTypes = null; + Class[] argTypes = null; Object[] newArgs = null; if (eventPropertyName == null) { // Nullary method. diff --git a/jdk/src/share/classes/java/beans/EventSetDescriptor.java b/jdk/src/share/classes/java/beans/EventSetDescriptor.java index 78bc44d2978..ca8dbadb04e 100644 --- a/jdk/src/share/classes/java/beans/EventSetDescriptor.java +++ b/jdk/src/share/classes/java/beans/EventSetDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -81,7 +81,7 @@ public class EventSetDescriptor extends FeatureDescriptor { String eventName = NameGenerator.capitalize(eventSetName) + "Event"; Method[] listenerMethods = getListenerMethods(); if (listenerMethods.length > 0) { - Class[] args = getParameterTypes(getClass0(), listenerMethods[0]); + Class[] args = getParameterTypes(getClass0(), listenerMethods[0]); // Check for EventSet compliance. Special case for vetoableChange. See 4529996 if (!"vetoableChange".equals(eventSetName) && !args[0].getName().endsWith(eventName)) { throw new IntrospectionException("Method \"" + listenerMethodName + diff --git a/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java b/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java index 1f329a31c55..84f20ee4a1a 100644 --- a/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java +++ b/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -353,7 +353,7 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { Class indexedPropertyType = null; if (indexedReadMethod != null) { - Class params[] = getParameterTypes(getClass0(), indexedReadMethod); + Class[] params = getParameterTypes(getClass0(), indexedReadMethod); if (params.length != 1) { throw new IntrospectionException("bad indexed read method arg count"); } @@ -366,7 +366,7 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { } } if (indexedWriteMethod != null) { - Class params[] = getParameterTypes(getClass0(), indexedWriteMethod); + Class[] params = getParameterTypes(getClass0(), indexedWriteMethod); if (params.length != 2) { throw new IntrospectionException("bad indexed write method arg count"); } diff --git a/jdk/src/share/classes/java/beans/Introspector.java b/jdk/src/share/classes/java/beans/Introspector.java index 10efa7ae5a8..469238a601e 100644 --- a/jdk/src/share/classes/java/beans/Introspector.java +++ b/jdk/src/share/classes/java/beans/Introspector.java @@ -1384,7 +1384,7 @@ public class Introspector { * parameter list on a given class. */ private static Method internalFindMethod(Class start, String methodName, - int argCount, Class args[]) { + int argCount, Class args[]) { // For overriden methods we need to find the most derived version. // So we start with the given class and walk up the superclass chain. @@ -1426,7 +1426,7 @@ public class Introspector { // Now check any inherited interfaces. This is necessary both when // the argument class is itself an interface, and when the argument // class is an abstract class. - Class ifcs[] = start.getInterfaces(); + Class[] ifcs = start.getInterfaces(); for (int i = 0 ; i < ifcs.length; i++) { // Note: The original implementation had both methods calling // the 3 arg method. This is preserved but perhaps it should @@ -1459,7 +1459,7 @@ public class Introspector { * @return the method or null if not found */ static Method findMethod(Class cls, String methodName, int argCount, - Class args[]) { + Class[] args) { if (methodName == null) { return null; } @@ -1502,7 +1502,7 @@ public class Introspector { * Return true iff the given method throws the given exception. */ private boolean throwsException(Method method, Class exception) { - Class exs[] = method.getExceptionTypes(); + Class[] exs = method.getExceptionTypes(); for (int i = 0; i < exs.length; i++) { if (exs[i] == exception) { return true; diff --git a/jdk/src/share/classes/java/beans/MetaData.java b/jdk/src/share/classes/java/beans/MetaData.java index 3ae1e0375f9..d0e7108179d 100644 --- a/jdk/src/share/classes/java/beans/MetaData.java +++ b/jdk/src/share/classes/java/beans/MetaData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1401,7 +1401,7 @@ static final class sun_swing_PrintColorUIResource_PersistenceDelegate extends Pe } private static boolean isValid(Constructor constructor, String[] names) { - Class[] parameters = constructor.getParameterTypes(); + Class[] parameters = constructor.getParameterTypes(); if (names.length != parameters.length) { return false; } diff --git a/jdk/src/share/classes/java/beans/PropertyDescriptor.java b/jdk/src/share/classes/java/beans/PropertyDescriptor.java index 07149f9752d..fb0b349c000 100644 --- a/jdk/src/share/classes/java/beans/PropertyDescriptor.java +++ b/jdk/src/share/classes/java/beans/PropertyDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -112,7 +112,7 @@ public class PropertyDescriptor extends FeatureDescriptor { // If this class or one of its base classes allow PropertyChangeListener, // then we assume that any properties we discover are "bound". // See Introspector.getTargetPropertyInfo() method. - Class[] args = { PropertyChangeListener.class }; + Class[] args = { PropertyChangeListener.class }; this.bound = null != Introspector.findMethod(beanClass, "addPropertyChangeListener", args.length, args); } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceAvailableEvent.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceAvailableEvent.java index c1034ef73cc..24eb66aa96f 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceAvailableEvent.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceAvailableEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,7 +47,7 @@ public class BeanContextServiceAvailableEvent extends BeanContextEvent { * @param bcs The context in which the service has become available * @param sc A Class reference to the newly available service */ - public BeanContextServiceAvailableEvent(BeanContextServices bcs, Class sc) { + public BeanContextServiceAvailableEvent(BeanContextServices bcs, Class sc) { super((BeanContext)bcs); serviceClass = sc; @@ -65,13 +65,13 @@ public class BeanContextServiceAvailableEvent extends BeanContextEvent { * Gets the service class that is the subject of this notification. * @return A Class reference to the newly available service */ - public Class getServiceClass() { return serviceClass; } + public Class getServiceClass() { return serviceClass; } /** * Gets the list of service dependent selectors. * @return the current selectors available from the service */ - public Iterator getCurrentServiceSelectors() { + public Iterator getCurrentServiceSelectors() { return ((BeanContextServices)getSource()).getCurrentServiceSelectors(serviceClass); } @@ -82,5 +82,5 @@ public class BeanContextServiceAvailableEvent extends BeanContextEvent { /** * A Class reference to the newly available service */ - protected Class serviceClass; + protected Class serviceClass; } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceProvider.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceProvider.java index 5e724ca325f..104051e3952 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceProvider.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -70,7 +70,7 @@ public interface BeanContextServiceProvider { * * @return a reference to the requested service */ - Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector); + Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector); /** * Invoked by BeanContextServices, @@ -100,5 +100,5 @@ public interface BeanContextServiceProvider { * @param serviceClass the specified service * @return the current service selectors for the specified serviceClass */ - Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass); + Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass); } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceRevokedEvent.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceRevokedEvent.java index 30d99862903..b886e30a86f 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceRevokedEvent.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceRevokedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,7 +46,7 @@ public class BeanContextServiceRevokedEvent extends BeanContextEvent { * @param sc the service that is being revoked * @param invalidate true for immediate revocation */ - public BeanContextServiceRevokedEvent(BeanContextServices bcs, Class sc, boolean invalidate) { + public BeanContextServiceRevokedEvent(BeanContextServices bcs, Class sc, boolean invalidate) { super((BeanContext)bcs); serviceClass = sc; @@ -67,7 +67,7 @@ public class BeanContextServiceRevokedEvent extends BeanContextEvent { * @return A Class reference to the * service that is being revoked */ - public Class getServiceClass() { return serviceClass; } + public Class getServiceClass() { return serviceClass; } /** * Checks this event to determine whether or not @@ -76,7 +76,7 @@ public class BeanContextServiceRevokedEvent extends BeanContextEvent { * @return true if the service being revoked is of the * same class as the specified service */ - public boolean isServiceClass(Class service) { + public boolean isServiceClass(Class service) { return serviceClass.equals(service); } @@ -94,6 +94,6 @@ public class BeanContextServiceRevokedEvent extends BeanContextEvent { /** * A Class reference to the service that is being revoked. */ - protected Class serviceClass; + protected Class serviceClass; private boolean invalidateRefs; } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServices.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServices.java index 0348817bfe8..62652ec5443 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServices.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServices.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -62,7 +62,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * associated with the service * @return true if the service was successful added, false otherwise */ - boolean addService(Class serviceClass, BeanContextServiceProvider serviceProvider); + boolean addService(Class serviceClass, BeanContextServiceProvider serviceProvider); /** * BeanContextServiceProviders wishing to remove @@ -83,7 +83,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * terminate service to all currently outstanding references * to the specified service. */ - void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow); + void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow); /** * Reports whether or not a given service is @@ -91,7 +91,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * @param serviceClass the service in question * @return true if the service is available */ - boolean hasService(Class serviceClass); + boolean hasService(Class serviceClass); /** * A BeanContextChild, or any arbitrary object @@ -113,7 +113,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * @return a reference to this context's named * Service as requested or null */ - Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException; + Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException; /** * Releases a BeanContextChild's @@ -131,7 +131,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * @return an Iterator consisting of the * currently available services */ - Iterator getCurrentServiceClasses(); + Iterator getCurrentServiceClasses(); /** * Gets the list of service dependent service parameters @@ -142,7 +142,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * @return the currently available service selectors * for the named serviceClass */ - Iterator getCurrentServiceSelectors(Class serviceClass); + Iterator getCurrentServiceSelectors(Class serviceClass); /** * Adds a BeanContextServicesListener to this BeanContext diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServicesSupport.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServicesSupport.java index 41cfa9d7a89..507e8ec0215 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServicesSupport.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServicesSupport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -129,9 +129,8 @@ public class BeanContextServicesSupport extends BeanContextSupport public void initialize() { super.initialize(); - - services = new HashMap(serializable + 1); - bcsListeners = new ArrayList(1); + services = new HashMap<>(serializable + 1); + bcsListeners = new ArrayList<>(1); } /** @@ -169,7 +168,7 @@ public class BeanContextServicesSupport extends BeanContextSupport // create an instance of a service ref - BCSSCServiceClassRef(Class sc, BeanContextServiceProvider bcsp, boolean delegated) { + BCSSCServiceClassRef(Class sc, BeanContextServiceProvider bcsp, boolean delegated) { super(); serviceClass = sc; @@ -183,7 +182,7 @@ public class BeanContextServicesSupport extends BeanContextSupport // add a requestor and assoc listener void addRequestor(Object requestor, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { - BeanContextServiceRevokedListener cbcsrl = (BeanContextServiceRevokedListener)requestors.get(requestor); + BeanContextServiceRevokedListener cbcsrl = requestors.get(requestor); if (cbcsrl != null && !cbcsrl.equals(bcsrl)) throw new TooManyListenersException(); @@ -200,7 +199,7 @@ public class BeanContextServicesSupport extends BeanContextSupport // check a requestors listener void verifyRequestor(Object requestor, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { - BeanContextServiceRevokedListener cbcsrl = (BeanContextServiceRevokedListener)requestors.get(requestor); + BeanContextServiceRevokedListener cbcsrl = requestors.get(requestor); if (cbcsrl != null && !cbcsrl.equals(bcsrl)) throw new TooManyListenersException(); @@ -230,15 +229,18 @@ public class BeanContextServicesSupport extends BeanContextSupport } - Iterator cloneOfEntries() { - return ((HashMap)requestors.clone()).entrySet().iterator(); + @SuppressWarnings("unchecked") // Cast from clone + Iterator> cloneOfEntries() { + return ((HashMap)requestors.clone()).entrySet().iterator(); } - Iterator entries() { return requestors.entrySet().iterator(); } + Iterator> entries() { + return requestors.entrySet().iterator(); + } boolean isEmpty() { return requestors.isEmpty(); } - Class getServiceClass() { return serviceClass; } + Class getServiceClass() { return serviceClass; } BeanContextServiceProvider getServiceProvider() { return serviceProvider; @@ -281,7 +283,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * fields */ - Class serviceClass; + Class serviceClass; BeanContextServiceProvider serviceProvider; int serviceRefs; @@ -289,7 +291,7 @@ public class BeanContextServicesSupport extends BeanContextSupport BeanContextServiceProvider delegateProvider; // proxy int delegateRefs; - HashMap requestors = new HashMap(1); + HashMap requestors = new HashMap<>(1); } /* @@ -322,16 +324,16 @@ public class BeanContextServicesSupport extends BeanContextSupport // note usage of service per requestor, per service - synchronized void usingService(Object requestor, Object service, Class serviceClass, BeanContextServiceProvider bcsp, boolean isDelegated, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException, UnsupportedOperationException { + synchronized void usingService(Object requestor, Object service, Class serviceClass, BeanContextServiceProvider bcsp, boolean isDelegated, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException, UnsupportedOperationException { // first, process mapping from serviceClass to requestor(s) BCSSCServiceClassRef serviceClassRef = null; if (serviceClasses == null) - serviceClasses = new HashMap(1); + serviceClasses = new HashMap<>(1); else - serviceClassRef = (BCSSCServiceClassRef)serviceClasses.get(serviceClass); + serviceClassRef = serviceClasses.get(serviceClass); if (serviceClassRef == null) { // new service being used ... serviceClassRef = new BCSSCServiceClassRef(serviceClass, bcsp, isDelegated); @@ -348,20 +350,20 @@ public class BeanContextServicesSupport extends BeanContextSupport // now handle mapping from requestor to service(s) BCSSCServiceRef serviceRef = null; - Map services = null; + Map services = null; if (serviceRequestors == null) { - serviceRequestors = new HashMap(1); + serviceRequestors = new HashMap<>(1); } else { - services = (Map)serviceRequestors.get(requestor); + services = serviceRequestors.get(requestor); } if (services == null) { - services = new HashMap(1); + services = new HashMap<>(1); serviceRequestors.put(requestor, services); } else - serviceRef = (BCSSCServiceRef)services.get(service); + serviceRef = services.get(service); if (serviceRef == null) { serviceRef = new BCSSCServiceRef(serviceClassRef, isDelegated); @@ -377,11 +379,11 @@ public class BeanContextServicesSupport extends BeanContextSupport synchronized void releaseService(Object requestor, Object service) { if (serviceRequestors == null) return; - Map services = (Map)serviceRequestors.get(requestor); + Map services = serviceRequestors.get(requestor); if (services == null) return; // oops its not there anymore! - BCSSCServiceRef serviceRef = (BCSSCServiceRef)services.get(service); + BCSSCServiceRef serviceRef = services.get(service); if (serviceRef == null) return; // oops its not there anymore! @@ -418,33 +420,33 @@ public class BeanContextServicesSupport extends BeanContextSupport // revoke a service - synchronized void revokeService(Class serviceClass, boolean isDelegated, boolean revokeNow) { + synchronized void revokeService(Class serviceClass, boolean isDelegated, boolean revokeNow) { if (serviceClasses == null) return; - BCSSCServiceClassRef serviceClassRef = (BCSSCServiceClassRef)serviceClasses.get(serviceClass); + BCSSCServiceClassRef serviceClassRef = serviceClasses.get(serviceClass); if (serviceClassRef == null) return; - Iterator i = serviceClassRef.cloneOfEntries(); + Iterator> i = serviceClassRef.cloneOfEntries(); BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(BeanContextServicesSupport.this.getBeanContextServicesPeer(), serviceClass, revokeNow); boolean noMoreRefs = false; while (i.hasNext() && serviceRequestors != null) { - Map.Entry entry = (Map.Entry)i.next(); - BeanContextServiceRevokedListener listener = (BeanContextServiceRevokedListener)entry.getValue(); + Map.Entry entry = i.next(); + BeanContextServiceRevokedListener listener = entry.getValue(); if (revokeNow) { Object requestor = entry.getKey(); - Map services = (Map)serviceRequestors.get(requestor); + Map services = serviceRequestors.get(requestor); if (services != null) { - Iterator i1 = services.entrySet().iterator(); + Iterator> i1 = services.entrySet().iterator(); while (i1.hasNext()) { - Map.Entry tmp = (Map.Entry)i1.next(); + Map.Entry tmp = i1.next(); - BCSSCServiceRef serviceRef = (BCSSCServiceRef)tmp.getValue(); + BCSSCServiceRef serviceRef = tmp.getValue(); if (serviceRef.getServiceClassRef().equals(serviceClassRef) && isDelegated == serviceRef.isDelegated()) { i1.remove(); } @@ -479,19 +481,19 @@ public class BeanContextServicesSupport extends BeanContextSupport if (serviceRequestors == null) return; - Iterator requestors = serviceRequestors.entrySet().iterator(); + Iterator>> requestors = serviceRequestors.entrySet().iterator(); while(requestors.hasNext()) { - Map.Entry tmp = (Map.Entry)requestors.next(); + Map.Entry> tmp = requestors.next(); Object requestor = tmp.getKey(); - Iterator services = ((Map)tmp.getValue()).entrySet().iterator(); + Iterator> services = tmp.getValue().entrySet().iterator(); requestors.remove(); while (services.hasNext()) { - Map.Entry entry = (Map.Entry)services.next(); + Map.Entry entry = services.next(); Object service = entry.getKey(); - BCSSCServiceRef sref = (BCSSCServiceRef)entry.getValue(); + BCSSCServiceRef sref = entry.getValue(); BCSSCServiceClassRef scref = sref.getServiceClassRef(); @@ -513,32 +515,32 @@ public class BeanContextServicesSupport extends BeanContextSupport void revokeAllDelegatedServicesNow() { if (serviceClasses == null) return; - Iterator serviceClassRefs = - new HashSet(serviceClasses.values()).iterator(); + Iterator serviceClassRefs = + new HashSet<>(serviceClasses.values()).iterator(); while (serviceClassRefs.hasNext()) { - BCSSCServiceClassRef serviceClassRef = (BCSSCServiceClassRef)serviceClassRefs.next(); + BCSSCServiceClassRef serviceClassRef = serviceClassRefs.next(); if (!serviceClassRef.isDelegated()) continue; - Iterator i = serviceClassRef.cloneOfEntries(); + Iterator> i = serviceClassRef.cloneOfEntries(); BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(BeanContextServicesSupport.this.getBeanContextServicesPeer(), serviceClassRef.getServiceClass(), true); boolean noMoreRefs = false; while (i.hasNext()) { - Map.Entry entry = (Map.Entry)i.next(); - BeanContextServiceRevokedListener listener = (BeanContextServiceRevokedListener)entry.getValue(); + Map.Entry entry = i.next(); + BeanContextServiceRevokedListener listener = entry.getValue(); Object requestor = entry.getKey(); - Map services = (Map)serviceRequestors.get(requestor); + Map services = serviceRequestors.get(requestor); if (services != null) { - Iterator i1 = services.entrySet().iterator(); + Iterator> i1 = services.entrySet().iterator(); while (i1.hasNext()) { - Map.Entry tmp = (Map.Entry)i1.next(); + Map.Entry tmp = i1.next(); - BCSSCServiceRef serviceRef = (BCSSCServiceRef)tmp.getValue(); + BCSSCServiceRef serviceRef = tmp.getValue(); if (serviceRef.getServiceClassRef().equals(serviceClassRef) && serviceRef.isDelegated()) { i1.remove(); } @@ -568,8 +570,8 @@ public class BeanContextServicesSupport extends BeanContextSupport * fields */ - private transient HashMap serviceClasses; - private transient HashMap serviceRequestors; + private transient HashMap, BCSSCServiceClassRef> serviceClasses; + private transient HashMap> serviceRequestors; } /** @@ -597,7 +599,7 @@ public class BeanContextServicesSupport extends BeanContextSupport protected static class BCSSServiceProvider implements Serializable { private static final long serialVersionUID = 861278251667444782L; - BCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { + BCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { super(); serviceProvider = bcsp; @@ -627,7 +629,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @return a service provider without overriding addService() */ - protected BCSSServiceProvider createBCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { + protected BCSSServiceProvider createBCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { return new BCSSServiceProvider(sc, bcsp); } @@ -671,7 +673,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @param bcsp the service provider */ - public boolean addService(Class serviceClass, BeanContextServiceProvider bcsp) { + public boolean addService(Class serviceClass, BeanContextServiceProvider bcsp) { return addService(serviceClass, bcsp, true); } @@ -683,7 +685,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @return true if the service was successfully added */ - protected boolean addService(Class serviceClass, BeanContextServiceProvider bcsp, boolean fireEvent) { + protected boolean addService(Class serviceClass, BeanContextServiceProvider bcsp, boolean fireEvent) { if (serviceClass == null) throw new NullPointerException("serviceClass"); if (bcsp == null) throw new NullPointerException("bcsp"); @@ -704,7 +706,7 @@ public class BeanContextServicesSupport extends BeanContextSupport fireServiceAdded(bcssae); synchronized(children) { - Iterator i = children.keySet().iterator(); + Iterator i = children.keySet().iterator(); while (i.hasNext()) { Object c = i.next(); @@ -727,7 +729,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @param revokeCurrentServicesNow whether or not to revoke the service */ - public void revokeService(Class serviceClass, BeanContextServiceProvider bcsp, boolean revokeCurrentServicesNow) { + public void revokeService(Class serviceClass, BeanContextServiceProvider bcsp, boolean revokeCurrentServicesNow) { if (serviceClass == null) throw new NullPointerException("serviceClass"); if (bcsp == null) throw new NullPointerException("bcsp"); @@ -735,7 +737,7 @@ public class BeanContextServicesSupport extends BeanContextSupport synchronized(BeanContext.globalHierarchyLock) { if (!services.containsKey(serviceClass)) return; - BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); + BCSSServiceProvider bcsssp = services.get(serviceClass); if (!bcsssp.getServiceProvider().equals(bcsp)) throw new IllegalArgumentException("service provider mismatch"); @@ -744,7 +746,7 @@ public class BeanContextServicesSupport extends BeanContextSupport if (bcsp instanceof Serializable) serializable--; - Iterator i = bcsChildren(); // get the BCSChild values. + Iterator i = bcsChildren(); // get the BCSChild values. while (i.hasNext()) { ((BCSSChild)i.next()).revokeService(serviceClass, false, revokeCurrentServicesNow); @@ -758,7 +760,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * has a service, which may be delegated */ - public synchronized boolean hasService(Class serviceClass) { + public synchronized boolean hasService(Class serviceClass) { if (serviceClass == null) throw new NullPointerException("serviceClass"); synchronized(BeanContext.globalHierarchyLock) { @@ -791,7 +793,7 @@ public class BeanContextServicesSupport extends BeanContextSupport nestingCtxt = bcs; } - public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) { + public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) { Object service = null; try { @@ -807,12 +809,12 @@ public class BeanContextServicesSupport extends BeanContextSupport nestingCtxt.releaseService(bcs, requestor, service); } - public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) { + public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) { return nestingCtxt.getCurrentServiceSelectors(serviceClass); } public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) { - Iterator i = bcsChildren(); // get the BCSChild values. + Iterator i = bcsChildren(); // get the BCSChild values. while (i.hasNext()) { ((BCSSChild)i.next()).revokeService(bcsre.getServiceClass(), true, bcsre.isCurrentServiceInvalidNow()); @@ -832,7 +834,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * obtain a service which may be delegated */ - public Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { + public Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { if (child == null) throw new NullPointerException("child"); if (serviceClass == null) throw new NullPointerException("serviceClass"); if (requestor == null) throw new NullPointerException("requestor"); @@ -847,7 +849,7 @@ public class BeanContextServicesSupport extends BeanContextSupport if (bcsc == null) throw new IllegalArgumentException("not a child of this context"); // not a child ... - BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); + BCSSServiceProvider bcsssp = services.get(serviceClass); if (bcsssp != null) { BeanContextServiceProvider bcsp = bcsssp.getServiceProvider(); @@ -918,7 +920,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @return an iterator for all the currently registered service classes. */ - public Iterator getCurrentServiceClasses() { + public Iterator getCurrentServiceClasses() { return new BCSIterator(services.keySet().iterator()); } @@ -927,9 +929,9 @@ public class BeanContextServicesSupport extends BeanContextSupport * (if any) available for the specified service. */ - public Iterator getCurrentServiceSelectors(Class serviceClass) { + public Iterator getCurrentServiceSelectors(Class serviceClass) { - BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); + BCSSServiceProvider bcsssp = services.get(serviceClass); return bcsssp != null ? new BCSIterator(bcsssp.getServiceProvider().getCurrentServiceSelectors(getBeanContextServicesPeer(), serviceClass)) : null; } @@ -950,7 +952,7 @@ public class BeanContextServicesSupport extends BeanContextSupport fireServiceAdded(bcssae); - Iterator i; + Iterator i; synchronized(children) { i = children.keySet().iterator(); @@ -982,7 +984,7 @@ public class BeanContextServicesSupport extends BeanContextSupport fireServiceRevoked(bcssre); - Iterator i; + Iterator i; synchronized(children) { i = children.keySet().iterator(); @@ -1085,7 +1087,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * Fires a BeanContextServiceEvent notifying of a new service. * @param serviceClass the service class */ - protected final void fireServiceAdded(Class serviceClass) { + protected final void fireServiceAdded(Class serviceClass) { BeanContextServiceAvailableEvent bcssae = new BeanContextServiceAvailableEvent(getBeanContextServicesPeer(), serviceClass); fireServiceAdded(bcssae); @@ -1129,7 +1131,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @param serviceClass the service class * @param revokeNow whether or not the event should be revoked now */ - protected final void fireServiceRevoked(Class serviceClass, boolean revokeNow) { + protected final void fireServiceRevoked(Class serviceClass, boolean revokeNow) { Object[] copy; BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), serviceClass, revokeNow); @@ -1159,14 +1161,14 @@ public class BeanContextServicesSupport extends BeanContextSupport int count = 0; - Iterator i = services.entrySet().iterator(); + Iterator> i = services.entrySet().iterator(); while (i.hasNext() && count < serializable) { - Map.Entry entry = (Map.Entry)i.next(); + Map.Entry entry = i.next(); BCSSServiceProvider bcsp = null; try { - bcsp = (BCSSServiceProvider)entry.getValue(); + bcsp = entry.getValue(); } catch (ClassCastException cce) { continue; } @@ -1201,7 +1203,7 @@ public class BeanContextServicesSupport extends BeanContextSupport int count = serializable; while (count > 0) { - services.put(ois.readObject(), ois.readObject()); + services.put(ois.readObject(), (BCSSServiceProvider)ois.readObject()); count--; } } @@ -1236,7 +1238,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * all accesses to the protected transient HashMap services * field should be synchronized on that object */ - protected transient HashMap services; + protected transient HashMap services; /** * The number of instances of a serializable BeanContextServceProvider. @@ -1253,5 +1255,5 @@ public class BeanContextServicesSupport extends BeanContextSupport /** * List of BeanContextServicesListener objects. */ - protected transient ArrayList bcsListeners; + protected transient ArrayList bcsListeners; } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextSupport.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextSupport.java index e8cd43b6293..4845650e745 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextSupport.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextSupport.java @@ -254,7 +254,7 @@ public class BeanContextSupport extends BeanContextChildSupport * currently nested in this BeanContext. * @return an Iterator of the nested children */ - public Iterator iterator() { + public Iterator iterator() { synchronized(children) { return new BCSIterator(children.keySet().iterator()); } @@ -292,14 +292,14 @@ public class BeanContextSupport extends BeanContextChildSupport * a noop remove() method. */ - protected static final class BCSIterator implements Iterator { - BCSIterator(Iterator i) { super(); src = i; } + protected static final class BCSIterator implements Iterator { + BCSIterator(Iterator i) { super(); src = i; } public boolean hasNext() { return src.hasNext(); } - public Object next() { return src.next(); } + public Object next() { return src.next(); } public void remove() { /* do nothing */ } - private Iterator src; + private Iterator src; } /************************************************************************/ @@ -504,7 +504,7 @@ public class BeanContextSupport extends BeanContextChildSupport throw new IllegalStateException(); } - BCSChild bcsc = (BCSChild)children.get(targetChild); + BCSChild bcsc = children.get(targetChild); BCSChild pbcsc = null; Object peer = null; @@ -533,7 +533,7 @@ public class BeanContextSupport extends BeanContextChildSupport children.remove(targetChild); if (bcsc.isProxyPeer()) { - pbcsc = (BCSChild)children.get(peer = bcsc.getProxyPeer()); + pbcsc = children.get(peer = bcsc.getProxyPeer()); children.remove(peer); } } @@ -566,9 +566,10 @@ public class BeanContextSupport extends BeanContextChildSupport * in the collection are children of * this BeanContext, false if not. */ + @SuppressWarnings("rawtypes") public boolean containsAll(Collection c) { synchronized(children) { - Iterator i = c.iterator(); + Iterator i = c.iterator(); while (i.hasNext()) if(!contains(i.next())) return false; @@ -583,6 +584,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @throws UnsupportedOperationException thrown unconditionally by this implementation * @return this implementation unconditionally throws {@code UnsupportedOperationException} */ + @SuppressWarnings("rawtypes") public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } @@ -594,6 +596,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @return this implementation unconditionally throws {@code UnsupportedOperationException} */ + @SuppressWarnings("rawtypes") public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } @@ -605,6 +608,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @throws UnsupportedOperationException thrown unconditionally by this implementation * @return this implementation unconditionally throws {@code UnsupportedOperationException} */ + @SuppressWarnings("rawtypes") public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } @@ -763,7 +767,7 @@ public class BeanContextSupport extends BeanContextChildSupport } synchronized(children) { - for (Iterator i = children.keySet().iterator(); i.hasNext();) { + for (Iterator i = children.keySet().iterator(); i.hasNext();) { Object c = i.next(); try { @@ -790,7 +794,7 @@ public class BeanContextSupport extends BeanContextChildSupport // lets also tell the Children that can that they may not use their GUI's synchronized(children) { - for (Iterator i = children.keySet().iterator(); i.hasNext();) { + for (Iterator i = children.keySet().iterator(); i.hasNext();) { Visibility v = getChildVisibility(i.next()); if (v != null) v.dontUseGui(); @@ -809,7 +813,7 @@ public class BeanContextSupport extends BeanContextChildSupport // lets also tell the Children that can that they may use their GUI's synchronized(children) { - for (Iterator i = children.keySet().iterator(); i.hasNext();) { + for (Iterator i = children.keySet().iterator(); i.hasNext();) { Visibility v = getChildVisibility(i.next()); if (v != null) v.okToUseGui(); @@ -841,7 +845,7 @@ public class BeanContextSupport extends BeanContextChildSupport * of this BeanContext. * @return an iterator for all the current BCSChild values */ - protected Iterator bcsChildren() { synchronized(children) { return children.values().iterator(); } } + protected Iterator bcsChildren() { synchronized(children) { return children.values().iterator(); } } /** * called by writeObject after defaultWriteObject() but prior to @@ -896,7 +900,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @param coll the Collection to serialize * @throws IOException if serialization failed */ - protected final void serialize(ObjectOutputStream oos, Collection coll) throws IOException { + protected final void serialize(ObjectOutputStream oos, Collection coll) throws IOException { int count = 0; Object[] objects = coll.toArray(); @@ -926,6 +930,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @throws IOException if deserialization failed * @throws ClassNotFoundException if needed classes are not found */ + @SuppressWarnings({"rawtypes", "unchecked"}) protected final void deserialize(ObjectInputStream ois, Collection coll) throws IOException, ClassNotFoundException { int count = 0; @@ -953,10 +958,10 @@ public class BeanContextSupport extends BeanContextChildSupport int count = 0; synchronized(children) { - Iterator i = children.entrySet().iterator(); + Iterator> i = children.entrySet().iterator(); while (i.hasNext() && count < serializable) { - Map.Entry entry = (Map.Entry)i.next(); + Map.Entry entry = i.next(); if (entry.getKey() instanceof Serializable) { try { @@ -1082,7 +1087,7 @@ public class BeanContextSupport extends BeanContextChildSupport if (serializable > 0 && this.equals(getBeanContextPeer())) readChildren(ois); - deserialize(ois, bcmListeners = new ArrayList(1)); + deserialize(ois, bcmListeners = new ArrayList<>(1)); } } @@ -1101,7 +1106,7 @@ public class BeanContextSupport extends BeanContextChildSupport ) { if (!validatePendingRemove(source)) { throw new PropertyVetoException("current BeanContext vetoes setBeanContext()", pce); - } else ((BCSChild)children.get(source)).setRemovePending(true); + } else children.get(source).setRemovePending(true); } } } @@ -1117,13 +1122,13 @@ public class BeanContextSupport extends BeanContextChildSupport synchronized(children) { if ("beanContext".equals(propertyName) && containsKey(source) && - ((BCSChild)children.get(source)).isRemovePending()) { + children.get(source).isRemovePending()) { BeanContext bc = getBeanContextPeer(); if (bc.equals(pce.getOldValue()) && !bc.equals(pce.getNewValue())) { remove(source, false); } else { - ((BCSChild)children.get(source)).setRemovePending(false); + children.get(source).setRemovePending(false); } } } @@ -1312,8 +1317,8 @@ public class BeanContextSupport extends BeanContextChildSupport */ protected synchronized void initialize() { - children = new HashMap(serializable + 1); - bcmListeners = new ArrayList(1); + children = new HashMap<>(serializable + 1); + bcmListeners = new ArrayList<>(1); childPCL = new PropertyChangeListener() { @@ -1359,7 +1364,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @param second the second object * @return true if equal, false if not */ - protected static final boolean classEquals(Class first, Class second) { + protected static final boolean classEquals(Class first, Class second) { return first.equals(second) || first.getName().equals(second.getName()); } @@ -1373,7 +1378,7 @@ public class BeanContextSupport extends BeanContextChildSupport * all accesses to the protected HashMap children field * shall be synchronized on that object. */ - protected transient HashMap children; + protected transient HashMap children; private int serializable = 0; // children serializable @@ -1381,7 +1386,7 @@ public class BeanContextSupport extends BeanContextChildSupport * all accesses to the protected ArrayList bcmListeners field * shall be synchronized on that object. */ - protected transient ArrayList bcmListeners; + protected transient ArrayList bcmListeners; // From 628e9352544d8034ece43f2c5202e26fd2370c99 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Tue, 3 Jun 2014 21:03:35 +0400 Subject: [PATCH 038/192] 7084904: Introspector returns isX() from base package-private class that throws exception Reviewed-by: serb --- .../Introspector/7084904/Test7084904.java | 50 +++++++++++++++++++ .../beans/Introspector/7084904/bean/Base.java | 29 +++++++++++ .../Introspector/7084904/bean/Derived.java | 26 ++++++++++ 3 files changed, 105 insertions(+) create mode 100644 jdk/test/java/beans/Introspector/7084904/Test7084904.java create mode 100644 jdk/test/java/beans/Introspector/7084904/bean/Base.java create mode 100644 jdk/test/java/beans/Introspector/7084904/bean/Derived.java diff --git a/jdk/test/java/beans/Introspector/7084904/Test7084904.java b/jdk/test/java/beans/Introspector/7084904/Test7084904.java new file mode 100644 index 00000000000..ded9c160d95 --- /dev/null +++ b/jdk/test/java/beans/Introspector/7084904/Test7084904.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import bean.Derived; +import java.lang.reflect.Method; +/* + * @test + * @bug 7084904 + * @summary Compares reflection and bean introspection + * @author Sergey Malenkov + */ +public class Test7084904 { + public static void main(String[] args) throws Exception { + System.setSecurityManager(new SecurityManager()); + Derived bean = new Derived(); + Class type = bean.getClass(); + Method method1 = test("reflection", bean, type.getMethod("isAllowed")); + Method method2 = test("bean introspection", bean, BeanUtils.getPropertyDescriptor(type, "allowed").getReadMethod()); + if (!method1.equals(method2)) { + throw new Error("first method is not equal to the second one"); + } + } + + private static Method test(String name, Object bean, Method method) throws Exception { + System.out.println("\n === use " + name + " ==="); + System.out.println(method); + System.out.println("declaring " + method.getDeclaringClass()); + System.out.println("invocation result: " + method.invoke(bean)); + return method; + } +} diff --git a/jdk/test/java/beans/Introspector/7084904/bean/Base.java b/jdk/test/java/beans/Introspector/7084904/bean/Base.java new file mode 100644 index 00000000000..7efc9a03b8c --- /dev/null +++ b/jdk/test/java/beans/Introspector/7084904/bean/Base.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package bean; + +class Base { + public boolean isAllowed() { + return true; + } +} diff --git a/jdk/test/java/beans/Introspector/7084904/bean/Derived.java b/jdk/test/java/beans/Introspector/7084904/bean/Derived.java new file mode 100644 index 00000000000..4c506bb409c --- /dev/null +++ b/jdk/test/java/beans/Introspector/7084904/bean/Derived.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package bean; + +public class Derived extends Base { +} From f14291c31836827d74187b6576bd41c0eddad71e Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 3 Jun 2014 12:32:25 -0700 Subject: [PATCH 039/192] 8044694: Fix finally lint warnings in sun.print Reviewed-by: prr --- jdk/src/share/classes/sun/print/PSPrinterJob.java | 2 +- jdk/src/solaris/classes/sun/print/UnixPrintJob.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/sun/print/PSPrinterJob.java b/jdk/src/share/classes/sun/print/PSPrinterJob.java index fdaeb349992..325bfd8e718 100644 --- a/jdk/src/share/classes/sun/print/PSPrinterJob.java +++ b/jdk/src/share/classes/sun/print/PSPrinterJob.java @@ -708,8 +708,8 @@ public class PSPrinterJob extends RasterPrinterJob { } } finally { pw.flush(); - throw new IOException(sw.toString()); } + throw new IOException(sw.toString()); } } diff --git a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java index 57939732315..366a62f0e49 100644 --- a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java +++ b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java @@ -992,8 +992,8 @@ public class UnixPrintJob implements CancelablePrintJob { } } finally { pw.flush(); - throw new IOException(sw.toString()); } + throw new IOException(sw.toString()); } } From c7056f1df17a6b1c860c6f87234818c1e8742039 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 3 Jun 2014 17:03:29 -0700 Subject: [PATCH 040/192] 8044698: Fix finally lint warnings in javax.swing Reviewed-by: prr, henryjen --- jdk/src/share/classes/javax/swing/JEditorPane.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/share/classes/javax/swing/JEditorPane.java b/jdk/src/share/classes/javax/swing/JEditorPane.java index bc738185d20..bf2e28fbd37 100644 --- a/jdk/src/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/share/classes/javax/swing/JEditorPane.java @@ -679,8 +679,8 @@ public class JEditorPane extends JTextComponent { } }); } - return (pageLoaded ? page : old); } + return (pageLoaded ? page : old); } /** From 8dc26f1a171284dbb206f44ccfa2048f09502636 Mon Sep 17 00:00:00 2001 From: Staffan Larsen Date: Wed, 4 Jun 2014 11:05:30 +0200 Subject: [PATCH 041/192] 8044107: Add Diagnostic Command to list all ClassLoaders Reviewed-by: mgerdin, stefank --- .../share/vm/classfile/classLoaderData.cpp | 6 + .../share/vm/classfile/classLoaderData.hpp | 1 + .../share/vm/classfile/classLoaderStats.cpp | 167 ++++++++++++++++++ .../share/vm/classfile/classLoaderStats.hpp | 152 ++++++++++++++++ hotspot/src/share/vm/memory/metaspace.cpp | 11 ++ hotspot/src/share/vm/memory/metaspace.hpp | 3 + .../src/share/vm/runtime/vm_operations.hpp | 1 + .../share/vm/services/diagnosticCommand.cpp | 2 + .../dcmd/ClassLoaderStatsTest.java | 155 ++++++++++++++++ 9 files changed, 498 insertions(+) create mode 100644 hotspot/src/share/vm/classfile/classLoaderStats.cpp create mode 100644 hotspot/src/share/vm/classfile/classLoaderStats.hpp create mode 100644 hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java diff --git a/hotspot/src/share/vm/classfile/classLoaderData.cpp b/hotspot/src/share/vm/classfile/classLoaderData.cpp index bc88beb4343..efbde89ee30 100644 --- a/hotspot/src/share/vm/classfile/classLoaderData.cpp +++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp @@ -624,6 +624,12 @@ void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* kl } } +void ClassLoaderDataGraph::cld_do(CLDClosure* cl) { + for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) { + cl->do_cld(cld); + } +} + void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) { for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) { cld->classes_do(klass_closure); diff --git a/hotspot/src/share/vm/classfile/classLoaderData.hpp b/hotspot/src/share/vm/classfile/classLoaderData.hpp index 5be3caa6515..964e4289ffe 100644 --- a/hotspot/src/share/vm/classfile/classLoaderData.hpp +++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp @@ -77,6 +77,7 @@ class ClassLoaderDataGraph : public AllStatic { static void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim); static void always_strong_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim); static void keep_alive_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim); + static void cld_do(CLDClosure* cl); static void classes_do(KlassClosure* klass_closure); static void classes_do(void f(Klass* const)); static void methods_do(void f(Method*)); diff --git a/hotspot/src/share/vm/classfile/classLoaderStats.cpp b/hotspot/src/share/vm/classfile/classLoaderStats.cpp new file mode 100644 index 00000000000..4eb98ed321c --- /dev/null +++ b/hotspot/src/share/vm/classfile/classLoaderStats.cpp @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "classfile/classLoaderStats.hpp" +#include "utilities/globalDefinitions.hpp" + + +class ClassStatsClosure : public KlassClosure { +public: + int _num_classes; + + ClassStatsClosure() : + _num_classes(0) { + } + + virtual void do_klass(Klass* k) { + _num_classes++; + } +}; + + +void ClassLoaderStatsClosure::do_cld(ClassLoaderData* cld) { + oop cl = cld->class_loader(); + ClassLoaderStats* cls; + + // The hashtable key is the ClassLoader oop since we want to account + // for "real" classes and anonymous classes together + ClassLoaderStats** cls_ptr = _stats->get(cl); + if (cls_ptr == NULL) { + cls = new ClassLoaderStats(); + _stats->put(cl, cls); + _total_loaders++; + } else { + cls = *cls_ptr; + } + + if (!cld->is_anonymous()) { + cls->_cld = cld; + } + + cls->_class_loader = cl; + if (cl != NULL) { + cls->_parent = java_lang_ClassLoader::parent(cl); + addEmptyParents(cls->_parent); + } + + ClassStatsClosure csc; + cld->classes_do(&csc); + if(cld->is_anonymous()) { + cls->_anon_classes_count += csc._num_classes; + } else { + cls->_classes_count = csc._num_classes; + } + _total_classes += csc._num_classes; + + Metaspace* ms = cld->metaspace_or_null(); + if (ms != NULL) { + if(cld->is_anonymous()) { + cls->_anon_chunk_sz += ms->allocated_chunks_bytes(); + cls->_anon_block_sz += ms->allocated_blocks_bytes(); + } else { + cls->_chunk_sz = ms->allocated_chunks_bytes(); + cls->_block_sz = ms->allocated_blocks_bytes(); + } + _total_chunk_sz += ms->allocated_chunks_bytes(); + _total_block_sz += ms->allocated_blocks_bytes(); + } +} + + +// Handles the difference in pointer width on 32 and 64 bit platforms +#ifdef _LP64 + #define SPACE "%8s" +#else + #define SPACE "%s" +#endif + + +bool ClassLoaderStatsClosure::do_entry(oop const& key, ClassLoaderStats* const& cls) { + Klass* class_loader_klass = (cls->_class_loader == NULL ? NULL : cls->_class_loader->klass()); + Klass* parent_klass = (cls->_parent == NULL ? NULL : cls->_parent->klass()); + + _out->print(INTPTR_FORMAT " " INTPTR_FORMAT " " INTPTR_FORMAT " " UINTX_FORMAT_W(6) " " SIZE_FORMAT_W(8) " " SIZE_FORMAT_W(8) " ", + p2i(class_loader_klass), p2i(parent_klass), p2i(cls->_cld), + cls->_classes_count, + cls->_chunk_sz, cls->_block_sz); + if (class_loader_klass != NULL) { + _out->print("%s", class_loader_klass->external_name()); + } else { + _out->print(""); + } + _out->cr(); + if (cls->_anon_classes_count > 0) { + _out->print_cr(SPACE SPACE SPACE " " UINTX_FORMAT_W(6) " " SIZE_FORMAT_W(8) " " SIZE_FORMAT_W(8) " + unsafe anonymous classes", + "", "", "", + cls->_anon_classes_count, + cls->_anon_chunk_sz, cls->_anon_block_sz); + } + return true; +} + + +void ClassLoaderStatsClosure::print() { + _out->print_cr("ClassLoader" SPACE " Parent" SPACE " CLD*" SPACE " Classes ChunkSz BlockSz Type", "", "", ""); + _stats->iterate(this); + _out->print("Total = " UINTX_FORMAT_W(-6), _total_loaders); + _out->print(SPACE SPACE SPACE " ", "", "", ""); + _out->print_cr(UINTX_FORMAT_W(6) " " SIZE_FORMAT_W(8) " " SIZE_FORMAT_W(8) " ", + _total_classes, + _total_chunk_sz, + _total_block_sz); + _out->print_cr("ChunkSz: Total size of all allocated metaspace chunks"); + _out->print_cr("BlockSz: Total size of all allocated metaspace blocks (each chunk has several blocks)"); +} + + +void ClassLoaderStatsClosure::addEmptyParents(oop cl) { + while (cl != NULL && java_lang_ClassLoader::loader_data(cl) == NULL) { + // This classloader has not loaded any classes + ClassLoaderStats** cls_ptr = _stats->get(cl); + if (cls_ptr == NULL) { + // It does not exist in our table - add it + ClassLoaderStats* cls = new ClassLoaderStats(); + cls->_class_loader = cl; + cls->_parent = java_lang_ClassLoader::parent(cl); + _stats->put(cl, cls); + _total_loaders++; + } + + cl = java_lang_ClassLoader::parent(cl); + } +} + + +void ClassLoaderStatsVMOperation::doit() { + ClassLoaderStatsClosure clsc (_out); + ClassLoaderDataGraph::cld_do(&clsc); + clsc.print(); +} + + +void ClassLoaderStatsDCmd::execute(DCmdSource source, TRAPS) { + ClassLoaderStatsVMOperation op(output()); + VMThread::execute(&op); +} diff --git a/hotspot/src/share/vm/classfile/classLoaderStats.hpp b/hotspot/src/share/vm/classfile/classLoaderStats.hpp new file mode 100644 index 00000000000..89e0e473b3b --- /dev/null +++ b/hotspot/src/share/vm/classfile/classLoaderStats.hpp @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#ifndef SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP +#define SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP + + +#include "classfile/classLoaderData.hpp" +#include "oops/klass.hpp" +#include "oops/oopsHierarchy.hpp" +#include "runtime/vm_operations.hpp" +#include "services/diagnosticCommand.hpp" +#include "utilities/resourceHash.hpp" + + +class ClassLoaderStatsDCmd : public DCmd { +public: + ClassLoaderStatsDCmd(outputStream* output, bool heap) : + DCmd(output, heap) { + } + + static const char* name() { + return "VM.classloader_stats"; + } + + static const char* description() { + return "Print statistics about all ClassLoaders."; + } + + static const char* impact() { + return "Low"; + } + + virtual void execute(DCmdSource source, TRAPS); + + static int num_arguments() { + return 0; + } + + static const JavaPermission permission() { + JavaPermission p = {"java.lang.management.ManagementPermission", + "monitor", NULL}; + return p; + } +}; + + +class ClassLoaderStats : public ResourceObj { +public: + ClassLoaderData* _cld; + oop _class_loader; + oop _parent; + + size_t _chunk_sz; + size_t _block_sz; + uintx _classes_count; + + size_t _anon_chunk_sz; + size_t _anon_block_sz; + uintx _anon_classes_count; + + ClassLoaderStats() : + _cld(0), + _class_loader(0), + _parent(0), + _chunk_sz(0), + _block_sz(0), + _classes_count(0), + _anon_block_sz(0), + _anon_chunk_sz(0), + _anon_classes_count(0) { + } +}; + + +class ClassLoaderStatsClosure : public CLDClosure { +protected: + static bool oop_equals(oop const& s1, oop const& s2) { + return s1 == s2; + } + + static unsigned oop_hash(oop const& s1) { + unsigned hash = (unsigned)((uintptr_t)&s1); + return hash ^ (hash >> LogMinObjAlignment); + } + + typedef ResourceHashtable StatsTable; + + outputStream* _out; + StatsTable* _stats; + uintx _total_loaders; + uintx _total_classes; + size_t _total_chunk_sz; + size_t _total_block_sz; + +public: + ClassLoaderStatsClosure(outputStream* out) : + _out(out), + _total_loaders(0), + _total_block_sz(0), + _total_chunk_sz(0), + _total_classes(0), + _stats(new StatsTable()) { + } + + virtual void do_cld(ClassLoaderData* cld); + virtual bool do_entry(oop const& key, ClassLoaderStats* const& cls); + void print(); + +private: + void addEmptyParents(oop cl); +}; + + +class ClassLoaderStatsVMOperation : public VM_Operation { + outputStream* _out; + +public: + ClassLoaderStatsVMOperation(outputStream* out) : + _out(out) { + } + + VMOp_Type type() const { + return VMOp_ClassLoaderStatsOperation; + } + + void doit(); +}; + +#endif // SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP diff --git a/hotspot/src/share/vm/memory/metaspace.cpp b/hotspot/src/share/vm/memory/metaspace.cpp index cd5fceff2d0..4dce7a9c3cc 100644 --- a/hotspot/src/share/vm/memory/metaspace.cpp +++ b/hotspot/src/share/vm/memory/metaspace.cpp @@ -697,6 +697,7 @@ class SpaceManager : public CHeapObj { size_t allocated_blocks_words() const { return _allocated_blocks_words; } size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; } size_t allocated_chunks_words() const { return _allocated_chunks_words; } + size_t allocated_chunks_bytes() const { return _allocated_chunks_words * BytesPerWord; } size_t allocated_chunks_count() const { return _allocated_chunks_count; } bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); } @@ -3349,6 +3350,16 @@ size_t Metaspace::capacity_bytes_slow(MetadataType mdtype) const { return capacity_words_slow(mdtype) * BytesPerWord; } +size_t Metaspace::allocated_blocks_bytes() const { + return vsm()->allocated_blocks_bytes() + + (using_class_space() ? class_vsm()->allocated_blocks_bytes() : 0); +} + +size_t Metaspace::allocated_chunks_bytes() const { + return vsm()->allocated_chunks_bytes() + + (using_class_space() ? class_vsm()->allocated_chunks_bytes() : 0); +} + void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) { assert(!SafepointSynchronize::is_at_safepoint() || Thread::current()->is_VM_thread(), "should be the VM thread"); diff --git a/hotspot/src/share/vm/memory/metaspace.hpp b/hotspot/src/share/vm/memory/metaspace.hpp index 22e21b80d3d..453fef5deee 100644 --- a/hotspot/src/share/vm/memory/metaspace.hpp +++ b/hotspot/src/share/vm/memory/metaspace.hpp @@ -225,6 +225,9 @@ class Metaspace : public CHeapObj { size_t used_bytes_slow(MetadataType mdtype) const; size_t capacity_bytes_slow(MetadataType mdtype) const; + size_t allocated_blocks_bytes() const; + size_t allocated_chunks_bytes() const; + static MetaWord* allocate(ClassLoaderData* loader_data, size_t word_size, bool read_only, MetaspaceObj::Type type, TRAPS); void deallocate(MetaWord* ptr, size_t byte_size, bool is_class); diff --git a/hotspot/src/share/vm/runtime/vm_operations.hpp b/hotspot/src/share/vm/runtime/vm_operations.hpp index 8f2f0ba06f7..4e32a3adfa2 100644 --- a/hotspot/src/share/vm/runtime/vm_operations.hpp +++ b/hotspot/src/share/vm/runtime/vm_operations.hpp @@ -98,6 +98,7 @@ template(LinuxDllLoad) \ template(RotateGCLog) \ template(WhiteBoxOperation) \ + template(ClassLoaderStatsOperation) \ class VM_Operation: public CHeapObj { public: diff --git a/hotspot/src/share/vm/services/diagnosticCommand.cpp b/hotspot/src/share/vm/services/diagnosticCommand.cpp index ca031f87963..892e2ce57b6 100644 --- a/hotspot/src/share/vm/services/diagnosticCommand.cpp +++ b/hotspot/src/share/vm/services/diagnosticCommand.cpp @@ -23,6 +23,7 @@ */ #include "precompiled.hpp" +#include "classfile/classLoaderStats.hpp" #include "gc_implementation/shared/vmGCOperations.hpp" #include "runtime/javaCalls.hpp" #include "runtime/os.hpp" @@ -58,6 +59,7 @@ void DCmdRegistrant::register_dcmds(){ #endif // INCLUDE_SERVICES DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(full_export, true, false)); DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(full_export, true, false)); + DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(full_export, true, false)); // Enhanced JMX Agent Support // These commands won't be exported via the DiagnosticCommandMBean until an diff --git a/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java b/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java new file mode 100644 index 00000000000..0b229a8a9a1 --- /dev/null +++ b/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * + * @build ClassLoaderStatsTest DcmdUtil + * @run main ClassLoaderStatsTest + */ + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.StringReader; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ClassLoaderStatsTest { + + // ClassLoader Parent CLD* Classes ChunkSz BlockSz Type + // 0x00000007c0215928 0x0000000000000000 0x0000000000000000 0 0 0 org.eclipse.osgi.baseadaptor.BaseAdaptor$1 + // 0x00000007c0009868 0x0000000000000000 0x00007fc52aebcc80 1 6144 3768 sun.reflect.DelegatingClassLoader + // 0x00000007c0009868 0x0000000000000000 0x00007fc52b8916d0 1 6144 3688 sun.reflect.DelegatingClassLoader + // 0x00000007c0009868 0x00000007c0038ba8 0x00007fc52afb8760 1 6144 3688 sun.reflect.DelegatingClassLoader + // 0x00000007c0009868 0x0000000000000000 0x00007fc52afbb1a0 1 6144 3688 sun.reflect.DelegatingClassLoader + // 0x0000000000000000 0x0000000000000000 0x00007fc523416070 5019 30060544 29956216 + // 455 1210368 672848 + unsafe anonymous classes + // 0x00000007c016b5c8 0x00000007c0038ba8 0x00007fc52a995000 5 8192 5864 org.netbeans.StandardModule$OneModuleClassLoader + // 0x00000007c0009868 0x00000007c016b5c8 0x00007fc52ac13640 1 6144 3896 sun.reflect.DelegatingClassLoader + // ... + + static Pattern clLine = Pattern.compile("0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*(.*)"); + static Pattern anonLine = Pattern.compile("\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*.*"); + + public static DummyClassLoader dummyloader; + + public static void main(String arg[]) throws Exception { + + // create a classloader and load our special class + dummyloader = new DummyClassLoader(); + Class c = Class.forName("TestClass", true, dummyloader); + if (c.getClassLoader() != dummyloader) { + throw new RuntimeException("TestClass defined by wrong classloader: " + c.getClassLoader()); + } + + String result = DcmdUtil.executeDcmd("VM.classloader_stats"); + BufferedReader r = new BufferedReader(new StringReader(result)); + String line; + while((line = r.readLine()) != null) { + Matcher m = clLine.matcher(line); + if (m.matches()) { + // verify that DummyClassLoader has loaded 1 class and 1 anonymous class + if (m.group(4).equals("ClassLoaderStatsTest$DummyClassLoader")) { + System.out.println("line: " + line); + if (!m.group(1).equals("1")) { + throw new Exception("Should have loaded 1 class: " + line); + } + checkPositiveInt(m.group(2)); + checkPositiveInt(m.group(3)); + + String next = r.readLine(); + System.out.println("next: " + next); + Matcher m1 = anonLine.matcher(next); + m1.matches(); + if (!m1.group(1).equals("1")) { + throw new Exception("Should have loaded 1 anonymous class, but found : " + m1.group(1)); + } + checkPositiveInt(m1.group(2)); + checkPositiveInt(m1.group(3)); + } + } + } + } + + private static void checkPositiveInt(String s) throws Exception { + if (Integer.parseInt(s) <= 0) { + throw new Exception("Value should have been > 0: " + s); + } + } + + public static class DummyClassLoader extends ClassLoader { + + public static final String CLASS_NAME = "TestClass"; + + static ByteBuffer readClassFile(String name) + { + File f = new File(System.getProperty("test.classes", "."), + name); + try (FileInputStream fin = new FileInputStream(f); + FileChannel fc = fin.getChannel()) + { + return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); + } catch (IOException e) { + throw new RuntimeException("Can't open file: " + name, e); + } + } + + protected Class loadClass(String name, boolean resolve) + throws ClassNotFoundException + { + Class c; + if (!"TestClass".equals(name)) { + c = super.loadClass(name, resolve); + } else { + // should not delegate to the system class loader + c = findClass(name); + if (resolve) { + resolveClass(c); + } + } + return c; + } + + protected Class findClass(String name) + throws ClassNotFoundException + { + if (!"TestClass".equals(name)) { + throw new ClassNotFoundException("Unexpected class: " + name); + } + return defineClass(name, readClassFile(name + ".class"), null); + } + } /* DummyClassLoader */ + +} + +class TestClass { + static { + // force creation of anonymous class (for the lambdaform) + Runnable r = () -> System.out.println("Hello"); + r.run(); + } +} From 61a1a26d7a6064c3b4ba7a00536786c2e9b225ea Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 4 Jun 2014 16:55:06 +0400 Subject: [PATCH 042/192] 8041129: [OGL] surface->sw blit is extremely slow 8017626: [OGL] Translucent VolatileImages don't paint correctly Reviewed-by: bae, flar --- .../sun/java2d/opengl/OGLBlitLoops.java | 12 +- .../native/sun/java2d/opengl/OGLBlitLoops.c | 80 +++++++-- .../DrawImage/IncorrectAlphaSurface2SW.java | 161 +++++++++++++++++ .../DrawImage/IncorrectDestinationOffset.java | 164 ++++++++++++++++++ .../DrawImage/IncorrectSourceOffset.java | 100 +++++++++++ 5 files changed, 495 insertions(+), 22 deletions(-) create mode 100644 jdk/test/java/awt/image/DrawImage/IncorrectAlphaSurface2SW.java create mode 100644 jdk/test/java/awt/image/DrawImage/IncorrectDestinationOffset.java create mode 100644 jdk/test/java/awt/image/DrawImage/IncorrectSourceOffset.java diff --git a/jdk/src/share/classes/sun/java2d/opengl/OGLBlitLoops.java b/jdk/src/share/classes/sun/java2d/opengl/OGLBlitLoops.java index 64459c1145e..aeab20823bb 100644 --- a/jdk/src/share/classes/sun/java2d/opengl/OGLBlitLoops.java +++ b/jdk/src/share/classes/sun/java2d/opengl/OGLBlitLoops.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,6 +71,8 @@ class OGLBlitLoops { // surface->sw ops new OGLSurfaceToSwBlit(SurfaceType.IntArgb, OGLSurfaceData.PF_INT_ARGB), + new OGLSurfaceToSwBlit(SurfaceType.IntArgbPre, + OGLSurfaceData.PF_INT_ARGB_PRE), // sw->surface ops blitIntArgbPreToSurface, @@ -505,12 +507,12 @@ class OGLRTTSurfaceToSurfaceTransform extends TransformBlit { } } -class OGLSurfaceToSwBlit extends Blit { +final class OGLSurfaceToSwBlit extends Blit { - private int typeval; + private final int typeval; - // REMIND: destination will actually be opaque/premultiplied... - OGLSurfaceToSwBlit(SurfaceType dstType, int typeval) { + // destination will actually be ArgbPre or Argb + OGLSurfaceToSwBlit(final SurfaceType dstType,final int typeval) { super(OGLSurfaceData.OpenGLSurface, CompositeType.SrcNoEa, dstType); diff --git a/jdk/src/share/native/sun/java2d/opengl/OGLBlitLoops.c b/jdk/src/share/native/sun/java2d/opengl/OGLBlitLoops.c index 828298672e8..fa9a2fe34a5 100644 --- a/jdk/src/share/native/sun/java2d/opengl/OGLBlitLoops.c +++ b/jdk/src/share/native/sun/java2d/opengl/OGLBlitLoops.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,10 @@ #include "OGLSurfaceData.h" #include "GraphicsPrimitiveMgr.h" +#include // malloc +#include // memcpy +#include "IntArgbPre.h" + extern OGLPixelFormat PixelFormats[]; /** @@ -335,6 +339,9 @@ OGLBlitToSurfaceViaTexture(OGLContext *oglc, SurfaceDataRasInfo *srcInfo, 0, 0, sw, sh, pf->format, pf->type, srcInfo->rasBase); + + j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); + j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); } // the texture image is "right side up", so we align the @@ -696,6 +703,50 @@ OGLBlitLoops_Blit(JNIEnv *env, SurfaceData_InvokeUnlock(env, srcOps, &srcInfo); } +/** + * This method makes vertical flip of the provided area of Surface and convert + * pixel's data from argbPre to argb format if requested. + */ +void flip(void *pDst, juint w, juint h, jint scanStride, jboolean convert) { + const size_t clippedStride = 4 * w; + void *tempRow = (h > 1 && !convert) ? malloc(clippedStride) : NULL; + juint i = 0; + juint step = 0; + // vertical flip and convert argbpre to argb if necessary + for (; i < h / 2; ++i) { + juint *r1 = PtrAddBytes(pDst, (i * scanStride)); + juint *r2 = PtrAddBytes(pDst, (h - i - 1) * scanStride); + if (tempRow) { + // fast path + memcpy(tempRow, r1, clippedStride); + memcpy(r1, r2, clippedStride); + memcpy(r2, tempRow, clippedStride); + } else { + // slow path + for (step = 0; step < w; ++step) { + juint tmp = r1[step]; + if (convert) { + LoadIntArgbPreTo1IntArgb(r2, 0, step, r1[step]); + LoadIntArgbPreTo1IntArgb(&tmp, 0, 0, r2[step]); + } else { + r1[step] = r2[step]; + r2[step] = tmp; + } + } + } + } + // convert the middle line if necessary + if (convert && h % 2) { + juint *r1 = PtrAddBytes(pDst, (i * scanStride)); + for (step = 0; step < w; ++step) { + LoadIntArgbPreTo1IntArgb(r1, 0, step, r1[step]); + } + } + if (tempRow) { + free(tempRow); + } +} + /** * Specialized blit method for copying a native OpenGL "Surface" (pbuffer, * window, etc.) to a system memory ("Sw") surface. @@ -758,7 +809,9 @@ OGLBlitLoops_SurfaceToSwBlit(JNIEnv *env, OGLContext *oglc, width = srcInfo.bounds.x2 - srcInfo.bounds.x1; height = srcInfo.bounds.y2 - srcInfo.bounds.y1; - j2d_glPixelStorei(GL_PACK_SKIP_PIXELS, dstx); + pDst = PtrAddBytes(pDst, dstx * dstInfo.pixelStride); + pDst = PtrAddBytes(pDst, dsty * dstInfo.scanStride); + j2d_glPixelStorei(GL_PACK_ROW_LENGTH, dstInfo.scanStride / dstInfo.pixelStride); j2d_glPixelStorei(GL_PACK_ALIGNMENT, pf.alignment); @@ -779,27 +832,20 @@ OGLBlitLoops_SurfaceToSwBlit(JNIEnv *env, OGLContext *oglc, // this accounts for lower-left origin of the source region srcx = srcOps->xOffset + srcx; - srcy = srcOps->yOffset + srcOps->height - (srcy + 1); - - // we must read one scanline at a time because there is no way - // to read starting at the top-left corner of the source region - while (height > 0) { - j2d_glPixelStorei(GL_PACK_SKIP_ROWS, dsty); - j2d_glReadPixels(srcx, srcy, width, 1, - pf.format, pf.type, pDst); - srcy--; - dsty++; - height--; - } + srcy = srcOps->yOffset + srcOps->height - srcy - height; + // Note that glReadPixels() is extremely slow! + // So we call it only once and flip the image using memcpy. + j2d_glReadPixels(srcx, srcy, width, height, + pf.format, pf.type, pDst); + // It was checked above that width and height are positive. + flip(pDst, (juint) width, (juint) height, dstInfo.scanStride, + !pf.isPremult && !srcOps->isOpaque); #ifdef MACOSX if (srcOps->isOpaque) { j2d_glPixelTransferf(GL_ALPHA_BIAS, 0.0); } #endif - - j2d_glPixelStorei(GL_PACK_SKIP_PIXELS, 0); - j2d_glPixelStorei(GL_PACK_SKIP_ROWS, 0); j2d_glPixelStorei(GL_PACK_ROW_LENGTH, 0); j2d_glPixelStorei(GL_PACK_ALIGNMENT, 4); } diff --git a/jdk/test/java/awt/image/DrawImage/IncorrectAlphaSurface2SW.java b/jdk/test/java/awt/image/DrawImage/IncorrectAlphaSurface2SW.java new file mode 100644 index 00000000000..e6fb519d7af --- /dev/null +++ b/jdk/test/java/awt/image/DrawImage/IncorrectAlphaSurface2SW.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.awt.image.VolatileImage; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; + +import static java.awt.Transparency.TRANSLUCENT; +import static java.awt.image.BufferedImage.TYPE_4BYTE_ABGR; +import static java.awt.image.BufferedImage.TYPE_4BYTE_ABGR_PRE; +import static java.awt.image.BufferedImage.TYPE_INT_ARGB; +import static java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE; + +/** + * @test + * @bug 8017626 + * @summary Tests drawing transparent volatile image to transparent BI. + * Results of the blit compatibleImage to transparent BI used for + * comparison. + * @author Sergey Bylokhov + */ +public final class IncorrectAlphaSurface2SW { + + private static final int[] SCALES = {1, 2, 4, 8}; + private static final int[] SIZES = {1, 2, 3, 127, 128, 254, 255, 256}; + private static final int[] dstTypes = {TYPE_INT_ARGB, TYPE_INT_ARGB_PRE, + TYPE_4BYTE_ABGR, TYPE_4BYTE_ABGR_PRE}; + private static final int[] srcTypes = {TRANSLUCENT}; + + + public static void main(final String[] args) throws IOException { + GraphicsEnvironment ge = GraphicsEnvironment + .getLocalGraphicsEnvironment(); + GraphicsConfiguration gc = ge.getDefaultScreenDevice() + .getDefaultConfiguration(); + BufferedImage destVI; + BufferedImage destBI; + BufferedImage sourceBI; + VolatileImage sourceVI; + + for (final int s : SIZES) { + for (final int srcType : srcTypes) { + for (final int dstType : dstTypes) { + for (final int scale : SCALES) { + int sw = s * scale; + destVI = new BufferedImage(sw, sw, dstType); + destBI = new BufferedImage(sw, sw, dstType); + sourceBI = gc.createCompatibleImage(sw, sw, srcType); + sourceVI = gc.createCompatibleVolatileImage(s, s, srcType); + + // draw to dest BI using compatible image + fill(sourceBI, s); + Graphics2D big = destBI.createGraphics(); + big.setComposite(AlphaComposite.Src); + big.drawImage(sourceBI, 0, 0, sw, sw, null); + big.dispose(); + + // draw to dest BI using compatible image + fill(sourceVI, s); + drawVItoBI(gc, destVI, sourceVI); + + validate(destVI, destBI); + sourceVI.flush(); + } + } + } + } + System.out.println("Test PASSED"); + } + + private static void drawVItoBI(GraphicsConfiguration gc, + BufferedImage bi, VolatileImage vi) { + while (true) { + vi.validate(gc); + fill(vi, vi.getHeight()); + if (vi.validate(gc) != VolatileImage.IMAGE_OK) { + try { + Thread.sleep(100); + } catch (final InterruptedException ignored) { + } + continue; + } + + Graphics2D big = bi.createGraphics(); + big.setComposite(AlphaComposite.Src); + big.drawImage(vi, 0, 0, bi.getWidth(), bi.getHeight(), null); + big.dispose(); + + if (vi.contentsLost()) { + try { + Thread.sleep(100); + } catch (final InterruptedException ignored) { + } + continue; + } + break; + } + } + + private static void validate(BufferedImage bi, BufferedImage gold) + throws IOException { + for (int x = 0; x < bi.getWidth(); ++x) { + for (int y = 0; y < bi.getHeight(); ++y) { + if (gold.getRGB(x, y) != bi.getRGB(x, y)) { + System.err.println("Expected color = " + gold.getRGB(x, y)); + System.err.println("Actual color = " + bi.getRGB(x, y)); + ImageIO.write(gold, "png", new File("gold.png")); + ImageIO.write(bi, "png", new File("bi.png")); + throw new RuntimeException("Test failed."); + } + } + } + } + + /** + * Fills the whole image using different alpha for each row. + * + * @param image to fill + */ + private static void fill(final Image image, final int size) { + Graphics2D graphics = (Graphics2D) image.getGraphics(); + graphics.setComposite(AlphaComposite.Src); + graphics.setColor(Color.GREEN); + graphics.fillRect(0, 0, image.getWidth(null), image.getHeight(null)); + int row = image.getHeight(null) / size; + for (int i = 0; i < size; ++i) { + graphics.setColor(new Color(23, 127, 189, i)); + graphics.fillRect(0, i * row, image.getWidth(null), row); + } + graphics.dispose(); + } +} diff --git a/jdk/test/java/awt/image/DrawImage/IncorrectDestinationOffset.java b/jdk/test/java/awt/image/DrawImage/IncorrectDestinationOffset.java new file mode 100644 index 00000000000..66fafdf5756 --- /dev/null +++ b/jdk/test/java/awt/image/DrawImage/IncorrectDestinationOffset.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.image.BufferedImage; +import java.awt.image.VolatileImage; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; + +/** + * @test + * @bug 8041129 + * @summary Destination offset should be correct in case of Surface->SW blit. + * Destination outside of the drawing area should be untouched. + * @author Sergey Bylokhov + */ +public final class IncorrectDestinationOffset { + + private static final int SIZE = 128; + private static final double[] SCALES = {0.25, 0.5, 1, 1.5, 2.0, 4}; + + public static void main(final String[] args) throws IOException { + GraphicsEnvironment ge = GraphicsEnvironment + .getLocalGraphicsEnvironment(); + GraphicsConfiguration gc = ge.getDefaultScreenDevice() + .getDefaultConfiguration(); + VolatileImage vi = gc.createCompatibleVolatileImage(SIZE, SIZE); + BufferedImage bi = new BufferedImage(SIZE, SIZE, + BufferedImage.TYPE_INT_ARGB); + for (double scale : SCALES) { + while (true) { + // initialize Volatile Image + vi.validate(gc); + Graphics2D g2d = vi.createGraphics(); + g2d.setColor(Color.green); + g2d.fillRect(0, 0, SIZE, SIZE); + g2d.dispose(); + + if (vi.validate(gc) != VolatileImage.IMAGE_OK) { + try { + Thread.sleep(100); + } catch (InterruptedException ignored) { + } + continue; + } + // Draw the VolatileImage to BI with scale and offsets + Graphics2D g = bi.createGraphics(); + g.setComposite(AlphaComposite.Src); + g.setColor(Color.RED); + g.fillRect(0, 0, SIZE / 2, SIZE / 2); + g.setColor(Color.BLUE); + g.fillRect(SIZE / 2, 0, SIZE / 2, SIZE / 2); + g.setColor(Color.ORANGE); + g.fillRect(0, SIZE / 2, SIZE / 2, SIZE / 2); + g.setColor(Color.MAGENTA); + g.fillRect(SIZE / 2, SIZE / 2, SIZE / 2, SIZE / 2); + + int point2draw = (int) (100 * scale); + int size2draw = (int) (SIZE * scale); + g.drawImage(vi, point2draw, point2draw, size2draw, size2draw, + null); + g.dispose(); + + if (vi.contentsLost()) { + try { + Thread.sleep(100); + } catch (InterruptedException ignored) { + } + continue; + } + validate(bi, point2draw, size2draw); + break; + } + } + } + + private static void validate(BufferedImage bi, int point2draw, + int size2draw) + throws IOException { + for (int x = 0; x < SIZE; ++x) { + for (int y = 0; y < SIZE; ++y) { + if (isInsideGreenArea(point2draw, size2draw, x, y)) { + if (bi.getRGB(x, y) != Color.green.getRGB()) { + ImageIO.write(bi, "png", new File("image.png")); + throw new RuntimeException("Test failed."); + } + } else { + if (isRedArea(x, y)) { + if (bi.getRGB(x, y) != Color.red.getRGB()) { + ImageIO.write(bi, "png", new File("image.png")); + throw new RuntimeException("Test failed."); + } + } + if (isBlueArea(x, y)) { + if (bi.getRGB(x, y) != Color.blue.getRGB()) { + ImageIO.write(bi, "png", new File("image.png")); + throw new RuntimeException("Test failed."); + } + } + if (isOrangeArea(x, y)) { + if (bi.getRGB(x, y) != Color.orange.getRGB()) { + ImageIO.write(bi, "png", new File("image.png")); + throw new RuntimeException("Test failed."); + } + } + if (isMagentaArea(x, y)) { + if (bi.getRGB(x, y) != Color.magenta.getRGB()) { + ImageIO.write(bi, "png", new File("image.png")); + throw new RuntimeException("Test failed."); + } + } + } + } + } + } + + private static boolean isRedArea(int x, int y) { + return x < SIZE / 2 && y < SIZE / 2; + } + + private static boolean isBlueArea(int x, int y) { + return x >= SIZE / 2 && y < SIZE / 2; + } + + private static boolean isOrangeArea(int x, int y) { + return x < SIZE / 2 && y >= SIZE / 2; + } + + private static boolean isMagentaArea(int x, int y) { + return x >= SIZE / 2 && y >= SIZE / 2; + } + + private static boolean isInsideGreenArea(int point2draw, int size2draw, + int x, int y) { + return x >= point2draw && x < point2draw + size2draw && y >= + point2draw && y < point2draw + size2draw; + } +} diff --git a/jdk/test/java/awt/image/DrawImage/IncorrectSourceOffset.java b/jdk/test/java/awt/image/DrawImage/IncorrectSourceOffset.java new file mode 100644 index 00000000000..5dd4f490b64 --- /dev/null +++ b/jdk/test/java/awt/image/DrawImage/IncorrectSourceOffset.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.awt.image.VolatileImage; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; + +/** + * @test + * @bug 8041129 + * @summary Tests asymmetric source offsets. + * @author Sergey Bylokhov + */ +public final class IncorrectSourceOffset { + + public static void main(final String[] args) throws IOException { + GraphicsEnvironment ge = GraphicsEnvironment + .getLocalGraphicsEnvironment(); + GraphicsConfiguration gc = ge.getDefaultScreenDevice() + .getDefaultConfiguration(); + VolatileImage vi = gc.createCompatibleVolatileImage(511, 255); + BufferedImage bi = new BufferedImage(511, 255, + BufferedImage.TYPE_INT_ARGB); + BufferedImage gold = new BufferedImage(511, 255, + BufferedImage.TYPE_INT_ARGB); + fill(gold); + while (true) { + vi.validate(gc); + fill(vi); + if (vi.validate(gc) != VolatileImage.IMAGE_OK) { + try { + Thread.sleep(100); + } catch (final InterruptedException ignored) { + } + continue; + } + + Graphics2D big = bi.createGraphics(); + big.drawImage(vi, 7, 11, 127, 111, 7, 11, 127, 111, null); + big.dispose(); + if (vi.contentsLost()) { + try { + Thread.sleep(100); + } catch (final InterruptedException ignored) { + } + continue; + } + break; + } + + for (int x = 7; x < 127; ++x) { + for (int y = 11; y < 111; ++y) { + if (gold.getRGB(x, y) != bi.getRGB(x, y)) { + ImageIO.write(gold, "png", new File("gold.png")); + ImageIO.write(bi, "png", new File("bi.png")); + throw new RuntimeException("Test failed."); + } + } + } + } + + private static void fill(Image image) { + Graphics2D graphics = (Graphics2D) image.getGraphics(); + graphics.setComposite(AlphaComposite.Src); + for (int i = 0; i < image.getHeight(null); ++i) { + graphics.setColor(new Color(i, 0, 0)); + graphics.fillRect(0, i, image.getWidth(null), 1); + } + graphics.dispose(); + } +} From e31033ff1a8ff0053bb5dfa7f121539e7ef8df72 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 4 Jun 2014 17:14:56 +0400 Subject: [PATCH 043/192] 8043979: Javadoc cleanup of javax.sound.sampled package Reviewed-by: pchelko, azvegint --- .../javax/sound/sampled/AudioFileFormat.java | 196 ++- .../javax/sound/sampled/AudioFormat.java | 462 ++++--- .../javax/sound/sampled/AudioInputStream.java | 200 +-- .../javax/sound/sampled/AudioPermission.java | 58 +- .../javax/sound/sampled/AudioSystem.java | 1088 ++++++++--------- .../javax/sound/sampled/BooleanControl.java | 127 +- .../classes/javax/sound/sampled/Clip.java | 240 ++-- .../javax/sound/sampled/CompoundControl.java | 66 +- .../classes/javax/sound/sampled/Control.java | 79 +- .../classes/javax/sound/sampled/DataLine.java | 408 +++---- .../javax/sound/sampled/EnumControl.java | 130 +- .../javax/sound/sampled/FloatControl.java | 382 +++--- .../classes/javax/sound/sampled/Line.java | 311 +++-- .../javax/sound/sampled/LineEvent.java | 148 +-- .../javax/sound/sampled/LineListener.java | 41 +- .../sampled/LineUnavailableException.java | 31 +- .../classes/javax/sound/sampled/Mixer.java | 343 +++--- .../classes/javax/sound/sampled/Port.java | 104 +- .../javax/sound/sampled/ReverbType.java | 168 ++- .../javax/sound/sampled/SourceDataLine.java | 197 ++- .../javax/sound/sampled/TargetDataLine.java | 170 ++- .../UnsupportedAudioFileException.java | 21 +- .../sound/sampled/spi/AudioFileReader.java | 2 +- .../sampled/spi/FormatConversionProvider.java | 8 +- 24 files changed, 2319 insertions(+), 2661 deletions(-) diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java b/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java index 63f43dcc160..31a279d56ee 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java @@ -25,36 +25,29 @@ package javax.sound.sampled; -import java.io.File; -import java.io.OutputStream; -import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; - /** - * An instance of the AudioFileFormat class describes - * an audio file, including the file type, the file's length in bytes, - * the length in sample frames of the audio data contained in the file, - * and the format of the audio data. + * An instance of the {@code AudioFileFormat} class describes an audio file, + * including the file type, the file's length in bytes, the length in sample + * frames of the audio data contained in the file, and the format of the audio + * data. *

- * The {@link AudioSystem} class includes methods for determining the format - * of an audio file, obtaining an audio input stream from an audio file, and + * The {@link AudioSystem} class includes methods for determining the format of + * an audio file, obtaining an audio input stream from an audio file, and * writing an audio file from an audio input stream. - * - *

An AudioFileFormat object can - * include a set of properties. A property is a pair of key and value: - * the key is of type String, the associated property - * value is an arbitrary object. - * Properties specify additional informational - * meta data (like a author, copyright, or file duration). - * Properties are optional information, and file reader and file - * writer implementations are not required to provide or - * recognize properties. - * - *

The following table lists some common properties that should - * be used in implementations: + *

+ * An {@code AudioFileFormat} object can include a set of properties. A property + * is a pair of key and value: the key is of type {@code String}, the associated + * property value is an arbitrary object. Properties specify additional + * informational meta data (like a author, copyright, or file duration). + * Properties are optional information, and file reader and file writer + * implementations are not required to provide or recognize properties. + *

+ * The following table lists some common properties that should be used in + * implementations: * * * @@ -104,17 +97,13 @@ import java.util.Map; */ public class AudioFileFormat { - - // INSTANCE VARIABLES - - /** * File type. */ private Type type; /** - * File length in bytes + * File length in bytes. */ private int byteLength; @@ -124,25 +113,26 @@ public class AudioFileFormat { private AudioFormat format; /** - * Audio data length in sample frames + * Audio data length in sample frames. */ private int frameLength; - - /** The set of properties */ + /** + * The set of properties. + */ private HashMap properties; - /** - * Constructs an audio file format object. - * This protected constructor is intended for use by providers of file-reading - * services when returning information about an audio file or about supported audio file - * formats. - * @param type the type of the audio file - * @param byteLength the length of the file in bytes, or AudioSystem.NOT_SPECIFIED - * @param format the format of the audio data contained in the file - * @param frameLength the audio data length in sample frames, or AudioSystem.NOT_SPECIFIED + * Constructs an audio file format object. This protected constructor is + * intended for use by providers of file-reading services when returning + * information about an audio file or about supported audio file formats. * + * @param type the type of the audio file + * @param byteLength the length of the file in bytes, or + * {@code AudioSystem.NOT_SPECIFIED} + * @param format the format of the audio data contained in the file + * @param frameLength the audio data length in sample frames, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getType */ protected AudioFileFormat(Type type, int byteLength, AudioFormat format, int frameLength) { @@ -154,14 +144,15 @@ public class AudioFileFormat { this.properties = null; } - /** - * Constructs an audio file format object. - * This public constructor may be used by applications to describe the - * properties of a requested audio file. - * @param type the type of the audio file - * @param format the format of the audio data contained in the file - * @param frameLength the audio data length in sample frames, or AudioSystem.NOT_SPECIFIED + * Constructs an audio file format object. This public constructor may be + * used by applications to describe the properties of a requested audio + * file. + * + * @param type the type of the audio file + * @param format the format of the audio data contained in the file + * @param frameLength the audio data length in sample frames, or + * {@code AudioSystem.NOT_SPECIFIED} */ public AudioFileFormat(Type type, AudioFormat format, int frameLength) { @@ -170,19 +161,16 @@ public class AudioFileFormat { } /** - * Construct an audio file format object with a set of - * defined properties. + * Construct an audio file format object with a set of defined properties. * This public constructor may be used by applications to describe the - * properties of a requested audio file. The properties map - * will be copied to prevent any changes to it. - * - * @param type the type of the audio file - * @param format the format of the audio data contained in the file - * @param frameLength the audio data length in sample frames, or - * AudioSystem.NOT_SPECIFIED - * @param properties a Map<String,Object> object - * with properties + * properties of a requested audio file. The properties map will be copied + * to prevent any changes to it. * + * @param type the type of the audio file + * @param format the format of the audio data contained in the file + * @param frameLength the audio data length in sample frames, or + * {@code AudioSystem.NOT_SPECIFIED} + * @param properties a {@code Map} object with properties * @since 1.5 */ public AudioFileFormat(Type type, AudioFormat format, @@ -191,11 +179,10 @@ public class AudioFileFormat { this.properties = new HashMap(properties); } - /** - * Obtains the audio file type, such as WAVE or AU. - * @return the audio file type + * Obtains the audio file type, such as {@code WAVE} or {@code AU}. * + * @return the audio file type * @see Type#WAVE * @see Type#AU * @see Type#AIFF @@ -207,7 +194,9 @@ public class AudioFileFormat { } /** - * Obtains the size in bytes of the entire audio file (not just its audio data). + * Obtains the size in bytes of the entire audio file (not just its audio + * data). + * * @return the audio file length in bytes * @see AudioSystem#NOT_SPECIFIED */ @@ -217,6 +206,7 @@ public class AudioFileFormat { /** * Obtains the format of the audio data contained in the audio file. + * * @return the audio data format */ public AudioFormat getFormat() { @@ -224,7 +214,9 @@ public class AudioFileFormat { } /** - * Obtains the length of the audio data contained in the file, expressed in sample frames. + * Obtains the length of the audio data contained in the file, expressed in + * sample frames. + * * @return the number of sample frames of audio data in the file * @see AudioSystem#NOT_SPECIFIED */ @@ -233,18 +225,15 @@ public class AudioFileFormat { } /** - * Obtain an unmodifiable map of properties. - * The concept of properties is further explained in - * the {@link AudioFileFormat class description}. - * - * @return a Map<String,Object> object containing - * all properties. If no properties are recognized, an empty map is - * returned. + * Obtain an unmodifiable map of properties. The concept of properties is + * further explained in the {@link AudioFileFormat class description}. * + * @return a {@code Map} object containing all properties. + * If no properties are recognized, an empty map is returned. * @see #getProperty(String) * @since 1.5 */ - public Map properties() { + public Map properties() { Map ret; if (properties == null) { ret = new HashMap(0); @@ -254,20 +243,16 @@ public class AudioFileFormat { return Collections.unmodifiableMap(ret); } - /** - * Obtain the property value specified by the key. - * The concept of properties is further explained in - * the {@link AudioFileFormat class description}. - * - *

If the specified property is not defined for a - * particular file format, this method returns - * null. - * - * @param key the key of the desired property - * @return the value of the property with the specified key, - * or null if the property does not exist. + * Obtain the property value specified by the key. The concept of properties + * is further explained in the {@link AudioFileFormat class description}. + *

+ * If the specified property is not defined for a particular file format, + * this method returns {@code null}. * + * @param key the key of the desired property + * @return the value of the property with the specified key, or {@code null} + * if the property does not exist * @see #properties() * @since 1.5 */ @@ -278,11 +263,12 @@ public class AudioFileFormat { return properties.get(key); } - /** * Provides a string representation of the file format. + * * @return the file format as a string */ + @Override public String toString() { StringBuffer buf = new StringBuffer(); @@ -307,11 +293,9 @@ public class AudioFileFormat { return new String(buf); } - /** - * An instance of the Type class represents one of the - * standard types of audio file. Static instances are provided for the - * common types. + * An instance of the {@code Type} class represents one of the standard + * types of audio file. Static instances are provided for the common types. */ public static class Type { @@ -342,9 +326,6 @@ public class AudioFileFormat { */ public static final Type SND = new Type("SND", "snd"); - - // INSTANCE VARIABLES - /** * File type name. */ @@ -355,27 +336,22 @@ public class AudioFileFormat { */ private final String extension; - - // CONSTRUCTOR - /** * Constructs a file type. - * @param name the string that names the file type - * @param extension the string that commonly marks the file type - * without leading dot. + * + * @param name the string that names the file type + * @param extension the string that commonly marks the file type + * without leading dot */ public Type(String name, String extension) { - this.name = name; this.extension = extension; } - - // METHODS - /** - * Finalizes the equals method + * Finalizes the equals method. */ + @Override public final boolean equals(Object obj) { if (toString() == null) { return (obj != null) && (obj.toString() == null); @@ -387,8 +363,9 @@ public class AudioFileFormat { } /** - * Finalizes the hashCode method + * Finalizes the hashCode method. */ + @Override public final int hashCode() { if (toString() == null) { return 0; @@ -397,22 +374,23 @@ public class AudioFileFormat { } /** - * Provides the file type's name as the String representation - * of the file type. + * Provides the file type's name as the {@code String} representation of + * the file type. + * * @return the file type's name */ + @Override public final String toString() { return name; } /** * Obtains the common file name extension for this file type. + * * @return file type extension */ public String getExtension() { return extension; } - - } // class Type - -} // class AudioFileFormat + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java b/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java index cd084fcd32d..9ea70f975f1 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java @@ -30,59 +30,63 @@ import java.util.HashMap; import java.util.Map; /** - * AudioFormat is the class that specifies a particular arrangement of data in a sound stream. - * By examining the information stored in the audio format, you can discover how to interpret the bits in the - * binary sound data. + * {@code AudioFormat} is the class that specifies a particular arrangement of + * data in a sound stream. By examining the information stored in the audio + * format, you can discover how to interpret the bits in the binary sound data. *

- * Every data line has an audio format associated with its data stream. The audio format of a source (playback) data line indicates - * what kind of data the data line expects to receive for output. For a target (capture) data line, the audio format specifies the kind - * of the data that can be read from the line. - * Sound files also have audio formats, of course. The {@link AudioFileFormat} - * class encapsulates an AudioFormat in addition to other, - * file-specific information. Similarly, an {@link AudioInputStream} has an - * AudioFormat. + * Every data line has an audio format associated with its data stream. The + * audio format of a source (playback) data line indicates what kind of data the + * data line expects to receive for output. For a target (capture) data line, + * the audio format specifies the kind of the data that can be read from the + * line. + * Sound files also have audio formats, of course. The {@link AudioFileFormat} + * class encapsulates an {@code AudioFormat} in addition to other, file-specific + * information. Similarly, an {@link AudioInputStream} has an + * {@code AudioFormat}. *

- * The AudioFormat class accommodates a number of common sound-file encoding techniques, including - * pulse-code modulation (PCM), mu-law encoding, and a-law encoding. These encoding techniques are predefined, - * but service providers can create new encoding types. - * The encoding that a specific format uses is named by its encoding field. - *

- * In addition to the encoding, the audio format includes other properties that further specify the exact - * arrangement of the data. - * These include the number of channels, sample rate, sample size, byte order, frame rate, and frame size. - * Sounds may have different numbers of audio channels: one for mono, two for stereo. - * The sample rate measures how many "snapshots" (samples) of the sound pressure are taken per second, per channel. - * (If the sound is stereo rather than mono, two samples are actually measured at each instant of time: one for the left channel, - * and another for the right channel; however, the sample rate still measures the number per channel, so the rate is the same - * regardless of the number of channels. This is the standard use of the term.) - * The sample size indicates how many bits are used to store each snapshot; 8 and 16 are typical values. - * For 16-bit samples (or any other sample size larger than a byte), - * byte order is important; the bytes in each sample are arranged in - * either the "little-endian" or "big-endian" style. - * For encodings like PCM, a frame consists of the set of samples for all channels at a given - * point in time, and so the size of a frame (in bytes) is always equal to the size of a sample (in bytes) times - * the number of channels. However, with some other sorts of encodings a frame can contain - * a bundle of compressed data for a whole series of samples, as well as additional, non-sample - * data. For such encodings, the sample rate and sample size refer to the data after it is decoded into PCM, - * and so they are completely different from the frame rate and frame size. - * - *

An AudioFormat object can include a set of - * properties. A property is a pair of key and value: the key - * is of type String, the associated property - * value is an arbitrary object. Properties specify - * additional format specifications, like the bit rate for - * compressed formats. Properties are mainly used as a means - * to transport additional information of the audio format - * to and from the service providers. Therefore, properties - * are ignored in the {@link #matches(AudioFormat)} method. - * However, methods which rely on the installed service - * providers, like {@link AudioSystem#isConversionSupported - * (AudioFormat, AudioFormat) isConversionSupported} may consider - * properties, depending on the respective service provider - * implementation. - * - *

The following table lists some common properties which - * service providers should use, if applicable: + * The {@code AudioFormat} class accommodates a number of common sound-file + * encoding techniques, including pulse-code modulation (PCM), mu-law encoding, + * and a-law encoding. These encoding techniques are predefined, but service + * providers can create new encoding types. The encoding that a specific format + * uses is named by its {@code encoding} field. + *

+ * In addition to the encoding, the audio format includes other properties that + * further specify the exact arrangement of the data. These include the number + * of channels, sample rate, sample size, byte order, frame rate, and frame + * size. Sounds may have different numbers of audio channels: one for mono, two + * for stereo. The sample rate measures how many "snapshots" (samples) of the + * sound pressure are taken per second, per channel. (If the sound is stereo + * rather than mono, two samples are actually measured at each instant of time: + * one for the left channel, and another for the right channel; however, the + * sample rate still measures the number per channel, so the rate is the same + * regardless of the number of channels. This is the standard use of the term.) + * The sample size indicates how many bits are used to store each snapshot; 8 + * and 16 are typical values. For 16-bit samples (or any other sample size + * larger than a byte), byte order is important; the bytes in each sample are + * arranged in either the "little-endian" or "big-endian" style. For encodings + * like PCM, a frame consists of the set of samples for all channels at a given + * point in time, and so the size of a frame (in bytes) is always equal to the + * size of a sample (in bytes) times the number of channels. However, with some + * other sorts of encodings a frame can contain a bundle of compressed data for + * a whole series of samples, as well as additional, non-sample data. For such + * encodings, the sample rate and sample size refer to the data after it is + * decoded into PCM, and so they are completely different from the frame rate + * and frame size. + *

+ * An {@code AudioFormat} object can include a set of properties. A property is + * a pair of key and value: the key is of type {@code String}, the associated + * property value is an arbitrary object. Properties specify additional format + * specifications, like the bit rate for compressed formats. Properties are + * mainly used as a means to transport additional information of the audio + * format to and from the service providers. Therefore, properties are ignored + * in the {@link #matches(AudioFormat)} method. However, methods which rely on + * the installed service providers, like + * {@link AudioSystem#isConversionSupported (AudioFormat, AudioFormat) + * isConversionSupported} may consider properties, depending on the respective + * service provider implementation. + *

+ * The following table lists some common properties which service providers + * should use, if applicable: * *

Audio File Format Properties
* @@ -99,7 +103,7 @@ import java.util.Map; * * * - * * * @@ -108,11 +112,10 @@ import java.util.Map; * * *
Audio Format Properties
"vbr"{@link java.lang.Boolean Boolean}true, if the file is encoded in variable bit + * {@code true}, if the file is encoded in variable bit * rate (VBR)
encoding/conversion quality, 1..100
- * - *

Vendors of service providers (plugins) are encouraged - * to seek information about other already established - * properties in third party plugins, and follow the same - * conventions. + *

+ * Vendors of service providers (plugins) are encouraged to seek information + * about other already established properties in third party plugins, and follow + * the same conventions. * * @author Kara Kytle * @author Florian Bomers @@ -124,16 +127,14 @@ import java.util.Map; */ public class AudioFormat { - // INSTANCE VARIABLES - - /** * The audio encoding technique used by this format. */ protected Encoding encoding; /** - * The number of samples played or recorded per second, for sounds that have this format. + * The number of samples played or recorded per second, for sounds that have + * this format. */ protected float sampleRate; @@ -153,34 +154,37 @@ public class AudioFormat { protected int frameSize; /** - * The number of frames played or recorded per second, for sounds that have this format. + * The number of frames played or recorded per second, for sounds that have + * this format. */ protected float frameRate; /** - * Indicates whether the audio data is stored in big-endian or little-endian order. + * Indicates whether the audio data is stored in big-endian or little-endian + * order. */ protected boolean bigEndian; - - /** The set of properties */ + /** + * The set of properties. + */ private HashMap properties; - /** - * Constructs an AudioFormat with the given parameters. - * The encoding specifies the convention used to represent the data. - * The other parameters are further explained in the {@link AudioFormat - * class description}. - * @param encoding the audio encoding technique - * @param sampleRate the number of samples per second - * @param sampleSizeInBits the number of bits in each sample - * @param channels the number of channels (1 for mono, 2 for stereo, and so on) - * @param frameSize the number of bytes in each frame - * @param frameRate the number of frames per second - * @param bigEndian indicates whether the data for a single sample - * is stored in big-endian byte order (false - * means little-endian) + * Constructs an {@code AudioFormat} with the given parameters. The encoding + * specifies the convention used to represent the data. The other parameters + * are further explained in the {@link AudioFormat class description}. + * + * @param encoding the audio encoding technique + * @param sampleRate the number of samples per second + * @param sampleSizeInBits the number of bits in each sample + * @param channels the number of channels (1 for mono, 2 for stereo, + * and so on) + * @param frameSize the number of bytes in each frame + * @param frameRate the number of frames per second + * @param bigEndian indicates whether the data for a single sample is + * stored in big-endian byte order ({@code false} means + * little-endian) */ public AudioFormat(Encoding encoding, float sampleRate, int sampleSizeInBits, int channels, int frameSize, float frameRate, boolean bigEndian) { @@ -195,25 +199,22 @@ public class AudioFormat { this.properties = null; } - /** - * Constructs an AudioFormat with the given parameters. - * The encoding specifies the convention used to represent the data. - * The other parameters are further explained in the {@link AudioFormat - * class description}. - * @param encoding the audio encoding technique - * @param sampleRate the number of samples per second - * @param sampleSizeInBits the number of bits in each sample - * @param channels the number of channels (1 for mono, 2 for - * stereo, and so on) - * @param frameSize the number of bytes in each frame - * @param frameRate the number of frames per second - * @param bigEndian indicates whether the data for a single sample - * is stored in big-endian byte order - * (false means little-endian) - * @param properties a Map<String,Object> object - * containing format properties + * Constructs an {@code AudioFormat} with the given parameters. The encoding + * specifies the convention used to represent the data. The other parameters + * are further explained in the {@link AudioFormat class description}. * + * @param encoding the audio encoding technique + * @param sampleRate the number of samples per second + * @param sampleSizeInBits the number of bits in each sample + * @param channels the number of channels (1 for mono, 2 for stereo, and so + * on) + * @param frameSize the number of bytes in each frame + * @param frameRate the number of frames per second + * @param bigEndian indicates whether the data for a single sample is + * stored in big-endian byte order ({@code false} means little-endian) + * @param properties a {@code Map} object containing format + * properties * @since 1.5 */ public AudioFormat(Encoding encoding, float sampleRate, @@ -225,20 +226,20 @@ public class AudioFormat { this.properties = new HashMap(properties); } - /** - * Constructs an AudioFormat with a linear PCM encoding and - * the given parameters. The frame size is set to the number of bytes - * required to contain one sample from each channel, and the frame rate - * is set to the sample rate. + * Constructs an {@code AudioFormat} with a linear PCM encoding and the + * given parameters. The frame size is set to the number of bytes required + * to contain one sample from each channel, and the frame rate is set to the + * sample rate. * - * @param sampleRate the number of samples per second - * @param sampleSizeInBits the number of bits in each sample - * @param channels the number of channels (1 for mono, 2 for stereo, and so on) - * @param signed indicates whether the data is signed or unsigned - * @param bigEndian indicates whether the data for a single sample - * is stored in big-endian byte order (false - * means little-endian) + * @param sampleRate the number of samples per second + * @param sampleSizeInBits the number of bits in each sample + * @param channels the number of channels (1 for mono, 2 for stereo, and so + * on) + * @param signed indicates whether the data is signed or unsigned + * @param bigEndian indicates whether the data for a single sample is + * stored in big-endian byte order ({@code false} means + * little-endian) */ public AudioFormat(float sampleRate, int sampleSizeInBits, int channels, boolean signed, boolean bigEndian) { @@ -269,19 +270,17 @@ public class AudioFormat { } /** - * Obtains the sample rate. - * For compressed formats, the return value is the sample rate of the uncompressed - * audio data. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a sample rate of - * AudioSystem.NOT_SPECIFIED means that any sample rate is - * acceptable. AudioSystem.NOT_SPECIFIED is also returned when - * the sample rate is not defined for this audio format. - * @return the number of samples per second, - * or AudioSystem.NOT_SPECIFIED + * Obtains the sample rate. For compressed formats, the return value is the + * sample rate of the uncompressed audio data. When this AudioFormat is used + * for queries (e.g. {@link AudioSystem#isConversionSupported(AudioFormat, + * AudioFormat) AudioSystem.isConversionSupported}) or capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a sample rate + * of {@code AudioSystem.NOT_SPECIFIED} means that any sample rate is + * acceptable. {@code AudioSystem.NOT_SPECIFIED} is also returned when the + * sample rate is not defined for this audio format. * + * @return the number of samples per second, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getFrameRate() * @see AudioSystem#NOT_SPECIFIED */ @@ -291,19 +290,18 @@ public class AudioFormat { } /** - * Obtains the size of a sample. - * For compressed formats, the return value is the sample size of the - * uncompressed audio data. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a sample size of - * AudioSystem.NOT_SPECIFIED means that any sample size is - * acceptable. AudioSystem.NOT_SPECIFIED is also returned when - * the sample size is not defined for this audio format. - * @return the number of bits in each sample, - * or AudioSystem.NOT_SPECIFIED + * Obtains the size of a sample. For compressed formats, the return value is + * the sample size of the uncompressed audio data. When this AudioFormat is + * used for queries (e.g. {@link AudioSystem#isConversionSupported( + * AudioFormat,AudioFormat) AudioSystem.isConversionSupported}) or + * capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a sample size + * of {@code AudioSystem.NOT_SPECIFIED} means that any sample size is + * acceptable. {@code AudioSystem.NOT_SPECIFIED} is also returned when the + * sample size is not defined for this audio format. * + * @return the number of bits in each sample, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getFrameSize() * @see AudioSystem#NOT_SPECIFIED */ @@ -313,16 +311,15 @@ public class AudioFormat { } /** - * Obtains the number of channels. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a return value of - * AudioSystem.NOT_SPECIFIED means that any (positive) number of channels is - * acceptable. - * @return The number of channels (1 for mono, 2 for stereo, etc.), - * or AudioSystem.NOT_SPECIFIED + * Obtains the number of channels. When this AudioFormat is used for queries + * (e.g. {@link AudioSystem#isConversionSupported(AudioFormat, AudioFormat) + * AudioSystem.isConversionSupported}) or capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a return + * value of {@code AudioSystem.NOT_SPECIFIED} means that any (positive) + * number of channels is acceptable. * + * @return The number of channels (1 for mono, 2 for stereo, etc.), or + * {@code AudioSystem.NOT_SPECIFIED} * @see AudioSystem#NOT_SPECIFIED */ public int getChannels() { @@ -331,17 +328,16 @@ public class AudioFormat { } /** - * Obtains the frame size in bytes. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a frame size of - * AudioSystem.NOT_SPECIFIED means that any frame size is - * acceptable. AudioSystem.NOT_SPECIFIED is also returned when - * the frame size is not defined for this audio format. - * @return the number of bytes per frame, - * or AudioSystem.NOT_SPECIFIED + * Obtains the frame size in bytes. When this AudioFormat is used for + * queries (e.g. {@link AudioSystem#isConversionSupported(AudioFormat, + * AudioFormat) AudioSystem.isConversionSupported}) or capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a frame size + * of {@code AudioSystem.NOT_SPECIFIED} means that any frame size is + * acceptable. {@code AudioSystem.NOT_SPECIFIED} is also returned when the + * frame size is not defined for this audio format. * + * @return the number of bytes per frame, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getSampleSizeInBits() * @see AudioSystem#NOT_SPECIFIED */ @@ -351,17 +347,17 @@ public class AudioFormat { } /** - * Obtains the frame rate in frames per second. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a frame rate of - * AudioSystem.NOT_SPECIFIED means that any frame rate is - * acceptable. AudioSystem.NOT_SPECIFIED is also returned when - * the frame rate is not defined for this audio format. - * @return the number of frames per second, - * or AudioSystem.NOT_SPECIFIED + * Obtains the frame rate in frames per second. When this AudioFormat is + * used for queries (e.g. {@link AudioSystem#isConversionSupported( + * AudioFormat,AudioFormat) AudioSystem.isConversionSupported}) or + * capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a frame rate + * of {@code AudioSystem.NOT_SPECIFIED} means that any frame rate is + * acceptable. {@code AudioSystem.NOT_SPECIFIED} is also returned when the + * frame rate is not defined for this audio format. * + * @return the number of frames per second, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getSampleRate() * @see AudioSystem#NOT_SPECIFIED */ @@ -370,29 +366,25 @@ public class AudioFormat { return frameRate; } - /** * Indicates whether the audio data is stored in big-endian or little-endian - * byte order. If the sample size is not more than one byte, the return value is - * irrelevant. - * @return true if the data is stored in big-endian byte order, - * false if little-endian + * byte order. If the sample size is not more than one byte, the return + * value is irrelevant. + * + * @return {@code true} if the data is stored in big-endian byte order, + * {@code false} if little-endian */ public boolean isBigEndian() { return bigEndian; } - /** - * Obtain an unmodifiable map of properties. - * The concept of properties is further explained in - * the {@link AudioFileFormat class description}. - * - * @return a Map<String,Object> object containing - * all properties. If no properties are recognized, an empty map is - * returned. + * Obtain an unmodifiable map of properties. The concept of properties is + * further explained in the {@link AudioFileFormat class description}. * + * @return a {@code Map} object containing all properties. + * If no properties are recognized, an empty map is returned. * @see #getProperty(String) * @since 1.5 */ @@ -406,20 +398,16 @@ public class AudioFormat { return Collections.unmodifiableMap(ret); } - /** - * Obtain the property value specified by the key. - * The concept of properties is further explained in - * the {@link AudioFileFormat class description}. - * - *

If the specified property is not defined for a - * particular file format, this method returns - * null. - * - * @param key the key of the desired property - * @return the value of the property with the specified key, - * or null if the property does not exist. + * Obtain the property value specified by the key. The concept of properties + * is further explained in the {@link AudioFileFormat class description}. + *

+ * If the specified property is not defined for a particular file format, + * this method returns {@code null}. * + * @param key the key of the desired property + * @return the value of the property with the specified key, or {@code null} + * if the property does not exist * @see #properties() * @since 1.5 */ @@ -430,21 +418,18 @@ public class AudioFormat { return properties.get(key); } - /** - * Indicates whether this format matches the one specified. - * To match, two formats must have the same encoding, - * and consistent values of the number of channels, sample rate, sample size, - * frame rate, and frame size. - * The values of the property are consistent if they are equal - * or the specified format has the property value - * {@code AudioSystem.NOT_SPECIFIED}. - * The byte order (big-endian or little-endian) must be the same - * if the sample size is greater than one byte. + * Indicates whether this format matches the one specified. To match, two + * formats must have the same encoding, and consistent values of the number + * of channels, sample rate, sample size, frame rate, and frame size. The + * values of the property are consistent if they are equal or the specified + * format has the property value {@code AudioSystem.NOT_SPECIFIED}. The byte + * order (big-endian or little-endian) must be the same if the sample size + * is greater than one byte. * - * @param format format to test for match + * @param format format to test for match * @return {@code true} if this format matches the one specified, - * {@code false} otherwise. + * {@code false} otherwise */ public boolean matches(AudioFormat format) { if (format.getEncoding().equals(getEncoding()) @@ -465,14 +450,14 @@ public class AudioFormat { return false; } - /** - * Returns a string that describes the format, such as: - * "PCM SIGNED 22050 Hz 16 bit mono big-endian". The contents of the string - * may vary between implementations of Java Sound. + * Returns a string that describes the format, such as: "PCM SIGNED 22050 Hz + * 16 bit mono big-endian". The contents of the string may vary between + * implementations of Java Sound. * * @return a string that describes the format parameters */ + @Override public String toString() { String sEncoding = ""; if (getEncoding() != null) { @@ -546,42 +531,36 @@ public class AudioFormat { } /** - * The Encoding class names the specific type of data representation - * used for an audio stream. The encoding includes aspects of the - * sound format other than the number of channels, sample rate, sample size, - * frame rate, frame size, and byte order. + * The {@code Encoding} class names the specific type of data representation + * used for an audio stream. The encoding includes aspects of the sound + * format other than the number of channels, sample rate, sample size, frame + * rate, frame size, and byte order. *

* One ubiquitous type of audio encoding is pulse-code modulation (PCM), * which is simply a linear (proportional) representation of the sound - * waveform. With PCM, the number stored in each sample is proportional - * to the instantaneous amplitude of the sound pressure at that point in - * time. The numbers may be signed or unsigned integers or floats. - * Besides PCM, other encodings include mu-law and a-law, which are nonlinear - * mappings of the sound amplitude that are often used for recording speech. + * waveform. With PCM, the number stored in each sample is proportional to + * the instantaneous amplitude of the sound pressure at that point in time. + * The numbers may be signed or unsigned integers or floats. Besides PCM, + * other encodings include mu-law and a-law, which are nonlinear mappings of + * the sound amplitude that are often used for recording speech. *

* You can use a predefined encoding by referring to one of the static - * objects created by this class, such as PCM_SIGNED or - * PCM_UNSIGNED. Service providers can create new encodings, such as - * compressed audio formats, and make - * these available through the {@link AudioSystem} class. + * objects created by this class, such as PCM_SIGNED or PCM_UNSIGNED. + * Service providers can create new encodings, such as compressed audio + * formats, and make these available through the {@link AudioSystem} class. *

- * The Encoding class is static, so that all - * AudioFormat objects that have the same encoding will refer - * to the same object (rather than different instances of the same class). - * This allows matches to be made by checking that two format's encodings - * are equal. - * - * @see AudioFormat - * @see javax.sound.sampled.spi.FormatConversionProvider + * The {@code Encoding} class is static, so that all {@code AudioFormat} + * objects that have the same encoding will refer to the same object (rather + * than different instances of the same class). This allows matches to be + * made by checking that two format's encodings are equal. * * @author Kara Kytle + * @see AudioFormat + * @see javax.sound.sampled.spi.FormatConversionProvider * @since 1.3 */ public static class Encoding { - - // ENCODING DEFINES - /** * Specifies signed, linear PCM data. */ @@ -609,31 +588,24 @@ public class AudioFormat { */ public static final Encoding ALAW = new Encoding("ALAW"); - - // INSTANCE VARIABLES - /** * Encoding name. */ private String name; - - // CONSTRUCTOR - /** * Constructs a new encoding. - * @param name the name of the new type of encoding + * + * @param name the name of the new type of encoding */ public Encoding(String name) { this.name = name; } - - // METHODS - /** - * Finalizes the equals method + * Finalizes the equals method. */ + @Override public final boolean equals(Object obj) { if (toString() == null) { return (obj != null) && (obj.toString() == null); @@ -645,8 +617,9 @@ public class AudioFormat { } /** - * Finalizes the hashCode method + * Finalizes the hashCode method. */ + @Override public final int hashCode() { if (toString() == null) { return 0; @@ -655,16 +628,17 @@ public class AudioFormat { } /** - * Provides the String representation of the encoding. This String is - * the same name that was passed to the constructor. For the predefined encodings, the name - * is similar to the encoding's variable (field) name. For example, PCM_SIGNED.toString() returns - * the name "pcm_signed". + * Provides the {@code String} representation of the encoding. This + * {@code String} is the same name that was passed to the constructor. + * For the predefined encodings, the name is similar to the encoding's + * variable (field) name. For example, {@code PCM_SIGNED.toString()} + * returns the name "pcm_signed". * * @return the encoding name */ + @Override public final String toString() { return name; } - - } // class Encoding + } } diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioInputStream.java b/jdk/src/share/classes/javax/sound/sampled/AudioInputStream.java index ea4162fa2f3..14e7b537f1b 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioInputStream.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,27 +25,24 @@ package javax.sound.sampled; -import java.io.InputStream; -import java.io.PushbackInputStream; import java.io.IOException; +import java.io.InputStream; /** * An audio input stream is an input stream with a specified audio format and - * length. The length is expressed in sample frames, not bytes. - * Several methods are provided for reading a certain number of bytes from - * the stream, or an unspecified number of bytes. - * The audio input stream keeps track of the last byte that was read. - * You can skip over an arbitrary number of bytes to get to a later position - * for reading. An audio input stream may support marks. When you set a mark, - * the current position is remembered so that you can return to it later. + * length. The length is expressed in sample frames, not bytes. Several methods + * are provided for reading a certain number of bytes from the stream, or an + * unspecified number of bytes. The audio input stream keeps track of the last + * byte that was read. You can skip over an arbitrary number of bytes to get to + * a later position for reading. An audio input stream may support marks. When + * you set a mark, the current position is remembered so that you can return to + * it later. *

- * The AudioSystem class includes many methods that manipulate - * AudioInputStream objects. - * For example, the methods let you: + * The {@code AudioSystem} class includes many methods that manipulate + * {@code AudioInputStream} objects. For example, the methods let you: *

    - *
  • obtain an - * audio input stream from an external audio file, stream, or URL + *
  • obtain an audio input stream from an external audio file, stream, or URL *
  • write an external file from an audio input stream *
  • convert an audio input stream to a different audio format *
@@ -53,16 +50,15 @@ import java.io.IOException; * @author David Rivas * @author Kara Kytle * @author Florian Bomers - * * @see AudioSystem - * @see Clip#open(AudioInputStream) Clip.open(AudioInputStream) + * @see Clip#open(AudioInputStream) * @since 1.3 */ public class AudioInputStream extends InputStream { /** - * The InputStream from which this AudioInputStream - * object was constructed. + * The {@code InputStream} from which this {@code AudioInputStream} object + * was constructed. */ private InputStream stream; @@ -92,35 +88,34 @@ public class AudioInputStream extends InputStream { private long markpos; /** - * When the underlying stream could only return - * a non-integral number of frames, store - * the remainder in a temporary buffer + * When the underlying stream could only return a non-integral number of + * frames, store the remainder in a temporary buffer. */ private byte[] pushBackBuffer = null; /** - * number of valid bytes in the pushBackBuffer + * number of valid bytes in the pushBackBuffer. */ private int pushBackLen = 0; /** - * MarkBuffer at mark position + * MarkBuffer at mark position. */ private byte[] markPushBackBuffer = null; /** - * number of valid bytes in the markPushBackBuffer + * number of valid bytes in the markPushBackBuffer. */ private int markPushBackLen = 0; - /** - * Constructs an audio input stream that has the requested format and length in sample frames, - * using audio data from the specified input stream. - * @param stream the stream on which this AudioInputStream - * object is based - * @param format the format of this stream's audio data - * @param length the length in sample frames of the data in this stream + * Constructs an audio input stream that has the requested format and length + * in sample frames, using audio data from the specified input stream. + * + * @param stream the stream on which this {@code AudioInputStream} object + * is based + * @param format the format of this stream's audio data + * @param length the length in sample frames of the data in this stream */ public AudioInputStream(InputStream stream, AudioFormat format, long length) { @@ -141,12 +136,12 @@ public class AudioInputStream extends InputStream { markpos = 0; } - /** - * Constructs an audio input stream that reads its data from the target - * data line indicated. The format of the stream is the same as that of - * the target data line, and the length is AudioSystem#NOT_SPECIFIED. - * @param line the target data line from which this stream obtains its data. + * Constructs an audio input stream that reads its data from the target data + * line indicated. The format of the stream is the same as that of the + * target data line, and the length is AudioSystem#NOT_SPECIFIED. + * + * @param line the target data line from which this stream obtains its data * @see AudioSystem#NOT_SPECIFIED */ public AudioInputStream(TargetDataLine line) { @@ -164,29 +159,29 @@ public class AudioInputStream extends InputStream { markpos = 0; } - /** * Obtains the audio format of the sound data in this audio input stream. + * * @return an audio format object describing this stream's format */ public AudioFormat getFormat() { return format; } - /** - * Obtains the length of the stream, expressed in sample frames rather than bytes. + * Obtains the length of the stream, expressed in sample frames rather than + * bytes. + * * @return the length in sample frames */ public long getFrameLength() { return frameLength; } - /** - * Reads the next byte of data from the audio input stream. The audio input - * stream's frame size must be one byte, or an IOException - * will be thrown. + * Reads the next byte of data from the audio input stream. The audio input + * stream's frame size must be one byte, or an {@code IOException} will be + * thrown. * * @return the next byte of data, or -1 if the end of the stream is reached * @throws IOException if an input or output error occurs @@ -194,6 +189,7 @@ public class AudioInputStream extends InputStream { * @see #read(byte[]) * @see #available */ + @Override public int read() throws IOException { if( frameSize != 1 ) { throw new IOException("cannot read a single byte if frame size > 1"); @@ -208,50 +204,50 @@ public class AudioInputStream extends InputStream { return data[0] & 0xFF; } - /** - * Reads some number of bytes from the audio input stream and stores them into - * the buffer array b. The number of bytes actually read is - * returned as an integer. This method blocks until input data is - * available, the end of the stream is detected, or an exception is thrown. - *

This method will always read an integral number of frames. - * If the length of the array is not an integral number - * of frames, a maximum of b.length - (b.length % frameSize) - * bytes will be read. + * Reads some number of bytes from the audio input stream and stores them + * into the buffer array {@code b}. The number of bytes actually read is + * returned as an integer. This method blocks until input data is available, + * the end of the stream is detected, or an exception is thrown. + *

+ * This method will always read an integral number of frames. If the length + * of the array is not an integral number of frames, a maximum of + * {@code b.length - (b.length % frameSize)} bytes will be read. * - * @param b the buffer into which the data is read - * @return the total number of bytes read into the buffer, or -1 if there - * is no more data because the end of the stream has been reached + * @param b the buffer into which the data is read + * @return the total number of bytes read into the buffer, or -1 if there is + * no more data because the end of the stream has been reached * @throws IOException if an input or output error occurs * @see #read(byte[], int, int) * @see #read() * @see #available */ + @Override public int read(byte[] b) throws IOException { return read(b,0,b.length); } - /** * Reads up to a specified maximum number of bytes of data from the audio * stream, putting them into the given byte array. - *

This method will always read an integral number of frames. - * If len does not specify an integral number - * of frames, a maximum of len - (len % frameSize) - * bytes will be read. + *

+ * This method will always read an integral number of frames. If {@code len} + * does not specify an integral number of frames, a maximum of + * {@code len - (len % frameSize)} bytes will be read. * - * @param b the buffer into which the data is read - * @param off the offset, from the beginning of array b, at which - * the data will be written - * @param len the maximum number of bytes to read - * @return the total number of bytes read into the buffer, or -1 if there - * is no more data because the end of the stream has been reached + * @param b the buffer into which the data is read + * @param off the offset, from the beginning of array {@code b}, at which + * the data will be written + * @param len the maximum number of bytes to read + * @return the total number of bytes read into the buffer, or -1 if there is + * no more data because the end of the stream has been reached * @throws IOException if an input or output error occurs * @see #read(byte[]) * @see #read() * @see #skip * @see #available */ + @Override public int read(byte[] b, int off, int len) throws IOException { // make sure we don't read fractions of a frame. @@ -313,16 +309,17 @@ public class AudioInputStream extends InputStream { return bytesRead; } - /** - * Skips over and discards a specified number of bytes from this - * audio input stream. - * @param n the requested number of bytes to be skipped + * Skips over and discards a specified number of bytes from this audio input + * stream. + * + * @param n the requested number of bytes to be skipped * @return the actual number of bytes skipped * @throws IOException if an input or output error occurs * @see #read * @see #available */ + @Override public long skip(long n) throws IOException { // make sure not to skip fractional frames @@ -351,21 +348,23 @@ public class AudioInputStream extends InputStream { } - /** - * Returns the maximum number of bytes that can be read (or skipped over) from this - * audio input stream without blocking. This limit applies only to the next invocation of - * a read or skip method for this audio input stream; the limit - * can vary each time these methods are invoked. - * Depending on the underlying stream,an IOException may be thrown if this - * stream is closed. - * @return the number of bytes that can be read from this audio input stream without blocking + * Returns the maximum number of bytes that can be read (or skipped over) + * from this audio input stream without blocking. This limit applies only + * to the next invocation of a {@code read} or {@code skip} method for this + * audio input stream; the limit can vary each time these methods are + * invoked. Depending on the underlying stream, an IOException may be thrown + * if this stream is closed. + * + * @return the number of bytes that can be read from this audio input stream + * without blocking * @throws IOException if an input or output error occurs * @see #read(byte[], int, int) * @see #read(byte[]) * @see #read() * @see #skip */ + @Override public int available() throws IOException { int temp = stream.available(); @@ -378,25 +377,26 @@ public class AudioInputStream extends InputStream { } } - /** - * Closes this audio input stream and releases any system resources associated - * with the stream. + * Closes this audio input stream and releases any system resources + * associated with the stream. + * * @throws IOException if an input or output error occurs */ + @Override public void close() throws IOException { stream.close(); } - /** * Marks the current position in this audio input stream. - * @param readlimit the maximum number of bytes that can be read before - * the mark position becomes invalid. + * + * @param readlimit the maximum number of bytes that can be read before the + * mark position becomes invalid. * @see #reset * @see #markSupported */ - + @Override public void mark(int readlimit) { stream.mark(readlimit); @@ -413,14 +413,15 @@ public class AudioInputStream extends InputStream { } } - /** - * Repositions this audio input stream to the position it had at the time its - * mark method was last invoked. - * @throws IOException if an input or output error occurs. + * Repositions this audio input stream to the position it had at the time + * its {@code mark} method was last invoked. + * + * @throws IOException if an input or output error occurs * @see #mark * @see #markSupported */ + @Override public void reset() throws IOException { stream.reset(); @@ -435,21 +436,21 @@ public class AudioInputStream extends InputStream { } } - /** - * Tests whether this audio input stream supports the mark and - * reset methods. - * @return true if this stream supports the mark - * and reset methods; false otherwise + * Tests whether this audio input stream supports the {@code mark} and + * {@code reset} methods. + * + * @return {@code true} if this stream supports the {@code mark} and + * {@code reset} methods; {@code false} otherwise * @see #mark * @see #reset */ + @Override public boolean markSupported() { return stream.markSupported(); } - /** * Private inner class that makes a TargetDataLine look like an InputStream. */ @@ -460,19 +461,19 @@ public class AudioInputStream extends InputStream { */ TargetDataLine line; - TargetDataLineInputStream(TargetDataLine line) { super(); this.line = line; } - + @Override public int available() throws IOException { return line.available(); } //$$fb 2001-07-16: added this method to correctly close the underlying TargetDataLine. // fixes bug 4479984 + @Override public void close() throws IOException { // the line needs to be flushed and stopped to avoid a dead lock... // Probably related to bugs 4417527, 4334868, 4383457 @@ -483,6 +484,7 @@ public class AudioInputStream extends InputStream { line.close(); } + @Override public int read() throws IOException { byte[] b = new byte[1]; @@ -502,7 +504,7 @@ public class AudioInputStream extends InputStream { return value; } - + @Override public int read(byte[] b, int off, int len) throws IOException { try { return line.read(b, off, len); diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioPermission.java b/jdk/src/share/classes/javax/sound/sampled/AudioPermission.java index 4e7dcef9602..13655254bf0 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioPermission.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioPermission.java @@ -28,18 +28,18 @@ package javax.sound.sampled; import java.security.BasicPermission; /** - * The AudioPermission class represents access rights to the audio - * system resources. An AudioPermission contains a target name - * but no actions list; you either have the named permission or you don't. + * The {@code AudioPermission} class represents access rights to the audio + * system resources. An {@code AudioPermission} contains a target name but no + * actions list; you either have the named permission or you don't. *

* The target name is the name of the audio permission (see the table below). - * The names follow the hierarchical property-naming convention. Also, an asterisk - * can be used to represent all the audio permissions. + * The names follow the hierarchical property-naming convention. Also, an + * asterisk can be used to represent all the audio permissions. *

- * The following table lists the possible AudioPermission target names. - * For each name, the table provides a description of exactly what that permission - * allows, as well as a discussion of the risks of granting code the permission. - * + * The following table lists the possible {@code AudioPermission} target names. + * For each name, the table provides a description of exactly what that + * permission allows, as well as a discussion of the risks of granting code the + * permission. * * * @@ -57,7 +57,7 @@ import java.security.BasicPermission; * applications because the audio from one line may be mixed with other audio * being played on the system, or because manipulation of a mixer affects the * audio for all lines using that mixer. - * + * * * * @@ -68,42 +68,40 @@ import java.security.BasicPermission; * applications because manipulation of a mixer affects the audio for all lines * using that mixer. * This permission can enable an applet or application to eavesdrop on a user. - * - *
record
- *

+ * + * * * @author Kara Kytle * @since 1.3 */ public class AudioPermission extends BasicPermission { + private static final long serialVersionUID = -5518053473477801126L; /** - * Creates a new AudioPermission object that has the specified - * symbolic name, such as "play" or "record". An asterisk can be used to indicate - * all audio permissions. - * @param name the name of the new AudioPermission + * Creates a new {@code AudioPermission} object that has the specified + * symbolic name, such as "play" or "record". An asterisk can be used to + * indicate all audio permissions. * - * @throws NullPointerException if name is null. - * @throws IllegalArgumentException if name is empty. + * @param name the name of the new {@code AudioPermission} + * @throws NullPointerException if {@code name} is {@code null} + * @throws IllegalArgumentException if {@code name} is empty */ - public AudioPermission(String name) { - + public AudioPermission(final String name) { super(name); } /** - * Creates a new AudioPermission object that has the specified - * symbolic name, such as "play" or "record". The actions - * parameter is currently unused and should be null. - * @param name the name of the new AudioPermission - * @param actions (unused; should be null) + * Creates a new {@code AudioPermission} object that has the specified + * symbolic name, such as "play" or "record". The {@code actions} parameter + * is currently unused and should be {@code null}. * - * @throws NullPointerException if name is null. - * @throws IllegalArgumentException if name is empty. + * @param name the name of the new {@code AudioPermission} + * @param actions (unused; should be {@code null}) + * @throws NullPointerException if {@code name} is {@code null} + * @throws IllegalArgumentException if {@code name} is empty */ - public AudioPermission(String name, String actions) { - + public AudioPermission(final String name, final String actions) { super(name, actions); } } diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java b/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java index 235ed234276..7b5428b1c19 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java @@ -50,29 +50,24 @@ import com.sun.media.sound.JDK13Services; /** - * The AudioSystem class acts as the entry point to the - * sampled-audio system resources. This class lets you query and - * access the mixers that are installed on the system. - * AudioSystem includes a number of - * methods for converting audio data between different formats, and for - * translating between audio files and streams. It also provides a method - * for obtaining a {@link Line} directly from the - * AudioSystem without dealing explicitly + * The {@code AudioSystem} class acts as the entry point to the sampled-audio + * system resources. This class lets you query and access the mixers that are + * installed on the system. {@code AudioSystem} includes a number of methods for + * converting audio data between different formats, and for translating between + * audio files and streams. It also provides a method for obtaining a + * {@link Line} directly from the {@code AudioSystem} without dealing explicitly * with mixers. - * - *

Properties can be used to specify the default mixer - * for specific line types. - * Both system properties and a properties file are considered. - * The sound.properties properties file is read from - * an implementation-specific location (typically it is the lib - * directory in the Java installation directory). - * If a property exists both as a system property and in the - * properties file, the system property takes precedence. If none is - * specified, a suitable default is chosen among the available devices. - * The syntax of the properties file is specified in - * {@link java.util.Properties#load(InputStream) Properties.load}. The - * following table lists the available property keys and which methods - * consider them: + *

+ * Properties can be used to specify the default mixer for specific line types. + * Both system properties and a properties file are considered. The + * {@code sound.properties} properties file is read from an + * implementation-specific location (typically it is the {@code lib} directory + * in the Java installation directory). If a property exists both as a system + * property and in the properties file, the system property takes precedence. + * If none is specified, a suitable default is chosen among the available + * devices. The syntax of the properties file is specified in + * {@link java.util.Properties#load(InputStream) Properties.load}. The following + * table lists the available property keys and which methods consider them: * * * @@ -82,84 +77,68 @@ import com.sun.media.sound.JDK13Services; * * * - * + * * * * * - * + * * * * * - * + * * * * * - * + * * * * *
Audio System Property Keys
Affected Method(s)
javax.sound.sampled.Clip{@code javax.sound.sampled.Clip}{@link Clip}{@link #getLine}, {@link #getClip}
javax.sound.sampled.Port{@code javax.sound.sampled.Port}{@link Port}{@link #getLine}
javax.sound.sampled.SourceDataLine{@code javax.sound.sampled.SourceDataLine}{@link SourceDataLine}{@link #getLine}, {@link #getSourceDataLine}
javax.sound.sampled.TargetDataLine{@code javax.sound.sampled.TargetDataLine}{@link TargetDataLine}{@link #getLine}, {@link #getTargetDataLine}
* - * The property value consists of the provider class name - * and the mixer name, separated by the hash mark ("#"). - * The provider class name is the fully-qualified - * name of a concrete {@link javax.sound.sampled.spi.MixerProvider - * mixer provider} class. The mixer name is matched against - * the String returned by the getName - * method of Mixer.Info. - * Either the class name, or the mixer name may be omitted. - * If only the class name is specified, the trailing hash mark - * is optional. - * - *

If the provider class is specified, and it can be - * successfully retrieved from the installed providers, the list of - * Mixer.Info objects is retrieved - * from the provider. Otherwise, or when these mixers - * do not provide a subsequent match, the list is retrieved - * from {@link #getMixerInfo} to contain - * all available Mixer.Info objects. - * - *

If a mixer name is specified, the resulting list of - * Mixer.Info objects is searched: - * the first one with a matching name, and whose - * Mixer provides the + * The property value consists of the provider class name and the mixer name, + * separated by the hash mark ("#"). The provider class name is the + * fully-qualified name of a concrete + * {@link javax.sound.sampled.spi.MixerProvider mixer provider} class. The mixer + * name is matched against the {@code String} returned by the {@code getName} + * method of {@code Mixer.Info}. Either the class name, or the mixer name may be + * omitted. If only the class name is specified, the trailing hash mark is + * optional. + *

+ * If the provider class is specified, and it can be successfully retrieved from + * the installed providers, the list of {@code Mixer.Info} objects is retrieved + * from the provider. Otherwise, or when these mixers do not provide a + * subsequent match, the list is retrieved from {@link #getMixerInfo} to contain + * all available {@code Mixer.Info} objects. + *

+ * If a mixer name is specified, the resulting list of {@code Mixer.Info} + * objects is searched: the first one with a matching name, and whose + * {@code Mixer} provides the respective line interface, will be returned. If no + * matching {@code Mixer.Info} object is found, or the mixer name is not + * specified, the first mixer from the resulting list, which provides the * respective line interface, will be returned. - * If no matching Mixer.Info object - * is found, or the mixer name is not specified, - * the first mixer from the resulting - * list, which provides the respective line - * interface, will be returned. * - * For example, the property javax.sound.sampled.Clip - * with a value - * "com.sun.media.sound.MixerProvider#SunClip" - * will have the following consequences when - * getLine is called requesting a Clip - * instance: - * if the class com.sun.media.sound.MixerProvider exists - * in the list of installed mixer providers, - * the first Clip from the first mixer with name - * "SunClip" will be returned. If it cannot - * be found, the first Clip from the first mixer - * of the specified provider will be returned, regardless of name. - * If there is none, the first Clip from the first - * Mixer with name - * "SunClip" in the list of all mixers - * (as returned by getMixerInfo) will be returned, - * or, if not found, the first Clip of the first - * Mixerthat can be found in the list of all - * mixers is returned. - * If that fails, too, an IllegalArgumentException - * is thrown. + * For example, the property {@code javax.sound.sampled.Clip} with a value + * {@code "com.sun.media.sound.MixerProvider#SunClip"} + * will have the following consequences when {@code getLine} is called + * requesting a {@code Clip} instance: if the class + * {@code com.sun.media.sound.MixerProvider} exists in the list of installed + * mixer providers, the first {@code Clip} from the first mixer with name + * {@code "SunClip"} will be returned. If it cannot be found, the + * first {@code Clip} from the first mixer of the specified provider will be + * returned, regardless of name. If there is none, the first {@code Clip} from + * the first {@code Mixer} with name {@code "SunClip"} in the list of + * all mixers (as returned by {@code getMixerInfo}) will be returned, or, if not + * found, the first {@code Clip} of the first {@code Mixer} that can be found in + * the list of all mixers is returned. If that fails, too, an + * {@code IllegalArgumentException} is thrown. * * @author Kara Kytle * @author Florian Bomers * @author Matthias Pfisterer * @author Kevin P. Smith - * * @see AudioFormat * @see AudioInputStream * @see Mixer @@ -170,13 +149,12 @@ import com.sun.media.sound.JDK13Services; public class AudioSystem { /** - * An integer that stands for an unknown numeric value. - * This value is appropriate only for signed quantities that do not - * normally take negative values. Examples include file sizes, frame - * sizes, buffer sizes, and sample rates. - * A number of Java Sound constructors accept - * a value of NOT_SPECIFIED for such parameters. Other - * methods may also accept or return this value, as documented. + * An integer that stands for an unknown numeric value. This value is + * appropriate only for signed quantities that do not normally take negative + * values. Examples include file sizes, frame sizes, buffer sizes, and + * sample rates. A number of Java Sound constructors accept a value of + * {@code NOT_SPECIFIED} for such parameters. Other methods may also accept + * or return this value, as documented. */ public static final int NOT_SPECIFIED = -1; @@ -186,12 +164,13 @@ public class AudioSystem { private AudioSystem() { } - /** - * Obtains an array of mixer info objects that represents - * the set of audio mixers that are currently installed on the system. - * @return an array of info objects for the currently installed mixers. If no mixers - * are available on the system, an array of length 0 is returned. + * Obtains an array of mixer info objects that represents the set of audio + * mixers that are currently installed on the system. + * + * @return an array of info objects for the currently installed mixers. If + * no mixers are available on the system, an array of length 0 is + * returned. * @see #getMixer */ public static Mixer.Info[] getMixerInfo() { @@ -201,16 +180,16 @@ public class AudioSystem { return allInfos; } - /** * Obtains the requested audio mixer. - * @param info a Mixer.Info object representing the desired - * mixer, or null for the system default mixer + * + * @param info a {@code Mixer.Info} object representing the desired mixer, + * or {@code null} for the system default mixer * @return the requested mixer - * @throws SecurityException if the requested mixer - * is unavailable because of security restrictions - * @throws IllegalArgumentException if the info object does not represent - * a mixer installed on the system + * @throws SecurityException if the requested mixer is unavailable because + * of security restrictions + * @throws IllegalArgumentException if the info object does not represent a + * mixer installed on the system * @see #getMixerInfo */ public static Mixer getMixer(Mixer.Info info) { @@ -259,17 +238,17 @@ public class AudioSystem { + (info!=null?info.toString():"null")); } - //$$fb 2002-11-26: fix for 4757930: DOC: AudioSystem.getTarget/SourceLineInfo() is ambiguous + /** - * Obtains information about all source lines of a particular type that are supported - * by the installed mixers. - * @param info a Line.Info object that specifies the kind of - * lines about which information is requested - * @return an array of Line.Info objects describing source lines matching - * the type requested. If no matching source lines are supported, an array of length 0 - * is returned. + * Obtains information about all source lines of a particular type that are + * supported by the installed mixers. * + * @param info a {@code Line.Info} object that specifies the kind of lines + * about which information is requested + * @return an array of {@code Line.Info} objects describing source lines + * matching the type requested. If no matching source lines are + * supported, an array of length 0 is returned. * @see Mixer#getSourceLineInfo(Line.Info) */ public static Line.Info[] getSourceLineInfo(Line.Info info) { @@ -300,16 +279,15 @@ public class AudioSystem { return returnedArray; } - /** - * Obtains information about all target lines of a particular type that are supported - * by the installed mixers. - * @param info a Line.Info object that specifies the kind of - * lines about which information is requested - * @return an array of Line.Info objects describing target lines matching - * the type requested. If no matching target lines are supported, an array of length 0 - * is returned. + * Obtains information about all target lines of a particular type that are + * supported by the installed mixers. * + * @param info a {@code Line.Info} object that specifies the kind of lines + * about which information is requested + * @return an array of {@code Line.Info} objects describing target lines + * matching the type requested. If no matching target lines are + * supported, an array of length 0 is returned. * @see Mixer#getTargetLineInfo(Line.Info) */ public static Line.Info[] getTargetLineInfo(Line.Info info) { @@ -340,15 +318,15 @@ public class AudioSystem { return returnedArray; } - /** - * Indicates whether the system supports any lines that match - * the specified Line.Info object. A line is supported if - * any installed mixer supports it. - * @param info a Line.Info object describing the line for which support is queried - * @return true if at least one matching line is - * supported, otherwise false + * Indicates whether the system supports any lines that match the specified + * {@code Line.Info} object. A line is supported if any installed mixer + * supports it. * + * @param info a {@code Line.Info} object describing the line for which + * support is queried + * @return {@code true} if at least one matching line is supported, + * otherwise {@code false} * @see Mixer#isLineSupported(Line.Info) */ public static boolean isLineSupported(Line.Info info) { @@ -371,40 +349,36 @@ public class AudioSystem { /** * Obtains a line that matches the description in the specified - * Line.Info object. + * {@code Line.Info} object. + *

+ * If a {@code DataLine} is requested, and {@code info} is an instance of + * {@code DataLine.Info} specifying at least one fully qualified audio + * format, the last one will be used as the default format of the returned + * {@code DataLine}. + *

+ * If system properties + * {@code javax.sound.sampled.Clip}, + * {@code javax.sound.sampled.Port}, + * {@code javax.sound.sampled.SourceDataLine} and + * {@code javax.sound.sampled.TargetDataLine} are defined or they are + * defined in the file "sound.properties", they are used to retrieve default + * lines. For details, refer to the {@link AudioSystem class description}. * - *

If a DataLine is requested, and info - * is an instance of DataLine.Info specifying at least - * one fully qualified audio format, the last one - * will be used as the default format of the returned - * DataLine. + * If the respective property is not set, or the mixer requested in the + * property is not installed or does not provide the requested line, all + * installed mixers are queried for the requested line type. A Line will be + * returned from the first mixer providing the requested line type. * - *

If system properties - * javax.sound.sampled.Clip, - * javax.sound.sampled.Port, - * javax.sound.sampled.SourceDataLine and - * javax.sound.sampled.TargetDataLine are defined - * or they are defined in the file "sound.properties", - * they are used to retrieve default lines. - * For details, refer to the {@link AudioSystem class description}. - * - * If the respective property is not set, or the mixer - * requested in the property is not installed or does not provide the - * requested line, all installed mixers are queried for the - * requested line type. A Line will be returned from the first mixer - * providing the requested line type. - * - * @param info a Line.Info object describing the desired kind of line + * @param info a {@code Line.Info} object describing the desired kind of + * line * @return a line of the requested kind - * - * @throws LineUnavailableException if a matching line - * is not available due to resource restrictions - * @throws SecurityException if a matching line - * is not available due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one line matching the specified - * Line.Info object - * through any installed mixer + * @throws LineUnavailableException if a matching line is not available due + * to resource restrictions + * @throws SecurityException if a matching line is not available due to + * security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one line matching the specified {@code Line.Info} object through + * any installed mixer */ public static Line getLine(Line.Info info) throws LineUnavailableException { LineUnavailableException lue = null; @@ -479,37 +453,30 @@ public class AudioSystem { info.toString() + " is supported."); } - /** - * Obtains a clip that can be used for playing back - * an audio file or an audio stream. The returned clip - * will be provided by the default system mixer, or, - * if not possible, by any other mixer installed in the - * system that supports a Clip - * object. - * - *

The returned clip must be opened with the - * open(AudioFormat) or - * open(AudioInputStream) method. - * - *

This is a high-level method that uses getMixer - * and getLine internally. - * - *

If the system property - * javax.sound.sampled.Clip - * is defined or it is defined in the file "sound.properties", - * it is used to retrieve the default clip. - * For details, refer to the {@link AudioSystem class description}. + * Obtains a clip that can be used for playing back an audio file or an + * audio stream. The returned clip will be provided by the default system + * mixer, or, if not possible, by any other mixer installed in the system + * that supports a {@code Clip} object. + *

+ * The returned clip must be opened with the {@code open(AudioFormat)} or + * {@code open(AudioInputStream)} method. + *

+ * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

+ * If the system property {@code javax.sound.sampled.Clip} is defined or it + * is defined in the file "sound.properties", it is used to retrieve the + * default clip. For details, refer to the + * {@link AudioSystem class description}. * * @return the desired clip object - * - * @throws LineUnavailableException if a clip object - * is not available due to resource restrictions - * @throws SecurityException if a clip object - * is not available due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one clip instance through any installed mixer - * + * @throws LineUnavailableException if a clip object is not available due to + * resource restrictions + * @throws SecurityException if a clip object is not available due to + * security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one clip instance through any installed mixer * @see #getClip(Mixer.Info) * @since 1.5 */ @@ -522,29 +489,26 @@ public class AudioSystem { return (Clip) AudioSystem.getLine(info); } - /** - * Obtains a clip from the specified mixer that can be - * used for playing back an audio file or an audio stream. + * Obtains a clip from the specified mixer that can be used for playing back + * an audio file or an audio stream. + *

+ * The returned clip must be opened with the {@code open(AudioFormat)} or + * {@code open(AudioInputStream)} method. + *

+ * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. * - *

The returned clip must be opened with the - * open(AudioFormat) or - * open(AudioInputStream) method. - * - *

This is a high-level method that uses getMixer - * and getLine internally. - * - * @param mixerInfo a Mixer.Info object representing the - * desired mixer, or null for the system default mixer + * @param mixerInfo a {@code Mixer.Info} object representing the desired + * mixer, or {@code null} for the system default mixer * @return a clip object from the specified mixer * - * @throws LineUnavailableException if a clip - * is not available from this mixer due to resource restrictions - * @throws SecurityException if a clip - * is not available from this mixer due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one clip through the specified mixer - * + * @throws LineUnavailableException if a clip is not available from this + * mixer due to resource restrictions + * @throws SecurityException if a clip is not available from this mixer due + * to security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one clip through the specified mixer * @see #getClip() * @since 1.5 */ @@ -558,45 +522,38 @@ public class AudioSystem { return (Clip) mixer.getLine(info); } - /** - * Obtains a source data line that can be used for playing back - * audio data in the format specified by the - * AudioFormat object. The returned line - * will be provided by the default system mixer, or, - * if not possible, by any other mixer installed in the - * system that supports a matching - * SourceDataLine object. - * - *

The returned line should be opened with the - * open(AudioFormat) or - * open(AudioFormat, int) method. - * - *

This is a high-level method that uses getMixer - * and getLine internally. - * - *

The returned SourceDataLine's default - * audio format will be initialized with format. - * - *

If the system property - * javax.sound.sampled.SourceDataLine - * is defined or it is defined in the file "sound.properties", - * it is used to retrieve the default source data line. - * For details, refer to the {@link AudioSystem class description}. - * - * @param format an AudioFormat object specifying - * the supported audio format of the returned line, - * or null for any audio format - * @return the desired SourceDataLine object - * - * @throws LineUnavailableException if a matching source data line - * is not available due to resource restrictions - * @throws SecurityException if a matching source data line - * is not available due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one source data line supporting the - * specified audio format through any installed mixer + * Obtains a source data line that can be used for playing back audio data + * in the format specified by the {@code AudioFormat} object. The returned + * line will be provided by the default system mixer, or, if not possible, + * by any other mixer installed in the system that supports a matching + * {@code SourceDataLine} object. + *

+ * The returned line should be opened with the {@code open(AudioFormat)} or + * {@code open(AudioFormat, int)} method. + *

+ * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

+ * The returned {@code SourceDataLine}'s default audio format will be + * initialized with {@code format}. + *

+ * If the system property {@code javax.sound.sampled.SourceDataLine} is + * defined or it is defined in the file "sound.properties", it is used to + * retrieve the default source data line. For details, refer to the + * {@link AudioSystem class description}. * + * @param format an {@code AudioFormat} object specifying the supported + * audio format of the returned line, or {@code null} for any audio + * format + * @return the desired {@code SourceDataLine} object + * @throws LineUnavailableException if a matching source data line is not + * available due to resource restrictions + * @throws SecurityException if a matching source data line is not available + * due to security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one source data line supporting the specified audio format + * through any installed mixer * @see #getSourceDataLine(AudioFormat, Mixer.Info) * @since 1.5 */ @@ -606,41 +563,33 @@ public class AudioSystem { return (SourceDataLine) AudioSystem.getLine(info); } - /** - * Obtains a source data line that can be used for playing back - * audio data in the format specified by the - * AudioFormat object, provided by the mixer - * specified by the Mixer.Info object. - * - *

The returned line should be opened with the - * open(AudioFormat) or - * open(AudioFormat, int) method. - * - *

This is a high-level method that uses getMixer - * and getLine internally. - * - *

The returned SourceDataLine's default - * audio format will be initialized with format. - * - * @param format an AudioFormat object specifying - * the supported audio format of the returned line, - * or null for any audio format - * @param mixerinfo a Mixer.Info object representing - * the desired mixer, or null for the system - * default mixer - * @return the desired SourceDataLine object - * - * @throws LineUnavailableException if a matching source data - * line is not available from the specified mixer due - * to resource restrictions - * @throws SecurityException if a matching source data line - * is not available from the specified mixer due to - * security restrictions - * @throws IllegalArgumentException if the specified mixer does - * not support at least one source data line supporting - * the specified audio format + * Obtains a source data line that can be used for playing back audio data + * in the format specified by the {@code AudioFormat} object, provided by + * the mixer specified by the {@code Mixer.Info} object. + *

+ * The returned line should be opened with the {@code open(AudioFormat)} or + * {@code open(AudioFormat, int)} method. + *

+ * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

+ * The returned {@code SourceDataLine}'s default audio format will be + * initialized with {@code format}. * + * @param format an {@code AudioFormat} object specifying the supported + * audio format of the returned line, or {@code null} for any audio + * format + * @param mixerinfo a {@code Mixer.Info} object representing the desired + * mixer, or {@code null} for the system default mixer + * @return the desired {@code SourceDataLine} object + * @throws LineUnavailableException if a matching source data line is not + * available from the specified mixer due to resource restrictions + * @throws SecurityException if a matching source data line is not available + * from the specified mixer due to security restrictions + * @throws IllegalArgumentException if the specified mixer does not support + * at least one source data line supporting the specified audio + * format * @see #getSourceDataLine(AudioFormat) * @since 1.5 */ @@ -650,47 +599,40 @@ public class AudioSystem { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); Mixer mixer = AudioSystem.getMixer(mixerinfo); return (SourceDataLine) mixer.getLine(info); - } - + } /** - * Obtains a target data line that can be used for recording - * audio data in the format specified by the - * AudioFormat object. The returned line - * will be provided by the default system mixer, or, - * if not possible, by any other mixer installed in the - * system that supports a matching - * TargetDataLine object. - * - *

The returned line should be opened with the - * open(AudioFormat) or - * open(AudioFormat, int) method. - * - *

This is a high-level method that uses getMixer - * and getLine internally. - * - *

The returned TargetDataLine's default - * audio format will be initialized with format. - * - *

If the system property - * {@code javax.sound.sampled.TargetDataLine} - * is defined or it is defined in the file "sound.properties", - * it is used to retrieve the default target data line. - * For details, refer to the {@link AudioSystem class description}. - * - * @param format an AudioFormat object specifying - * the supported audio format of the returned line, - * or null for any audio format - * @return the desired TargetDataLine object - * - * @throws LineUnavailableException if a matching target data line - * is not available due to resource restrictions - * @throws SecurityException if a matching target data line - * is not available due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one target data line supporting the - * specified audio format through any installed mixer + * Obtains a target data line that can be used for recording audio data in + * the format specified by the {@code AudioFormat} object. The returned line + * will be provided by the default system mixer, or, if not possible, by any + * other mixer installed in the system that supports a matching + * {@code TargetDataLine} object. + *

+ * The returned line should be opened with the {@code open(AudioFormat)} or + * {@code open(AudioFormat, int)} method. + *

+ * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

+ * The returned {@code TargetDataLine}'s default audio format will be + * initialized with {@code format}. + *

+ * If the system property {@code javax.sound.sampled.TargetDataLine} is + * defined or it is defined in the file "sound.properties", it is used to + * retrieve the default target data line. For details, refer to the + * {@link AudioSystem class description}. * + * @param format an {@code AudioFormat} object specifying the supported + * audio format of the returned line, or {@code null} for any audio + * format + * @return the desired {@code TargetDataLine} object + * @throws LineUnavailableException if a matching target data line is not + * available due to resource restrictions + * @throws SecurityException if a matching target data line is not available + * due to security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one target data line supporting the specified audio format + * through any installed mixer * @see #getTargetDataLine(AudioFormat, Mixer.Info) * @see AudioPermission * @since 1.5 @@ -702,41 +644,33 @@ public class AudioSystem { return (TargetDataLine) AudioSystem.getLine(info); } - - /** - * Obtains a target data line that can be used for recording - * audio data in the format specified by the - * AudioFormat object, provided by the mixer - * specified by the Mixer.Info object. - * - *

The returned line should be opened with the - * open(AudioFormat) or - * open(AudioFormat, int) method. - * - *

This is a high-level method that uses getMixer - * and getLine internally. - * - *

The returned TargetDataLine's default - * audio format will be initialized with format. - * - * @param format an AudioFormat object specifying - * the supported audio format of the returned line, - * or null for any audio format - * @param mixerinfo a Mixer.Info object representing the - * desired mixer, or null for the system default mixer - * @return the desired TargetDataLine object - * - * @throws LineUnavailableException if a matching target data - * line is not available from the specified mixer due - * to resource restrictions - * @throws SecurityException if a matching target data line - * is not available from the specified mixer due to - * security restrictions - * @throws IllegalArgumentException if the specified mixer does - * not support at least one target data line supporting - * the specified audio format + * Obtains a target data line that can be used for recording audio data in + * the format specified by the {@code AudioFormat} object, provided by the + * mixer specified by the {@code Mixer.Info} object. + *

+ * The returned line should be opened with the {@code open(AudioFormat)} or + * {@code open(AudioFormat, int)} method. + *

+ * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

+ * The returned {@code TargetDataLine}'s default audio format will be + * initialized with {@code format}. * + * @param format an {@code AudioFormat} object specifying the supported + * audio format of the returned line, or {@code null} for any audio + * format + * @param mixerinfo a {@code Mixer.Info} object representing the desired + * mixer, or {@code null} for the system default mixer + * @return the desired {@code TargetDataLine} object + * @throws LineUnavailableException if a matching target data line is not + * available from the specified mixer due to resource restrictions + * @throws SecurityException if a matching target data line is not available + * from the specified mixer due to security restrictions + * @throws IllegalArgumentException if the specified mixer does not support + * at least one target data line supporting the specified audio + * format * @see #getTargetDataLine(AudioFormat) * @see AudioPermission * @since 1.5 @@ -750,17 +684,19 @@ public class AudioSystem { return (TargetDataLine) mixer.getLine(info); } - // $$fb 2002-04-12: fix for 4662082: behavior of AudioSystem.getTargetEncodings() methods doesn't match the spec + /** - * Obtains the encodings that the system can obtain from an - * audio input stream with the specified encoding using the set - * of installed format converters. - * @param sourceEncoding the encoding for which conversion support - * is queried - * @return array of encodings. If sourceEncodingis not supported, - * an array of length 0 is returned. Otherwise, the array will have a length - * of at least 1, representing sourceEncoding (no conversion). + * Obtains the encodings that the system can obtain from an audio input + * stream with the specified encoding using the set of installed format + * converters. + * + * @param sourceEncoding the encoding for which conversion support is + * queried + * @return array of encodings. If {@code sourceEncoding}is not supported, an + * array of length 0 is returned. Otherwise, the array will have a + * length of at least 1, representing {@code sourceEncoding} + * (no conversion). */ public static AudioFormat.Encoding[] getTargetEncodings(AudioFormat.Encoding sourceEncoding) { @@ -783,18 +719,18 @@ public class AudioSystem { return encs2; } - - // $$fb 2002-04-12: fix for 4662082: behavior of AudioSystem.getTargetEncodings() methods doesn't match the spec + /** - * Obtains the encodings that the system can obtain from an - * audio input stream with the specified format using the set - * of installed format converters. - * @param sourceFormat the audio format for which conversion - * is queried - * @return array of encodings. If sourceFormatis not supported, - * an array of length 0 is returned. Otherwise, the array will have a length - * of at least 1, representing the encoding of sourceFormat (no conversion). + * Obtains the encodings that the system can obtain from an audio input + * stream with the specified format using the set of installed format + * converters. + * + * @param sourceFormat the audio format for which conversion is queried + * @return array of encodings. If {@code sourceFormat}is not supported, an + * array of length 0 is returned. Otherwise, the array will have a + * length of at least 1, representing the encoding of + * {@code sourceFormat} (no conversion). */ public static AudioFormat.Encoding[] getTargetEncodings(AudioFormat sourceFormat) { @@ -826,15 +762,14 @@ public class AudioSystem { return encs2; } - /** - * Indicates whether an audio input stream of the specified encoding - * can be obtained from an audio input stream that has the specified - * format. - * @param targetEncoding the desired encoding after conversion - * @param sourceFormat the audio format before conversion - * @return true if the conversion is supported, - * otherwise false + * Indicates whether an audio input stream of the specified encoding can be + * obtained from an audio input stream that has the specified format. + * + * @param targetEncoding the desired encoding after conversion + * @param sourceFormat the audio format before conversion + * @return {@code true} if the conversion is supported, otherwise + * {@code false} */ public static boolean isConversionSupported(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) { @@ -850,12 +785,12 @@ public class AudioSystem { return false; } - /** - * Obtains an audio input stream of the indicated encoding, by converting the - * provided audio input stream. - * @param targetEncoding the desired encoding after conversion - * @param sourceStream the stream to be converted + * Obtains an audio input stream of the indicated encoding, by converting + * the provided audio input stream. + * + * @param targetEncoding the desired encoding after conversion + * @param sourceStream the stream to be converted * @return an audio input stream of the indicated encoding * @throws IllegalArgumentException if the conversion is not supported * @see #getTargetEncodings(AudioFormat.Encoding) @@ -878,15 +813,15 @@ public class AudioSystem { throw new IllegalArgumentException("Unsupported conversion: " + targetEncoding + " from " + sourceStream.getFormat()); } - /** - * Obtains the formats that have a particular encoding and that the system can - * obtain from a stream of the specified format using the set of + * Obtains the formats that have a particular encoding and that the system + * can obtain from a stream of the specified format using the set of * installed format converters. - * @param targetEncoding the desired encoding after conversion - * @param sourceFormat the audio format before conversion - * @return array of formats. If no formats of the specified - * encoding are supported, an array of length 0 is returned. + * + * @param targetEncoding the desired encoding after conversion + * @param sourceFormat the audio format before conversion + * @return array of formats. If no formats of the specified encoding are + * supported, an array of length 0 is returned. */ public static AudioFormat[] getTargetFormats(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) { @@ -918,16 +853,15 @@ public class AudioSystem { return fmts2; } - /** - * Indicates whether an audio input stream of a specified format - * can be obtained from an audio input stream of another specified format. - * @param targetFormat the desired audio format after conversion - * @param sourceFormat the audio format before conversion - * @return true if the conversion is supported, - * otherwise false + * Indicates whether an audio input stream of a specified format can be + * obtained from an audio input stream of another specified format. + * + * @param targetFormat the desired audio format after conversion + * @param sourceFormat the audio format before conversion + * @return {@code true} if the conversion is supported, otherwise + * {@code false} */ - public static boolean isConversionSupported(AudioFormat targetFormat, AudioFormat sourceFormat) { List codecs = getFormatConversionProviders(); @@ -941,15 +875,15 @@ public class AudioSystem { return false; } - /** * Obtains an audio input stream of the indicated format, by converting the * provided audio input stream. - * @param targetFormat the desired audio format after conversion - * @param sourceStream the stream to be converted + * + * @param targetFormat the desired audio format after conversion + * @param sourceStream the stream to be converted * @return an audio input stream of the indicated format * @throws IllegalArgumentException if the conversion is not supported - * #see #getTargetEncodings(AudioFormat) + * @see #getTargetEncodings(AudioFormat) * @see #getTargetFormats(AudioFormat.Encoding, AudioFormat) * @see #isConversionSupported(AudioFormat, AudioFormat) * @see #getAudioInputStream(AudioFormat.Encoding, AudioInputStream) @@ -974,20 +908,22 @@ public class AudioSystem { throw new IllegalArgumentException("Unsupported conversion: " + targetFormat + " from " + sourceStream.getFormat()); } - /** - * Obtains the audio file format of the provided input stream. The stream must - * point to valid audio file data. The implementation of this method may require - * multiple parsers to examine the stream to determine whether they support it. - * These parsers must be able to mark the stream, read enough data to determine whether they - * support the stream, and, if not, reset the stream's read pointer to its original - * position. If the input stream does not support these operations, this method may fail - * with an IOException. - * @param stream the input stream from which file format information should be - * extracted - * @return an AudioFileFormat object describing the stream's audio file format - * @throws UnsupportedAudioFileException if the stream does not point to valid audio - * file data recognized by the system + * Obtains the audio file format of the provided input stream. The stream + * must point to valid audio file data. The implementation of this method + * may require multiple parsers to examine the stream to determine whether + * they support it. These parsers must be able to mark the stream, read + * enough data to determine whether they support the stream, and, if not, + * reset the stream's read pointer to its original position. If the input + * stream does not support these operations, this method may fail with an + * {@code IOException}. + * + * @param stream the input stream from which file format information should + * be extracted + * @return an {@code AudioFileFormat} object describing the stream's audio + * file format + * @throws UnsupportedAudioFileException if the stream does not point to + * valid audio file data recognized by the system * @throws IOException if an input/output exception occurs * @see InputStream#markSupported * @see InputStream#mark @@ -1016,13 +952,15 @@ public class AudioSystem { } /** - * Obtains the audio file format of the specified URL. The URL must - * point to valid audio file data. - * @param url the URL from which file format information should be - * extracted - * @return an AudioFileFormat object describing the audio file format - * @throws UnsupportedAudioFileException if the URL does not point to valid audio - * file data recognized by the system + * Obtains the audio file format of the specified URL. The URL must point to + * valid audio file data. + * + * @param url the URL from which file format information should be + * extracted + * @return an {@code AudioFileFormat} object describing the audio file + * format + * @throws UnsupportedAudioFileException if the URL does not point to valid + * audio file data recognized by the system * @throws IOException if an input/output exception occurs */ public static AudioFileFormat getAudioFileFormat(URL url) @@ -1049,13 +987,15 @@ public class AudioSystem { } /** - * Obtains the audio file format of the specified File. The File must - * point to valid audio file data. - * @param file the File from which file format information should be - * extracted - * @return an AudioFileFormat object describing the audio file format - * @throws UnsupportedAudioFileException if the File does not point to valid audio - * file data recognized by the system + * Obtains the audio file format of the specified {@code File}. The + * {@code File} must point to valid audio file data. + * + * @param file the {@code File} from which file format information should + * be extracted + * @return an {@code AudioFileFormat} object describing the audio file + * format + * @throws UnsupportedAudioFileException if the {@code File} does not point + * to valid audio file data recognized by the system * @throws IOException if an I/O exception occurs */ public static AudioFileFormat getAudioFileFormat(File file) @@ -1081,22 +1021,22 @@ public class AudioSystem { } } - /** - * Obtains an audio input stream from the provided input stream. The stream must - * point to valid audio file data. The implementation of this method may - * require multiple parsers to - * examine the stream to determine whether they support it. These parsers must - * be able to mark the stream, read enough data to determine whether they - * support the stream, and, if not, reset the stream's read pointer to its original - * position. If the input stream does not support these operation, this method may fail - * with an IOException. - * @param stream the input stream from which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data contained - * in the input stream. - * @throws UnsupportedAudioFileException if the stream does not point to valid audio - * file data recognized by the system + * Obtains an audio input stream from the provided input stream. The stream + * must point to valid audio file data. The implementation of this method + * may require multiple parsers to examine the stream to determine whether + * they support it. These parsers must be able to mark the stream, read + * enough data to determine whether they support the stream, and, if not, + * reset the stream's read pointer to its original position. If the input + * stream does not support these operation, this method may fail with an + * {@code IOException}. + * + * @param stream the input stream from which the {@code AudioInputStream} + * should be constructed + * @return an {@code AudioInputStream} object based on the audio file data + * contained in the input stream + * @throws UnsupportedAudioFileException if the stream does not point to + * valid audio file data recognized by the system * @throws IOException if an I/O exception occurs * @see InputStream#markSupported * @see InputStream#mark @@ -1125,14 +1065,15 @@ public class AudioSystem { } /** - * Obtains an audio input stream from the URL provided. The URL must - * point to valid audio file data. - * @param url the URL for which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data pointed - * to by the URL - * @throws UnsupportedAudioFileException if the URL does not point to valid audio - * file data recognized by the system + * Obtains an audio input stream from the URL provided. The URL must point + * to valid audio file data. + * + * @param url the URL for which the {@code AudioInputStream} should be + * constructed + * @return an {@code AudioInputStream} object based on the audio file data + * pointed to by the URL + * @throws UnsupportedAudioFileException if the URL does not point to valid + * audio file data recognized by the system * @throws IOException if an I/O exception occurs */ public static AudioInputStream getAudioInputStream(URL url) @@ -1159,14 +1100,15 @@ public class AudioSystem { } /** - * Obtains an audio input stream from the provided File. The File must - * point to valid audio file data. - * @param file the File for which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data pointed - * to by the File - * @throws UnsupportedAudioFileException if the File does not point to valid audio - * file data recognized by the system + * Obtains an audio input stream from the provided {@code File}. The + * {@code File} must point to valid audio file data. + * + * @param file the {@code File} for which the {@code AudioInputStream} + * should be constructed + * @return an {@code AudioInputStream} object based on the audio file data + * pointed to by the {@code File} + * @throws UnsupportedAudioFileException if the {@code File} does not point + * to valid audio file data recognized by the system * @throws IOException if an I/O exception occurs */ public static AudioInputStream getAudioInputStream(File file) @@ -1192,11 +1134,12 @@ public class AudioSystem { } } - /** - * Obtains the file types for which file writing support is provided by the system. - * @return array of unique file types. If no file types are supported, - * an array of length 0 is returned. + * Obtains the file types for which file writing support is provided by the + * system. + * + * @return array of unique file types. If no file types are supported, an + * array of length 0 is returned. */ public static AudioFileFormat.Type[] getAudioFileTypes() { List providers = getAudioFileWriters(); @@ -1214,13 +1157,13 @@ public class AudioSystem { return returnTypes; } - /** - * Indicates whether file writing support for the specified file type is provided - * by the system. - * @param fileType the file type for which write capabilities are queried - * @return true if the file type is supported, - * otherwise false + * Indicates whether file writing support for the specified file type is + * provided by the system. + * + * @param fileType the file type for which write capabilities are queried + * @return {@code true} if the file type is supported, otherwise + * {@code false} */ public static boolean isFileTypeSupported(AudioFileFormat.Type fileType) { @@ -1235,14 +1178,14 @@ public class AudioSystem { return false; } - /** - * Obtains the file types that the system can write from the - * audio input stream specified. - * @param stream the audio input stream for which audio file type support - * is queried - * @return array of file types. If no file types are supported, - * an array of length 0 is returned. + * Obtains the file types that the system can write from the audio input + * stream specified. + * + * @param stream the audio input stream for which audio file type + * support is queried + * @return array of file types. If no file types are supported, an array of + * length 0 is returned. */ public static AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) { List providers = getAudioFileWriters(); @@ -1260,14 +1203,14 @@ public class AudioSystem { return returnTypes; } - /** * Indicates whether an audio file of the specified file type can be written * from the indicated audio input stream. - * @param fileType the file type for which write capabilities are queried - * @param stream the stream for which file-writing support is queried - * @return true if the file type is supported for this audio input stream, - * otherwise false + * + * @param fileType the file type for which write capabilities are queried + * @param stream the stream for which file-writing support is queried + * @return {@code true} if the file type is supported for this audio input + * stream, otherwise {@code false} */ public static boolean isFileTypeSupported(AudioFileFormat.Type fileType, AudioInputStream stream) { @@ -1283,25 +1226,24 @@ public class AudioSystem { return false; } - /** - * Writes a stream of bytes representing an audio file of the specified file type - * to the output stream provided. Some file types require that - * the length be written into the file header; such files cannot be written from - * start to finish unless the length is known in advance. An attempt - * to write a file of such a type will fail with an IOException if the length in - * the audio file type is AudioSystem.NOT_SPECIFIED. + * Writes a stream of bytes representing an audio file of the specified file + * type to the output stream provided. Some file types require that the + * length be written into the file header; such files cannot be written from + * start to finish unless the length is known in advance. An attempt to + * write a file of such a type will fail with an IOException if the length + * in the audio file type is {@code AudioSystem.NOT_SPECIFIED}. * - * @param stream the audio input stream containing audio data to be - * written to the file - * @param fileType the kind of audio file to write - * @param out the stream to which the file data should be written + * @param stream the audio input stream containing audio data to be written + * to the file + * @param fileType the kind of audio file to write + * @param out the stream to which the file data should be written * @return the number of bytes written to the output stream * @throws IOException if an input/output exception occurs - * @throws IllegalArgumentException if the file type is not supported by - * the system + * @throws IllegalArgumentException if the file type is not supported by the + * system * @see #isFileTypeSupported - * @see #getAudioFileTypes + * @see #getAudioFileTypes */ public static int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException { @@ -1328,20 +1270,20 @@ public class AudioSystem { } } - /** - * Writes a stream of bytes representing an audio file of the specified file type - * to the external file provided. - * @param stream the audio input stream containing audio data to be - * written to the file - * @param fileType the kind of audio file to write - * @param out the external file to which the file data should be written + * Writes a stream of bytes representing an audio file of the specified file + * type to the external file provided. + * + * @param stream the audio input stream containing audio data to be written + * to the file + * @param fileType the kind of audio file to write + * @param out the external file to which the file data should be written * @return the number of bytes written to the file * @throws IOException if an I/O exception occurs - * @throws IllegalArgumentException if the file type is not supported by - * the system + * @throws IllegalArgumentException if the file type is not supported by the + * system * @see #isFileTypeSupported - * @see #getAudioFileTypes + * @see #getAudioFileTypes */ public static int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException { @@ -1368,7 +1310,6 @@ public class AudioSystem { } } - // METHODS FOR INTERNAL IMPLEMENTATION USE /** @@ -1378,55 +1319,54 @@ public class AudioSystem { return getProviders(MixerProvider.class); } - /** - * Obtains the set of format converters (codecs, transcoders, etc.) - * that are currently installed on the system. - * @return an array of - * {@link javax.sound.sampled.spi.FormatConversionProvider - * FormatConversionProvider} - * objects representing the available format converters. If no format - * converters readers are available on the system, an array of length 0 is - * returned. + * Obtains the set of format converters (codecs, transcoders, etc.) that are + * currently installed on the system. + * + * @return an array of {@link javax.sound.sampled.spi.FormatConversionProvider + * FormatConversionProvider} objects representing the available + * format converters. If no format converters readers are available + * on the system, an array of length 0 is returned. */ private static List getFormatConversionProviders() { return getProviders(FormatConversionProvider.class); } - /** - * Obtains the set of audio file readers that are currently installed on the system. - * @return a List of - * {@link javax.sound.sampled.spi.AudioFileReader - * AudioFileReader} - * objects representing the installed audio file readers. If no audio file - * readers are available on the system, an empty List is returned. + * Obtains the set of audio file readers that are currently installed on the + * system. + * + * @return a List of {@link javax.sound.sampled.spi.AudioFileReader + * AudioFileReader} objects representing the installed audio file + * readers. If no audio file readers are available on the system, an + * empty List is returned. */ private static List getAudioFileReaders() { return getProviders(AudioFileReader.class); } - /** - * Obtains the set of audio file writers that are currently installed on the system. - * @return a List of - * {@link javax.sound.samples.spi.AudioFileWriter AudioFileWriter} - * objects representing the available audio file writers. If no audio file - * writers are available on the system, an empty List is returned. + * Obtains the set of audio file writers that are currently installed on the + * system. + * + * @return a List of {@link javax.sound.sampled.spi.AudioFileWriter + * AudioFileWriter} objects representing the available audio file + * writers. If no audio file writers are available on the system, an + * empty List is returned. */ private static List getAudioFileWriters() { return getProviders(AudioFileWriter.class); } - - - /** Attempts to locate and return a default Mixer that provides lines - * of the specified type. + /** + * Attempts to locate and return a default Mixer that provides lines of the + * specified type. * - * @param providers the installed mixer providers - * @param info The requested line type - * TargetDataLine.class, Clip.class or Port.class. - * @return a Mixer that matches the requirements, or null if no default mixer found + * @param providers the installed mixer providers + * @param info The requested line type TargetDataLine.class, Clip.class or + * Port.class + * @return a Mixer that matches the requirements, or null if no default + * mixer found */ private static Mixer getDefaultMixer(List providers, Line.Info info) { Class lineClass = info.getLineClass(); @@ -1469,16 +1409,13 @@ public class AudioSystem { return null; } - - - /** Return a MixerProvider of a given class from the list of - MixerProviders. - - This method never requires the returned Mixer to do mixing. - @param providerClassName The class name of the provider to be returned. - @param providers The list of MixerProviders that is searched. - @return A MixerProvider of the requested class, or null if none is - found. + /** + * Return a MixerProvider of a given class from the list of MixerProviders. + * This method never requires the returned Mixer to do mixing. + * + * @param providerClassName The class name of the provider to be returned + * @param providers The list of MixerProviders that is searched + * @return A MixerProvider of the requested class, or null if none is found */ private static MixerProvider getNamedProvider(String providerClassName, List providers) { @@ -1491,15 +1428,14 @@ public class AudioSystem { return null; } - - /** Return a Mixer with a given name from a given MixerProvider. - This method never requires the returned Mixer to do mixing. - @param mixerName The name of the Mixer to be returned. - @param provider The MixerProvider to check for Mixers. - @param info The type of line the returned Mixer is required to - support. - - @return A Mixer matching the requirements, or null if none is found. + /** + * Return a Mixer with a given name from a given MixerProvider. This method + * never requires the returned Mixer to do mixing. + * + * @param mixerName The name of the Mixer to be returned + * @param provider The MixerProvider to check for Mixers + * @param info The type of line the returned Mixer is required to support + * @return A Mixer matching the requirements, or null if none is found */ private static Mixer getNamedMixer(String mixerName, MixerProvider provider, @@ -1516,14 +1452,14 @@ public class AudioSystem { return null; } - - /** From a List of MixerProviders, return a Mixer with a given name. - This method never requires the returned Mixer to do mixing. - @param mixerName The name of the Mixer to be returned. - @param providers The List of MixerProviders to check for Mixers. - @param info The type of line the returned Mixer is required to - support. - @return A Mixer matching the requirements, or null if none is found. + /** + * From a List of MixerProviders, return a Mixer with a given name. This + * method never requires the returned Mixer to do mixing. + * + * @param mixerName The name of the Mixer to be returned + * @param providers The List of MixerProviders to check for Mixers + * @param info The type of line the returned Mixer is required to support + * @return A Mixer matching the requirements, or null if none is found */ private static Mixer getNamedMixer(String mixerName, List providers, @@ -1538,16 +1474,14 @@ public class AudioSystem { return null; } - - /** From a given MixerProvider, return the first appropriate Mixer. - @param provider The MixerProvider to check for Mixers. - @param info The type of line the returned Mixer is required to - support. - @param isMixingRequired If true, only Mixers that support mixing are - returned for line types of SourceDataLine and Clip. - - @return A Mixer that is considered appropriate, or null - if none is found. + /** + * From a given MixerProvider, return the first appropriate Mixer. + * + * @param provider The MixerProvider to check for Mixers + * @param info The type of line the returned Mixer is required to support + * @param isMixingRequired If true, only Mixers that support mixing are + * returned for line types of SourceDataLine and Clip + * @return A Mixer that is considered appropriate, or null if none is found */ private static Mixer getFirstMixer(MixerProvider provider, Line.Info info, @@ -1562,15 +1496,14 @@ public class AudioSystem { return null; } - - /** Checks if a Mixer is appropriate. - A Mixer is considered appropriate if it support the given line type. - If isMixingRequired is true and the line type is an output one - (SourceDataLine, Clip), the mixer is appropriate if it supports - at least 2 (concurrent) lines of the given type. - - @return true if the mixer is considered appropriate according to the - rules given above, false otherwise. + /** + * Checks if a Mixer is appropriate. A Mixer is considered appropriate if it + * support the given line type. If isMixingRequired is true and the line + * type is an output one (SourceDataLine, Clip), the mixer is appropriate if + * it supports at least 2 (concurrent) lines of the given type. + * + * @return {@code true} if the mixer is considered appropriate according to + * the rules given above, {@code false} otherwise */ private static boolean isAppropriateMixer(Mixer mixer, Line.Info lineInfo, @@ -1588,19 +1521,16 @@ public class AudioSystem { return true; } - - /** - * Like getMixerInfo, but return List + * Like getMixerInfo, but return List. */ private static List getMixerInfoList() { List providers = getMixerProviders(); return getMixerInfoList(providers); } - /** - * Like getMixerInfo, but return List + * Like getMixerInfo, but return List. */ private static List getMixerInfoList(List providers) { List infos = new ArrayList(); @@ -1619,12 +1549,12 @@ public class AudioSystem { return infos; } - /** - * Obtains the set of services currently installed on the system - * using the SPI mechanism in 1.3. - * @return a List of instances of providers for the requested service. - * If no providers are available, a vector of length 0 will be returned. + * Obtains the set of services currently installed on the system using the + * SPI mechanism in 1.3. + * + * @return a List of instances of providers for the requested service. If no + * providers are available, a vector of length 0 will be returned. */ private static List getProviders(Class providerClass) { return JDK13Services.getProviders(providerClass); diff --git a/jdk/src/share/classes/javax/sound/sampled/BooleanControl.java b/jdk/src/share/classes/javax/sound/sampled/BooleanControl.java index e48e06c339c..4f81d7c6514 100644 --- a/jdk/src/share/classes/javax/sound/sampled/BooleanControl.java +++ b/jdk/src/share/classes/javax/sound/sampled/BooleanControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,34 +26,29 @@ package javax.sound.sampled; /** - * A BooleanControl provides the ability to switch between - * two possible settings that affect a line's audio. The settings are boolean - * values (true and false). A graphical user interface - * might represent the control by a two-state button, an on/off switch, two - * mutually exclusive buttons, or a checkbox (among other possibilities). - * For example, depressing a button might activate a - * {@link BooleanControl.Type#MUTE MUTE} control to silence - * the line's audio. + * A {@code BooleanControl} provides the ability to switch between two possible + * settings that affect a line's audio. The settings are boolean values + * ({@code true} and {@code false}). A graphical user interface might represent + * the control by a two-state button, an on/off switch, two mutually exclusive + * buttons, or a checkbox (among other possibilities). For example, depressing a + * button might activate a {@link BooleanControl.Type#MUTE MUTE} control to + * silence the line's audio. *

- * As with other {@link Control} subclasses, a method is - * provided that returns string labels for the values, suitable for - * display in the user interface. + * As with other {@code Control} subclasses, a method is provided that returns + * string labels for the values, suitable for display in the user interface. * * @author Kara Kytle * @since 1.3 */ public abstract class BooleanControl extends Control { - - // INSTANCE VARIABLES - /** - * The true state label, such as "true" or "on." + * The {@code true} state label, such as "true" or "on". */ private final String trueStateLabel; /** - * The false state label, such as "false" or "off." + * The {@code false} state label, such as "false" or "off". */ private final String falseStateLabel; @@ -62,19 +57,15 @@ public abstract class BooleanControl extends Control { */ private boolean value; - - // CONSTRUCTORS - - /** * Constructs a new boolean control object with the given parameters. * - * @param type the type of control represented this float control object - * @param initialValue the initial control value - * @param trueStateLabel the label for the state represented by true, - * such as "true" or "on." - * @param falseStateLabel the label for the state represented by false, - * such as "false" or "off." + * @param type the type of control represented this float control object + * @param initialValue the initial control value + * @param trueStateLabel the label for the state represented by + * {@code true}, such as "true" or "on" + * @param falseStateLabel the label for the state represented by + * {@code false}, such as "false" or "off" */ protected BooleanControl(Type type, boolean initialValue, String trueStateLabel, String falseStateLabel) { @@ -84,110 +75,88 @@ public abstract class BooleanControl extends Control { this.falseStateLabel = falseStateLabel; } - /** - * Constructs a new boolean control object with the given parameters. - * The labels for the true and false states - * default to "true" and "false." + * Constructs a new boolean control object with the given parameters. The + * labels for the {@code true} and {@code false} states default to "true" + * and "false". * - * @param type the type of control represented by this float control object - * @param initialValue the initial control value + * @param type the type of control represented by this float control object + * @param initialValue the initial control value */ protected BooleanControl(Type type, boolean initialValue) { this(type, initialValue, "true", "false"); } - - // METHODS - - /** - * Sets the current value for the control. The default - * implementation simply sets the value as indicated. - * Some controls require that their line be open before they can be affected - * by setting a value. - * @param value desired new value. + * Sets the current value for the control. The default implementation simply + * sets the value as indicated. Some controls require that their line be + * open before they can be affected by setting a value. + * + * @param value desired new value */ public void setValue(boolean value) { this.value = value; } - - /** * Obtains this control's current value. - * @return current value. + * + * @return current value */ public boolean getValue() { return value; } - /** * Obtains the label for the specified state. - * @param state the state whose label will be returned - * @return the label for the specified state, such as "true" or "on" - * for true, or "false" or "off" for false. + * + * @param state the state whose label will be returned + * @return the label for the specified state, such as "true" or "on" for + * {@code true}, or "false" or "off" for {@code false} */ public String getStateLabel(boolean state) { return ((state == true) ? trueStateLabel : falseStateLabel); } - - - // ABSTRACT METHOD IMPLEMENTATIONS: CONTROL - - /** - * Provides a string representation of the control + * Provides a string representation of the control. + * * @return a string description */ + @Override public String toString() { return new String(super.toString() + " with current value: " + getStateLabel(getValue())); } - - // INNER CLASSES - - /** - * An instance of the BooleanControl.Type class identifies one kind of - * boolean control. Static instances are provided for the - * common types. + * An instance of the {@code BooleanControl.Type} class identifies one kind + * of boolean control. Static instances are provided for the common types. * * @author Kara Kytle * @since 1.3 */ public static class Type extends Control.Type { - - // TYPE DEFINES - - /** - * Represents a control for the mute status of a line. - * Note that mute status does not affect gain. + * Represents a control for the mute status of a line. Note that mute + * status does not affect gain. */ public static final Type MUTE = new Type("Mute"); /** - * Represents a control for whether reverberation is applied - * to a line. Note that the status of this control not affect - * the reverberation settings for a line, but does affect whether - * these settings are used. + * Represents a control for whether reverberation is applied to a line. + * Note that the status of this control not affect the reverberation + * settings for a line, but does affect whether these settings are used. */ public static final Type APPLY_REVERB = new Type("Apply Reverb"); - - // CONSTRUCTOR - - /** * Constructs a new boolean control type. - * @param name the name of the new boolean control type + * + * @param name the name of the new boolean control type */ - protected Type(String name) { + protected Type(final String name) { super(name); } - } // class Type + } } diff --git a/jdk/src/share/classes/javax/sound/sampled/Clip.java b/jdk/src/share/classes/javax/sound/sampled/Clip.java index 03965f35528..5ed01df832c 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Clip.java +++ b/jdk/src/share/classes/javax/sound/sampled/Clip.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,188 +25,184 @@ package javax.sound.sampled; -import java.io.InputStream; import java.io.IOException; /** - * The Clip interface represents a special kind of data line whose - * audio data can be loaded prior to playback, instead of being streamed in - * real time. + * The {@code Clip} interface represents a special kind of data line whose audio + * data can be loaded prior to playback, instead of being streamed in real time. *

- * Because the data is pre-loaded and has a known length, you can set a clip - * to start playing at any position in its audio data. You can also create a - * loop, so that when the clip is played it will cycle repeatedly. Loops are - * specified with a starting and ending sample frame, along with the number of - * times that the loop should be played. + * Because the data is pre-loaded and has a known length, you can set a clip to + * start playing at any position in its audio data. You can also create a loop, + * so that when the clip is played it will cycle repeatedly. Loops are specified + * with a starting and ending sample frame, along with the number of times that + * the loop should be played. *

- * Clips may be obtained from a {@link Mixer} that supports lines - * of this type. Data is loaded into a clip when it is opened. + * Clips may be obtained from a {@link Mixer} that supports lines of this type. + * Data is loaded into a clip when it is opened. *

- * Playback of an audio clip may be started and stopped using the start - * and stop methods. These methods do not reset the media position; - * start causes playback to continue from the position where playback - * was last stopped. To restart playback from the beginning of the clip's audio - * data, simply follow the invocation of {@link DataLine#stop stop} - * with setFramePosition(0), which rewinds the media to the beginning - * of the clip. + * Playback of an audio clip may be started and stopped using the + * {@link #start start} and {@link #stop stop} methods. These methods do not + * reset the media position; {@code start} causes playback to continue from the + * position where playback was last stopped. To restart playback from the + * beginning of the clip's audio data, simply follow the invocation of + * {@code stop} with {@code setFramePosition(0)}, which rewinds the media to the + * beginning of the clip. * * @author Kara Kytle * @since 1.3 */ public interface Clip extends DataLine { - /** * A value indicating that looping should continue indefinitely rather than * complete after a specific number of loops. + * * @see #loop */ - public static final int LOOP_CONTINUOUSLY = -1; + int LOOP_CONTINUOUSLY = -1; /** - * Opens the clip, meaning that it should acquire any required - * system resources and become operational. The clip is opened - * with the format and audio data indicated. - * If this operation succeeds, the line is marked as open and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched - * to the line's listeners. + * Opens the clip, meaning that it should acquire any required system + * resources and become operational. The clip is opened with the format and + * audio data indicated. If this operation succeeds, the line is marked as + * open and an {@link LineEvent.Type#OPEN OPEN} event is dispatched to the + * line's listeners. *

- * Invoking this method on a line which is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line which is already open is illegal and may + * result in an {@code IllegalStateException}. *

- * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * {@link LineUnavailableException}. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in a {@code LineUnavailableException}. * - * @param format the format of the supplied audio data - * @param data a byte array containing audio data to load into the clip - * @param offset the point at which to start copying, expressed in - * bytes from the beginning of the array - * @param bufferSize the number of bytes - * of data to load into the clip from the array. - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if the buffer size does not represent - * an integral number of sample frames, - * or if format is not fully specified or invalid + * @param format the format of the supplied audio data + * @param data a byte array containing audio data to load into the clip + * @param offset the point at which to start copying, expressed in + * bytes from the beginning of the array + * @param bufferSize the number of bytes of data to load into the + * clip from the array + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if the buffer size does not represent an + * integral number of sample frames, or if {@code format} is not + * fully specified or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #close * @see #isOpen * @see LineListener */ - public void open(AudioFormat format, byte[] data, int offset, int bufferSize) throws LineUnavailableException; + void open(AudioFormat format, byte[] data, int offset, int bufferSize) + throws LineUnavailableException; /** - * Opens the clip with the format and audio data present in the provided audio - * input stream. Opening a clip means that it should acquire any required - * system resources and become operational. If this operation - * input stream. If this operation - * succeeds, the line is marked open and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched - * to the line's listeners. + * Opens the clip with the format and audio data present in the provided + * audio input stream. Opening a clip means that it should acquire any + * required system resources and become operational. If this operation input + * stream. If this operation succeeds, the line is marked open and an + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

- * Invoking this method on a line which is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line which is already open is illegal and may + * result in an {@code IllegalStateException}. *

- * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * {@link LineUnavailableException}. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in a {@code LineUnavailableException}. * - * @param stream an audio input stream from which audio data will be read into - * the clip - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IOException if an I/O exception occurs during reading of - * the stream - * @throws IllegalArgumentException if the stream's audio format - * is not fully specified or invalid + * @param stream an audio input stream from which audio data will be read + * into the clip + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IOException if an I/O exception occurs during reading of the + * stream + * @throws IllegalArgumentException if the stream's audio format is not + * fully specified or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #close * @see #isOpen * @see LineListener */ - public void open(AudioInputStream stream) throws LineUnavailableException, IOException; + void open(AudioInputStream stream) + throws LineUnavailableException, IOException; /** * Obtains the media length in sample frames. - * @return the media length, expressed in sample frames, - * or AudioSystem.NOT_SPECIFIED if the line is not open. + * + * @return the media length, expressed in sample frames, or + * {@code AudioSystem.NOT_SPECIFIED} if the line is not open * @see AudioSystem#NOT_SPECIFIED */ - public int getFrameLength(); + int getFrameLength(); /** - * Obtains the media duration in microseconds - * @return the media duration, expressed in microseconds, - * or AudioSystem.NOT_SPECIFIED if the line is not open. + * Obtains the media duration in microseconds. + * + * @return the media duration, expressed in microseconds, or + * {@code AudioSystem.NOT_SPECIFIED} if the line is not open * @see AudioSystem#NOT_SPECIFIED */ - public long getMicrosecondLength(); + long getMicrosecondLength(); /** - * Sets the media position in sample frames. The position is zero-based; - * the first frame is frame number zero. When the clip begins playing the - * next time, it will start by playing the frame at this position. + * Sets the media position in sample frames. The position is zero-based; the + * first frame is frame number zero. When the clip begins playing the next + * time, it will start by playing the frame at this position. *

* To obtain the current position in sample frames, use the - * {@link DataLine#getFramePosition getFramePosition} - * method of DataLine. + * {@link DataLine#getFramePosition getFramePosition} method of + * {@code DataLine}. * - * @param frames the desired new media position, expressed in sample frames + * @param frames the desired new media position, expressed in sample frames */ - public void setFramePosition(int frames); + void setFramePosition(int frames); /** - * Sets the media position in microseconds. When the clip begins playing the - * next time, it will start at this position. - * The level of precision is not guaranteed. For example, an implementation - * might calculate the microsecond position from the current frame position - * and the audio sample frame rate. The precision in microseconds would - * then be limited to the number of microseconds per sample frame. + * Sets the media position in microseconds. When the clip begins playing the + * next time, it will start at this position. The level of precision is not + * guaranteed. For example, an implementation might calculate the + * microsecond position from the current frame position and the audio sample + * frame rate. The precision in microseconds would then be limited to the + * number of microseconds per sample frame. *

* To obtain the current position in microseconds, use the - * {@link DataLine#getMicrosecondPosition getMicrosecondPosition} - * method of DataLine. + * {@link DataLine#getMicrosecondPosition getMicrosecondPosition} method of + * {@code DataLine}. * - * @param microseconds the desired new media position, expressed in microseconds + * @param microseconds the desired new media position, expressed in + * microseconds */ - public void setMicrosecondPosition(long microseconds); + void setMicrosecondPosition(long microseconds); /** - * Sets the first and last sample frames that will be played in - * the loop. The ending point must be greater than - * or equal to the starting point, and both must fall within the - * the size of the loaded media. A value of 0 for the starting - * point means the beginning of the loaded media. Similarly, a value of -1 - * for the ending point indicates the last frame of the media. - * @param start the loop's starting position, in sample frames (zero-based) - * @param end the loop's ending position, in sample frames (zero-based), or - * -1 to indicate the final frame - * @throws IllegalArgumentException if the requested - * loop points cannot be set, usually because one or both falls outside - * the media's duration or because the ending point is - * before the starting point + * Sets the first and last sample frames that will be played in the loop. + * The ending point must be greater than or equal to the starting point, and + * both must fall within the the size of the loaded media. A value of 0 for + * the starting point means the beginning of the loaded media. Similarly, a + * value of -1 for the ending point indicates the last frame of the media. + * + * @param start the loop's starting position, in sample frames (zero-based) + * @param end the loop's ending position, in sample frames (zero-based), + * or -1 to indicate the final frame + * @throws IllegalArgumentException if the requested loop points cannot be + * set, usually because one or both falls outside the media's + * duration or because the ending point is before the starting point */ - public void setLoopPoints(int start, int end); + void setLoopPoints(int start, int end); /** - * Starts looping playback from the current position. Playback will - * continue to the loop's end point, then loop back to the loop start point - * count times, and finally continue playback to the end of - * the clip. + * Starts looping playback from the current position. Playback will continue + * to the loop's end point, then loop back to the loop start point + * {@code count} times, and finally continue playback to the end of the + * clip. *

* If the current position when this method is invoked is greater than the - * loop end point, playback simply continues to the - * end of the clip without looping. + * loop end point, playback simply continues to the end of the clip without + * looping. *

- * A count value of 0 indicates that any current looping should - * cease and playback should continue to the end of the clip. The behavior + * A {@code count} value of 0 indicates that any current looping should + * cease and playback should continue to the end of the clip. The behavior * is undefined when this method is invoked with any other value during a * loop operation. *

@@ -214,10 +210,10 @@ public interface Clip extends DataLine { * cleared; the behavior of subsequent loop and start requests is not * affected by an interrupted loop operation. * - * @param count the number of times playback should loop back from the - * loop's end position to the loop's start position, or - * {@link #LOOP_CONTINUOUSLY} to indicate that looping should - * continue until interrupted + * @param count the number of times playback should loop back from the + * loop's end position to the loop's start position, or + * {@link #LOOP_CONTINUOUSLY} to indicate that looping should + * continue until interrupted */ - public void loop(int count); + void loop(int count); } diff --git a/jdk/src/share/classes/javax/sound/sampled/CompoundControl.java b/jdk/src/share/classes/javax/sound/sampled/CompoundControl.java index 1c7ba46ede9..50c92a5efe2 100644 --- a/jdk/src/share/classes/javax/sound/sampled/CompoundControl.java +++ b/jdk/src/share/classes/javax/sound/sampled/CompoundControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,55 +26,37 @@ package javax.sound.sampled; /** - * A CompoundControl, such as a graphic equalizer, provides control - * over two or more related properties, each of which is itself represented as - * a Control. + * A {@code CompoundControl}, such as a graphic equalizer, provides control over + * two or more related properties, each of which is itself represented as a + * {@code Control}. * * @author Kara Kytle * @since 1.3 */ public abstract class CompoundControl extends Control { - - // TYPE DEFINES - - - // INSTANCE VARIABLES - - /** * The set of member controls. */ private Control[] controls; - - - // CONSTRUCTORS - - /** * Constructs a new compound control object with the given parameters. * - * @param type the type of control represented this compound control object - * @param memberControls the set of member controls + * @param type the type of control represented this compound control object + * @param memberControls the set of member controls */ protected CompoundControl(Type type, Control[] memberControls) { - super(type); this.controls = memberControls; } - - - // METHODS - - /** * Returns the set of member controls that comprise the compound control. - * @return the set of member controls. + * + * @return the set of member controls */ public Control[] getMemberControls() { - Control[] localArray = new Control[controls.length]; for (int i = 0; i < controls.length; i++) { @@ -84,14 +66,12 @@ public abstract class CompoundControl extends Control { return localArray; } - - // ABSTRACT METHOD IMPLEMENTATIONS: CONTROL - - /** - * Provides a string representation of the control + * Provides a string representation of the control. + * * @return a string description */ + @Override public String toString() { StringBuffer buf = new StringBuffer(); @@ -108,13 +88,9 @@ public abstract class CompoundControl extends Control { return new String(getType() + " Control containing " + buf + " Controls."); } - - // INNER CLASSES - - /** - * An instance of the CompoundControl.Type inner class identifies one kind of - * compound control. Static instances are provided for the + * An instance of the {@code CompoundControl.Type} inner class identifies + * one kind of compound control. Static instances are provided for the * common types. * * @author Kara Kytle @@ -122,19 +98,13 @@ public abstract class CompoundControl extends Control { */ public static class Type extends Control.Type { - - // TYPE DEFINES - - // CONSTRUCTOR - - /** * Constructs a new compound control type. - * @param name the name of the new compound control type + * + * @param name the name of the new compound control type */ - protected Type(String name) { + protected Type(final String name) { super(name); } - } // class Type - -} // class CompoundControl + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/Control.java b/jdk/src/share/classes/javax/sound/sampled/Control.java index 6b8b9c6a5e4..a3257b8539e 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Control.java +++ b/jdk/src/share/classes/javax/sound/sampled/Control.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,121 +26,102 @@ package javax.sound.sampled; /** - * {@link Line Lines} often have a set of controls, such as gain and pan, that affect - * the audio signal passing through the line. Java Sound's Line objects - * let you obtain a particular control object by passing its class as the - * argument to a {@link Line#getControl(Control.Type) getControl} method. + * {@link Line Lines} often have a set of controls, such as gain and pan, that + * affect the audio signal passing through the line. Java Sound's {@code Line} + * objects let you obtain a particular control object by passing its class as + * the argument to a {@link Line#getControl(Control.Type) getControl} method. *

* Because the various types of controls have different purposes and features, - * all of their functionality is accessed from the subclasses that define - * each kind of control. + * all of their functionality is accessed from the subclasses that define each + * kind of control. * * @author Kara Kytle - * * @see Line#getControls * @see Line#isControlSupported * @since 1.3 */ public abstract class Control { - - // INSTANCE VARIABLES - /** * The control type. */ private final Type type; - - - // CONSTRUCTORS - /** * Constructs a Control with the specified type. - * @param type the kind of control desired + * + * @param type the kind of control desired */ protected Control(Type type) { this.type = type; } - - // METHODS - /** * Obtains the control's type. - * @return the control's type. + * + * @return the control's type */ public Type getType() { return type; } - - // ABSTRACT METHODS - /** * Obtains a String describing the control type and its current state. - * @return a String representation of the Control. + * + * @return a String representation of the Control */ + @Override public String toString() { return new String(getType() + " Control"); } - /** - * An instance of the Type class represents the type of - * the control. Static instances are provided for the - * common types. + * An instance of the {@code Type} class represents the type of the control. + * Static instances are provided for the common types. */ public static class Type { - // CONTROL TYPE DEFINES - - // INSTANCE VARIABLES - /** * Type name. */ private String name; - - // CONSTRUCTOR - /** - * Constructs a new control type with the name specified. - * The name should be a descriptive string appropriate for - * labelling the control in an application, such as "Gain" or "Balance." - * @param name the name of the new control type. + * Constructs a new control type with the name specified. The name + * should be a descriptive string appropriate for labelling the control + * in an application, such as "Gain" or "Balance". + * + * @param name the name of the new control type */ protected Type(String name) { this.name = name; } - - // METHODS - /** - * Finalizes the equals method + * Finalizes the equals method. */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } /** - * Finalizes the hashCode method + * Finalizes the hashCode method. */ + @Override public final int hashCode() { return super.hashCode(); } /** - * Provides the String representation of the control type. This String is - * the same name that was passed to the constructor. + * Provides the {@code String} representation of the control type. This + * {@code String} is the same name that was passed to the constructor. * * @return the control type name */ + @Override public final String toString() { return name; } - } // class Type - -} // class Control + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/DataLine.java b/jdk/src/share/classes/javax/sound/sampled/DataLine.java index d0030c9baae..7bba329caec 100644 --- a/jdk/src/share/classes/javax/sound/sampled/DataLine.java +++ b/jdk/src/share/classes/javax/sound/sampled/DataLine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,40 +28,35 @@ package javax.sound.sampled; import java.util.Arrays; /** - * DataLine adds media-related functionality to its - * superinterface, {@link Line}. This functionality includes - * transport-control methods that start, stop, drain, and flush - * the audio data that passes through the line. A data line can also - * report the current position, volume, and audio format of the media. - * Data lines are used for output of audio by means of the - * subinterfaces {@link SourceDataLine} or - * {@link Clip}, which allow an application program to write data. Similarly, - * audio input is handled by the subinterface {@link TargetDataLine}, - * which allows data to be read. + * {@code DataLine} adds media-related functionality to its superinterface, + * {@code Line}. This functionality includes transport-control methods that + * start, stop, drain, and flush the audio data that passes through the line. A + * data line can also report the current position, volume, and audio format of + * the media. Data lines are used for output of audio by means of the + * subinterfaces {@link SourceDataLine} or {@link Clip}, which allow an + * application program to write data. Similarly, audio input is handled by the + * subinterface {@link TargetDataLine}, which allows data to be read. *

- * A data line has an internal buffer in which - * the incoming or outgoing audio data is queued. The - * {@link #drain()} method blocks until this internal buffer - * becomes empty, usually because all queued data has been processed. The - * {@link #flush()} method discards any available queued data - * from the internal buffer. + * A data line has an internal buffer in which the incoming or outgoing audio + * data is queued. The {@link #drain()} method blocks until this internal buffer + * becomes empty, usually because all queued data has been processed. The + * {@link #flush()} method discards any available queued data from the internal + * buffer. *

- * A data line produces {@link LineEvent.Type#START START} and - * {@link LineEvent.Type#STOP STOP} events whenever - * it begins or ceases active presentation or capture of data. These events - * can be generated in response to specific requests, or as a result of - * less direct state changes. For example, if {@link #start()} is called - * on an inactive data line, and data is available for capture or playback, a - * START event will be generated shortly, when data playback - * or capture actually begins. Or, if the flow of data to an active data - * line is constricted so that a gap occurs in the presentation of data, - * a STOP event is generated. + * A data line produces {@link LineEvent.Type#START START} and + * {@link LineEvent.Type#STOP STOP} events whenever it begins or ceases active + * presentation or capture of data. These events can be generated in response to + * specific requests, or as a result of less direct state changes. For example, + * if {@link #start()} is called on an inactive data line, and data is available + * for capture or playback, a {@code START} event will be generated shortly, + * when data playback or capture actually begins. Or, if the flow of data to an + * active data line is constricted so that a gap occurs in the presentation of + * data, a {@code STOP} event is generated. *

* Mixers often support synchronized control of multiple data lines. * Synchronization can be established through the Mixer interface's - * {@link Mixer#synchronize synchronize} method. - * See the description of the {@link Mixer Mixer} interface - * for a more complete description. + * {@link Mixer#synchronize synchronize} method. See the description of the + * {@link Mixer Mixer} interface for a more complete description. * * @author Kara Kytle * @see LineEvent @@ -69,220 +64,217 @@ import java.util.Arrays; */ public interface DataLine extends Line { - /** - * Drains queued data from the line by continuing data I/O until the - * data line's internal buffer has been emptied. - * This method blocks until the draining is complete. Because this is a - * blocking method, it should be used with care. If drain() - * is invoked on a stopped line that has data in its queue, the method will - * block until the line is running and the data queue becomes empty. If - * drain() is invoked by one thread, and another continues to - * fill the data queue, the operation will not complete. - * This method always returns when the data line is closed. + * Drains queued data from the line by continuing data I/O until the data + * line's internal buffer has been emptied. This method blocks until the + * draining is complete. Because this is a blocking method, it should be + * used with care. If {@code drain()} is invoked on a stopped line that has + * data in its queue, the method will block until the line is running and + * the data queue becomes empty. If {@code drain()} is invoked by one + * thread, and another continues to fill the data queue, the operation will + * not complete. This method always returns when the data line is closed. * * @see #flush() */ - public void drain(); + void drain(); /** - * Flushes queued data from the line. The flushed data is discarded. - * In some cases, not all queued data can be discarded. For example, a - * mixer can flush data from the buffer for a specific input line, but any - * unplayed data already in the output buffer (the result of the mix) will - * still be played. You can invoke this method after pausing a line (the - * normal case) if you want to skip the "stale" data when you restart - * playback or capture. (It is legal to flush a line that is not stopped, - * but doing so on an active line is likely to cause a discontinuity in the - * data, resulting in a perceptible click.) + * Flushes queued data from the line. The flushed data is discarded. In some + * cases, not all queued data can be discarded. For example, a mixer can + * flush data from the buffer for a specific input line, but any unplayed + * data already in the output buffer (the result of the mix) will still be + * played. You can invoke this method after pausing a line (the normal case) + * if you want to skip the "stale" data when you restart playback or + * capture. (It is legal to flush a line that is not stopped, but doing so + * on an active line is likely to cause a discontinuity in the data, + * resulting in a perceptible click.) * * @see #stop() * @see #drain() */ - public void flush(); + void flush(); /** - * Allows a line to engage in data I/O. If invoked on a line - * that is already running, this method does nothing. Unless the data in - * the buffer has been flushed, the line resumes I/O starting - * with the first frame that was unprocessed at the time the line was - * stopped. When audio capture or playback starts, a - * {@link LineEvent.Type#START START} event is generated. + * Allows a line to engage in data I/O. If invoked on a line that is already + * running, this method does nothing. Unless the data in the buffer has been + * flushed, the line resumes I/O starting with the first frame that was + * unprocessed at the time the line was stopped. When audio capture or + * playback starts, a {@link LineEvent.Type#START START} event is generated. * * @see #stop() * @see #isRunning() * @see LineEvent */ - public void start(); + void start(); /** - * Stops the line. A stopped line should cease I/O activity. - * If the line is open and running, however, it should retain the resources required - * to resume activity. A stopped line should retain any audio data in its buffer - * instead of discarding it, so that upon resumption the I/O can continue where it left off, - * if possible. (This doesn't guarantee that there will never be discontinuities beyond the - * current buffer, of course; if the stopped condition continues - * for too long, input or output samples might be dropped.) If desired, the retained data can be - * discarded by invoking the flush method. - * When audio capture or playback stops, a {@link LineEvent.Type#STOP STOP} event is generated. + * Stops the line. A stopped line should cease I/O activity. If the line is + * open and running, however, it should retain the resources required to + * resume activity. A stopped line should retain any audio data in its + * buffer instead of discarding it, so that upon resumption the I/O can + * continue where it left off, if possible. (This doesn't guarantee that + * there will never be discontinuities beyond the current buffer, of course; + * if the stopped condition continues for too long, input or output samples + * might be dropped.) If desired, the retained data can be discarded by + * invoking the {@code flush} method. When audio capture or playback stops, + * a {@link LineEvent.Type#STOP STOP} event is generated. * * @see #start() * @see #isRunning() * @see #flush() * @see LineEvent */ - public void stop(); + void stop(); /** - * Indicates whether the line is running. The default is false. - * An open line begins running when the first data is presented in response to an - * invocation of the start method, and continues - * until presentation ceases in response to a call to stop or - * because playback completes. - * @return true if the line is running, otherwise false + * Indicates whether the line is running. The default is {@code false}. An + * open line begins running when the first data is presented in response to + * an invocation of the {@code start} method, and continues until + * presentation ceases in response to a call to {@code stop} or because + * playback completes. + * + * @return {@code true} if the line is running, otherwise {@code false} * @see #start() * @see #stop() */ - public boolean isRunning(); + boolean isRunning(); /** - * Indicates whether the line is engaging in active I/O (such as playback - * or capture). When an inactive line becomes active, it sends a - * {@link LineEvent.Type#START START} event to its listeners. Similarly, when - * an active line becomes inactive, it sends a - * {@link LineEvent.Type#STOP STOP} event. - * @return true if the line is actively capturing or rendering - * sound, otherwise false + * Indicates whether the line is engaging in active I/O (such as playback or + * capture). When an inactive line becomes active, it sends a + * {@link LineEvent.Type#START START} event to its listeners. Similarly, + * when an active line becomes inactive, it sends a + * {@link LineEvent.Type#STOP STOP} event. + * + * @return {@code true} if the line is actively capturing or rendering + * sound, otherwise {@code false} * @see #isOpen * @see #addLineListener * @see #removeLineListener * @see LineEvent * @see LineListener */ - public boolean isActive(); + boolean isActive(); /** * Obtains the current format (encoding, sample rate, number of channels, * etc.) of the data line's audio data. - * - *

If the line is not open and has never been opened, it returns - * the default format. The default format is an implementation - * specific audio format, or, if the DataLine.Info - * object, which was used to retrieve this DataLine, - * specifies at least one fully qualified audio format, the - * last one will be used as the default format. Opening the - * line with a specific audio format (e.g. - * {@link SourceDataLine#open(AudioFormat)}) will override the - * default format. + *

+ * If the line is not open and has never been opened, it returns the default + * format. The default format is an implementation specific audio format, + * or, if the {@code DataLine.Info} object, which was used to retrieve this + * {@code DataLine}, specifies at least one fully qualified audio format, + * the last one will be used as the default format. Opening the line with a + * specific audio format (e.g. {@link SourceDataLine#open(AudioFormat)}) + * will override the default format. * * @return current audio data format * @see AudioFormat */ - public AudioFormat getFormat(); + AudioFormat getFormat(); /** - * Obtains the maximum number of bytes of data that will fit in the data line's - * internal buffer. For a source data line, this is the size of the buffer to - * which data can be written. For a target data line, it is the size of - * the buffer from which data can be read. Note that - * the units used are bytes, but will always correspond to an integral - * number of sample frames of audio data. + * Obtains the maximum number of bytes of data that will fit in the data + * line's internal buffer. For a source data line, this is the size of the + * buffer to which data can be written. For a target data line, it is the + * size of the buffer from which data can be read. Note that the units used + * are bytes, but will always correspond to an integral number of sample + * frames of audio data. * * @return the size of the buffer in bytes */ - public int getBufferSize(); + int getBufferSize(); /** * Obtains the number of bytes of data currently available to the - * application for processing in the data line's internal buffer. For a + * application for processing in the data line's internal buffer. For a * source data line, this is the amount of data that can be written to the - * buffer without blocking. For a target data line, this is the amount of data - * available to be read by the application. For a clip, this value is always - * 0 because the audio data is loaded into the buffer when the clip is opened, - * and persists without modification until the clip is closed. + * buffer without blocking. For a target data line, this is the amount of + * data available to be read by the application. For a clip, this value is + * always 0 because the audio data is loaded into the buffer when the clip + * is opened, and persists without modification until the clip is closed. *

- * Note that the units used are bytes, but will always - * correspond to an integral number of sample frames of audio data. + * Note that the units used are bytes, but will always correspond to an + * integral number of sample frames of audio data. *

- * An application is guaranteed that a read or - * write operation of up to the number of bytes returned from - * available() will not block; however, there is no guarantee - * that attempts to read or write more data will block. + * An application is guaranteed that a read or write operation of up to the + * number of bytes returned from {@code available()} will not block; + * however, there is no guarantee that attempts to read or write more data + * will block. * * @return the amount of data available, in bytes */ - public int available(); + int available(); /** - * Obtains the current position in the audio data, in sample frames. - * The frame position measures the number of sample - * frames captured by, or rendered from, the line since it was opened. - * This return value will wrap around after 2^31 frames. It is recommended - * to use getLongFramePosition instead. + * Obtains the current position in the audio data, in sample frames. The + * frame position measures the number of sample frames captured by, or + * rendered from, the line since it was opened. This return value will wrap + * around after 2^31 frames. It is recommended to use + * {@code getLongFramePosition} instead. * * @return the number of frames already processed since the line was opened * @see #getLongFramePosition() */ - public int getFramePosition(); - + int getFramePosition(); /** - * Obtains the current position in the audio data, in sample frames. - * The frame position measures the number of sample - * frames captured by, or rendered from, the line since it was opened. + * Obtains the current position in the audio data, in sample frames. The + * frame position measures the number of sample frames captured by, or + * rendered from, the line since it was opened. * * @return the number of frames already processed since the line was opened * @since 1.5 */ - public long getLongFramePosition(); - + long getLongFramePosition(); /** - * Obtains the current position in the audio data, in microseconds. - * The microsecond position measures the time corresponding to the number - * of sample frames captured by, or rendered from, the line since it was opened. - * The level of precision is not guaranteed. For example, an implementation - * might calculate the microsecond position from the current frame position - * and the audio sample frame rate. The precision in microseconds would - * then be limited to the number of microseconds per sample frame. + * Obtains the current position in the audio data, in microseconds. The + * microsecond position measures the time corresponding to the number of + * sample frames captured by, or rendered from, the line since it was + * opened. The level of precision is not guaranteed. For example, an + * implementation might calculate the microsecond position from the current + * frame position and the audio sample frame rate. The precision in + * microseconds would then be limited to the number of microseconds per + * sample frame. * - * @return the number of microseconds of data processed since the line was opened + * @return the number of microseconds of data processed since the line was + * opened */ - public long getMicrosecondPosition(); + long getMicrosecondPosition(); /** - * Obtains the current volume level for the line. This level is a measure - * of the signal's current amplitude, and should not be confused with the - * current setting of a gain control. The range is from 0.0 (silence) to - * 1.0 (maximum possible amplitude for the sound waveform). The units - * measure linear amplitude, not decibels. + * Obtains the current volume level for the line. This level is a measure of + * the signal's current amplitude, and should not be confused with the + * current setting of a gain control. The range is from 0.0 (silence) to 1.0 + * (maximum possible amplitude for the sound waveform). The units measure + * linear amplitude, not decibels. * * @return the current amplitude of the signal in this line, or - * {@link AudioSystem#NOT_SPECIFIED} + * {@link AudioSystem#NOT_SPECIFIED} */ - public float getLevel(); + float getLevel(); /** * Besides the class information inherited from its superclass, - * DataLine.Info provides additional information specific to data lines. - * This information includes: + * {@code DataLine.Info} provides additional information specific to data + * lines. This information includes: *

    *
  • the audio formats supported by the data line *
  • the minimum and maximum sizes of its internal buffer *
- * Because a Line.Info knows the class of the line its describes, a - * DataLine.Info object can describe DataLine - * subinterfaces such as {@link SourceDataLine}, - * {@link TargetDataLine}, and {@link Clip}. - * You can query a mixer for lines of any of these types, passing an appropriate - * instance of DataLine.Info as the argument to a method such as - * {@link Mixer#getLine Mixer.getLine(Line.Info)}. + * Because a {@code Line.Info} knows the class of the line its describes, a + * {@code DataLine.Info} object can describe {@code DataLine} subinterfaces + * such as {@link SourceDataLine}, {@link TargetDataLine}, and {@link Clip}. + * You can query a mixer for lines of any of these types, passing an + * appropriate instance of {@code DataLine.Info} as the argument to a method + * such as {@link Mixer#getLine(Line.Info)}. * * @see Line.Info * @author Kara Kytle * @since 1.3 */ - public static class Info extends Line.Info { + class Info extends Line.Info { private final AudioFormat[] formats; private final int minBufferSize; @@ -290,14 +282,17 @@ public interface DataLine extends Line { /** * Constructs a data line's info object from the specified information, - * which includes a set of supported audio formats and a range for the buffer size. - * This constructor is typically used by mixer implementations - * when returning information about a supported line. + * which includes a set of supported audio formats and a range for the + * buffer size. This constructor is typically used by mixer + * implementations when returning information about a supported line. * - * @param lineClass the class of the data line described by the info object - * @param formats set of formats supported - * @param minBufferSize minimum buffer size supported by the data line, in bytes - * @param maxBufferSize maximum buffer size supported by the data line, in bytes + * @param lineClass the class of the data line described by the info + * object + * @param formats set of formats supported + * @param minBufferSize minimum buffer size supported by the data + * line, in bytes + * @param maxBufferSize maximum buffer size supported by the data + * line, in bytes */ public Info(Class lineClass, AudioFormat[] formats, int minBufferSize, int maxBufferSize) { @@ -313,16 +308,16 @@ public interface DataLine extends Line { this.maxBufferSize = maxBufferSize; } - /** * Constructs a data line's info object from the specified information, - * which includes a single audio format and a desired buffer size. - * This constructor is typically used by an application to - * describe a desired line. + * which includes a single audio format and a desired buffer size. This + * constructor is typically used by an application to describe a desired + * line. * - * @param lineClass the class of the data line described by the info object - * @param format desired format - * @param bufferSize desired buffer size in bytes + * @param lineClass the class of the data line described by the info + * object + * @param format desired format + * @param bufferSize desired buffer size in bytes */ public Info(Class lineClass, AudioFormat format, int bufferSize) { @@ -338,39 +333,36 @@ public interface DataLine extends Line { this.maxBufferSize = bufferSize; } - /** * Constructs a data line's info object from the specified information, - * which includes a single audio format. - * This constructor is typically used by an application to - * describe a desired line. + * which includes a single audio format. This constructor is typically + * used by an application to describe a desired line. * - * @param lineClass the class of the data line described by the info object - * @param format desired format + * @param lineClass the class of the data line described by the info + * object + * @param format desired format */ public Info(Class lineClass, AudioFormat format) { this(lineClass, format, AudioSystem.NOT_SPECIFIED); } - /** - * Obtains a set of audio formats supported by the data line. - * Note that isFormatSupported(AudioFormat) might return - * true for certain additional formats that are missing from - * the set returned by getFormats(). The reverse is not - * the case: isFormatSupported(AudioFormat) is guaranteed to return - * true for all formats returned by getFormats(). - * + * Obtains a set of audio formats supported by the data line. Note that + * {@code isFormatSupported(AudioFormat)} might return {@code true} for + * certain additional formats that are missing from the set returned by + * {@code getFormats()}. The reverse is not the case: + * {@code isFormatSupported(AudioFormat)} is guaranteed to return + * {@code true} for all formats returned by {@code getFormats()}. + *

* Some fields in the AudioFormat instances can be set to * {@link javax.sound.sampled.AudioSystem#NOT_SPECIFIED NOT_SPECIFIED} - * if that field does not apply to the format, - * or if the format supports a wide range of values for that field. - * For example, a multi-channel device supporting up to - * 64 channels, could set the channel field in the - * AudioFormat instances returned by this - * method to NOT_SPECIFIED. + * if that field does not apply to the format, or if the format supports + * a wide range of values for that field. For example, a multi-channel + * device supporting up to 64 channels, could set the channel field in + * the {@code AudioFormat} instances returned by this method to + * {@code NOT_SPECIFIED}. * - * @return a set of supported audio formats. + * @return a set of supported audio formats * @see #isFormatSupported(AudioFormat) */ public AudioFormat[] getFormats() { @@ -379,11 +371,12 @@ public interface DataLine extends Line { /** * Indicates whether this data line supports a particular audio format. - * The default implementation of this method simply returns true if - * the specified format matches any of the supported formats. + * The default implementation of this method simply returns {@code true} + * if the specified format matches any of the supported formats. * - * @param format the audio format for which support is queried. - * @return true if the format is supported, otherwise false + * @param format the audio format for which support is queried + * @return {@code true} if the format is supported, otherwise + * {@code false} * @see #getFormats * @see AudioFormat#matches */ @@ -400,32 +393,36 @@ public interface DataLine extends Line { /** * Obtains the minimum buffer size supported by the data line. - * @return minimum buffer size in bytes, or AudioSystem.NOT_SPECIFIED + * + * @return minimum buffer size in bytes, or + * {@code AudioSystem.NOT_SPECIFIED} */ public int getMinBufferSize() { return minBufferSize; } - /** * Obtains the maximum buffer size supported by the data line. - * @return maximum buffer size in bytes, or AudioSystem.NOT_SPECIFIED + * + * @return maximum buffer size in bytes, or + * {@code AudioSystem.NOT_SPECIFIED} */ public int getMaxBufferSize() { return maxBufferSize; } - /** - * Determines whether the specified info object matches this one. - * To match, the superclass match requirements must be met. In - * addition, this object's minimum buffer size must be at least as - * large as that of the object specified, its maximum buffer size must - * be at most as large as that of the object specified, and all of its - * formats must match formats supported by the object specified. - * @return true if this object matches the one specified, - * otherwise false. + * Determines whether the specified info object matches this one. To + * match, the superclass match requirements must be met. In addition, + * this object's minimum buffer size must be at least as large as that + * of the object specified, its maximum buffer size must be at most as + * large as that of the object specified, and all of its formats must + * match formats supported by the object specified. + * + * @return {@code true} if this object matches the one specified, + * otherwise {@code false} */ + @Override public boolean matches(Line.Info info) { if (! (super.matches(info)) ) { @@ -467,8 +464,10 @@ public interface DataLine extends Line { /** * Obtains a textual description of the data line info. + * * @return a string description */ + @Override public String toString() { StringBuffer buf = new StringBuffer(); @@ -489,6 +488,5 @@ public interface DataLine extends Line { return new String(super.toString() + buf); } - } // class Info - -} // interface DataLine + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/EnumControl.java b/jdk/src/share/classes/javax/sound/sampled/EnumControl.java index d9f4baccbda..c029f224ebc 100644 --- a/jdk/src/share/classes/javax/sound/sampled/EnumControl.java +++ b/jdk/src/share/classes/javax/sound/sampled/EnumControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,83 +26,63 @@ package javax.sound.sampled; /** - * A EnumControl provides control over a set of - * discrete possible values, each represented by an object. In a - * graphical user interface, such a control might be represented - * by a set of buttons, each of which chooses one value or setting. For - * example, a reverb control might provide several preset reverberation - * settings, instead of providing continuously adjustable parameters - * of the sort that would be represented by {@link FloatControl} + * A {@code EnumControl} provides control over a set of discrete possible values + * , each represented by an object. In a graphical user interface, such a + * control might be represented by a set of buttons, each of which chooses one + * value or setting. For example, a reverb control might provide several preset + * reverberation settings, instead of providing continuously adjustable + * parameters of the sort that would be represented by {@link FloatControl} * objects. *

- * Controls that provide a choice between only two settings can often be implemented - * instead as a {@link BooleanControl}, and controls that provide - * a set of values along some quantifiable dimension might be implemented - * instead as a FloatControl with a coarse resolution. - * However, a key feature of EnumControl is that the returned values - * are arbitrary objects, rather than numerical or boolean values. This means that each - * returned object can provide further information. As an example, the settings - * of a {@link EnumControl.Type#REVERB REVERB} control are instances of - * {@link ReverbType} that can be queried for the parameter values - * used for each setting. + * Controls that provide a choice between only two settings can often be + * implemented instead as a {@link BooleanControl}, and controls that provide a + * set of values along some quantifiable dimension might be implemented instead + * as a {@code FloatControl} with a coarse resolution. However, a key feature of + * {@code EnumControl} is that the returned values are arbitrary objects, rather + * than numerical or boolean values. This means that each returned object can + * provide further information. As an example, the settings of a + * {@link EnumControl.Type#REVERB REVERB} control are instances of + * {@link ReverbType} that can be queried for the parameter values used for each + * setting. * * @author Kara Kytle * @since 1.3 */ public abstract class EnumControl extends Control { - - // TYPE DEFINES - - - // INSTANCE VARIABLES - - /** * The set of possible values. */ private Object[] values; - /** * The current value. */ private Object value; - - - // CONSTRUCTORS - - /** * Constructs a new enumerated control object with the given parameters. * - * @param type the type of control represented this enumerated control object - * @param values the set of possible values for the control - * @param value the initial control value + * @param type the type of control represented this enumerated control + * object + * @param values the set of possible values for the control + * @param value the initial control value */ protected EnumControl(Type type, Object[] values, Object value) { - super(type); - this.values = values; this.value = value; } - - - // METHODS - - /** - * Sets the current value for the control. The default implementation - * simply sets the value as indicated. If the value indicated is not - * supported, an IllegalArgumentException is thrown. - * Some controls require that their line be open before they can be affected - * by setting a value. - * @param value the desired new value + * Sets the current value for the control. The default implementation simply + * sets the value as indicated. If the value indicated is not supported, an + * {@code IllegalArgumentException} is thrown. Some controls require that + * their line be open before they can be affected by setting a value. + * + * @param value the desired new value * @throws IllegalArgumentException if the value indicated does not fall - * within the allowable range + * within the allowable range */ public void setValue(Object value) { if (!isValueSupported(value)) { @@ -112,18 +92,18 @@ public abstract class EnumControl extends Control { this.value = value; } - /** * Obtains this control's current value. + * * @return the current value */ public Object getValue() { return value; } - /** * Returns the set of possible values for this control. + * * @return the set of possible values */ public Object[] getValues() { @@ -137,12 +117,11 @@ public abstract class EnumControl extends Control { return localArray; } - /** * Indicates whether the value specified is supported. - * @param value the value for which support is queried - * @return true if the value is supported, - * otherwise false + * + * @param value the value for which support is queried + * @return {@code true} if the value is supported, otherwise {@code false} */ private boolean isValueSupported(Object value) { @@ -157,58 +136,43 @@ public abstract class EnumControl extends Control { return false; } - - - // ABSTRACT METHOD IMPLEMENTATIONS: CONTROL - - /** * Provides a string representation of the control. + * * @return a string description */ + @Override public String toString() { return new String(getType() + " with current value: " + getValue()); } - - // INNER CLASSES - - /** - * An instance of the EnumControl.Type inner class identifies one kind of - * enumerated control. Static instances are provided for the - * common types. - * - * @see EnumControl + * An instance of the {@code EnumControl.Type} inner class identifies one + * kind of enumerated control. Static instances are provided for the common + * types. * * @author Kara Kytle + * @see EnumControl * @since 1.3 */ public static class Type extends Control.Type { - - // TYPE DEFINES - /** * Represents a control over a set of possible reverberation settings. * Each reverberation setting is described by an instance of the - * {@link ReverbType} class. (To access these settings, - * invoke {@link EnumControl#getValues} on an - * enumerated control of type REVERB.) + * {@link ReverbType} class. (To access these settings, invoke + * {@link EnumControl#getValues} on an enumerated control of type + * {@code REVERB}.) */ public static final Type REVERB = new Type("Reverb"); - - // CONSTRUCTOR - - /** * Constructs a new enumerated control type. - * @param name the name of the new enumerated control type + * + * @param name the name of the new enumerated control type */ - protected Type(String name) { + protected Type(final String name) { super(name); } - } // class Type - -} // class EnumControl + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/FloatControl.java b/jdk/src/share/classes/javax/sound/sampled/FloatControl.java index b2678d11428..27d59fefe1f 100644 --- a/jdk/src/share/classes/javax/sound/sampled/FloatControl.java +++ b/jdk/src/share/classes/javax/sound/sampled/FloatControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,39 +26,31 @@ package javax.sound.sampled; /** - * A FloatControl object provides control over a range of - * floating-point values. Float controls are often - * represented in graphical user interfaces by continuously - * adjustable objects such as sliders or rotary knobs. Concrete subclasses - * of FloatControl implement controls, such as gain and pan, that - * affect a line's audio signal in some way that an application can manipulate. - * The {@link FloatControl.Type} - * inner class provides static instances of types that are used to - * identify some common kinds of float control. + * A {@code FloatControl} object provides control over a range of floating-point + * values. Float controls are often represented in graphical user interfaces by + * continuously adjustable objects such as sliders or rotary knobs. Concrete + * subclasses of {@code FloatControl} implement controls, such as gain and pan, + * that affect a line's audio signal in some way that an application can + * manipulate. The {@link FloatControl.Type} inner class provides static + * instances of types that are used to identify some common kinds of float + * control. *

- * The FloatControl abstract class provides methods to set and get - * the control's current floating-point value. Other methods obtain the possible + * The {@code FloatControl} abstract class provides methods to set and get the + * control's current floating-point value. Other methods obtain the possible * range of values and the control's resolution (the smallest increment between - * returned values). Some float controls allow ramping to a - * new value over a specified period of time. FloatControl also - * includes methods that return string labels for the minimum, maximum, and midpoint - * positions of the control. - * - * @see Line#getControls - * @see Line#isControlSupported + * returned values). Some float controls allow ramping to a new value over a + * specified period of time. {@code FloatControl} also includes methods that + * return string labels for the minimum, maximum, and midpoint positions of the + * control. * * @author David Rivas * @author Kara Kytle + * @see Line#getControls + * @see Line#isControlSupported * @since 1.3 */ public abstract class FloatControl extends Control { - - // INSTANCE VARIABLES - - - // FINAL VARIABLES - /** * The minimum supported value. */ @@ -75,66 +67,60 @@ public abstract class FloatControl extends Control { private float precision; /** - * The smallest time increment in which a value change - * can be effected during a value shift, in microseconds. + * The smallest time increment in which a value change can be effected + * during a value shift, in microseconds. */ private int updatePeriod; - /** - * A label for the units in which the control values are expressed, - * such as "dB" for decibels. + * A label for the units in which the control values are expressed, such as + * "dB" for decibels. */ private final String units; /** - * A label for the minimum value, such as "Left." + * A label for the minimum value, such as "Left". */ private final String minLabel; /** - * A label for the maximum value, such as "Right." + * A label for the maximum value, such as "Right". */ private final String maxLabel; /** - * A label for the mid-point value, such as "Center." + * A label for the mid-point value, such as "Center". */ private final String midLabel; - - // STATE VARIABLES - /** * The current value. */ private float value; - - - // CONSTRUCTORS - - /** - * Constructs a new float control object with the given parameters + * Constructs a new float control object with the given parameters. * - * @param type the kind of control represented by this float control object - * @param minimum the smallest value permitted for the control - * @param maximum the largest value permitted for the control - * @param precision the resolution or granularity of the control. - * This is the size of the increment between discrete valid values. - * @param updatePeriod the smallest time interval, in microseconds, over which the control - * can change from one discrete value to the next during a {@link #shift(float,float,int) shift} - * @param initialValue the value that the control starts with when constructed - * @param units the label for the units in which the control's values are expressed, - * such as "dB" or "frames per second" - * @param minLabel the label for the minimum value, such as "Left" or "Off" - * @param midLabel the label for the midpoint value, such as "Center" or "Default" - * @param maxLabel the label for the maximum value, such as "Right" or "Full" - * - * @throws IllegalArgumentException if {@code minimum} is greater - * than {@code maximum} or {@code initialValue} does not fall - * within the allowable range + * @param type the kind of control represented by this float control object + * @param minimum the smallest value permitted for the control + * @param maximum the largest value permitted for the control + * @param precision the resolution or granularity of the control. This is + * the size of the increment between discrete valid values. + * @param updatePeriod the smallest time interval, in microseconds, over + * which the control can change from one discrete value to the next + * during a {@link #shift(float,float,int) shift} + * @param initialValue the value that the control starts with when + * constructed + * @param units the label for the units in which the control's values are + * expressed, such as "dB" or "frames per second" + * @param minLabel the label for the minimum value, such as "Left" or "Off" + * @param midLabel the label for the midpoint value, such as "Center" or + * "Default" + * @param maxLabel the label for the maximum value, such as "Right" or + * "Full" + * @throws IllegalArgumentException if {@code minimum} is greater than + * {@code maximum} or {@code initialValue} does not fall within the + * allowable range */ protected FloatControl(Type type, float minimum, float maximum, float precision, int updatePeriod, float initialValue, @@ -169,26 +155,26 @@ public abstract class FloatControl extends Control { this.maxLabel = ( (maxLabel == null) ? "" : maxLabel); } - /** - * Constructs a new float control object with the given parameters. - * The labels for the minimum, maximum, and mid-point values are set - * to zero-length strings. + * Constructs a new float control object with the given parameters. The + * labels for the minimum, maximum, and mid-point values are set to + * zero-length strings. * - * @param type the kind of control represented by this float control object - * @param minimum the smallest value permitted for the control - * @param maximum the largest value permitted for the control - * @param precision the resolution or granularity of the control. - * This is the size of the increment between discrete valid values. - * @param updatePeriod the smallest time interval, in microseconds, over which the control - * can change from one discrete value to the next during a {@link #shift(float,float,int) shift} - * @param initialValue the value that the control starts with when constructed - * @param units the label for the units in which the control's values are expressed, - * such as "dB" or "frames per second" - * - * @throws IllegalArgumentException if {@code minimum} is greater - * than {@code maximum} or {@code initialValue} does not fall - * within the allowable range + * @param type the kind of control represented by this float control object + * @param minimum the smallest value permitted for the control + * @param maximum the largest value permitted for the control + * @param precision the resolution or granularity of the control. This is + * the size of the increment between discrete valid values. + * @param updatePeriod the smallest time interval, in microseconds, over + * which the control can change from one discrete value to the next + * during a {@link #shift(float,float,int) shift} + * @param initialValue the value that the control starts with when + * constructed + * @param units the label for the units in which the control's values are + * expressed, such as "dB" or "frames per second" + * @throws IllegalArgumentException if {@code minimum} is greater than + * {@code maximum} or {@code initialValue} does not fall within the + * allowable range */ protected FloatControl(Type type, float minimum, float maximum, float precision, int updatePeriod, float initialValue, String units) { @@ -196,21 +182,16 @@ public abstract class FloatControl extends Control { initialValue, units, "", "", ""); } - - - // METHODS - - /** - * Sets the current value for the control. The default implementation - * simply sets the value as indicated. If the value indicated is greater - * than the maximum value, or smaller than the minimum value, an - * IllegalArgumentException is thrown. - * Some controls require that their line be open before they can be affected - * by setting a value. - * @param newValue desired new value + * Sets the current value for the control. The default implementation simply + * sets the value as indicated. If the value indicated is greater than the + * maximum value, or smaller than the minimum value, an + * {@code IllegalArgumentException} is thrown. Some controls require that + * their line be open before they can be affected by setting a value. + * + * @param newValue desired new value * @throws IllegalArgumentException if the value indicated does not fall - * within the allowable range + * within the allowable range */ public void setValue(float newValue) { @@ -225,113 +206,114 @@ public abstract class FloatControl extends Control { value = newValue; } - /** * Obtains this control's current value. + * * @return the current value */ public float getValue() { return value; } - /** * Obtains the maximum value permitted. + * * @return the maximum allowable value */ public float getMaximum() { return maximum; } - /** * Obtains the minimum value permitted. + * * @return the minimum allowable value */ public float getMinimum() { return minimum; } - /** - * Obtains the label for the units in which the control's values are expressed, - * such as "dB" or "frames per second." + * Obtains the label for the units in which the control's values are + * expressed, such as "dB" or "frames per second." + * * @return the units label, or a zero-length string if no label */ public String getUnits() { return units; } - /** - * Obtains the label for the minimum value, such as "Left" or "Off." - * @return the minimum value label, or a zero-length string if no label * has been set + * Obtains the label for the minimum value, such as "Left" or "Off". + * + * @return the minimum value label, or a zero-length string if no label has + * been set */ public String getMinLabel() { return minLabel; } - /** - * Obtains the label for the mid-point value, such as "Center" or "Default." - * @return the mid-point value label, or a zero-length string if no label * has been set + * Obtains the label for the mid-point value, such as "Center" or "Default". + * + * @return the mid-point value label, or a zero-length string if no label + * has been set */ public String getMidLabel() { return midLabel; } - /** - * Obtains the label for the maximum value, such as "Right" or "Full." - * @return the maximum value label, or a zero-length string if no label * has been set + * Obtains the label for the maximum value, such as "Right" or "Full". + * + * @return the maximum value label, or a zero-length string if no label has + * been set */ public String getMaxLabel() { return maxLabel; } - /** - * Obtains the resolution or granularity of the control, in the units - * that the control measures. - * The precision is the size of the increment between discrete valid values - * for this control, over the set of supported floating-point values. + * Obtains the resolution or granularity of the control, in the units that + * the control measures. The precision is the size of the increment between + * discrete valid values for this control, over the set of supported + * floating-point values. + * * @return the control's precision */ public float getPrecision() { return precision; } - /** - * Obtains the smallest time interval, in microseconds, over which the control's value can - * change during a shift. The update period is the inverse of the frequency with which - * the control updates its value during a shift. If the implementation does not support value shifting over - * time, it should set the control's value to the final value immediately - * and return -1 from this method. + * Obtains the smallest time interval, in microseconds, over which the + * control's value can change during a shift. The update period is the + * inverse of the frequency with which the control updates its value during + * a shift. If the implementation does not support value shifting over time, + * it should set the control's value to the final value immediately and + * return -1 from this method. * - * @return update period in microseconds, or -1 if shifting over time is unsupported + * @return update period in microseconds, or -1 if shifting over time is + * unsupported * @see #shift */ public int getUpdatePeriod() { return updatePeriod; } - /** - * Changes the control value from the initial value to the final - * value linearly over the specified time period, specified in microseconds. - * This method returns without blocking; it does not wait for the shift - * to complete. An implementation should complete the operation within the time - * specified. The default implementation simply changes the value - * to the final value immediately. - * - * @param from initial value at the beginning of the shift - * @param to final value after the shift - * @param microseconds maximum duration of the shift in microseconds + * Changes the control value from the initial value to the final value + * linearly over the specified time period, specified in microseconds. This + * method returns without blocking; it does not wait for the shift to + * complete. An implementation should complete the operation within the time + * specified. The default implementation simply changes the value to the + * final value immediately. * + * @param from initial value at the beginning of the shift + * @param to final value after the shift + * @param microseconds maximum duration of the shift in microseconds * @throws IllegalArgumentException if either {@code from} or {@code to} - * value does not fall within the allowable range - * + * value does not fall within the allowable range * @see #getUpdatePeriod */ public void shift(float from, float to, int microseconds) { @@ -347,12 +329,9 @@ public abstract class FloatControl extends Control { setValue(to); } - - // ABSTRACT METHOD IMPLEMENTATIONS: CONTROL - - /** - * Provides a string representation of the control + * Provides a string representation of the control. + * * @return a string description */ public String toString() { @@ -360,55 +339,45 @@ public abstract class FloatControl extends Control { " (range: " + minimum + " - " + maximum + ")"); } - - // INNER CLASSES - - /** - * An instance of the FloatControl.Type inner class identifies one kind of - * float control. Static instances are provided for the - * common types. + * An instance of the {@code FloatControl.Type} inner class identifies one + * kind of float control. Static instances are provided for the common + * types. * * @author Kara Kytle * @since 1.3 */ public static class Type extends Control.Type { - - // TYPE DEFINES - - - // GAIN TYPES - /** * Represents a control for the overall gain on a line. *

* Gain is a quantity in decibels (dB) that is added to the intrinsic - * decibel level of the audio signal--that is, the level of - * the signal before it is altered by the gain control. A positive - * gain amplifies (boosts) the signal's volume, and a negative gain - * attenuates (cuts) it. + * decibel level of the audio signal--that is, the level of the signal + * before it is altered by the gain control. A positive gain amplifies + * (boosts) the signal's volume, and a negative gain attenuates(cuts)it. * The gain setting defaults to a value of 0.0 dB, meaning the signal's - * loudness is unaffected. Note that gain measures dB, not amplitude. + * loudness is unaffected. Note that gain measures dB, not amplitude. * The relationship between a gain in decibels and the corresponding * linear amplitude multiplier is: * - *

linearScalar = pow(10.0, gainDB/20.0)
+ *
{@code linearScalar = pow(10.0, gainDB/20.0)}
*

- * The FloatControl class has methods to impose a maximum and - * minimum allowable value for gain. However, because an audio signal might - * already be at a high amplitude, the maximum setting does not guarantee - * that the signal will be undistorted when the gain is applied to it (unless - * the maximum is zero or negative). To avoid numeric overflow from excessively - * large gain settings, a gain control can implement - * clipping, meaning that the signal's amplitude will be limited to the maximum - * value representable by its audio format, instead of wrapping around. + * The {@code FloatControl} class has methods to impose a maximum and + * minimum allowable value for gain. However, because an audio signal + * might already be at a high amplitude, the maximum setting does not + * guarantee that the signal will be undistorted when the gain is + * applied to it (unless the maximum is zero or negative). To avoid + * numeric overflow from excessively large gain settings, a gain control + * can implement clipping, meaning that the signal's amplitude will be + * limited to the maximum value representable by its audio format, + * instead of wrapping around. *

- * These comments apply to gain controls in general, not just master gain controls. - * A line can have more than one gain control. For example, a mixer (which is - * itself a line) might have a master gain control, an auxiliary return control, - * a reverb return control, and, on each of its source lines, an individual aux - * send and reverb send. + * These comments apply to gain controls in general, not just master + * gain controls. A line can have more than one gain control. For + * example, a mixer (which is itself a line) might have a master gain + * control, an auxiliary return control, a reverb return control, and, + * on each of its source lines, an individual aux send and reverb send. * * @see #AUX_SEND * @see #AUX_RETURN @@ -435,9 +404,9 @@ public abstract class FloatControl extends Control { public static final Type AUX_RETURN = new Type("AUX Return"); /** - * Represents a control for the pre-reverb gain on a line. - * This control may be used to affect how much - * of a line's signal is directed to a mixer's internal reverberation unit. + * Represents a control for the pre-reverb gain on a line. This control + * may be used to affect how much of a line's signal is directed to a + * mixer's internal reverberation unit. * * @see #MASTER_GAIN * @see #REVERB_RETURN @@ -446,18 +415,15 @@ public abstract class FloatControl extends Control { public static final Type REVERB_SEND = new Type("Reverb Send"); /** - * Represents a control for the post-reverb gain on a line. - * This control may be used to control the relative amplitude - * of the signal returned from an internal reverberation unit. + * Represents a control for the post-reverb gain on a line. This control + * may be used to control the relative amplitude of the signal returned + * from an internal reverberation unit. * * @see #MASTER_GAIN * @see #REVERB_SEND */ public static final Type REVERB_RETURN = new Type("Reverb Return"); - - // VOLUME - /** * Represents a control for the volume on a line. */ @@ -466,64 +432,52 @@ public abstract class FloatControl extends Control { */ public static final Type VOLUME = new Type("Volume"); - - // PAN - /** - * Represents a control for the relative pan (left-right positioning) - * of the signal. The signal may be mono; the pan setting affects how - * it is distributed by the mixer in a stereo mix. The valid range of values is -1.0 - * (left channel only) to 1.0 (right channel - * only). The default is 0.0 (centered). + * Represents a control for the relative pan (left-right positioning) of + * the signal. The signal may be mono; the pan setting affects how it is + * distributed by the mixer in a stereo mix. The valid range of values + * is -1.0 (left channel only) to 1.0 (right channel only). The default + * is 0.0 (centered). * * @see #BALANCE */ public static final Type PAN = new Type("Pan"); - - // BALANCE - /** * Represents a control for the relative balance of a stereo signal - * between two stereo speakers. The valid range of values is -1.0 (left channel only) to 1.0 (right channel - * only). The default is 0.0 (centered). + * between two stereo speakers. The valid range of values is -1.0 (left + * channel only) to 1.0 (right channel only). The default is 0.0 + * (centered). * * @see #PAN */ public static final Type BALANCE = new Type("Balance"); - - // SAMPLE RATE - /** - * Represents a control that changes the sample rate of audio playback. The net effect - * of changing the sample rate depends on the relationship between - * the media's natural rate and the rate that is set via this control. - * The natural rate is the sample rate that is specified in the data line's - * AudioFormat object. For example, if the natural rate - * of the media is 11025 samples per second and the sample rate is set - * to 22050 samples per second, the media will play back at twice the - * normal speed. + * Represents a control that changes the sample rate of audio playback. + * The net effect of changing the sample rate depends on the + * relationship between the media's natural rate and the rate that is + * set via this control. The natural rate is the sample rate that is + * specified in the data line's {@code AudioFormat} object. For example, + * if the natural rate of the media is 11025 samples per second and the + * sample rate is set to 22050 samples per second, the media will play + * back at twice the normal speed. *

- * Changing the sample rate with this control does not affect the data line's - * audio format. Also note that whenever you change a sound's sample rate, a - * change in the sound's pitch results. For example, doubling the sample - * rate has the effect of doubling the frequencies in the sound's spectrum, - * which raises the pitch by an octave. + * Changing the sample rate with this control does not affect the data + * line's audio format. Also note that whenever you change a sound's + * sample rate, a change in the sound's pitch results. For example, + * doubling the sample rate has the effect of doubling the frequencies + * in the sound's spectrum, which raises the pitch by an octave. */ public static final Type SAMPLE_RATE = new Type("Sample Rate"); - - // CONSTRUCTOR - /** * Constructs a new float control type. - * @param name the name of the new float control type + * + * @param name the name of the new float control type */ - protected Type(String name) { + protected Type(final String name) { super(name); } - - } // class Type - -} // class FloatControl + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/Line.java b/jdk/src/share/classes/javax/sound/sampled/Line.java index dfab63470cc..0b9d96c0b89 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Line.java +++ b/jdk/src/share/classes/javax/sound/sampled/Line.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,96 +26,90 @@ package javax.sound.sampled; /** - * The Line interface represents a mono or multi-channel - * audio feed. A line is an element of the digital audio - * "pipeline," such as a mixer, an input or output port, - * or a data path into or out of a mixer. + * The {@code Line} interface represents a mono or multi-channel audio feed. A + * line is an element of the digital audio "pipeline," such as a mixer, an input + * or output port, or a data path into or out of a mixer. *

- * A line can have controls, such as gain, pan, and reverb. - * The controls themselves are instances of classes that extend the - * base {@link Control} class. - * The Line interface provides two accessor methods for - * obtaining the line's controls: {@link #getControls getControls} returns the - * entire set, and {@link #getControl getControl} returns a single control of - * specified type. + * A line can have controls, such as gain, pan, and reverb. The controls + * themselves are instances of classes that extend the base {@link Control} + * class. The {@code Line} interface provides two accessor methods for obtaining + * the line's controls: {@link #getControls getControls} returns the entire set, + * and {@link #getControl getControl} returns a single control of specified + * type. *

- * Lines exist in various states at different times. When a line opens, it reserves system - * resources for itself, and when it closes, these resources are freed for - * other objects or applications. The {@link #isOpen()} method lets - * you discover whether a line is open or closed. - * An open line need not be processing data, however. Such processing is - * typically initiated by subinterface methods such as - * {@link SourceDataLine#write SourceDataLine.write} and - * {@link TargetDataLine#read TargetDataLine.read}. - *

- * You can register an object to receive notifications whenever the line's - * state changes. The object must implement the {@link LineListener} - * interface, which consists of the single method - * {@link LineListener#update update}. - * This method will be invoked when a line opens and closes (and, if it's a - * {@link DataLine}, when it starts and stops). - *

- * An object can be registered to listen to multiple lines. The event it - * receives in its update method will specify which line created - * the event, what type of event it was - * (OPEN, CLOSE, START, or STOP), - * and how many sample frames the line had processed at the time the event occurred. + * Lines exist in various states at different times. When a line opens, it + * reserves system resources for itself, and when it closes, these resources are + * freed for other objects or applications. The {@link #isOpen()} method lets + * you discover whether a line is open or closed. An open line need not be + * processing data, however. Such processing is typically initiated by + * subinterface methods such as + * {@link SourceDataLine#write SourceDataLine.write} and + * {@link TargetDataLine#read TargetDataLine.read}. + *

+ * You can register an object to receive notifications whenever the line's state + * changes. The object must implement the {@link LineListener} interface, which + * consists of the single method {@link LineListener#update update}. This method + * will be invoked when a line opens and closes (and, if it's a {@link DataLine} + * , when it starts and stops). + *

+ * An object can be registered to listen to multiple lines. The event it + * receives in its {@code update} method will specify which line created the + * event, what type of event it was ({@code OPEN}, {@code CLOSE}, {@code START}, + * or {@code STOP}), and how many sample frames the line had processed at the + * time the event occurred. *

* Certain line operations, such as open and close, can generate security * exceptions if invoked by unprivileged code when the line is a shared audio * resource. * * @author Kara Kytle - * * @see LineEvent * @since 1.3 */ public interface Line extends AutoCloseable { /** - * Obtains the Line.Info object describing this - * line. + * Obtains the {@code Line.Info} object describing this line. + * * @return description of the line */ - public Line.Info getLineInfo(); + Line.Info getLineInfo(); /** - * Opens the line, indicating that it should acquire any required - * system resources and become operational. - * If this operation - * succeeds, the line is marked as open, and an OPEN event is dispatched - * to the line's listeners. + * Opens the line, indicating that it should acquire any required system + * resources and become operational. If this operation succeeds, the line is + * marked as open, and an {@code OPEN} event is dispatched to the line's + * listeners. *

- * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in an LineUnavailableException. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in an {@code LineUnavailableException}. *

- * Some types of lines have configurable properties that may affect - * resource allocation. For example, a DataLine must - * be opened with a particular format and buffer size. Such lines - * should provide a mechanism for configuring these properties, such - * as an additional open method or methods which allow - * an application to specify the desired settings. + * Some types of lines have configurable properties that may affect resource + * allocation. For example, a {@code DataLine} must be opened with a + * particular format and buffer size. Such lines should provide a mechanism + * for configuring these properties, such as an additional {@code open} + * method or methods which allow an application to specify the desired + * settings. *

* This method takes no arguments, and opens the line with the current - * settings. For {@link SourceDataLine} and - * {@link TargetDataLine} objects, this means that the line is - * opened with default settings. For a {@link Clip}, however, - * the buffer size is determined when data is loaded. Since this method does not - * allow the application to specify any data to load, an IllegalArgumentException - * is thrown. Therefore, you should instead use one of the open methods - * provided in the Clip interface to load data into the Clip. + * settings. For {@link SourceDataLine} and {@link TargetDataLine} objects, + * this means that the line is opened with default settings. For a + * {@link Clip}, however, the buffer size is determined when data is loaded. + * Since this method does not allow the application to specify any data to + * load, an {@code IllegalArgumentException} is thrown. Therefore, you + * should instead use one of the {@code open} methods provided in the + * {@code Clip} interface to load data into the {@code Clip}. *

- * For DataLine's, if the DataLine.Info - * object which was used to retrieve the line, specifies at least - * one fully qualified audio format, the last one will be used - * as the default format. - * - * @throws IllegalArgumentException if this method is called on a Clip instance. - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions. - * @throws SecurityException if the line cannot be - * opened due to security restrictions. + * For {@code DataLine}'s, if the {@code DataLine.Info} object which was + * used to retrieve the line, specifies at least one fully qualified audio + * format, the last one will be used as the default format. * + * @throws IllegalArgumentException if this method is called on a Clip + * instance + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #close * @see #isOpen * @see LineEvent @@ -123,133 +117,128 @@ public interface Line extends AutoCloseable { * @see Clip#open(AudioFormat, byte[], int, int) * @see Clip#open(AudioInputStream) */ - public void open() throws LineUnavailableException; - + void open() throws LineUnavailableException; /** - * Closes the line, indicating that any system resources - * in use by the line can be released. If this operation - * succeeds, the line is marked closed and a CLOSE event is dispatched - * to the line's listeners. - * @throws SecurityException if the line cannot be - * closed due to security restrictions. + * Closes the line, indicating that any system resources in use by the line + * can be released. If this operation succeeds, the line is marked closed + * and a {@code CLOSE} event is dispatched to the line's listeners. * + * @throws SecurityException if the line cannot be closed due to security + * restrictions * @see #open * @see #isOpen * @see LineEvent */ - public void close(); - - + @Override + void close(); /** - * Indicates whether the line is open, meaning that it has reserved - * system resources and is operational, although it might not currently be - * playing or capturing sound. - * @return true if the line is open, otherwise false + * Indicates whether the line is open, meaning that it has reserved system + * resources and is operational, although it might not currently be playing + * or capturing sound. * + * @return {@code true} if the line is open, otherwise {@code false} * @see #open() * @see #close() */ - public boolean isOpen(); - + boolean isOpen(); /** - * Obtains the set of controls associated with this line. - * Some controls may only be available when the line is open. - * If there are no controls, this method returns an array of length 0. + * Obtains the set of controls associated with this line. Some controls may + * only be available when the line is open. If there are no controls, this + * method returns an array of length 0. + * * @return the array of controls * @see #getControl */ - public Control[] getControls(); + Control[] getControls(); /** - * Indicates whether the line supports a control of the specified type. - * Some controls may only be available when the line is open. - * @param control the type of the control for which support is queried - * @return true if at least one control of the specified type is - * supported, otherwise false. + * Indicates whether the line supports a control of the specified type. Some + * controls may only be available when the line is open. + * + * @param control the type of the control for which support is queried + * @return {@code true} if at least one control of the specified type is + * supported, otherwise {@code false} */ - public boolean isControlSupported(Control.Type control); - + boolean isControlSupported(Control.Type control); /** - * Obtains a control of the specified type, - * if there is any. - * Some controls may only be available when the line is open. - * @param control the type of the requested control + * Obtains a control of the specified type, if there is any. Some controls + * may only be available when the line is open. + * + * @param control the type of the requested control * @return a control of the specified type - * @throws IllegalArgumentException if a control of the specified type - * is not supported + * @throws IllegalArgumentException if a control of the specified type is + * not supported * @see #getControls * @see #isControlSupported(Control.Type control) */ - public Control getControl(Control.Type control); - + Control getControl(Control.Type control); /** - * Adds a listener to this line. Whenever the line's status changes, the - * listener's update() method is called with a LineEvent object - * that describes the change. - * @param listener the object to add as a listener to this line + * Adds a listener to this line. Whenever the line's status changes, the + * listener's {@code update()} method is called with a {@code LineEvent} + * object that describes the change. + * + * @param listener the object to add as a listener to this line * @see #removeLineListener * @see LineListener#update * @see LineEvent */ - public void addLineListener(LineListener listener); - + void addLineListener(LineListener listener); /** * Removes the specified listener from this line's list of listeners. - * @param listener listener to remove + * + * @param listener listener to remove * @see #addLineListener */ - public void removeLineListener(LineListener listener); - + void removeLineListener(LineListener listener); /** - * A Line.Info object contains information about a line. - * The only information provided by Line.Info itself - * is the Java class of the line. - * A subclass of Line.Info adds other kinds of information - * about the line. This additional information depends on which Line - * subinterface is implemented by the kind of line that the Line.Info - * subclass describes. + * A {@code Line.Info} object contains information about a line. The only + * information provided by {@code Line.Info} itself is the Java class of the + * line. A subclass of {@code Line.Info} adds other kinds of information + * about the line. This additional information depends on which {@code Line} + * subinterface is implemented by the kind of line that the + * {@code Line.Info} subclass describes. *

- * A Line.Info can be retrieved using various methods of - * the Line, Mixer, and AudioSystem - * interfaces. Other such methods let you pass a Line.Info as - * an argument, to learn whether lines matching the specified configuration - * are available and to obtain them. + * A {@code Line.Info} can be retrieved using various methods of the + * {@code Line}, {@code Mixer}, and {@code AudioSystem} interfaces. Other + * such methods let you pass a {@code Line.Info} as an argument, to learn + * whether lines matching the specified configuration are available and to + * obtain them. * * @author Kara Kytle - * - * @see Line#getLineInfo - * @see Mixer#getSourceLineInfo - * @see Mixer#getTargetLineInfo - * @see Mixer#getLine Mixer.getLine(Line.Info) - * @see Mixer#getSourceLineInfo(Line.Info) Mixer.getSourceLineInfo(Line.Info) - * @see Mixer#getSourceLineInfo(Line.Info) Mixer.getTargetLineInfo(Line.Info) - * @see Mixer#isLineSupported Mixer.isLineSupported(Line.Info) - * @see AudioSystem#getLine AudioSystem.getLine(Line.Info) - * @see AudioSystem#getSourceLineInfo AudioSystem.getSourceLineInfo(Line.Info) - * @see AudioSystem#getTargetLineInfo AudioSystem.getTargetLineInfo(Line.Info) - * @see AudioSystem#isLineSupported AudioSystem.isLineSupported(Line.Info) + * @see Line#getLineInfo() + * @see Mixer#getSourceLineInfo() + * @see Mixer#getTargetLineInfo() + * @see Mixer#getLine(Line.Info) + * @see Mixer#getSourceLineInfo(Line.Info) + * @see Mixer#getTargetLineInfo(Line.Info) + * @see Mixer#isLineSupported(Line.Info) + * @see AudioSystem#getLine(Line.Info) + * @see AudioSystem#getSourceLineInfo(Line.Info) + * @see AudioSystem#getTargetLineInfo(Line.Info) + * @see AudioSystem#isLineSupported(Line.Info) * @since 1.3 */ - public static class Info { + class Info { /** * The class of the line described by the info object. */ private final Class lineClass; - /** - * Constructs an info object that describes a line of the specified class. - * This constructor is typically used by an application to + * Constructs an info object that describes a line of the specified + * class. This constructor is typically used by an application to * describe a desired line. - * @param lineClass the class of the line that the new Line.Info object describes + * + * @param lineClass the class of the line that the new Line.Info object + * describes */ public Info(Class lineClass) { @@ -260,33 +249,29 @@ public interface Line extends AutoCloseable { } } - - /** * Obtains the class of the line that this Line.Info object describes. + * * @return the described line's class */ public Class getLineClass() { return lineClass; } - /** - * Indicates whether the specified info object matches this one. - * To match, the specified object must be identical to or - * a special case of this one. The specified info object - * must be either an instance of the same class as this one, - * or an instance of a sub-type of this one. In addition, the - * attributes of the specified object must be compatible with the - * capabilities of this one. Specifically, the routing configuration - * for the specified info object must be compatible with that of this - * one. - * Subclasses may add other criteria to determine whether the two objects - * match. + * Indicates whether the specified info object matches this one. To + * match, the specified object must be identical to or a special case of + * this one. The specified info object must be either an instance of + * the same class as this one, or an instance of a sub-type of this one. + * In addition, the attributes of the specified object must be + * compatible with the capabilities of this one. Specifically, the + * routing configuration for the specified info object must be + * compatible with that of this one. Subclasses may add other criteria + * to determine whether the two objects match. * - * @param info the info object which is being compared to this one - * @return true if the specified object matches this one, - * false otherwise + * @param info the info object which is being compared to this one + * @return {@code true} if the specified object matches this one, + * {@code false} otherwise */ public boolean matches(Info info) { @@ -320,7 +305,6 @@ public interface Line extends AutoCloseable { return false; } - // this.isAssignableFrom(that) => this is same or super to that // => this is at least as general as that // => that may be subtype of this @@ -332,11 +316,12 @@ public interface Line extends AutoCloseable { return true; } - /** * Obtains a textual description of the line info. + * * @return a string description */ + @Override public String toString() { String fullPackagePath = "javax.sound.sampled."; @@ -353,7 +338,5 @@ public interface Line extends AutoCloseable { return finalString; } - - } // class Info - -} // interface Line + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/LineEvent.java b/jdk/src/share/classes/javax/sound/sampled/LineEvent.java index ff5b90f1ba1..035c38f74f5 100644 --- a/jdk/src/share/classes/javax/sound/sampled/LineEvent.java +++ b/jdk/src/share/classes/javax/sound/sampled/LineEvent.java @@ -25,61 +25,64 @@ package javax.sound.sampled; +import java.util.EventObject; + /** - * The LineEvent class encapsulates information that a line - * sends its listeners whenever the line opens, closes, starts, or stops. - * Each of these four state changes is represented by a corresponding - * type of event. A listener receives the event as a parameter to its - * {@link LineListener#update update} method. By querying the event, - * the listener can learn the type of event, the line responsible for - * the event, and how much data the line had processed when the event occurred. - * - *

Although this class implements Serializable, attempts to - * serialize a LineEvent object will fail. + * The {@code LineEvent} class encapsulates information that a line sends its + * listeners whenever the line opens, closes, starts, or stops. Each of these + * four state changes is represented by a corresponding type of event. A + * listener receives the event as a parameter to its + * {@link LineListener#update update} method. By querying the event, the + * listener can learn the type of event, the line responsible for the event, and + * how much data the line had processed when the event occurred. + *

+ * Although this class implements Serializable, attempts to serialize a + * {@code LineEvent} object will fail. * * @author Kara Kytle - * * @see Line * @see LineListener#update * @since 1.3 * * @serial exclude */ -public class LineEvent extends java.util.EventObject { +public class LineEvent extends EventObject { + private static final long serialVersionUID = -1274246333383880410L; - // INSTANCE VARIABLES - /** - * The kind of line event (OPEN, CLOSE, - * START, or STOP). - * @see #getType + * The kind of line event ({@code OPEN}, {@code CLOSE}, {@code START}, or + * {@code STOP}). + * * @serial + * @see #getType */ private final Type type; /** * The media position when the event occurred, expressed in sample frames. - * Note that this field is only relevant to certain events generated by - * data lines, such as START and STOP. For - * events generated by lines that do not count sample frames, and for any - * other events for which this value is not known, the position value - * should be {@link AudioSystem#NOT_SPECIFIED}. + * Note that this field is only relevant to certain events generated by data + * lines, such as {@code START} and {@code STOP}. For events generated by + * lines that do not count sample frames, and for any other events for which + * this value is not known, the position value should be + * {@link AudioSystem#NOT_SPECIFIED}. + * * @serial * @see #getFramePosition */ private final long position; - /** - * Constructs a new event of the specified type, originating from the specified line. - * @param line the source of this event - * @param type the event type (OPEN, CLOSE, START, or STOP) - * @param position the number of sample frames that the line had already processed when the event occurred, - * or {@link AudioSystem#NOT_SPECIFIED} + * Constructs a new event of the specified type, originating from the + * specified line. * - * @throws IllegalArgumentException if line is - * null. + * @param line the source of this event + * @param type the event type ({@code OPEN}, {@code CLOSE}, {@code START}, + * or {@code STOP}) + * @param position the number of sample frames that the line had already + * processed when the event occurred, or + * {@link AudioSystem#NOT_SPECIFIED} + * @throws IllegalArgumentException if {@code line} is {@code null}. */ public LineEvent(Line line, Type type, long position) { @@ -90,6 +93,7 @@ public class LineEvent extends java.util.EventObject { /** * Obtains the audio line that is the source of this event. + * * @return the line responsible for this event */ public final Line getLine() { @@ -97,11 +101,11 @@ public class LineEvent extends java.util.EventObject { return (Line)getSource(); } - /** * Obtains the event's type. + * * @return this event's type ({@link Type#OPEN}, {@link Type#CLOSE}, - * {@link Type#START}, or {@link Type#STOP}) + * {@link Type#START}, or {@link Type#STOP}) */ public final Type getType() { @@ -109,21 +113,24 @@ public class LineEvent extends java.util.EventObject { } /** - * Obtains the position in the line's audio data when the event occurred, expressed in sample frames. - * For example, if a source line had already played back 14 sample frames at the time it was - * paused, the pause event would report the line's position as 14. The next frame to be processed - * would be frame number 14 using zero-based numbering, or 15 using one-based numbering. + * Obtains the position in the line's audio data when the event occurred, + * expressed in sample frames. For example, if a source line had already + * played back 14 sample frames at the time it was paused, the pause event + * would report the line's position as 14. The next frame to be processed + * would be frame number 14 using zero-based numbering, or 15 using + * one-based numbering. *

- * Note that this field is relevant only to certain events generated by - * data lines, such as START and STOP. For - * events generated by lines that do not count sample frames, and for any - * other events for which this value is not known, the position value - * should be {@link AudioSystem#NOT_SPECIFIED}. + * Note that this field is relevant only to certain events generated by data + * lines, such as {@code START} and {@code STOP}. For events generated by + * lines that do not count sample frames, and for any other events for which + * this value is not known, the position value should be + * {@link AudioSystem#NOT_SPECIFIED}. * * @return the line's position as a sample frame number */ /* - * $$kk: 04.20.99: note to myself: should make sure our implementation is consistent with this. + * $$kk: 04.20.99: note to myself: should make sure our implementation is + * consistent with this. * which is a reasonable definition.... */ public final long getFramePosition() { @@ -132,10 +139,12 @@ public class LineEvent extends java.util.EventObject { } /** - * Obtains a string representation of the event. The contents of the string may vary - * between implementations of Java Sound. - * @return a string describing the event. + * Obtains a string representation of the event. The contents of the string + * may vary between implementations of Java Sound. + * + * @return a string describing the event */ + @Override public String toString() { String sType = ""; if (type != null) sType = type.toString()+" "; @@ -148,16 +157,15 @@ public class LineEvent extends java.util.EventObject { return new String(sType + "event from line " + sLine); } - /** - * The LineEvent.Type inner class identifies what kind of event occurred on a line. - * Static instances are provided for the common types (OPEN, CLOSE, START, and STOP). + * The LineEvent.Type inner class identifies what kind of event occurred on + * a line. Static instances are provided for the common types (OPEN, CLOSE, + * START, and STOP). * * @see LineEvent#getType() */ public static class Type { - /** * Type name. */ @@ -166,82 +174,84 @@ public class LineEvent extends java.util.EventObject { /** * Constructs a new event type. - * @param name name of the type + * + * @param name name of the type */ protected Type(String name) { this.name = name; } - //$$fb 2002-11-26: fix for 4695001: SPEC: description of equals() method contains typo + /** * Indicates whether the specified object is equal to this event type, - * returning true if the objects are identical. - * @param obj the reference object with which to compare - * @return true if this event type is the same as - * obj; false otherwise + * returning {@code true} if the objects are identical. + * + * @param obj the reference object with which to compare + * @return {@code true} if this event type is the same as {@code obj}; + * {@code false} otherwise */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } - /** * Finalizes the hashcode method. */ + @Override public final int hashCode() { return super.hashCode(); } - /** * Returns the type name as the string representation. */ + @Override public String toString() { return name; } - // LINE EVENT TYPE DEFINES /** * A type of event that is sent when a line opens, reserving system * resources for itself. + * * @see #CLOSE * @see Line#open */ public static final Type OPEN = new Type("Open"); - /** * A type of event that is sent when a line closes, freeing the system * resources it had obtained when it was opened. + * * @see #OPEN * @see Line#close */ public static final Type CLOSE = new Type("Close"); - /** * A type of event that is sent when a line begins to engage in active * input or output of audio data in response to a * {@link DataLine#start start} request. + * * @see #STOP * @see DataLine#start */ public static final Type START = new Type("Start"); - /** - * A type of event that is sent when a line ceases active input or output - * of audio data in response to a {@link DataLine#stop stop} request, - * or because the end of media has been reached. + * A type of event that is sent when a line ceases active input or + * output of audio data in response to a {@link DataLine#stop stop} + * request, or because the end of media has been reached. + * * @see #START * @see DataLine#stop */ public static final Type STOP = new Type("Stop"); - /** * A type of event that is sent when a line ceases to engage in active * input or output of audio data because the end of media has been reached. @@ -255,7 +265,6 @@ public class LineEvent extends java.util.EventObject { */ //public static final Type EOM = new Type("EOM"); - /** * A type of event that is sent when a line begins to engage in active * input or output of audio data. Examples of when this happens are @@ -268,7 +277,6 @@ public class LineEvent extends java.util.EventObject { */ //public static final Type ACTIVE = new Type("ACTIVE"); - /** * A type of event that is sent when a line ceases active input or output * of audio data. @@ -276,7 +284,5 @@ public class LineEvent extends java.util.EventObject { * @see DataLine#stop */ //public static final Type INACTIVE = new Type("INACTIVE"); - - } // class Type - -} // class LineEvent + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/LineListener.java b/jdk/src/share/classes/javax/sound/sampled/LineListener.java index 57d6468007d..5d0434d6d86 100644 --- a/jdk/src/share/classes/javax/sound/sampled/LineListener.java +++ b/jdk/src/share/classes/javax/sound/sampled/LineListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,44 +25,27 @@ package javax.sound.sampled; - +import java.util.EventListener; /** - * Instances of classes that implement the LineListener interface can register to - * receive events when a line's status changes. + * Instances of classes that implement the {@code LineListener} interface can + * register to receive events when a line's status changes. * * @author Kara Kytle - * * @see Line * @see Line#addLineListener * @see Line#removeLineListener * @see LineEvent - * * @since 1.3 */ -/* - * Instances of classes that implement the LineListener interface can register to - * receive events when a line's status changes. - * - * @see Line - * @see Line#addLineListener - * @see Line#removeLineListener - * @see LineEvent - * - * @author Kara Kytle - */ -public interface LineListener extends java.util.EventListener { +public interface LineListener extends EventListener { /** - * Informs the listener that a line's state has changed. The listener can then invoke - * LineEvent methods to obtain information about the event. - * @param event a line event that describes the change + * Informs the listener that a line's state has changed. The listener can + * then invoke {@code LineEvent} methods to obtain information about the + * event. + * + * @param event a line event that describes the change */ - /* - * Informs the listener that a line's state has changed. The listener can then invoke - * LineEvent methods to obtain information about the event. - * @param event a line event that describes the change - */ - public void update(LineEvent event); - -} // interface LineListener + void update(LineEvent event); +} diff --git a/jdk/src/share/classes/javax/sound/sampled/LineUnavailableException.java b/jdk/src/share/classes/javax/sound/sampled/LineUnavailableException.java index 1e72f75061e..701d8ee499a 100644 --- a/jdk/src/share/classes/javax/sound/sampled/LineUnavailableException.java +++ b/jdk/src/share/classes/javax/sound/sampled/LineUnavailableException.java @@ -26,43 +26,32 @@ package javax.sound.sampled; /** - * A LineUnavailableException is an exception indicating that a - * line cannot be opened because it is unavailable. This situation - * arises most commonly when a requested line is already in use - * by another application. + * A {@code LineUnavailableException} is an exception indicating that a line + * cannot be opened because it is unavailable. This situation arises most + * commonly when a requested line is already in use by another application. * * @author Kara Kytle * @since 1.3 */ -/* - * A LinenavailableException is an exception indicating that a - * line annot be opened because it is unavailable. This situation - * arises most commonly when a line is requested when it is already in use - * by another application. - * - * @author Kara Kytle - */ - public class LineUnavailableException extends Exception { + private static final long serialVersionUID = -2046718279487432130L; /** - * Constructs a LineUnavailableException that has - * null as its error detail message. + * Constructs a {@code LineUnavailableException} that has {@code null} as + * its error detail message. */ public LineUnavailableException() { - super(); } /** - * Constructs a LineUnavailableException that has - * the specified detail message. + * Constructs a {@code LineUnavailableException} that has the specified + * detail message. * - * @param message a string containing the error detail message + * @param message a string containing the error detail message */ - public LineUnavailableException(String message) { - + public LineUnavailableException(final String message) { super(message); } } diff --git a/jdk/src/share/classes/javax/sound/sampled/Mixer.java b/jdk/src/share/classes/javax/sound/sampled/Mixer.java index 755ab913342..87784ec62f1 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Mixer.java +++ b/jdk/src/share/classes/javax/sound/sampled/Mixer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,30 +25,27 @@ package javax.sound.sampled; - /** - * A mixer is an audio device with one or more lines. It need not be - * designed for mixing audio signals. A mixer that actually mixes audio - * has multiple input (source) lines and at least one output (target) line. - * The former are often instances of classes that implement - * {@link SourceDataLine}, - * and the latter, {@link TargetDataLine}. {@link Port} - * objects, too, are either source lines or target lines. - * A mixer can accept prerecorded, loopable sound as input, by having - * some of its source lines be instances of objects that implement the - * {@link Clip} interface. + * A mixer is an audio device with one or more lines. It need not be designed + * for mixing audio signals. A mixer that actually mixes audio has multiple + * input (source) lines and at least one output (target) line. The former are + * often instances of classes that implement {@link SourceDataLine}, and the + * latter, {@link TargetDataLine}. {@link Port} objects, too, are either source + * lines or target lines. A mixer can accept prerecorded, loopable sound as + * input, by having some of its source lines be instances of objects that + * implement the {@link Clip} interface. *

- * Through methods of the Line interface, which Mixer extends, - * a mixer might provide a set of controls that are global to the mixer. For example, - * the mixer can have a master gain control. These global controls are distinct - * from the controls belonging to each of the mixer's individual lines. + * Through methods of the {@code Line} interface, which {@code Mixer} extends, a + * mixer might provide a set of controls that are global to the mixer. For + * example, the mixer can have a master gain control. These global controls are + * distinct from the controls belonging to each of the mixer's individual lines. *

- * Some mixers, especially - * those with internal digital mixing capabilities, may provide - * additional capabilities by implementing the DataLine interface. + * Some mixers, especially those with internal digital mixing capabilities, may + * provide additional capabilities by implementing the {@code DataLine} + * interface. *

- * A mixer can support synchronization of its lines. When one line in - * a synchronized group is started or stopped, the other lines in the group + * A mixer can support synchronization of its lines. When one line in a + * synchronized group is started or stopped, the other lines in the group * automatically start or stop simultaneously with the explicitly affected one. * * @author Kara Kytle @@ -59,198 +56,201 @@ public interface Mixer extends Line { /** * Obtains information about this mixer, including the product's name, * version, vendor, etc. + * * @return a mixer info object that describes this mixer * @see Mixer.Info */ - public Info getMixerInfo(); - + Info getMixerInfo(); /** - * Obtains information about the set of source lines supported - * by this mixer. - * Some source lines may only be available when this mixer is open. - * @return array of Line.Info objects representing source lines - * for this mixer. If no source lines are supported, - * an array of length 0 is returned. + * Obtains information about the set of source lines supported by this + * mixer. Some source lines may only be available when this mixer is open. + * + * @return array of {@code Line.Info} objects representing source lines for + * this mixer. If no source lines are supported, an array of length + * 0 is returned. */ - public Line.Info[] getSourceLineInfo(); + Line.Info[] getSourceLineInfo(); /** - * Obtains information about the set of target lines supported - * by this mixer. - * Some target lines may only be available when this mixer is open. - * @return array of Line.Info objects representing target lines - * for this mixer. If no target lines are supported, - * an array of length 0 is returned. + * Obtains information about the set of target lines supported by this + * mixer. Some target lines may only be available when this mixer is open. + * + * @return array of {@code Line.Info} objects representing target lines for + * this mixer. If no target lines are supported, an array of length + * 0 is returned. */ - public Line.Info[] getTargetLineInfo(); - + Line.Info[] getTargetLineInfo(); /** - * Obtains information about source lines of a particular type supported - * by the mixer. - * Some source lines may only be available when this mixer is open. - * @param info a Line.Info object describing lines about which information - * is queried - * @return an array of Line.Info objects describing source lines matching - * the type requested. If no matching source lines are supported, an array of length 0 - * is returned. + * Obtains information about source lines of a particular type supported by + * the mixer. Some source lines may only be available when this mixer is + * open. + * + * @param info a {@code Line.Info} object describing lines about which + * information is queried + * @return an array of {@code Line.Info} objects describing source lines + * matching the type requested. If no matching source lines are + * supported, an array of length 0 is returned. */ - public Line.Info[] getSourceLineInfo(Line.Info info); - + Line.Info[] getSourceLineInfo(Line.Info info); /** - * Obtains information about target lines of a particular type supported - * by the mixer. - * Some target lines may only be available when this mixer is open. - * @param info a Line.Info object describing lines about which information - * is queried - * @return an array of Line.Info objects describing target lines matching - * the type requested. If no matching target lines are supported, an array of length 0 - * is returned. + * Obtains information about target lines of a particular type supported by + * the mixer. Some target lines may only be available when this mixer is + * open. + * + * @param info a {@code Line.Info} object describing lines about which + * information is queried + * @return an array of {@code Line.Info} objects describing target lines + * matching the type requested. If no matching target lines are + * supported, an array of length 0 is returned. */ - public Line.Info[] getTargetLineInfo(Line.Info info); - + Line.Info[] getTargetLineInfo(Line.Info info); /** - * Indicates whether the mixer supports a line (or lines) that match - * the specified Line.Info object. - * Some lines may only be supported when this mixer is open. - * @param info describes the line for which support is queried - * @return true if at least one matching line is - * supported, false otherwise + * Indicates whether the mixer supports a line (or lines) that match the + * specified {@code Line.Info} object. Some lines may only be supported when + * this mixer is open. + * + * @param info describes the line for which support is queried + * @return {@code true} if at least one matching line is supported, + * {@code false} otherwise */ - public boolean isLineSupported(Line.Info info); + boolean isLineSupported(Line.Info info); /** * Obtains a line that is available for use and that matches the description - * in the specified Line.Info object. + * in the specified {@code Line.Info} object. + *

+ * If a {@code DataLine} is requested, and {@code info} is an instance of + * {@code DataLine.Info} specifying at least one fully qualified audio + * format, the last one will be used as the default format of the returned + * {@code DataLine}. * - *

If a DataLine is requested, and info - * is an instance of DataLine.Info specifying at - * least one fully qualified audio format, the last one - * will be used as the default format of the returned - * DataLine. - * - * @param info describes the desired line + * @param info describes the desired line * @return a line that is available for use and that matches the description - * in the specified {@code Line.Info} object - * @throws LineUnavailableException if a matching line - * is not available due to resource restrictions - * @throws IllegalArgumentException if this mixer does - * not support any lines matching the description - * @throws SecurityException if a matching line - * is not available due to security restrictions + * in the specified {@code Line.Info} object + * @throws LineUnavailableException if a matching line is not available due + * to resource restrictions + * @throws IllegalArgumentException if this mixer does not support any lines + * matching the description + * @throws SecurityException if a matching line is not available due to + * security restrictions */ - public Line getLine(Line.Info info) throws LineUnavailableException; + Line getLine(Line.Info info) throws LineUnavailableException; //$$fb 2002-04-12: fix for 4667258: behavior of Mixer.getMaxLines(Line.Info) method doesn't match the spec /** - * Obtains the approximate maximum number of lines of the requested type that can be open - * simultaneously on the mixer. + * Obtains the approximate maximum number of lines of the requested type + * that can be open simultaneously on the mixer. * - * Certain types of mixers do not have a hard bound and may allow opening more lines. - * Since certain lines are a shared resource, a mixer may not be able to open the maximum - * number of lines if another process has opened lines of this mixer. + * Certain types of mixers do not have a hard bound and may allow opening + * more lines. Since certain lines are a shared resource, a mixer may not be + * able to open the maximum number of lines if another process has opened + * lines of this mixer. * - * The requested type is any line that matches the description in - * the provided Line.Info object. For example, if the info - * object represents a speaker - * port, and the mixer supports exactly one speaker port, this method - * should return 1. If the info object represents a source data line - * and the mixer supports the use of 32 source data lines simultaneously, - * the return value should be 32. - * If there is no limit, this function returns AudioSystem.NOT_SPECIFIED. - * @param info a Line.Info that describes the line for which - * the number of supported instances is queried - * @return the maximum number of matching lines supported, or AudioSystem.NOT_SPECIFIED + * The requested type is any line that matches the description in the + * provided {@code Line.Info} object. For example, if the info object + * represents a speaker port, and the mixer supports exactly one speaker + * port, this method should return 1. If the info object represents a + * source data line and the mixer supports the use of 32 source data lines + * simultaneously, the return value should be 32. If there is no limit, this + * function returns {@code AudioSystem.NOT_SPECIFIED}. + * + * @param info a {@code Line.Info} that describes the line for which the + * number of supported instances is queried + * @return the maximum number of matching lines supported, or + * {@code AudioSystem.NOT_SPECIFIED} */ - public int getMaxLines(Line.Info info); - + int getMaxLines(Line.Info info); /** * Obtains the set of all source lines currently open to this mixer. * - * @return the source lines currently open to the mixer. - * If no source lines are currently open to this mixer, an - * array of length 0 is returned. - * @throws SecurityException if the matching lines - * are not available due to security restrictions + * @return the source lines currently open to the mixer. If no source lines + * are currently open to this mixer, an array of length 0 is + * returned. + * @throws SecurityException if the matching lines are not available due to + * security restrictions */ - public Line[] getSourceLines(); + Line[] getSourceLines(); /** * Obtains the set of all target lines currently open from this mixer. * - * @return target lines currently open from the mixer. - * If no target lines are currently open from this mixer, an - * array of length 0 is returned. - * @throws SecurityException if the matching lines - * are not available due to security restrictions + * @return target lines currently open from the mixer. If no target lines + * are currently open from this mixer, an array of length 0 is + * returned. + * @throws SecurityException if the matching lines are not available due to + * security restrictions */ - public Line[] getTargetLines(); + Line[] getTargetLines(); /** - * Synchronizes two or more lines. Any subsequent command that starts or stops - * audio playback or capture for one of these lines will exert the - * same effect on the other lines in the group, so that they start or stop playing or - * capturing data simultaneously. - * - * @param lines the lines that should be synchronized - * @param maintainSync true if the synchronization - * must be precisely maintained (i.e., the synchronization must be sample-accurate) - * at all times during operation of the lines , or false - * if precise synchronization is required only during start and stop operations + * Synchronizes two or more lines. Any subsequent command that starts or + * stops audio playback or capture for one of these lines will exert the + * same effect on the other lines in the group, so that they start or stop + * playing or capturing data simultaneously. * + * @param lines the lines that should be synchronized + * @param maintainSync {@code true} if the synchronization must be + * precisely maintained (i.e., the synchronization must be + * sample-accurate) at all times during operation of the lines, or + * {@code false} if precise synchronization is required only during + * start and stop operations * @throws IllegalArgumentException if the lines cannot be synchronized. - * This may occur if the lines are of different types or have different - * formats for which this mixer does not support synchronization, or if - * all lines specified do not belong to this mixer. + * This may occur if the lines are of different types or have + * different formats for which this mixer does not support + * synchronization, or if all lines specified do not belong to this + * mixer. */ - public void synchronize(Line[] lines, boolean maintainSync); + void synchronize(Line[] lines, boolean maintainSync); /** - * Releases synchronization for the specified lines. The array must - * be identical to one for which synchronization has already been - * established; otherwise an exception may be thrown. However, null - * may be specified, in which case all currently synchronized lines that belong - * to this mixer are unsynchronized. - * @param lines the synchronized lines for which synchronization should be - * released, or null for all this mixer's synchronized lines + * Releases synchronization for the specified lines. The array must be + * identical to one for which synchronization has already been established; + * otherwise an exception may be thrown. However, {@code null} may be + * specified, in which case all currently synchronized lines that belong to + * this mixer are unsynchronized. * + * @param lines the synchronized lines for which synchronization should be + * released, or {@code null} for all this mixer's synchronized + * lines * @throws IllegalArgumentException if the lines cannot be unsynchronized. - * This may occur if the argument specified does not exactly match a set - * of lines for which synchronization has already been established. + * This may occur if the argument specified does not exactly match + * a set of lines for which synchronization has already been + * established. */ - public void unsynchronize(Line[] lines); - + void unsynchronize(Line[] lines); /** - * Reports whether this mixer supports synchronization of the specified set of lines. + * Reports whether this mixer supports synchronization of the specified set + * of lines. * - * @param lines the set of lines for which synchronization support is queried - * @param maintainSync true if the synchronization - * must be precisely maintained (i.e., the synchronization must be sample-accurate) - * at all times during operation of the lines , or false - * if precise synchronization is required only during start and stop operations - * - * @return true if the lines can be synchronized, false - * otherwise + * @param lines the set of lines for which synchronization support is + * queried + * @param maintainSync {@code true} if the synchronization must be + * precisely maintained (i.e., the synchronization must be + * sample-accurate) at all times during operation of the lines, or + * {@code false} if precise synchronization is required only during + * start and stop operations + * @return {@code true} if the lines can be synchronized, {@code false} + * otherwise */ - public boolean isSynchronizationSupported(Line[] lines, boolean maintainSync); - + boolean isSynchronizationSupported(Line[] lines, boolean maintainSync); /** - * The Mixer.Info class represents information about an audio mixer, + * The {@code Mixer.Info} class represents information about an audio mixer, * including the product's name, version, and vendor, along with a textual - * description. This information may be retrieved through the - * {@link Mixer#getMixerInfo() getMixerInfo} - * method of the Mixer interface. + * description. This information may be retrieved through the + * {@link Mixer#getMixerInfo() getMixerInfo} method of the {@code Mixer} + * interface. * * @author Kara Kytle * @since 1.3 */ - public static class Info { + class Info { /** * Mixer name. @@ -273,13 +273,14 @@ public interface Mixer extends Line { private final String version; /** - * Constructs a mixer's info object, passing it the given - * textual information. - * @param name the name of the mixer - * @param vendor the company who manufactures or creates the hardware - * or software mixer - * @param description descriptive text about the mixer - * @param version version information for the mixer + * Constructs a mixer's info object, passing it the given textual + * information. + * + * @param name the name of the mixer + * @param vendor the company who manufactures or creates the + * hardware or software mixer + * @param description descriptive text about the mixer + * @param version version information for the mixer */ protected Info(String name, String vendor, String description, String version) { @@ -289,15 +290,16 @@ public interface Mixer extends Line { this.version = version; } - /** - * Indicates whether two info objects are equal, returning true if - * they are identical. - * @param obj the reference object with which to compare this info - * object - * @return true if this info object is the same as the - * obj argument; false otherwise + * Indicates whether two info objects are equal, returning {@code true} + * if they are identical. + * + * @param obj the reference object with which to compare this info + * object + * @return {@code true} if this info object is the same as the + * {@code obj} argument; {@code false} otherwise */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } @@ -307,12 +309,14 @@ public interface Mixer extends Line { * * @return the hashcode for this object */ + @Override public final int hashCode() { return super.hashCode(); } /** * Obtains the name of the mixer. + * * @return a string that names the mixer */ public final String getName() { @@ -321,6 +325,7 @@ public interface Mixer extends Line { /** * Obtains the vendor of the mixer. + * * @return a string that names the mixer's vendor */ public final String getVendor() { @@ -329,6 +334,7 @@ public interface Mixer extends Line { /** * Obtains the description of the mixer. + * * @return a textual description of the mixer */ public final String getDescription() { @@ -337,6 +343,7 @@ public interface Mixer extends Line { /** * Obtains the version of the mixer. + * * @return textual version information for the mixer */ public final String getVersion() { @@ -345,10 +352,12 @@ public interface Mixer extends Line { /** * Provides a string representation of the mixer info. + * * @return a string describing the info object */ + @Override public final String toString() { return (name + ", version " + version); } - } // class Info + } } diff --git a/jdk/src/share/classes/javax/sound/sampled/Port.java b/jdk/src/share/classes/javax/sound/sampled/Port.java index 04b67a8fa3e..61f40c761a5 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Port.java +++ b/jdk/src/share/classes/javax/sound/sampled/Port.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,41 +25,36 @@ package javax.sound.sampled; - /** * Ports are simple lines for input or output of audio to or from audio devices. - * Common examples of ports that act as source lines (mixer inputs) include the microphone, - * line input, and CD-ROM drive. Ports that act as target lines (mixer outputs) include the - * speaker, headphone, and line output. You can access port using a {@link Port.Info} - * object. + * Common examples of ports that act as source lines (mixer inputs) include the + * microphone, line input, and CD-ROM drive. Ports that act as target lines + * (mixer outputs) include the speaker, headphone, and line output. You can + * access port using a {@link Port.Info} object. * * @author Kara Kytle * @since 1.3 */ public interface Port extends Line { - - // INNER CLASSES - - /** - * The Port.Info class extends {@link Line.Info} - * with additional information specific to ports, including the port's name - * and whether it is a source or a target for its mixer. - * By definition, a port acts as either a source or a target to its mixer, - * but not both. (Audio input ports are sources; audio output ports are targets.) + * The {@code Port.Info} class extends {@code Line.Info} with additional + * information specific to ports, including the port's name and whether it + * is a source or a target for its mixer. By definition, a port acts as + * either a source or a target to its mixer, but not both. (Audio input + * ports are sources; audio output ports are targets.) *

- * To learn what ports are available, you can retrieve port info objects through the - * {@link Mixer#getSourceLineInfo getSourceLineInfo} and - * {@link Mixer#getTargetLineInfo getTargetLineInfo} - * methods of the Mixer interface. Instances of the - * Port.Info class may also be constructed and used to obtain - * lines matching the parameters specified in the Port.Info object. + * To learn what ports are available, you can retrieve port info objects + * through the {@link Mixer#getSourceLineInfo getSourceLineInfo} and + * {@link Mixer#getTargetLineInfo getTargetLineInfo} methods of the + * {@code Mixer} interface. Instances of the {@code Port.Info} class may + * also be constructed and used to obtain lines matching the parameters + * specified in the {@code Port.Info} object. * * @author Kara Kytle * @since 1.3 */ - public static class Info extends Line.Info { + class Info extends Line.Info { // AUDIO PORT TYPE DEFINES @@ -68,7 +63,8 @@ public interface Port extends Line { // SOURCE PORTS /** - * A type of port that gets audio from a built-in microphone or a microphone jack. + * A type of port that gets audio from a built-in microphone or a + * microphone jack. */ public static final Info MICROPHONE = new Info(Port.class,"MICROPHONE", true); @@ -86,7 +82,8 @@ public interface Port extends Line { // TARGET PORTS /** - * A type of port that sends audio to a built-in speaker or a speaker jack. + * A type of port that sends audio to a built-in speaker or a speaker + * jack. */ public static final Info SPEAKER = new Info(Port.class,"SPEAKER", false); @@ -113,19 +110,16 @@ public interface Port extends Line { private String name; private boolean isSource; - - // CONSTRUCTOR - /** - * Constructs a port's info object from the information given. - * This constructor is typically used by an implementation - * of Java Sound to describe a supported line. + * Constructs a port's info object from the information given. This + * constructor is typically used by an implementation of Java Sound to + * describe a supported line. * - * @param lineClass the class of the port described by the info object. - * @param name the string that names the port - * @param isSource true if the port is a source port (such - * as a microphone), false if the port is a target port - * (such as a speaker). + * @param lineClass the class of the port described by the info object + * @param name the string that names the port + * @param isSource {@code true} if the port is a source port (such as a + * microphone), {@code false} if the port is a target port + * (such as a speaker) */ public Info(Class lineClass, String name, boolean isSource) { @@ -134,11 +128,9 @@ public interface Port extends Line { this.isSource = isSource; } - - // METHODS - /** * Obtains the name of the port. + * * @return the string that names the port */ public String getName() { @@ -147,20 +139,23 @@ public interface Port extends Line { /** * Indicates whether the port is a source or a target for its mixer. - * @return true if the port is a source port (such - * as a microphone), false if the port is a target port - * (such as a speaker). + * + * @return {@code true} if the port is a source port (such as a + * microphone), {@code false} if the port is a target port + * (such as a speaker) */ public boolean isSource() { return isSource; } /** - * Indicates whether this info object specified matches this one. - * To match, the match requirements of the superclass must be - * met and the types must be equal. - * @param info the info object for which the match is queried + * Indicates whether this info object specified matches this one. To + * match, the match requirements of the superclass must be met and the + * types must be equal. + * + * @param info the info object for which the match is queried */ + @Override public boolean matches(Line.Info info) { if (! (super.matches(info)) ) { @@ -178,31 +173,30 @@ public interface Port extends Line { return true; } - /** - * Finalizes the equals method + * Finalizes the equals method. */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } /** - * Finalizes the hashCode method + * Finalizes the hashCode method. */ + @Override public final int hashCode() { return super.hashCode(); } - - /** - * Provides a String representation - * of the port. - * @return a string that describes the port + * Provides a {@code String} representation of the port. + * + * @return a string that describes the port */ + @Override public final String toString() { return (name + ((isSource == true) ? " source" : " target") + " port"); } - - } // class Info + } } diff --git a/jdk/src/share/classes/javax/sound/sampled/ReverbType.java b/jdk/src/share/classes/javax/sound/sampled/ReverbType.java index 7afd7aefe56..e308b0f9402 100644 --- a/jdk/src/share/classes/javax/sound/sampled/ReverbType.java +++ b/jdk/src/share/classes/javax/sound/sampled/ReverbType.java @@ -25,46 +25,41 @@ package javax.sound.sampled; - /** - * The ReverbType class provides methods for - * accessing various reverberation settings to be applied to - * an audio signal. + * The {@code ReverbType} class provides methods for accessing various + * reverberation settings to be applied to an audio signal. *

- * Reverberation simulates the reflection of sound off of - * the walls, ceiling, and floor of a room. Depending on - * the size of the room, and how absorbent or reflective the materials in the - * room's surfaces are, the sound might bounce around for a - * long time before dying away. + * Reverberation simulates the reflection of sound off of the walls, ceiling, + * and floor of a room. Depending on the size of the room, and how absorbent or + * reflective the materials in the room's surfaces are, the sound might bounce + * around for a long time before dying away. *

- * The reverberation parameters provided by ReverbType consist - * of the delay time and intensity of early reflections, the delay time and - * intensity of late reflections, and an overall decay time. - * Early reflections are the initial individual low-order reflections of the - * direct signal off the surfaces in the room. - * The late Reflections are the dense, high-order reflections that characterize - * the room's reverberation. - * The delay times for the start of these two reflection types give the listener - * a sense of the overall size and complexity of the room's shape and contents. - * The larger the room, the longer the reflection delay times. - * The early and late reflections' intensities define the gain (in decibels) of the reflected - * signals as compared to the direct signal. These intensities give the - * listener an impression of the absorptive nature of the surfaces and objects - * in the room. + * The reverberation parameters provided by {@code ReverbType} consist of the + * delay time and intensity of early reflections, the delay time and intensity + * of late reflections, and an overall decay time. Early reflections are the + * initial individual low-order reflections of the direct signal off the + * surfaces in the room. The late Reflections are the dense, high-order + * reflections that characterize the room's reverberation. The delay times for + * the start of these two reflection types give the listener a sense of the + * overall size and complexity of the room's shape and contents. The larger the + * room, the longer the reflection delay times. The early and late reflections' + * intensities define the gain (in decibels) of the reflected signals as + * compared to the direct signal. These intensities give the listener an + * impression of the absorptive nature of the surfaces and objects in the room. * The decay time defines how long the reverberation takes to exponentially - * decay until it is no longer perceptible ("effective zero"). - * The larger and less absorbent the surfaces, the longer the decay time. + * decay until it is no longer perceptible ("effective zero"). The larger and + * less absorbent the surfaces, the longer the decay time. *

- * The set of parameters defined here may not include all aspects of reverberation - * as specified by some systems. For example, the Midi Manufacturer's Association - * (MMA) has an Interactive Audio Special Interest Group (IASIG), which has a - * 3-D Working Group that has defined a Level 2 Spec (I3DL2). I3DL2 - * supports filtering of reverberation and - * control of reverb density. These properties are not included in the JavaSound 1.0 - * definition of a reverb control. In such a case, the implementing system - * should either extend the defined reverb control to include additional - * parameters, or else interpret the system's additional capabilities in a way that fits - * the model described here. + * The set of parameters defined here may not include all aspects of + * reverberation as specified by some systems. For example, the Midi + * Manufacturer's Association (MMA) has an Interactive Audio Special Interest + * Group (IASIG), which has a 3-D Working Group that has defined a Level 2 Spec + * (I3DL2). I3DL2 supports filtering of reverberation and control of reverb + * density. These properties are not included in the JavaSound 1.0 definition of + * a reverb control. In such a case, the implementing system should either + * extend the defined reverb control to include additional parameters, or else + * interpret the system's additional capabilities in a way that fits the model + * described here. *

* If implementing JavaSound on a I3DL2-compliant device: *

    @@ -72,8 +67,8 @@ package javax.sound.sampled; *
  • Density parameters are set to midway between minimum and maximum *
*

- * The following table shows what parameter values an implementation might use for a - * representative set of reverberation settings. + * The following table shows what parameter values an implementation might use + * for a representative set of reverberation settings. *

* * Reverberation Types and Parameters @@ -142,7 +137,7 @@ package javax.sound.sampled; public class ReverbType { /** - * Descriptive name of the reverb type.. + * Descriptive name of the reverb type. */ private String name; @@ -167,20 +162,25 @@ public class ReverbType { private float lateReflectionIntensity; /** - * Total decay time + * Total decay time. */ private int decayTime; - /** * Constructs a new reverb type that has the specified reverberation * parameter values. - * @param name the name of the new reverb type, or a zero-length String - * @param earlyReflectionDelay the new type's early reflection delay time in microseconds - * @param earlyReflectionIntensity the new type's early reflection intensity in dB - * @param lateReflectionDelay the new type's late reflection delay time in microseconds - * @param lateReflectionIntensity the new type's late reflection intensity in dB - * @param decayTime the new type's decay time in microseconds + * + * @param name the name of the new reverb type, or a zero-length + * {@code String} + * @param earlyReflectionDelay the new type's early reflection delay time + * in microseconds + * @param earlyReflectionIntensity the new type's early reflection + * intensity in dB + * @param lateReflectionDelay the new type's late reflection delay time in + * microseconds + * @param lateReflectionIntensity the new type's late reflection intensity + * in dB + * @param decayTime the new type's decay time in microseconds */ protected ReverbType(String name, int earlyReflectionDelay, float earlyReflectionIntensity, int lateReflectionDelay, float lateReflectionIntensity, int decayTime) { @@ -192,9 +192,9 @@ public class ReverbType { this.decayTime = decayTime; } - /** * Obtains the name of this reverb type. + * * @return the name of this reverb type * @since 1.5 */ @@ -202,89 +202,88 @@ public class ReverbType { return name; } - /** - * Returns the early reflection delay time in microseconds. - * This is the amount of time between when the direct signal is - * heard and when the first early reflections are heard. - * @return early reflection delay time for this reverb type, in microseconds + * Returns the early reflection delay time in microseconds. This is the + * amount of time between when the direct signal is heard and when the first + * early reflections are heard. + * + * @return early reflection delay time for this reverb type, in microseconds */ public final int getEarlyReflectionDelay() { return earlyReflectionDelay; } - /** - * Returns the early reflection intensity in decibels. - * This is the amplitude attenuation of the first early reflections - * relative to the direct signal. - * @return early reflection intensity for this reverb type, in dB + * Returns the early reflection intensity in decibels. This is the amplitude + * attenuation of the first early reflections relative to the direct signal. + * + * @return early reflection intensity for this reverb type, in dB */ public final float getEarlyReflectionIntensity() { return earlyReflectionIntensity; } - /** - * Returns the late reflection delay time in microseconds. - * This is the amount of time between when the first early reflections - * are heard and when the first late reflections are heard. - * @return late reflection delay time for this reverb type, in microseconds + * Returns the late reflection delay time in microseconds. This is the + * amount of time between when the first early reflections are heard and + * when the first late reflections are heard. + * + * @return late reflection delay time for this reverb type, in microseconds */ public final int getLateReflectionDelay() { return lateReflectionDelay; } - /** - * Returns the late reflection intensity in decibels. - * This is the amplitude attenuation of the first late reflections - * relative to the direct signal. - * @return late reflection intensity for this reverb type, in dB + * Returns the late reflection intensity in decibels. This is the amplitude + * attenuation of the first late reflections relative to the direct signal. + * + * @return late reflection intensity for this reverb type, in dB */ public final float getLateReflectionIntensity() { return lateReflectionIntensity; } - /** - * Obtains the decay time, which is the amount of time over which the - * late reflections attenuate to effective zero. The effective zero - * value is implementation-dependent. - * @return the decay time of the late reflections, in microseconds + * Obtains the decay time, which is the amount of time over which the late + * reflections attenuate to effective zero. The effective zero value is + * implementation-dependent. + * + * @return the decay time of the late reflections, in microseconds */ public final int getDecayTime() { return decayTime; } - /** * Indicates whether the specified object is equal to this reverb type, - * returning true if the objects are identical. - * @param obj the reference object with which to compare - * @return true if this reverb type is the same as - * obj; false otherwise + * returning {@code true} if the objects are identical. + * + * @param obj the reference object with which to compare + * @return {@code true} if this reverb type is the same as {@code obj}; + * {@code false} otherwise */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } - /** * Finalizes the hashcode method. */ + @Override public final int hashCode() { return super.hashCode(); } - /** - * Provides a String representation of the reverb type, - * including its name and its parameter settings. - * The exact contents of the string may vary between implementations of - * Java Sound. + * Provides a {@code String} representation of the reverb type, including + * its name and its parameter settings. The exact contents of the string may + * vary between implementations of Java Sound. + * * @return reverberation type name and description */ + @Override public final String toString() { //$$fb2001-07-20: fix for bug 4385060: The "name" attribute of class "ReverbType" is not accessible. @@ -295,5 +294,4 @@ public class ReverbType { " ns, late reflection intensity " + lateReflectionIntensity + " dB, decay time " + decayTime); } - -} // class ReverbType +} diff --git a/jdk/src/share/classes/javax/sound/sampled/SourceDataLine.java b/jdk/src/share/classes/javax/sound/sampled/SourceDataLine.java index 5cfbccf2ccd..7749b3a86fc 100644 --- a/jdk/src/share/classes/javax/sound/sampled/SourceDataLine.java +++ b/jdk/src/share/classes/javax/sound/sampled/SourceDataLine.java @@ -25,36 +25,35 @@ package javax.sound.sampled; - /** - * A source data line is a data line to which data may be written. It acts as - * a source to its mixer. An application writes audio bytes to a source data line, - * which handles the buffering of the bytes and delivers them to the mixer. - * The mixer may mix the samples with those from other sources and then deliver - * the mix to a target such as an output port (which may represent an audio output + * A source data line is a data line to which data may be written. It acts as a + * source to its mixer. An application writes audio bytes to a source data line, + * which handles the buffering of the bytes and delivers them to the mixer. The + * mixer may mix the samples with those from other sources and then deliver the + * mix to a target such as an output port (which may represent an audio output * device on a sound card). *

* Note that the naming convention for this interface reflects the relationship - * between the line and its mixer. From the perspective of an application, - * a source data line may act as a target for audio data. + * between the line and its mixer. From the perspective of an application, a + * source data line may act as a target for audio data. *

* A source data line can be obtained from a mixer by invoking the - * {@link Mixer#getLine getLine} method of Mixer with - * an appropriate {@link DataLine.Info} object. + * {@link Mixer#getLine getLine} method of {@code Mixer} with an appropriate + * {@link DataLine.Info} object. *

- * The SourceDataLine interface provides a method for writing - * audio data to the data line's buffer. Applications that play or mix - * audio should write data to the source data line quickly enough to keep the - * buffer from underflowing (emptying), which could cause discontinuities in - * the audio that are perceived as clicks. Applications can use the - * {@link DataLine#available available} method defined in the - * DataLine interface to determine the amount of data currently - * queued in the data line's buffer. The amount of data which can be written - * to the buffer without blocking is the difference between the buffer size - * and the amount of queued data. If the delivery of audio output - * stops due to underflow, a {@link LineEvent.Type#STOP STOP} event is - * generated. A {@link LineEvent.Type#START START} event is generated - * when the audio output resumes. + * The {@code SourceDataLine} interface provides a method for writing audio data + * to the data line's buffer. Applications that play or mix audio should write + * data to the source data line quickly enough to keep the buffer from + * underflowing (emptying), which could cause discontinuities in the audio that + * are perceived as clicks. Applications can use the + * {@link DataLine#available available} method defined in the {@code DataLine} + * interface to determine the amount of data currently queued in the data line's + * buffer. The amount of data which can be written to the buffer without + * blocking is the difference between the buffer size and the amount of queued + * data. If the delivery of audio output stops due to underflow, a + * {@link LineEvent.Type#STOP STOP} event is generated. A + * {@link LineEvent.Type#START START} event is generated when the audio output + * resumes. * * @author Kara Kytle * @see Mixer @@ -64,138 +63,130 @@ package javax.sound.sampled; */ public interface SourceDataLine extends DataLine { - /** * Opens the line with the specified format and suggested buffer size, - * causing the line to acquire any required - * system resources and become operational. + * causing the line to acquire any required system resources and become + * operational. *

* The buffer size is specified in bytes, but must represent an integral - * number of sample frames. Invoking this method with a requested buffer + * number of sample frames. Invoking this method with a requested buffer * size that does not meet this requirement may result in an - * IllegalArgumentException. The actual buffer size for the open line may - * differ from the requested buffer size. The value actually set may be - * queried by subsequently calling {@link DataLine#getBufferSize}. + * {@code IllegalArgumentException}. The actual buffer size for the open + * line may differ from the requested buffer size. The value actually set + * may be queried by subsequently calling {@link DataLine#getBufferSize}. *

* If this operation succeeds, the line is marked as open, and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the - * line's listeners. + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

- * Invoking this method on a line which is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line which is already open is illegal and may + * result in an {@code IllegalStateException}. *

- * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * LineUnavailableException. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in a {@code LineUnavailableException}. * - * @param format the desired audio format - * @param bufferSize the desired buffer size - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if the buffer size does not represent - * an integral number of sample frames, - * or if format is not fully specified or invalid + * @param format the desired audio format + * @param bufferSize the desired buffer size + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if the buffer size does not represent an + * integral number of sample frames, or if {@code format} is not + * fully specified or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #open(AudioFormat) * @see Line#open * @see Line#close * @see Line#isOpen * @see LineEvent */ - public void open(AudioFormat format, int bufferSize) throws LineUnavailableException; - + void open(AudioFormat format, int bufferSize) + throws LineUnavailableException; /** * Opens the line with the specified format, causing the line to acquire any * required system resources and become operational. - * *

* The implementation chooses a buffer size, which is measured in bytes but - * which encompasses an integral number of sample frames. The buffer size + * which encompasses an integral number of sample frames. The buffer size * that the system has chosen may be queried by subsequently calling - * {@link DataLine#getBufferSize}. + * {@link DataLine#getBufferSize}. *

* If this operation succeeds, the line is marked as open, and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the - * line's listeners. + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

- * Invoking this method on a line which is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line which is already open is illegal and may + * result in an {@code IllegalStateException}. *

- * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * LineUnavailableException. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in a {@code LineUnavailableException}. * - * @param format the desired audio format - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if format - * is not fully specified or invalid + * @param format the desired audio format + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if {@code format} is not fully specified + * or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #open(AudioFormat, int) * @see Line#open * @see Line#close * @see Line#isOpen * @see LineEvent */ - public void open(AudioFormat format) throws LineUnavailableException; - + void open(AudioFormat format) throws LineUnavailableException; /** - * Writes audio data to the mixer via this source data line. The requested - * number of bytes of data are read from the specified array, - * starting at the given offset into the array, and written to the data - * line's buffer. If the caller attempts to write more data than can - * currently be written (see {@link DataLine#available available}), - * this method blocks until the requested amount of data has been written. - * This applies even if the requested amount of data to write is greater - * than the data line's buffer size. However, if the data line is closed, - * stopped, or flushed before the requested amount has been written, - * the method no longer blocks, but returns the number of bytes - * written thus far. + * Writes audio data to the mixer via this source data line. The requested + * number of bytes of data are read from the specified array, starting at + * the given offset into the array, and written to the data line's buffer. + * If the caller attempts to write more data than can currently be written + * (see {@link DataLine#available available}), this method blocks until the + * requested amount of data has been written. This applies even if the + * requested amount of data to write is greater than the data line's buffer + * size. However, if the data line is closed, stopped, or flushed before the + * requested amount has been written, the method no longer blocks, but + * returns the number of bytes written thus far. *

- * The number of bytes that can be written without blocking can be ascertained - * using the {@link DataLine#available available} method of the - * DataLine interface. (While it is guaranteed that - * this number of bytes can be written without blocking, there is no guarantee - * that attempts to write additional data will block.) + * The number of bytes that can be written without blocking can be + * ascertained using the {@link DataLine#available available} method of the + * {@code DataLine} interface. (While it is guaranteed that this number of + * bytes can be written without blocking, there is no guarantee that + * attempts to write additional data will block.) *

- * The number of bytes to write must represent an integral number of - * sample frames, such that: + * The number of bytes to write must represent an integral number of sample + * frames, such that: *
- *

[ bytes written ] % [frame size in bytes ] == 0
+ *
{@code [ bytes written ] % [frame size in bytes ] == 0}
*
- * The return value will always meet this requirement. A request to write a - * number of bytes representing a non-integral number of sample frames cannot - * be fulfilled and may result in an IllegalArgumentException. + * The return value will always meet this requirement. A request to write a + * number of bytes representing a non-integral number of sample frames + * cannot be fulfilled and may result in an + * {@code IllegalArgumentException}. * - * @param b a byte array containing data to be written to the data line - * @param len the length, in bytes, of the valid data in the array - * (in other words, the requested amount of data to write, in bytes) - * @param off the offset from the beginning of the array, in bytes + * @param b a byte array containing data to be written to the data line + * @param len the length, in bytes, of the valid data in the array (in + * other words, the requested amount of data to write, in bytes) + * @param off the offset from the beginning of the array, in bytes * @return the number of bytes actually written * @throws IllegalArgumentException if the requested number of bytes does - * not represent an integral number of sample frames, - * or if len is negative - * @throws ArrayIndexOutOfBoundsException if off is negative, - * or off+len is greater than the length of the array - * b. - * + * not represent an integral number of sample frames, or if + * {@code len} is negative + * @throws ArrayIndexOutOfBoundsException if {@code off} is negative, or + * {@code off+len} is greater than the length of the array {@code b} * @see TargetDataLine#read * @see DataLine#available */ - public int write(byte[] b, int off, int len); + int write(byte[] b, int off, int len); /** * Obtains the number of sample frames of audio data that can be written to - * the mixer, via this data line, without blocking. Note that the return + * the mixer, via this data line, without blocking. Note that the return * value measures sample frames, not bytes. + * * @return the number of sample frames currently available for writing * @see TargetDataLine#availableRead */ diff --git a/jdk/src/share/classes/javax/sound/sampled/TargetDataLine.java b/jdk/src/share/classes/javax/sound/sampled/TargetDataLine.java index a6f14269240..acacdbcccae 100644 --- a/jdk/src/share/classes/javax/sound/sampled/TargetDataLine.java +++ b/jdk/src/share/classes/javax/sound/sampled/TargetDataLine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,29 +26,28 @@ package javax.sound.sampled; /** - * A target data line is a type of {@link DataLine} from which - * audio data can be read. The most common example is a data line that gets - * its data from an audio capture device. (The device is implemented as a - * mixer that writes to the target data line.) + * A target data line is a type of {@link DataLine} from which audio data can be + * read. The most common example is a data line that gets its data from an audio + * capture device. (The device is implemented as a mixer that writes to the + * target data line.) *

* Note that the naming convention for this interface reflects the relationship - * between the line and its mixer. From the perspective of an application, - * a target data line may act as a source for audio data. + * between the line and its mixer. From the perspective of an application, a + * target data line may act as a source for audio data. *

* The target data line can be obtained from a mixer by invoking the - * {@link Mixer#getLine getLine} - * method of Mixer with an appropriate - * {@link DataLine.Info} object. + * {@link Mixer#getLine getLine} method of {@code Mixer} with an appropriate + * {@link DataLine.Info} object. *

- * The TargetDataLine interface provides a method for reading the - * captured data from the target data line's buffer.Applications - * that record audio should read data from the target data line quickly enough - * to keep the buffer from overflowing, which could cause discontinuities in - * the captured data that are perceived as clicks. Applications can use the - * {@link DataLine#available available} method defined in the - * DataLine interface to determine the amount of data currently - * queued in the data line's buffer. If the buffer does overflow, - * the oldest queued data is discarded and replaced by new data. + * The {@code TargetDataLine} interface provides a method for reading the + * captured data from the target data line's buffer. Applications that record + * audio should read data from the target data line quickly enough to keep the + * buffer from overflowing, which could cause discontinuities in the captured + * data that are perceived as clicks. Applications can use the + * {@link DataLine#available available} method defined in the {@code DataLine} + * interface to determine the amount of data currently queued in the data line's + * buffer. If the buffer does overflow, the oldest queued data is discarded and + * replaced by new data. * * @author Kara Kytle * @see Mixer @@ -58,133 +57,126 @@ package javax.sound.sampled; */ public interface TargetDataLine extends DataLine { - /** * Opens the line with the specified format and requested buffer size, * causing the line to acquire any required system resources and become * operational. *

* The buffer size is specified in bytes, but must represent an integral - * number of sample frames. Invoking this method with a requested buffer + * number of sample frames. Invoking this method with a requested buffer * size that does not meet this requirement may result in an - * IllegalArgumentException. The actual buffer size for the open line may - * differ from the requested buffer size. The value actually set may be - * queried by subsequently calling {@link DataLine#getBufferSize} + * {@code IllegalArgumentException}. The actual buffer size for the open + * line may differ from the requested buffer size. The value actually set + * may be queried by subsequently calling {@link DataLine#getBufferSize} *

* If this operation succeeds, the line is marked as open, and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the - * line's listeners. + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

- * Invoking this method on a line that is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line that is already open is illegal and may + * result in an {@code IllegalStateException}. *

- * Some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * LineUnavailableException. + * Some lines, once closed, cannot be reopened. Attempts to reopen such a + * line will always result in a {@code LineUnavailableException}. * - * @param format the desired audio format - * @param bufferSize the desired buffer size, in bytes. - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if the buffer size does not represent - * an integral number of sample frames, - * or if format is not fully specified or invalid + * @param format the desired audio format + * @param bufferSize the desired buffer size, in bytes + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if the buffer size does not represent an + * integral number of sample frames, or if {@code format} is not + * fully specified or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #open(AudioFormat) * @see Line#open * @see Line#close * @see Line#isOpen * @see LineEvent */ - public void open(AudioFormat format, int bufferSize) throws LineUnavailableException; - + void open(AudioFormat format, int bufferSize) throws LineUnavailableException; /** * Opens the line with the specified format, causing the line to acquire any * required system resources and become operational. - * *

* The implementation chooses a buffer size, which is measured in bytes but - * which encompasses an integral number of sample frames. The buffer size - * that the system has chosen may be queried by subsequently calling {@link DataLine#getBufferSize} + * which encompasses an integral number of sample frames. The buffer size + * that the system has chosen may be queried by subsequently calling + * {@link DataLine#getBufferSize} *

* If this operation succeeds, the line is marked as open, and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the - * line's listeners. + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

- * Invoking this method on a line that is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line that is already open is illegal and may + * result in an {@code IllegalStateException}. *

- * Some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * LineUnavailableException. + * Some lines, once closed, cannot be reopened. Attempts to reopen such a + * line will always result in a {@code LineUnavailableException}. * - * @param format the desired audio format - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if format - * is not fully specified or invalid + * @param format the desired audio format + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if {@code format} is not fully specified + * or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #open(AudioFormat, int) * @see Line#open * @see Line#close * @see Line#isOpen * @see LineEvent */ - public void open(AudioFormat format) throws LineUnavailableException; - + void open(AudioFormat format) throws LineUnavailableException; /** - * Reads audio data from the data line's input buffer. The requested - * number of bytes is read into the specified array, starting at - * the specified offset into the array in bytes. This method blocks until - * the requested amount of data has been read. However, if the data line - * is closed, stopped, drained, or flushed before the requested amount has - * been read, the method no longer blocks, but returns the number of bytes - * read thus far. + * Reads audio data from the data line's input buffer. The requested number + * of bytes is read into the specified array, starting at the specified + * offset into the array in bytes. This method blocks until the requested + * amount of data has been read. However, if the data line is closed, + * stopped, drained, or flushed before the requested amount has been read, + * the method no longer blocks, but returns the number of bytes read thus + * far. *

* The number of bytes that can be read without blocking can be ascertained - * using the {@link DataLine#available available} method of the - * DataLine interface. (While it is guaranteed that - * this number of bytes can be read without blocking, there is no guarantee - * that attempts to read additional data will block.) + * using the {@link DataLine#available available} method of the + * {@code DataLine} interface. (While it is guaranteed that this number of + * bytes can be read without blocking, there is no guarantee that attempts + * to read additional data will block.) *

* The number of bytes to be read must represent an integral number of * sample frames, such that: *
- *

[ bytes read ] % [frame size in bytes ] == 0
+ *
{@code [ bytes read ] % [frame size in bytes ] == 0}
*
- * The return value will always meet this requirement. A request to read a - * number of bytes representing a non-integral number of sample frames cannot - * be fulfilled and may result in an IllegalArgumentException. + * The return value will always meet this requirement. A request to read a + * number of bytes representing a non-integral number of sample frames + * cannot be fulfilled and may result in an IllegalArgumentException. * - * @param b a byte array that will contain the requested input data when - * this method returns - * @param off the offset from the beginning of the array, in bytes - * @param len the requested number of bytes to read + * @param b a byte array that will contain the requested input data when + * this method returns + * @param off the offset from the beginning of the array, in bytes + * @param len the requested number of bytes to read * @return the number of bytes actually read * @throws IllegalArgumentException if the requested number of bytes does - * not represent an integral number of sample frames. - * or if len is negative. - * @throws ArrayIndexOutOfBoundsException if off is negative, - * or off+len is greater than the length of the array - * b. + * not represent an integral number of sample frames, or if + * {@code len} is negative + * @throws ArrayIndexOutOfBoundsException if {@code off} is negative, or + * {@code off+len} is greater than the length of the array {@code b} * * @see SourceDataLine#write * @see DataLine#available */ - public int read(byte[] b, int off, int len); + int read(byte[] b, int off, int len); /** * Obtains the number of sample frames of audio data that can be read from - * the target data line without blocking. Note that the return value + * the target data line without blocking. Note that the return value * measures sample frames, not bytes. + * * @return the number of sample frames currently available for reading * @see SourceDataLine#availableWrite */ diff --git a/jdk/src/share/classes/javax/sound/sampled/UnsupportedAudioFileException.java b/jdk/src/share/classes/javax/sound/sampled/UnsupportedAudioFileException.java index 45acd480f35..31d68160995 100644 --- a/jdk/src/share/classes/javax/sound/sampled/UnsupportedAudioFileException.java +++ b/jdk/src/share/classes/javax/sound/sampled/UnsupportedAudioFileException.java @@ -26,33 +26,32 @@ package javax.sound.sampled; /** - * An UnsupportedAudioFileException is an exception indicating that an - * operation failed because a file did not contain valid data of a recognized file - * type and format. + * An {@code UnsupportedAudioFileException} is an exception indicating that an + * operation failed because a file did not contain valid data of a recognized + * file type and format. * * @author Kara Kytle * @since 1.3 */ public class UnsupportedAudioFileException extends Exception { + private static final long serialVersionUID = -139127412623160368L; /** - * Constructs a UnsupportedAudioFileException that has - * null as its error detail message. + * Constructs a {@code UnsupportedAudioFileException} that has {@code null} + * as its error detail message. */ public UnsupportedAudioFileException() { - super(); } /** - * Constructs a UnsupportedAudioFileException that has - * the specified detail message. + * Constructs a {@code UnsupportedAudioFileException} that has the specified + * detail message. * - * @param message a string containing the error detail message + * @param message a string containing the error detail message */ - public UnsupportedAudioFileException(String message) { - + public UnsupportedAudioFileException(final String message) { super(message); } } diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java index cc476452126..daa75556785 100644 --- a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java +++ b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java @@ -108,7 +108,7 @@ public abstract class AudioFileReader { * @param stream the input stream from which the {@code AudioInputStream} * should be constructed * @return an {@code AudioInputStream} object based on the audio file data - * contained in the input stream. + * contained in the input stream * @throws UnsupportedAudioFileException if the stream does not point to * valid audio file data recognized by the system * @throws IOException if an I/O exception occurs diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/FormatConversionProvider.java b/jdk/src/share/classes/javax/sound/sampled/spi/FormatConversionProvider.java index 7693087c9d9..8cb7fb68d5f 100644 --- a/jdk/src/share/classes/javax/sound/sampled/spi/FormatConversionProvider.java +++ b/jdk/src/share/classes/javax/sound/sampled/spi/FormatConversionProvider.java @@ -117,7 +117,7 @@ public abstract class FormatConversionProvider { * are supported for this source format, an array of length 0 is returned. * * @param sourceFormat format of the incoming data - * @return array of supported target format encodings. + * @return array of supported target format encodings */ public abstract Encoding[] getTargetEncodings(AudioFormat sourceFormat); @@ -150,7 +150,7 @@ public abstract class FormatConversionProvider { * * @param targetEncoding desired encoding of the stream after processing * @param sourceFormat format of the incoming data - * @return array of supported target formats. + * @return array of supported target formats */ public abstract AudioFormat[] getTargetFormats(Encoding targetEncoding, AudioFormat sourceFormat); @@ -187,7 +187,7 @@ public abstract class FormatConversionProvider { * @return stream from which processed data with the specified target * encoding may be read * @throws IllegalArgumentException if the format combination supplied is - * not supported. + * not supported */ public abstract AudioInputStream getAudioInputStream( Encoding targetEncoding, AudioInputStream sourceStream); @@ -202,7 +202,7 @@ public abstract class FormatConversionProvider { * @return stream from which processed data with the specified format may be * read * @throws IllegalArgumentException if the format combination supplied is - * not supported. + * not supported */ public abstract AudioInputStream getAudioInputStream( AudioFormat targetFormat, AudioInputStream sourceStream); From 28f895afc925d1df857a1ea2739b046e643498f2 Mon Sep 17 00:00:00 2001 From: Yuri Nesterenko Date: Wed, 4 Jun 2014 17:24:13 +0400 Subject: [PATCH 044/192] 8044157: [TEST_BUG] Improve recently submitted AWT_Mixing tests Reviewed-by: pchelko --- .../java/awt/Mixing/AWT_Mixing/FrameBorderCounter.java | 5 ----- .../Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java | 1 + .../AWT_Mixing/HierarchyBoundsListenerMixingTest.java | 9 ++++----- .../Mixing/AWT_Mixing/JButtonInGlassPaneOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JButtonOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JColorChooserOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JComboBoxOverlapping.java | 4 ++++ .../AWT_Mixing/JEditorPaneInGlassPaneOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JEditorPaneOverlapping.java | 2 ++ .../AWT_Mixing/JGlassPaneInternalFrameOverlapping.java | 5 ++++- .../awt/Mixing/AWT_Mixing/JGlassPaneMoveOverlapping.java | 5 ++++- .../Mixing/AWT_Mixing/JInternalFrameMoveOverlapping.java | 3 +++ .../awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java | 3 +++ .../Mixing/AWT_Mixing/JLabelInGlassPaneOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JLabelOverlapping.java | 2 ++ .../Mixing/AWT_Mixing/JListInGlassPaneOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JListOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java | 5 ++++- .../Mixing/AWT_Mixing/JPanelInGlassPaneOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JPanelOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java | 3 +++ .../AWT_Mixing/JProgressBarInGlassPaneOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JProgressBarOverlapping.java | 2 ++ .../AWT_Mixing/JScrollBarInGlassPaneOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JScrollBarOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java | 3 +++ .../Mixing/AWT_Mixing/JSliderInGlassPaneOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JSliderOverlapping.java | 2 ++ .../AWT_Mixing/JSpinnerInGlassPaneOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JSpinnerOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java | 5 ++++- .../Mixing/AWT_Mixing/JTableInGlassPaneOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JTableOverlapping.java | 2 ++ .../AWT_Mixing/JTextAreaInGlassPaneOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/JTextAreaOverlapping.java | 2 ++ .../AWT_Mixing/JTextFieldInGlassPaneOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JTextFieldOverlapping.java | 2 ++ .../AWT_Mixing/JToggleButtonInGlassPaneOverlapping.java | 2 ++ .../awt/Mixing/AWT_Mixing/JToggleButtonOverlapping.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java | 5 ++++- .../java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java | 9 ++++++--- .../java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java | 3 +++ .../awt/Mixing/AWT_Mixing/OpaqueOverlappingChoice.java | 2 ++ .../java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java | 3 ++- .../awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java | 1 + .../java/awt/Mixing/AWT_Mixing/ViewportOverlapping.java | 5 ++++- 46 files changed, 113 insertions(+), 20 deletions(-) diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/FrameBorderCounter.java b/jdk/test/java/awt/Mixing/AWT_Mixing/FrameBorderCounter.java index a7380cece35..17f76a6e3d3 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/FrameBorderCounter.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/FrameBorderCounter.java @@ -63,11 +63,6 @@ public class FrameBorderCounter { public void run() { frame = new Frame("Frame"); frame.setBounds(200, 200, 100, 100); - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); frame.setVisible(true); } }); diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java b/jdk/test/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java index 6b7ba1cc60e..06ffe239a2f 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java @@ -30,6 +30,7 @@ import java.lang.reflect.InvocationTargetException; import javax.swing.JFrame; import javax.swing.SpringLayout; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * Base class for testing overlapping of Swing and AWT component put into GlassPane. diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/HierarchyBoundsListenerMixingTest.java b/jdk/test/java/awt/Mixing/AWT_Mixing/HierarchyBoundsListenerMixingTest.java index 13e600b30e5..b9f8cabe239 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/HierarchyBoundsListenerMixingTest.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/HierarchyBoundsListenerMixingTest.java @@ -76,7 +76,6 @@ public class HierarchyBoundsListenerMixingTest { @Override public void windowClosing(WindowEvent event) { System.err.println("User closed the window"); - System.exit(1); } }); @@ -131,7 +130,7 @@ public class HierarchyBoundsListenerMixingTest { Thread.sleep(delay * 10); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + throw new RuntimeException("Robot creation exception."); } robot.mouseMove((int) components[0].getLocationOnScreen().x + components[0].getSize().width / 2, @@ -595,7 +594,7 @@ class Sysout { public static void createDialogWithInstructions(String[] instructions) { dialog = new TestDialog(new Frame(), "Instructions"); dialog.printInstructions(instructions); - dialog.setVisible(true); + //dialog.setVisible(true); println("Any messages for the tester will display here."); } @@ -603,7 +602,7 @@ class Sysout { dialog = new TestDialog(new Frame(), "Instructions"); String[] defInstr = {"Instructions will appear here. ", ""}; dialog.printInstructions(defInstr); - dialog.setVisible(true); + //dialog.setVisible(true); println("Any messages for the tester will display here."); } @@ -643,7 +642,7 @@ class TestDialog extends Dialog { pack(); - setVisible(true); + //setVisible(true); }// TestDialog() //DO NOT call this directly, go through Sysout diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JButtonInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JButtonInGlassPaneOverlapping.java index 11aef8209bd..867a28b34a3 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JButtonInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JButtonInGlassPaneOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JButton @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JButtonInGlassPaneOverlapping */ public class JButtonInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JButtonOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JButtonOverlapping.java index 119c131cc85..42070fa3ee0 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JButtonOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JButtonOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JButton @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JButtonOverlapping */ public class JButtonOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JColorChooserOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JColorChooserOverlapping.java index c756041db65..a21633b6b5f 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JColorChooserOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JColorChooserOverlapping.java @@ -31,6 +31,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JColorChooser @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JColorChooserOverlapping */ public class JColorChooserOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JComboBoxOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JComboBoxOverlapping.java index b0887068a09..8d69f7156f7 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JComboBoxOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JComboBoxOverlapping.java @@ -30,6 +30,8 @@ import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JFrame; +import test.java.awt.regtesthelpers.Util; + /** * AWT/Swing overlapping test for {@link javax.swing.JCombobox } component. @@ -40,6 +42,8 @@ import javax.swing.JFrame; @test @summary Overlapping test for javax.swing.JScrollPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JComboBoxOverlapping */ public class JComboBoxOverlapping extends OverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JEditorPaneInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JEditorPaneInGlassPaneOverlapping.java index d14f078aa2d..1c406a808b4 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JEditorPaneInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JEditorPaneInGlassPaneOverlapping.java @@ -33,6 +33,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JLabel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JEditorPaneInGlassPaneOverlapping */ public class JEditorPaneInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JEditorPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JEditorPaneOverlapping.java index 513ca0dce7f..6b0bf6d66ab 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JEditorPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JEditorPaneOverlapping.java @@ -31,6 +31,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JLabel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JEditorPaneOverlapping */ public class JEditorPaneOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JGlassPaneInternalFrameOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JGlassPaneInternalFrameOverlapping.java index 3e2575375e8..e647875b059 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JGlassPaneInternalFrameOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JGlassPaneInternalFrameOverlapping.java @@ -31,6 +31,7 @@ import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test with JInternalFrame being put in GlassPane. @@ -43,6 +44,8 @@ import javax.swing.SwingUtilities; @bug 6637655 6985776 @summary Overlapping test for javax.swing.JScrollPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JGlassPaneInternalFrameOverlapping */ public class JGlassPaneInternalFrameOverlapping extends OverlappingTestBase { @@ -63,7 +66,7 @@ public class JGlassPaneInternalFrameOverlapping extends OverlappingTestBase { }); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + throw new RuntimeException("Where is internal frame?"); } // run robot Robot robot = Util.createRobot(); diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JGlassPaneMoveOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JGlassPaneMoveOverlapping.java index 43e060a2438..2103c63f688 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JGlassPaneMoveOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JGlassPaneMoveOverlapping.java @@ -32,6 +32,7 @@ import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test with JInternalFrame being moved in GlassPane. @@ -44,6 +45,8 @@ import javax.swing.SwingUtilities; @bug 6637655 6981919 @summary Overlapping test for javax.swing.JScrollPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JGlassPaneMoveOverlapping */ public class JGlassPaneMoveOverlapping extends OverlappingTestBase { @@ -70,7 +73,7 @@ public class JGlassPaneMoveOverlapping extends OverlappingTestBase { }); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + throw new RuntimeException("Where is internal frame?"); } // run robot diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JInternalFrameMoveOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JInternalFrameMoveOverlapping.java index 99a9e015921..78e624323eb 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JInternalFrameMoveOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JInternalFrameMoveOverlapping.java @@ -30,6 +30,7 @@ import javax.swing.JButton; import javax.swing.JDesktopPane; import javax.swing.JFrame; import javax.swing.JInternalFrame; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for {@link javax.swing.JInternalFrame } component during move. @@ -40,6 +41,8 @@ import javax.swing.JInternalFrame; @bug 6985399 @summary Overlapping test for javax.swing.JScrollPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JInternalFrameMoveOverlapping */ public class JInternalFrameMoveOverlapping extends OverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java index 320a82adcce..17e3165e01c 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JInternalFrameOverlapping.java @@ -30,6 +30,7 @@ import javax.swing.JButton; import javax.swing.JDesktopPane; import javax.swing.JFrame; import javax.swing.JInternalFrame; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for {@link javax.swing.JInternalFrame } component. @@ -39,6 +40,8 @@ import javax.swing.JInternalFrame; @test @summary Overlapping test for javax.swing.JScrollPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JInternalFrameOverlapping */ public class JInternalFrameOverlapping extends OverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JLabelInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JLabelInGlassPaneOverlapping.java index bdde7409344..a469774db82 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JLabelInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JLabelInGlassPaneOverlapping.java @@ -33,6 +33,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JLabel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JLabelInGlassPaneOverlapping */ public class JLabelInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JLabelOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JLabelOverlapping.java index e6038bc8038..658a99db561 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JLabelOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JLabelOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JLabel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JLabelOverlapping */ public class JLabelOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JListInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JListInGlassPaneOverlapping.java index 4a2e1419bae..5a9123f5020 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JListInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JListInGlassPaneOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JList @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JListInGlassPaneOverlapping */ public class JListInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JListOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JListOverlapping.java index 76ee46ccbfa..bed4a98503a 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JListOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JListOverlapping.java @@ -31,6 +31,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JList @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JListOverlapping */ public class JListOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java index 5ae75bd55b7..b6816fb877b 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JMenuBarOverlapping.java @@ -36,6 +36,7 @@ import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JSeparator; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for {@link javax.swing.JMenuBar } and {@link javax.swing.JSeparator} components. @@ -46,6 +47,8 @@ import javax.swing.SwingUtilities; @test @summary Overlapping test for javax.swing.JScrollPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JMenuBarOverlapping */ public class JMenuBarOverlapping extends OverlappingTestBase { @@ -132,7 +135,7 @@ public class JMenuBarOverlapping extends OverlappingTestBase { }); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + throw new RuntimeException("Where is separator?"); } sepLoc.translate(20, 1); clickAndBlink(robot, sepLoc, false); diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JPanelInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JPanelInGlassPaneOverlapping.java index 189a17b000f..078557831a9 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JPanelInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JPanelInGlassPaneOverlapping.java @@ -33,6 +33,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JPanel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JPanelInGlassPaneOverlapping */ public class JPanelInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JPanelOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JPanelOverlapping.java index 5decd49d461..a8ca9e67baf 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JPanelOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JPanelOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JPanel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JPanelOverlapping */ public class JPanelOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java index fead4e441fd..ba72f755360 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java @@ -33,6 +33,7 @@ import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.SpringLayout; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for {@link javax.swing.JPopupMenu } component. @@ -43,6 +44,8 @@ import javax.swing.SwingUtilities; @test @summary Overlapping test for javax.swing.JScrollPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JPopupMenuOverlapping */ public class JPopupMenuOverlapping extends OverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JProgressBarInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JProgressBarInGlassPaneOverlapping.java index 1f60eefe5d6..be104e1fed1 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JProgressBarInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JProgressBarInGlassPaneOverlapping.java @@ -33,6 +33,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JProgressBar @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JProgressBarInGlassPaneOverlapping */ public class JProgressBarInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JProgressBarOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JProgressBarOverlapping.java index 3db75cc6e4d..c1c9aab77a2 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JProgressBarOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JProgressBarOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JProgressBar @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JProgressBarOverlapping */ public class JProgressBarOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollBarInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollBarInGlassPaneOverlapping.java index a12a6f8b5af..33d1a483998 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollBarInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollBarInGlassPaneOverlapping.java @@ -36,6 +36,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JScrollBar @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JScrollBarInGlassPaneOverlapping */ public class JScrollBarInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollBarOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollBarOverlapping.java index 9a3dd8e0a8a..8271f5b272a 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollBarOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollBarOverlapping.java @@ -35,6 +35,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JScrollBar @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JScrollBarOverlapping */ public class JScrollBarOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java index d4ae51d38e4..f7205cec299 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JScrollPaneOverlapping.java @@ -32,6 +32,7 @@ import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for {@link javax.swing.JScrollPane } component. @@ -41,6 +42,8 @@ import javax.swing.SwingUtilities; @test @summary Overlapping test for javax.swing.JScrollPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JScrollPaneOverlapping */ public class JScrollPaneOverlapping extends OverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JSliderInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JSliderInGlassPaneOverlapping.java index 8cdafc17903..ece5ea80537 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JSliderInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JSliderInGlassPaneOverlapping.java @@ -33,6 +33,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JSlider @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JSliderInGlassPaneOverlapping */ public class JSliderInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JSliderOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JSliderOverlapping.java index f6553db0311..bf28c046d7a 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JSliderOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JSliderOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JSlider @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JSliderOverlapping */ public class JSliderOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JSpinnerInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JSpinnerInGlassPaneOverlapping.java index 1c60597c5a2..805f111d4cf 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JSpinnerInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JSpinnerInGlassPaneOverlapping.java @@ -35,6 +35,8 @@ import javax.swing.event.ChangeListener; @test @summary Simple Overlapping test for javax.swing.JSpinner @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JSpinnerInGlassPaneOverlapping */ public class JSpinnerInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JSpinnerOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JSpinnerOverlapping.java index 90e4e5b85e9..be06e8bc670 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JSpinnerOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JSpinnerOverlapping.java @@ -34,6 +34,8 @@ import javax.swing.event.ChangeListener; @test @summary Simple Overlapping test for javax.swing.JSpinner @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JSpinnerOverlapping */ public class JSpinnerOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java index c4f2265824a..2af8101ef97 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JSplitPaneOverlapping.java @@ -36,6 +36,7 @@ import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for {@link javax.swing.JSplitPane } component. @@ -47,6 +48,8 @@ import javax.swing.SwingUtilities; @bug 6986109 @summary Overlapping test for javax.swing.JSplitPane @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JSplitPaneOverlapping */ public class JSplitPaneOverlapping extends OverlappingTestBase { @@ -99,7 +102,7 @@ public class JSplitPaneOverlapping extends OverlappingTestBase { }); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + throw new RuntimeException("Where is splitter?"); } // run robot Robot robot = Util.createRobot(); diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JTableInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JTableInGlassPaneOverlapping.java index af4803b9c50..634d707857c 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JTableInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JTableInGlassPaneOverlapping.java @@ -35,6 +35,8 @@ import javax.swing.event.TableModelListener; @test @summary Simple Overlapping test for JTable @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JTableInGlassPaneOverlapping */ public class JTableInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JTableOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JTableOverlapping.java index d96732feedc..bea7c6bcf88 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JTableOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JTableOverlapping.java @@ -31,6 +31,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for JTable @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JTableOverlapping */ public class JTableOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JTextAreaInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JTextAreaInGlassPaneOverlapping.java index dba86e2747f..7b7fb405af9 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JTextAreaInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JTextAreaInGlassPaneOverlapping.java @@ -33,6 +33,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JLabel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JTextAreaInGlassPaneOverlapping */ public class JTextAreaInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JTextAreaOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JTextAreaOverlapping.java index 51f2b5ffddb..683e47f9f6c 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JTextAreaOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JTextAreaOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JLabel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JTextAreaOverlapping */ public class JTextAreaOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JTextFieldInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JTextFieldInGlassPaneOverlapping.java index d6dd69436ea..0f58c9cbd40 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JTextFieldInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JTextFieldInGlassPaneOverlapping.java @@ -33,6 +33,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JLabel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JTextFieldInGlassPaneOverlapping */ public class JTextFieldInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JTextFieldOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JTextFieldOverlapping.java index ffaecdcb589..01f71df838f 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JTextFieldOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JTextFieldOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JLabel @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JTextFieldOverlapping */ public class JTextFieldOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JToggleButtonInGlassPaneOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JToggleButtonInGlassPaneOverlapping.java index 3c4a62d9f50..33657f2c9ca 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JToggleButtonInGlassPaneOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JToggleButtonInGlassPaneOverlapping.java @@ -32,6 +32,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JToggleButton @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JToggleButtonInGlassPaneOverlapping */ public class JToggleButtonInGlassPaneOverlapping extends GlassPaneOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/JToggleButtonOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/JToggleButtonOverlapping.java index 3b311d71e10..0ca9aee2597 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/JToggleButtonOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/JToggleButtonOverlapping.java @@ -31,6 +31,8 @@ import javax.swing.*; @test @summary Simple Overlapping test for javax.swing.JToggleButton @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main JToggleButtonOverlapping */ public class JToggleButtonOverlapping extends SimpleOverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java b/jdk/test/java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java index fd15ca1dc85..dbb01bb8047 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/MixingFrameResizing.java @@ -29,6 +29,7 @@ import java.awt.event.InputEvent; import javax.swing.JFrame; import javax.swing.SpringLayout; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test. @@ -40,6 +41,8 @@ import javax.swing.SwingUtilities; @bug 6777370 @summary Issues when resizing the JFrame with HW components @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main MixingFrameResizing */ public class MixingFrameResizing extends OverlappingTestBase { @@ -77,7 +80,7 @@ public class MixingFrameResizing extends OverlappingTestBase { }); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + throw new RuntimeException("Where is frame?"); } Robot robot = Util.createRobot(); robot.setAutoDelay(ROBOT_DELAY/2); diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java b/jdk/test/java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java index d7e46b9ffc6..4b94b4f5f0c 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java @@ -26,6 +26,7 @@ import java.awt.*; import java.awt.event.InputEvent; import javax.swing.*; import java.io.*; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for Panel and JPanel behavior during resizing. @@ -36,6 +37,8 @@ import java.io.*; @bug 6786219 @summary Issues when resizing the frame after mixing of heavy weight & light weight components @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @build FrameBorderCounter @run main MixingPanelsResizing */ @@ -365,7 +368,7 @@ class Sysout { public static void createDialogWithInstructions(String[] instructions) { dialog = new TestDialog(new Frame(), "Instructions"); dialog.printInstructions(instructions); - dialog.setVisible(true); + //dialog.setVisible(true); println("Any messages for the tester will display here."); } @@ -373,7 +376,7 @@ class Sysout { dialog = new TestDialog(new Frame(), "Instructions"); String[] defInstr = {"Instructions will appear here. ", ""}; dialog.printInstructions(defInstr); - dialog.setVisible(true); + //dialog.setVisible(true); println("Any messages for the tester will display here."); } @@ -413,7 +416,7 @@ class TestDialog extends Dialog { pack(); - setVisible(true); + //setVisible(true); }// TestDialog() //DO NOT call this directly, go through Sysout diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java index fcfd9ce12be..d0e2f8f77c4 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java @@ -33,6 +33,7 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for opaque Swing components. @@ -44,6 +45,8 @@ import javax.swing.SwingUtilities; @test @bug 6776743 @summary Opaque overlapping test for each AWT component +@library ../../regtesthelpers +@build Util @run main OpaqueOverlapping */ public class OpaqueOverlapping extends OverlappingTestBase { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlappingChoice.java b/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlappingChoice.java index 896b096b4bb..fa4b103159b 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlappingChoice.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlappingChoice.java @@ -31,6 +31,8 @@ @test @bug 6994264 @summary Opaque overlapping test for Choice AWT component +@library ../../regtesthelpers +@build Util @run main OpaqueOverlappingChoice */ public class OpaqueOverlappingChoice extends OpaqueOverlapping { diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java b/jdk/test/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java index f3730b89302..fd72ddac80f 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java @@ -31,6 +31,7 @@ import java.util.ArrayList; import javax.swing.*; import sun.awt.*; import java.io.*; +import test.java.awt.regtesthelpers.Util; /** *

This class provides basis for AWT Mixing testing. @@ -131,7 +132,7 @@ public abstract class OverlappingTestBase { isFrameBorderCalculated = true; } catch (IOException e) { e.printStackTrace(); - System.exit(1); + throw new RuntimeException("Problem calculating a native border size"); } } return borderShift; diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java b/jdk/test/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java index 4d81127a772..fb79a0a2ba7 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java @@ -24,6 +24,7 @@ import java.awt.*; import java.awt.event.*; import javax.swing.*; +import test.java.awt.regtesthelpers.Util; /** * Base class for testing overlapping of Swing and AWT component put into one frame. diff --git a/jdk/test/java/awt/Mixing/AWT_Mixing/ViewportOverlapping.java b/jdk/test/java/awt/Mixing/AWT_Mixing/ViewportOverlapping.java index 22e1e7730cd..923bb8a5707 100644 --- a/jdk/test/java/awt/Mixing/AWT_Mixing/ViewportOverlapping.java +++ b/jdk/test/java/awt/Mixing/AWT_Mixing/ViewportOverlapping.java @@ -37,6 +37,7 @@ import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; +import test.java.awt.regtesthelpers.Util; /** * AWT/Swing overlapping test for viewport @@ -49,6 +50,8 @@ import javax.swing.SwingUtilities; @bug 6778882 @summary Viewport overlapping test for each AWT component @author sergey.grinev@oracle.com: area=awt.mixing +@library ../../regtesthelpers +@build Util @run main ViewportOverlapping */ public class ViewportOverlapping extends OverlappingTestBase { @@ -116,7 +119,7 @@ public class ViewportOverlapping extends OverlappingTestBase { }); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + throw new RuntimeException("Problem preparing test GUI."); } // run robot Robot robot = Util.createRobot(); From fc858b5c962152c0b007eb357b2780dc0e7c0119 Mon Sep 17 00:00:00 2001 From: Henry Jen Date: Thu, 5 Jun 2014 10:37:24 -0700 Subject: [PATCH 045/192] 8044855: Add missing @since tag under java.beans.* Reviewed-by: prr, malenkov --- jdk/src/share/classes/java/beans/BeanDescriptor.java | 2 ++ jdk/src/share/classes/java/beans/BeanInfo.java | 2 ++ jdk/src/share/classes/java/beans/Beans.java | 4 ++++ jdk/src/share/classes/java/beans/Customizer.java | 2 ++ jdk/src/share/classes/java/beans/EventSetDescriptor.java | 2 ++ jdk/src/share/classes/java/beans/FeatureDescriptor.java | 4 ++++ .../classes/java/beans/IndexedPropertyDescriptor.java | 6 ++++++ .../share/classes/java/beans/IntrospectionException.java | 2 ++ jdk/src/share/classes/java/beans/Introspector.java | 9 +++++++++ jdk/src/share/classes/java/beans/MethodDescriptor.java | 2 ++ .../share/classes/java/beans/ParameterDescriptor.java | 2 ++ .../share/classes/java/beans/PropertyChangeEvent.java | 2 ++ .../share/classes/java/beans/PropertyChangeListener.java | 1 + .../share/classes/java/beans/PropertyChangeSupport.java | 7 +++++++ jdk/src/share/classes/java/beans/PropertyDescriptor.java | 3 +++ jdk/src/share/classes/java/beans/PropertyEditor.java | 2 ++ .../share/classes/java/beans/PropertyEditorManager.java | 2 ++ .../share/classes/java/beans/PropertyEditorSupport.java | 2 ++ .../share/classes/java/beans/PropertyVetoException.java | 1 + jdk/src/share/classes/java/beans/SimpleBeanInfo.java | 2 ++ .../share/classes/java/beans/VetoableChangeListener.java | 1 + .../share/classes/java/beans/VetoableChangeSupport.java | 7 +++++++ jdk/src/share/classes/java/beans/Visibility.java | 2 ++ 23 files changed, 69 insertions(+) diff --git a/jdk/src/share/classes/java/beans/BeanDescriptor.java b/jdk/src/share/classes/java/beans/BeanDescriptor.java index fee54153bd3..10912ed7f4d 100644 --- a/jdk/src/share/classes/java/beans/BeanDescriptor.java +++ b/jdk/src/share/classes/java/beans/BeanDescriptor.java @@ -33,6 +33,8 @@ import java.lang.ref.Reference; *

* This is one of the kinds of descriptor returned by a BeanInfo object, * which also returns descriptors for properties, method, and events. + * + * @since 1.1 */ public class BeanDescriptor extends FeatureDescriptor { diff --git a/jdk/src/share/classes/java/beans/BeanInfo.java b/jdk/src/share/classes/java/beans/BeanInfo.java index bb43f2fd4e8..92be1eb81a4 100644 --- a/jdk/src/share/classes/java/beans/BeanInfo.java +++ b/jdk/src/share/classes/java/beans/BeanInfo.java @@ -48,6 +48,8 @@ import java.awt.Image; * the {@code SimpleBeanInfo} class to define specific information. *

* See also the {@link Introspector} class to learn more about bean behavior. + * + * @since 1.1 */ public interface BeanInfo { diff --git a/jdk/src/share/classes/java/beans/Beans.java b/jdk/src/share/classes/java/beans/Beans.java index 5bf13fa7d09..cd864899ea6 100644 --- a/jdk/src/share/classes/java/beans/Beans.java +++ b/jdk/src/share/classes/java/beans/Beans.java @@ -56,6 +56,8 @@ import java.util.Vector; /** * This class provides some general purpose beans control methods. + * + * @since 1.1 */ public class Beans { @@ -96,6 +98,7 @@ public class Beans { * @exception ClassNotFoundException if the class of a serialized * object could not be found. * @exception IOException if an I/O error occurs. + * @since 1.2 */ public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext) throws IOException, ClassNotFoundException { @@ -152,6 +155,7 @@ public class Beans { * @exception ClassNotFoundException if the class of a serialized * object could not be found. * @exception IOException if an I/O error occurs. + * @since 1.2 */ public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext, AppletInitializer initializer) diff --git a/jdk/src/share/classes/java/beans/Customizer.java b/jdk/src/share/classes/java/beans/Customizer.java index 07d70631e78..5dcd03b0b5a 100644 --- a/jdk/src/share/classes/java/beans/Customizer.java +++ b/jdk/src/share/classes/java/beans/Customizer.java @@ -33,6 +33,8 @@ package java.beans; * it can be instantiated inside an AWT dialog or panel. *

* Each customizer should have a null constructor. + * + * @since 1.1 */ public interface Customizer { diff --git a/jdk/src/share/classes/java/beans/EventSetDescriptor.java b/jdk/src/share/classes/java/beans/EventSetDescriptor.java index ca8dbadb04e..d05d2f79375 100644 --- a/jdk/src/share/classes/java/beans/EventSetDescriptor.java +++ b/jdk/src/share/classes/java/beans/EventSetDescriptor.java @@ -36,6 +36,8 @@ import java.lang.reflect.Modifier; * The given group of events are all delivered as method calls on a single * event listener interface, and an event listener object can be registered * via a call on a registration method supplied by the event source. + * + * @since 1.1 */ public class EventSetDescriptor extends FeatureDescriptor { diff --git a/jdk/src/share/classes/java/beans/FeatureDescriptor.java b/jdk/src/share/classes/java/beans/FeatureDescriptor.java index 75f06f33fc2..6a82de9f971 100644 --- a/jdk/src/share/classes/java/beans/FeatureDescriptor.java +++ b/jdk/src/share/classes/java/beans/FeatureDescriptor.java @@ -46,6 +46,8 @@ import java.util.Map.Entry; *

* In addition it provides an extension mechanism so that arbitrary * attribute/value pairs can be associated with a design feature. + * + * @since 1.1 */ public class FeatureDescriptor { @@ -145,6 +147,7 @@ public class FeatureDescriptor { * important for presenting to humans. * * @return True if this feature should be preferentially shown to human users. + * @since 1.2 */ public boolean isPreferred() { return preferred; @@ -156,6 +159,7 @@ public class FeatureDescriptor { * * @param preferred True if this feature should be preferentially shown * to human users. + * @since 1.2 */ public void setPreferred(boolean preferred) { this.preferred = preferred; diff --git a/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java b/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java index 84f20ee4a1a..9449421eae2 100644 --- a/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java +++ b/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java @@ -36,6 +36,8 @@ import java.lang.reflect.Method; * An indexed property may also provide simple non-indexed read and write * methods. If these are present, they read and write arrays of the type * returned by the indexed read method. + * + * @since 1.1 */ public class IndexedPropertyDescriptor extends PropertyDescriptor { @@ -209,6 +211,8 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { * @param readMethod The new indexed read method. * @throws IntrospectionException if an exception occurs during * introspection. + * + * @since 1.2 */ public synchronized void setIndexedReadMethod(Method readMethod) throws IntrospectionException { @@ -288,6 +292,8 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { * @param writeMethod The new indexed write method. * @throws IntrospectionException if an exception occurs during * introspection. + * + * @since 1.2 */ public synchronized void setIndexedWriteMethod(Method writeMethod) throws IntrospectionException { diff --git a/jdk/src/share/classes/java/beans/IntrospectionException.java b/jdk/src/share/classes/java/beans/IntrospectionException.java index c9cf2eeb44b..432ba99e93b 100644 --- a/jdk/src/share/classes/java/beans/IntrospectionException.java +++ b/jdk/src/share/classes/java/beans/IntrospectionException.java @@ -32,6 +32,8 @@ package java.beans; * to a Class object, not being able to resolve a string method name, * or specifying a method name that has the wrong type signature for * its intended use. + * + * @since 1.1 */ public diff --git a/jdk/src/share/classes/java/beans/Introspector.java b/jdk/src/share/classes/java/beans/Introspector.java index 469238a601e..44bddc6a9c5 100644 --- a/jdk/src/share/classes/java/beans/Introspector.java +++ b/jdk/src/share/classes/java/beans/Introspector.java @@ -90,6 +90,8 @@ import sun.reflect.misc.ReflectUtil; * For more information about introspection and design patterns, please * consult the * JavaBeans™ specification. + * + * @since 1.1 */ public class Introspector { @@ -97,14 +99,17 @@ public class Introspector { // Flags that can be used to control getBeanInfo: /** * Flag to indicate to use of all beaninfo. + * @since 1.2 */ public final static int USE_ALL_BEANINFO = 1; /** * Flag to indicate to ignore immediate beaninfo. + * @since 1.2 */ public final static int IGNORE_IMMEDIATE_BEANINFO = 2; /** * Flag to indicate to ignore all beaninfo. + * @since 1.2 */ public final static int IGNORE_ALL_BEANINFO = 3; @@ -214,6 +219,7 @@ public class Introspector { * @return A BeanInfo object describing the target bean. * @exception IntrospectionException if an exception occurs during * introspection. + * @since 1.2 */ public static BeanInfo getBeanInfo(Class beanClass, int flags) throws IntrospectionException { @@ -354,6 +360,8 @@ public class Introspector { * not normally required. It is normally only needed by advanced * tools that update existing "Class" objects in-place and need * to make the Introspector re-analyze existing Class objects. + * + * @since 1.2 */ public static void flushCaches() { @@ -377,6 +385,7 @@ public class Introspector { * * @param clz Class object to be flushed. * @throws NullPointerException If the Class object is null. + * @since 1.2 */ public static void flushFromCaches(Class clz) { if (clz == null) { diff --git a/jdk/src/share/classes/java/beans/MethodDescriptor.java b/jdk/src/share/classes/java/beans/MethodDescriptor.java index 1e169046746..ca295be74dc 100644 --- a/jdk/src/share/classes/java/beans/MethodDescriptor.java +++ b/jdk/src/share/classes/java/beans/MethodDescriptor.java @@ -34,6 +34,8 @@ import java.util.ArrayList; /** * A MethodDescriptor describes a particular method that a Java Bean * supports for external access from other components. + * + * @since 1.1 */ public class MethodDescriptor extends FeatureDescriptor { diff --git a/jdk/src/share/classes/java/beans/ParameterDescriptor.java b/jdk/src/share/classes/java/beans/ParameterDescriptor.java index 3b7013f4ad0..243df016ea0 100644 --- a/jdk/src/share/classes/java/beans/ParameterDescriptor.java +++ b/jdk/src/share/classes/java/beans/ParameterDescriptor.java @@ -32,6 +32,8 @@ package java.beans; * class. *

* Currently all our state comes from the FeatureDescriptor base class. + * + * @since 1.1 */ public class ParameterDescriptor extends FeatureDescriptor { diff --git a/jdk/src/share/classes/java/beans/PropertyChangeEvent.java b/jdk/src/share/classes/java/beans/PropertyChangeEvent.java index eeaa6512730..ec7d8ed51c0 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeEvent.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeEvent.java @@ -43,6 +43,8 @@ import java.util.EventObject; * An event source may send a null object as the name to indicate that an * arbitrary set of if its properties have changed. In this case the * old and new values should also be null. + * + * @since 1.1 */ public class PropertyChangeEvent extends EventObject { private static final long serialVersionUID = 7042693688939648123L; diff --git a/jdk/src/share/classes/java/beans/PropertyChangeListener.java b/jdk/src/share/classes/java/beans/PropertyChangeListener.java index 5b78d482439..70d50a85caf 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeListener.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeListener.java @@ -29,6 +29,7 @@ package java.beans; * A "PropertyChange" event gets fired whenever a bean changes a "bound" * property. You can register a PropertyChangeListener with a source * bean so as to be notified of any bound property updates. + * @since 1.1 */ public interface PropertyChangeListener extends java.util.EventListener { diff --git a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java index d55ae76efc8..40e58ae1e5d 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java @@ -77,6 +77,7 @@ import java.util.Map.Entry; * non-serializable listeners will be skipped during serialization. * * @see VetoableChangeSupport + * @since 1.1 */ public class PropertyChangeSupport implements Serializable { private PropertyChangeListenerMap map = new PropertyChangeListenerMap(); @@ -191,6 +192,7 @@ public class PropertyChangeSupport implements Serializable { * * @param propertyName The name of the property to listen on. * @param listener The PropertyChangeListener to be added + * @since 1.2 */ public void addPropertyChangeListener( String propertyName, @@ -216,6 +218,7 @@ public class PropertyChangeSupport implements Serializable { * * @param propertyName The name of the property that was listened on. * @param listener The PropertyChangeListener to be removed + * @since 1.2 */ public void removePropertyChangeListener( String propertyName, @@ -277,6 +280,7 @@ public class PropertyChangeSupport implements Serializable { * @param propertyName the programmatic name of the property that was changed * @param oldValue the old value of the property * @param newValue the new value of the property + * @since 1.2 */ public void firePropertyChange(String propertyName, int oldValue, int newValue) { if (oldValue != newValue) { @@ -297,6 +301,7 @@ public class PropertyChangeSupport implements Serializable { * @param propertyName the programmatic name of the property that was changed * @param oldValue the old value of the property * @param newValue the new value of the property + * @since 1.2 */ public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { if (oldValue != newValue) { @@ -312,6 +317,7 @@ public class PropertyChangeSupport implements Serializable { * No event is fired if the given event's old and new values are equal and non-null. * * @param event the {@code PropertyChangeEvent} to be fired + * @since 1.2 */ public void firePropertyChange(PropertyChangeEvent event) { Object oldValue = event.getOldValue(); @@ -410,6 +416,7 @@ public class PropertyChangeSupport implements Serializable { * * @param propertyName the property name. * @return true if there are one or more listeners for the given property + * @since 1.2 */ public boolean hasListeners(String propertyName) { return this.map.hasListeners(propertyName); diff --git a/jdk/src/share/classes/java/beans/PropertyDescriptor.java b/jdk/src/share/classes/java/beans/PropertyDescriptor.java index fb0b349c000..9f26590418f 100644 --- a/jdk/src/share/classes/java/beans/PropertyDescriptor.java +++ b/jdk/src/share/classes/java/beans/PropertyDescriptor.java @@ -32,6 +32,7 @@ import java.lang.reflect.Constructor; /** * A PropertyDescriptor describes one property that a Java Bean * exports via a pair of accessor methods. + * @since 1.1 */ public class PropertyDescriptor extends FeatureDescriptor { @@ -244,6 +245,7 @@ public class PropertyDescriptor extends FeatureDescriptor { * * @param readMethod The new read method. * @throws IntrospectionException if the read method is invalid + * @since 1.2 */ public synchronized void setReadMethod(Method readMethod) throws IntrospectionException { @@ -314,6 +316,7 @@ public class PropertyDescriptor extends FeatureDescriptor { * * @param writeMethod The new write method. * @throws IntrospectionException if the write method is invalid + * @since 1.2 */ public synchronized void setWriteMethod(Method writeMethod) throws IntrospectionException { diff --git a/jdk/src/share/classes/java/beans/PropertyEditor.java b/jdk/src/share/classes/java/beans/PropertyEditor.java index 041cb805d9e..69ad2c04074 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditor.java +++ b/jdk/src/share/classes/java/beans/PropertyEditor.java @@ -51,6 +51,8 @@ package java.beans; * or support setAsText. *

* Each PropertyEditor should have a null constructor. + * + * @since 1.1 */ public interface PropertyEditor { diff --git a/jdk/src/share/classes/java/beans/PropertyEditorManager.java b/jdk/src/share/classes/java/beans/PropertyEditorManager.java index 46ec87de944..ae664b8c4cc 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditorManager.java +++ b/jdk/src/share/classes/java/beans/PropertyEditorManager.java @@ -48,6 +48,8 @@ package java.beans; * Default PropertyEditors will be provided for the Java primitive types * "boolean", "byte", "short", "int", "long", "float", and "double"; and * for the classes java.lang.String. java.awt.Color, and java.awt.Font. + * + * @since 1.1 */ public class PropertyEditorManager { diff --git a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java index 1569c652e97..cfc350fbb20 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java @@ -31,6 +31,8 @@ import java.beans.*; * This is a support class to help build property editors. *

* It can be used either as a base class or as a delegate. + * + * @since 1.1 */ public class PropertyEditorSupport implements PropertyEditor { diff --git a/jdk/src/share/classes/java/beans/PropertyVetoException.java b/jdk/src/share/classes/java/beans/PropertyVetoException.java index 27a2f82f341..86220b18785 100644 --- a/jdk/src/share/classes/java/beans/PropertyVetoException.java +++ b/jdk/src/share/classes/java/beans/PropertyVetoException.java @@ -29,6 +29,7 @@ package java.beans; /** * A PropertyVetoException is thrown when a proposed change to a * property represents an unacceptable value. + * @since 1.1 */ public diff --git a/jdk/src/share/classes/java/beans/SimpleBeanInfo.java b/jdk/src/share/classes/java/beans/SimpleBeanInfo.java index 29fd9cc4b5a..7b97e414ebb 100644 --- a/jdk/src/share/classes/java/beans/SimpleBeanInfo.java +++ b/jdk/src/share/classes/java/beans/SimpleBeanInfo.java @@ -34,6 +34,8 @@ package java.beans; * When the introspector sees the "noop" values, it will apply low * level introspection and design patterns to automatically analyze * the target bean. + * + * @since 1.1 */ public class SimpleBeanInfo implements BeanInfo { diff --git a/jdk/src/share/classes/java/beans/VetoableChangeListener.java b/jdk/src/share/classes/java/beans/VetoableChangeListener.java index 898fd82fb4b..9edc175375d 100644 --- a/jdk/src/share/classes/java/beans/VetoableChangeListener.java +++ b/jdk/src/share/classes/java/beans/VetoableChangeListener.java @@ -29,6 +29,7 @@ package java.beans; * A VetoableChange event gets fired whenever a bean changes a "constrained" * property. You can register a VetoableChangeListener with a source bean * so as to be notified of any constrained property updates. + * @since 1.1 */ public interface VetoableChangeListener extends java.util.EventListener { /** diff --git a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java index 293ae5af2c6..14902cc6276 100644 --- a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java +++ b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java @@ -77,6 +77,7 @@ import java.util.Map.Entry; * non-serializable listeners will be skipped during serialization. * * @see PropertyChangeSupport + * @since 1.1 */ public class VetoableChangeSupport implements Serializable { private VetoableChangeListenerMap map = new VetoableChangeListenerMap(); @@ -191,6 +192,7 @@ public class VetoableChangeSupport implements Serializable { * * @param propertyName The name of the property to listen on. * @param listener The VetoableChangeListener to be added + * @since 1.2 */ public void addVetoableChangeListener( String propertyName, @@ -216,6 +218,7 @@ public class VetoableChangeSupport implements Serializable { * * @param propertyName The name of the property that was listened on. * @param listener The VetoableChangeListener to be removed + * @since 1.2 */ public void removeVetoableChangeListener( String propertyName, @@ -292,6 +295,7 @@ public class VetoableChangeSupport implements Serializable { * @param oldValue the old value of the property * @param newValue the new value of the property * @throws PropertyVetoException if one of listeners vetoes the property update + * @since 1.2 */ public void fireVetoableChange(String propertyName, int oldValue, int newValue) throws PropertyVetoException { @@ -320,6 +324,7 @@ public class VetoableChangeSupport implements Serializable { * @param oldValue the old value of the property * @param newValue the new value of the property * @throws PropertyVetoException if one of listeners vetoes the property update + * @since 1.2 */ public void fireVetoableChange(String propertyName, boolean oldValue, boolean newValue) throws PropertyVetoException { @@ -343,6 +348,7 @@ public class VetoableChangeSupport implements Serializable { * * @param event the {@code PropertyChangeEvent} to be fired * @throws PropertyVetoException if one of listeners vetoes the property update + * @since 1.2 */ public void fireVetoableChange(PropertyChangeEvent event) throws PropertyVetoException { @@ -399,6 +405,7 @@ public class VetoableChangeSupport implements Serializable { * * @param propertyName the property name. * @return true if there are one or more listeners for the given property + * @since 1.2 */ public boolean hasListeners(String propertyName) { return this.map.hasListeners(propertyName); diff --git a/jdk/src/share/classes/java/beans/Visibility.java b/jdk/src/share/classes/java/beans/Visibility.java index af413833879..5aab3f3afe7 100644 --- a/jdk/src/share/classes/java/beans/Visibility.java +++ b/jdk/src/share/classes/java/beans/Visibility.java @@ -34,6 +34,8 @@ package java.beans; * This interface is for expert developers, and is not needed * for normal simple beans. To avoid confusing end-users we * avoid using getXXX setXXX design patterns for these methods. + * + * @since 1.1 */ public interface Visibility { From e26ff7211c1400e149ef258abc4ddf2560564100 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 11 Jun 2014 14:21:12 +0400 Subject: [PATCH 046/192] 8041644: [OGL] clip is ignored during surface->sw blit Reviewed-by: bae, prr --- .../sun/java2d/opengl/OGLBlitLoops.java | 56 ++++++ .../DrawImage/IncorrectClipSurface2SW.java | 166 ++++++++++++++++++ 2 files changed, 222 insertions(+) create mode 100644 jdk/test/java/awt/image/DrawImage/IncorrectClipSurface2SW.java diff --git a/jdk/src/share/classes/sun/java2d/opengl/OGLBlitLoops.java b/jdk/src/share/classes/sun/java2d/opengl/OGLBlitLoops.java index aeab20823bb..54cfaf1f58f 100644 --- a/jdk/src/share/classes/sun/java2d/opengl/OGLBlitLoops.java +++ b/jdk/src/share/classes/sun/java2d/opengl/OGLBlitLoops.java @@ -510,6 +510,7 @@ class OGLRTTSurfaceToSurfaceTransform extends TransformBlit { final class OGLSurfaceToSwBlit extends Blit { private final int typeval; + private WeakReference srcTmp; // destination will actually be ArgbPre or Argb OGLSurfaceToSwBlit(final SurfaceType dstType,final int typeval) { @@ -519,11 +520,66 @@ final class OGLSurfaceToSwBlit extends Blit { this.typeval = typeval; } + private synchronized void complexClipBlit(SurfaceData src, SurfaceData dst, + Composite comp, Region clip, + int sx, int sy, int dx, int dy, + int w, int h) { + SurfaceData cachedSrc = null; + if (srcTmp != null) { + // use cached intermediate surface, if available + cachedSrc = srcTmp.get(); + } + + // We can convert argb_pre data from OpenGL surface in two places: + // - During OpenGL surface -> SW blit + // - During SW -> SW blit + // The first one is faster when we use opaque OGL surface, because in + // this case we simply skip conversion and use color components as is. + // Because of this we align intermediate buffer type with type of + // destination not source. + final int type = typeval == OGLSurfaceData.PF_INT_ARGB_PRE ? + BufferedImage.TYPE_INT_ARGB_PRE : + BufferedImage.TYPE_INT_ARGB; + + src = convertFrom(this, src, sx, sy, w, h, cachedSrc, type); + + // copy intermediate SW to destination SW using complex clip + final Blit performop = Blit.getFromCache(src.getSurfaceType(), + CompositeType.SrcNoEa, + dst.getSurfaceType()); + performop.Blit(src, dst, comp, clip, 0, 0, dx, dy, w, h); + + if (src != cachedSrc) { + // cache the intermediate surface + srcTmp = new WeakReference<>(src); + } + } + public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int sx, int sy, int dx, int dy, int w, int h) { + if (clip != null) { + clip = clip.getIntersectionXYWH(dx, dy, w, h); + // At the end this method will flush the RenderQueue, we should exit + // from it as soon as possible. + if (clip.isEmpty()) { + return; + } + sx += clip.getLoX() - dx; + sy += clip.getLoY() - dy; + dx = clip.getLoX(); + dy = clip.getLoY(); + w = clip.getWidth(); + h = clip.getHeight(); + + if (!clip.isRectangular()) { + complexClipBlit(src, dst, comp, clip, sx, sy, dx, dy, w, h); + return; + } + } + OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { diff --git a/jdk/test/java/awt/image/DrawImage/IncorrectClipSurface2SW.java b/jdk/test/java/awt/image/DrawImage/IncorrectClipSurface2SW.java new file mode 100644 index 00000000000..3c972b661ea --- /dev/null +++ b/jdk/test/java/awt/image/DrawImage/IncorrectClipSurface2SW.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.Image; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.geom.AffineTransform; +import java.awt.geom.Ellipse2D; +import java.awt.image.BufferedImage; +import java.awt.image.VolatileImage; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; + +import static java.awt.geom.Rectangle2D.Double; + +/** + * @test + * @bug 8041644 + * @summary Tests drawing volatile image to BI using different clip. + * Results of the blit compatibleImage to BI used for comparison. + * @author Sergey Bylokhov + * @run main/othervm -Dsun.java2d.d3d=false IncorrectClipSurface2SW + */ +public final class IncorrectClipSurface2SW { + + private static int[] SCALES = {1, 2, 4}; + private static int[] SIZES = {127, 3, 2, 1}; + private static final Shape[] SHAPES = {new Rectangle(0, 0, 0, 0), + new Rectangle(0, 0, 1, 1), + new Rectangle(0, 1, 1, 1), + new Rectangle(1, 0, 1, 1), + new Rectangle(1, 1, 1, 1), + + new Ellipse2D.Double(0, 0, 1, 1), + new Ellipse2D.Double(0, 1, 1, 1), + new Ellipse2D.Double(1, 0, 1, 1), + new Ellipse2D.Double(1, 1, 1, 1), + new Ellipse2D.Double(.25, .25, .5, + .5), + + new Double(0, 0, 0.5, 0.5), + new Double(0, 0.5, 0.5, 0.5), + new Double(0.5, 0, 0.5, 0.5), + new Double(0.5, 0.5, 0.5, 0.5), + new Double(0.25, 0.25, 0.5, 0.5), + new Double(0, 0.25, 1, 0.5), + new Double(0.25, 0, 0.5, 1), + + new Double(.10, .10, .20, .20), + new Double(.75, .75, .20, .20), + new Double(.75, .10, .20, .20), + new Double(.10, .75, .20, .20),}; + + public static void main(final String[] args) throws IOException { + GraphicsEnvironment ge = GraphicsEnvironment + .getLocalGraphicsEnvironment(); + GraphicsConfiguration gc = ge.getDefaultScreenDevice() + .getDefaultConfiguration(); + AffineTransform at; + for (final int size : SIZES) { + for (final int scale : SCALES) { + final int sw = size * scale; + at = AffineTransform.getScaleInstance(sw, sw); + for (Shape clip : SHAPES) { + clip = at.createTransformedShape(clip); + for (Shape to : SHAPES) { + to = at.createTransformedShape(to); + // Prepare test images + VolatileImage vi = getVolatileImage(gc, size); + BufferedImage bi = getBufferedImage(sw); + // Prepare gold images + BufferedImage goldvi = getCompatibleImage(gc, size); + BufferedImage goldbi = getBufferedImage(sw); + draw(clip, to, vi, bi, scale); + draw(clip, to, goldvi, goldbi, scale); + validate(bi, goldbi); + } + } + } + } + } + + private static void draw(Shape clip, Shape to, Image vi, BufferedImage bi, + int scale) { + Graphics2D big = bi.createGraphics(); + big.setComposite(AlphaComposite.Src); + big.setClip(clip); + Rectangle toBounds = to.getBounds(); + int x1 = toBounds.x; + + int y1 = toBounds.y; + int x2 = x1 + toBounds.width; + int y2 = y1 + toBounds.height; + big.drawImage(vi, x1, y1, x2, y2, 0, 0, toBounds.width / scale, + toBounds.height / scale, null); + big.dispose(); + vi.flush(); + } + + private static BufferedImage getBufferedImage(int sw) { + BufferedImage bi = new BufferedImage(sw, sw, + BufferedImage.TYPE_INT_ARGB); + Graphics2D g2d = bi.createGraphics(); + g2d.setColor(Color.RED); + g2d.fillRect(0, 0, sw, sw); + return bi; + } + + private static VolatileImage getVolatileImage(GraphicsConfiguration gc, + int size) { + VolatileImage vi = gc.createCompatibleVolatileImage(size, size); + Graphics2D g2d = vi.createGraphics(); + g2d.setColor(Color.GREEN); + g2d.fillRect(0, 0, size, size); + return vi; + } + + private static BufferedImage getCompatibleImage(GraphicsConfiguration gc, + int size) { + BufferedImage image = gc.createCompatibleImage(size, size); + Graphics2D g2d = image.createGraphics(); + g2d.setColor(Color.GREEN); + g2d.fillRect(0, 0, size, size); + return image; + } + + private static void validate(BufferedImage bi, BufferedImage goldbi) + throws IOException { + for (int x = 0; x < bi.getWidth(); ++x) { + for (int y = 0; y < bi.getHeight(); ++y) { + if (goldbi.getRGB(x, y) != bi.getRGB(x, y)) { + ImageIO.write(bi, "png", new File("actual.png")); + ImageIO.write(goldbi, "png", new File("expected.png")); + throw new RuntimeException("Test failed."); + } + } + } + } +} From d1927658370b8568cb0997e37fa3a3d9ba65b486 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 11 Jun 2014 14:38:50 +0400 Subject: [PATCH 047/192] 8042103: Deserialization of empty java.awt.geom.Path2D will cause an exception Reviewed-by: bae, flar --- .../share/classes/java/awt/geom/Path2D.java | 6 ++- .../java/awt/geom/Path2D/EmptyCapacity.java | 42 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 jdk/test/java/awt/geom/Path2D/EmptyCapacity.java diff --git a/jdk/src/share/classes/java/awt/geom/Path2D.java b/jdk/src/share/classes/java/awt/geom/Path2D.java index 7a401d36cf4..d75adf0cb57 100644 --- a/jdk/src/share/classes/java/awt/geom/Path2D.java +++ b/jdk/src/share/classes/java/awt/geom/Path2D.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -285,6 +285,8 @@ public abstract class Path2D implements Shape, Cloneable { int grow = size; if (grow > EXPAND_MAX) { grow = EXPAND_MAX; + } else if (grow == 0) { + grow = 1; } pointTypes = Arrays.copyOf(pointTypes, size+grow); } @@ -1121,6 +1123,8 @@ public abstract class Path2D implements Shape, Cloneable { int grow = size; if (grow > EXPAND_MAX) { grow = EXPAND_MAX; + } else if (grow == 0) { + grow = 1; } pointTypes = Arrays.copyOf(pointTypes, size+grow); } diff --git a/jdk/test/java/awt/geom/Path2D/EmptyCapacity.java b/jdk/test/java/awt/geom/Path2D/EmptyCapacity.java new file mode 100644 index 00000000000..9f6d9c18dc8 --- /dev/null +++ b/jdk/test/java/awt/geom/Path2D/EmptyCapacity.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.geom.Path2D; + +/** + * @test + * @bug 8042103 + * @summary Path2D.moveTo() should work if empty initial capacity was set. + * @author Sergey Bylokhov + */ +public final class EmptyCapacity { + + public static void main(final String[] args) { + final Path2D path1 = new Path2D.Double(Path2D.WIND_EVEN_ODD, 0); + path1.moveTo(10, 10); + path1.lineTo(20, 20); + final Path2D path2 = new Path2D.Float(Path2D.WIND_EVEN_ODD, 0); + path2.moveTo(10, 10); + path2.lineTo(20, 20); + } +} From 57efe4955f0eb38608ece15c3c08f9259e808666 Mon Sep 17 00:00:00 2001 From: Dmitriy Ermashov Date: Wed, 11 Jun 2014 17:23:56 +0400 Subject: [PATCH 048/192] 8043972: Remove wrong copyright notice in jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java Reviewed-by: anthony --- .../awt/Frame/DecoratedExceptions/DecoratedExceptions.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java b/jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java index b2a0ddc6fdc..8dca632bb57 100644 --- a/jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java +++ b/jdk/test/java/awt/Frame/DecoratedExceptions/DecoratedExceptions.java @@ -20,10 +20,6 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -/* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. - */ import java.awt.*; From 8538800448bf5872fcdbb86609e2969be41b9ffe Mon Sep 17 00:00:00 2001 From: Henry Jen Date: Thu, 5 Jun 2014 13:59:01 -0700 Subject: [PATCH 049/192] 8044551: Fix raw and unchecked lint warnings in platform-specific sun.awt files 8044396: Fix raw and unchecked lint warnings in platform-specific sun.java2d.* Reviewed-by: darcy, prr --- .../windows/classes/sun/awt/Win32FontManager.java | 10 ++++------ .../windows/classes/sun/awt/Win32GraphicsDevice.java | 8 ++++---- .../classes/sun/awt/shell/Win32ShellFolder2.java | 12 ++++++------ .../sun/awt/shell/Win32ShellFolderManager2.java | 4 ++-- .../sun/awt/windows/WDragSourceContextPeer.java | 6 ++++-- .../classes/sun/awt/windows/WFontConfiguration.java | 12 ++++++------ .../classes/sun/awt/windows/WFontMetrics.java | 4 ++-- .../classes/sun/awt/windows/WInputMethod.java | 9 +++++---- .../windows/classes/sun/awt/windows/WToolkit.java | 1 + .../windows/classes/sun/java2d/d3d/D3DBlitLoops.java | 6 +++--- .../classes/sun/java2d/d3d/D3DGraphicsDevice.java | 5 ++--- .../sun/java2d/windows/GDIWindowSurfaceData.java | 2 +- .../classes/sun/java2d/windows/WindowsFlags.java | 2 +- 13 files changed, 41 insertions(+), 40 deletions(-) diff --git a/jdk/src/windows/classes/sun/awt/Win32FontManager.java b/jdk/src/windows/classes/sun/awt/Win32FontManager.java index 5e925f3ce45..68136e98f4e 100644 --- a/jdk/src/windows/classes/sun/awt/Win32FontManager.java +++ b/jdk/src/windows/classes/sun/awt/Win32FontManager.java @@ -42,8 +42,6 @@ import sun.awt.windows.WFontConfiguration; import sun.font.FontManager; import sun.font.SunFontManager; import sun.font.TrueTypeFont; -import sun.java2d.HeadlessGraphicsEnvironment; -import sun.java2d.SunGraphicsEnvironment; /** * The X11 implementation of {@link FontManager}. @@ -56,7 +54,7 @@ public class Win32FontManager extends SunFontManager { static { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction() { public Object run() { String eudcFile = getEUDCFontFile(); @@ -90,7 +88,7 @@ public class Win32FontManager extends SunFontManager { public Win32FontManager() { super(); - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction() { public Object run() { /* Register the JRE fonts so that the native platform can @@ -227,7 +225,7 @@ public class Win32FontManager extends SunFontManager { final String[] dirs = getPlatformFontDirs(true); if (dirs.length > 1) { String dir = (String) - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction() { public Object run() { for (int i=0; i() { public Object run() { File f1 = new File(pathName); String[] ls = f1.list(SunFontManager.getInstance(). diff --git a/jdk/src/windows/classes/sun/awt/Win32GraphicsDevice.java b/jdk/src/windows/classes/sun/awt/Win32GraphicsDevice.java index d7cfc58e1e8..8ff76dc7e13 100644 --- a/jdk/src/windows/classes/sun/awt/Win32GraphicsDevice.java +++ b/jdk/src/windows/classes/sun/awt/Win32GraphicsDevice.java @@ -172,7 +172,7 @@ public class Win32GraphicsDevice extends GraphicsDevice implements int max = getMaxConfigs(screen); int defaultPixID = getDefaultPixID(screen); - Vector v = new Vector( max ); + Vector v = new Vector<>( max ); if (defaultPixID == 0) { // Workaround for failing GDI calls defaultConfig = Win32GraphicsConfig.getConfig(this, @@ -437,7 +437,7 @@ public class Win32GraphicsDevice extends GraphicsDevice implements protected native void configDisplayMode(int screen, WindowPeer w, int width, int height, int bitDepth, int refreshRate); - protected native void enumDisplayModes(int screen, ArrayList modes); + protected native void enumDisplayModes(int screen, ArrayList modes); @Override public synchronized DisplayMode getDisplayMode() { @@ -447,12 +447,12 @@ public class Win32GraphicsDevice extends GraphicsDevice implements @Override public synchronized DisplayMode[] getDisplayModes() { - ArrayList modes = new ArrayList(); + ArrayList modes = new ArrayList<>(); enumDisplayModes(screen, modes); int listSize = modes.size(); DisplayMode[] retArray = new DisplayMode[listSize]; for (int i = 0; i < listSize; i++) { - retArray[i] = (DisplayMode)modes.get(i); + retArray[i] = modes.get(i); } return retArray; } diff --git a/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolder2.java b/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolder2.java index 696633917a2..42975132b15 100644 --- a/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolder2.java +++ b/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolder2.java @@ -894,10 +894,10 @@ final class Win32ShellFolder2 extends ShellFolder { // Icons - private static Map smallSystemImages = new HashMap(); - private static Map largeSystemImages = new HashMap(); - private static Map smallLinkedSystemImages = new HashMap(); - private static Map largeLinkedSystemImages = new HashMap(); + private static Map smallSystemImages = new HashMap<>(); + private static Map largeSystemImages = new HashMap<>(); + private static Map smallLinkedSystemImages = new HashMap<>(); + private static Map largeLinkedSystemImages = new HashMap<>(); // NOTE: this method uses COM and must be called on the 'COM thread'. See ComInvoker for the details private static native long getIShellIcon(long pIShellFolder); @@ -970,13 +970,13 @@ final class Win32ShellFolder2 extends ShellFolder { // These are cached per type (using the index in the system image list) int index = getIconIndex(parentIShellIcon, relativePIDL); if (index > 0) { - Map imageCache; + Map imageCache; if (isLink()) { imageCache = getLargeIcon ? largeLinkedSystemImages : smallLinkedSystemImages; } else { imageCache = getLargeIcon ? largeSystemImages : smallSystemImages; } - newIcon = (Image) imageCache.get(Integer.valueOf(index)); + newIcon = imageCache.get(Integer.valueOf(index)); if (newIcon == null) { long hIcon = getIcon(getAbsolutePath(), getLargeIcon); newIcon = makeIcon(hIcon, getLargeIcon); diff --git a/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java b/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java index 269eff2e421..426a0eb77ff 100644 --- a/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java +++ b/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java @@ -414,14 +414,14 @@ public class Win32ShellFolderManager2 extends ShellFolderManager { return false; } - private static List topFolderList = null; + private static List topFolderList = null; static int compareShellFolders(Win32ShellFolder2 sf1, Win32ShellFolder2 sf2) { boolean special1 = sf1.isSpecial(); boolean special2 = sf2.isSpecial(); if (special1 || special2) { if (topFolderList == null) { - ArrayList tmpTopFolderList = new ArrayList(); + ArrayList tmpTopFolderList = new ArrayList<>(); tmpTopFolderList.add(Win32ShellFolderManager2.getPersonal()); tmpTopFolderList.add(Win32ShellFolderManager2.getDesktop()); tmpTopFolderList.add(Win32ShellFolderManager2.getDrives()); diff --git a/jdk/src/windows/classes/sun/awt/windows/WDragSourceContextPeer.java b/jdk/src/windows/classes/sun/awt/windows/WDragSourceContextPeer.java index 36280f2e571..360d842834b 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WDragSourceContextPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WDragSourceContextPeer.java @@ -29,6 +29,7 @@ import java.awt.Component; import java.awt.Cursor; import java.awt.Image; import java.awt.Point; +import java.awt.datatransfer.DataFlavor; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; @@ -76,8 +77,9 @@ final class WDragSourceContextPeer extends SunDragSourceContextPeer { return theInstance; } + @Override protected void startDrag(Transferable trans, - long[] formats, Map formatMap) { + long[] formats, Map formatMap) { long nativeCtxtLocal = 0; @@ -153,7 +155,7 @@ final class WDragSourceContextPeer extends SunDragSourceContextPeer { InputEvent nativeTrigger, int actions, long[] formats, - Map formatMap); + Map formatMap); /** * downcall into native code diff --git a/jdk/src/windows/classes/sun/awt/windows/WFontConfiguration.java b/jdk/src/windows/classes/sun/awt/windows/WFontConfiguration.java index 7315b97db77..4cd88216bca 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WFontConfiguration.java +++ b/jdk/src/windows/classes/sun/awt/windows/WFontConfiguration.java @@ -53,7 +53,7 @@ public final class WFontConfiguration extends FontConfiguration { @Override protected void initReorderMap() { if (encoding.equalsIgnoreCase("windows-31j")) { - localeMap = new Hashtable(); + localeMap = new Hashtable<>(); /* Substitute Mincho for Gothic in this one case. * Note the windows fontconfig files already contain the mapping: * filename.MS_Mincho=MSMINCHO.TTC @@ -67,7 +67,7 @@ public final class WFontConfiguration extends FontConfiguration { localeMap.put("dialoginput.italic.japanese", "MS Mincho"); localeMap.put("dialoginput.bolditalic.japanese", "MS Mincho"); } - reorderMap = new HashMap(); + reorderMap = new HashMap<>(); reorderMap.put("UTF-8.hi", "devanagari"); reorderMap.put("windows-1255", "hebrew"); reorderMap.put("x-windows-874", "thai"); @@ -118,7 +118,7 @@ public final class WFontConfiguration extends FontConfiguration { @Override protected String makeAWTFontName(String platformFontName, String characterSubsetName) { - String windowsCharset = (String) subsetCharsetMap.get(characterSubsetName); + String windowsCharset = subsetCharsetMap.get(characterSubsetName); if (windowsCharset == null) { windowsCharset = "DEFAULT_CHARSET"; } @@ -127,7 +127,7 @@ public final class WFontConfiguration extends FontConfiguration { @Override protected String getEncoding(String awtFontName, String characterSubsetName) { - String encoding = (String) subsetEncodingMap.get(characterSubsetName); + String encoding = subsetEncodingMap.get(characterSubsetName); if (encoding == null) { encoding = "default"; } @@ -174,8 +174,8 @@ public final class WFontConfiguration extends FontConfiguration { return fontName; } - private static HashMap subsetCharsetMap = new HashMap(); - private static HashMap subsetEncodingMap = new HashMap(); + private static HashMap subsetCharsetMap = new HashMap<>(); + private static HashMap subsetEncodingMap = new HashMap<>(); private static String textInputCharset; private void initTables(String defaultEncoding) { diff --git a/jdk/src/windows/classes/sun/awt/windows/WFontMetrics.java b/jdk/src/windows/classes/sun/awt/windows/WFontMetrics.java index 01dae69c91a..8d8a9515df7 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WFontMetrics.java +++ b/jdk/src/windows/classes/sun/awt/windows/WFontMetrics.java @@ -199,10 +199,10 @@ final class WFontMetrics extends FontMetrics { native void init(); - static Hashtable table = new Hashtable(); + static Hashtable table = new Hashtable<>(); static FontMetrics getFontMetrics(Font font) { - FontMetrics fm = (FontMetrics)table.get(font); + FontMetrics fm = table.get(font); if (fm == null) { table.put(font, fm = new WFontMetrics(font)); } diff --git a/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java b/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java index de7c478c087..1d3c413dfc3 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java +++ b/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java @@ -86,26 +86,27 @@ final class WInputMethod extends InputMethodAdapter // Initialize highlight mapping table static { + @SuppressWarnings({"rawtypes", "unchecked"}) Map styles[] = new Map[4]; HashMap map; // UNSELECTED_RAW_TEXT_HIGHLIGHT - map = new HashMap(1); + map = new HashMap<>(1); map.put(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_DOTTED); styles[0] = Collections.unmodifiableMap(map); // SELECTED_RAW_TEXT_HIGHLIGHT - map = new HashMap(1); + map = new HashMap<>(1); map.put(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_GRAY); styles[1] = Collections.unmodifiableMap(map); // UNSELECTED_CONVERTED_TEXT_HIGHLIGHT - map = new HashMap(1); + map = new HashMap<>(1); map.put(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_DOTTED); styles[2] = Collections.unmodifiableMap(map); // SELECTED_CONVERTED_TEXT_HIGHLIGHT - map = new HashMap(4); + map = new HashMap<>(4); Color navyBlue = new Color(0, 0, 128); map.put(TextAttribute.FOREGROUND, navyBlue); map.put(TextAttribute.BACKGROUND, Color.white); diff --git a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java index 2a27c2df9cc..d33b991d7f8 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java +++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java @@ -843,6 +843,7 @@ public final class WToolkit extends SunToolkit implements Runnable { } @Override + @SuppressWarnings("unchecked") public T createDragGestureRecognizer(Class abstractRecognizerClass, DragSource ds, Component c, int srcActions, diff --git a/jdk/src/windows/classes/sun/java2d/d3d/D3DBlitLoops.java b/jdk/src/windows/classes/sun/java2d/d3d/D3DBlitLoops.java index b7b09e7b6dd..94495da083e 100644 --- a/jdk/src/windows/classes/sun/java2d/d3d/D3DBlitLoops.java +++ b/jdk/src/windows/classes/sun/java2d/d3d/D3DBlitLoops.java @@ -717,7 +717,7 @@ class D3DTextureToSurfaceTransform extends TransformBlit { class D3DGeneralBlit extends Blit { private Blit performop; - private WeakReference srcTmp; + private WeakReference srcTmp; D3DGeneralBlit(SurfaceType dstType, CompositeType compType, @@ -739,7 +739,7 @@ class D3DGeneralBlit extends Blit { SurfaceData cachedSrc = null; if (srcTmp != null) { // use cached intermediate surface, if available - cachedSrc = (SurfaceData)srcTmp.get(); + cachedSrc = srcTmp.get(); } // convert source to IntArgbPre @@ -752,7 +752,7 @@ class D3DGeneralBlit extends Blit { if (src != cachedSrc) { // cache the intermediate surface - srcTmp = new WeakReference(src); + srcTmp = new WeakReference<>(src); } } } diff --git a/jdk/src/windows/classes/sun/java2d/d3d/D3DGraphicsDevice.java b/jdk/src/windows/classes/sun/java2d/d3d/D3DGraphicsDevice.java index bf6134648c3..d30f1720bfc 100644 --- a/jdk/src/windows/classes/sun/java2d/d3d/D3DGraphicsDevice.java +++ b/jdk/src/windows/classes/sun/java2d/d3d/D3DGraphicsDevice.java @@ -41,7 +41,6 @@ import sun.awt.Win32GraphicsDevice; import sun.awt.windows.WWindowPeer; import sun.java2d.pipe.hw.ContextCapabilities; import sun.java2d.windows.WindowsFlags; -import static sun.java2d.pipe.BufferedOpCodes.*; import static sun.java2d.d3d.D3DContext.D3DContextCaps.*; import sun.java2d.d3d.D3DContext.D3DContextCaps; @@ -383,9 +382,9 @@ public class D3DGraphicsDevice extends Win32GraphicsDevice { } private static native void enumDisplayModesNative(int screen, - ArrayList modes); + ArrayList modes); @Override - protected void enumDisplayModes(final int screen, final ArrayList modes) { + protected void enumDisplayModes(final int screen, final ArrayList modes) { D3DRenderQueue rq = D3DRenderQueue.getInstance(); rq.lock(); try { diff --git a/jdk/src/windows/classes/sun/java2d/windows/GDIWindowSurfaceData.java b/jdk/src/windows/classes/sun/java2d/windows/GDIWindowSurfaceData.java index 49d9261bbd3..04ba1464001 100644 --- a/jdk/src/windows/classes/sun/java2d/windows/GDIWindowSurfaceData.java +++ b/jdk/src/windows/classes/sun/java2d/windows/GDIWindowSurfaceData.java @@ -75,7 +75,7 @@ public class GDIWindowSurfaceData extends SurfaceData { public static final SurfaceType ThreeByteBgrGdi = SurfaceType.ThreeByteBgr.deriveSubType(DESC_GDI); - private static native void initIDs(Class xorComp); + private static native void initIDs(Class xorComp); static { initIDs(XORComposite.class); diff --git a/jdk/src/windows/classes/sun/java2d/windows/WindowsFlags.java b/jdk/src/windows/classes/sun/java2d/windows/WindowsFlags.java index a6d265fd3f8..b8fc7510471 100644 --- a/jdk/src/windows/classes/sun/java2d/windows/WindowsFlags.java +++ b/jdk/src/windows/classes/sun/java2d/windows/WindowsFlags.java @@ -201,7 +201,7 @@ public class WindowsFlags { private static void initJavaFlags() { java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() + new java.security.PrivilegedAction() { public Object run() { magPresent = getBooleanProp( From 61431e72a805d76d30f6206a57d3d0ecac78fd31 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Thu, 5 Jun 2014 23:17:05 -0700 Subject: [PATCH 050/192] 8044553: Fix raw and unchecked lint warnings in javax.sound.* Reviewed-by: prr --- .../javax/sound/midi/MidiFileFormat.java | 1 + .../classes/javax/sound/midi/MidiSystem.java | 155 ++++++++-------- .../javax/sound/midi/SoundbankResource.java | 4 +- .../share/classes/javax/sound/midi/Track.java | 14 +- .../javax/sound/sampled/AudioFileFormat.java | 3 +- .../javax/sound/sampled/AudioFormat.java | 3 +- .../javax/sound/sampled/AudioSystem.java | 166 +++++++++--------- .../classes/javax/sound/sampled/Line.java | 2 +- 8 files changed, 178 insertions(+), 170 deletions(-) diff --git a/jdk/src/share/classes/javax/sound/midi/MidiFileFormat.java b/jdk/src/share/classes/javax/sound/midi/MidiFileFormat.java index 0d496490dd0..c34bb6d1900 100644 --- a/jdk/src/share/classes/javax/sound/midi/MidiFileFormat.java +++ b/jdk/src/share/classes/javax/sound/midi/MidiFileFormat.java @@ -266,6 +266,7 @@ public class MidiFileFormat { * @see #getProperty(String) * @since 1.5 */ + @SuppressWarnings("unchecked") // Cast of result of clone public Map properties() { Map ret; if (properties == null) { diff --git a/jdk/src/share/classes/javax/sound/midi/MidiSystem.java b/jdk/src/share/classes/javax/sound/midi/MidiSystem.java index c661e23304d..d6ef5432978 100644 --- a/jdk/src/share/classes/javax/sound/midi/MidiSystem.java +++ b/jdk/src/share/classes/javax/sound/midi/MidiSystem.java @@ -187,17 +187,17 @@ public class MidiSystem { * an array of length 0 is returned. */ public static MidiDevice.Info[] getMidiDeviceInfo() { - List allInfos = new ArrayList(); - List providers = getMidiDeviceProviders(); + List allInfos = new ArrayList<>(); + List providers = getMidiDeviceProviders(); for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); MidiDevice.Info[] tmpinfo = provider.getDeviceInfo(); for (int j = 0; j < tmpinfo.length; j++) { allInfos.add( tmpinfo[j] ); } } - MidiDevice.Info[] infosArray = (MidiDevice.Info[]) allInfos.toArray(new MidiDevice.Info[0]); + MidiDevice.Info[] infosArray = allInfos.toArray(new MidiDevice.Info[0]); return infosArray; } @@ -214,10 +214,10 @@ public class MidiSystem { * @see #getMidiDeviceInfo */ public static MidiDevice getMidiDevice(MidiDevice.Info info) throws MidiUnavailableException { - List providers = getMidiDeviceProviders(); + List providers = getMidiDeviceProviders(); for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); if (provider.isDeviceSupported(info)) { MidiDevice device = provider.getDevice(info); return device; @@ -528,10 +528,10 @@ public class MidiSystem { SoundbankReader sp = null; Soundbank s = null; - List providers = getSoundbankReaders(); + List providers = getSoundbankReaders(); for(int i = 0; i < providers.size(); i++) { - sp = (SoundbankReader)providers.get(i); + sp = providers.get(i); s = sp.getSoundbank(stream); if( s!= null) { @@ -559,10 +559,10 @@ public class MidiSystem { SoundbankReader sp = null; Soundbank s = null; - List providers = getSoundbankReaders(); + List providers = getSoundbankReaders(); for(int i = 0; i < providers.size(); i++) { - sp = (SoundbankReader)providers.get(i); + sp = providers.get(i); s = sp.getSoundbank(url); if( s!= null) { @@ -591,10 +591,10 @@ public class MidiSystem { SoundbankReader sp = null; Soundbank s = null; - List providers = getSoundbankReaders(); + List providers = getSoundbankReaders(); for(int i = 0; i < providers.size(); i++) { - sp = (SoundbankReader)providers.get(i); + sp = providers.get(i); s = sp.getSoundbank(file); if( s!= null) { @@ -641,11 +641,11 @@ public class MidiSystem { public static MidiFileFormat getMidiFileFormat(InputStream stream) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); MidiFileFormat format = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { format = reader.getMidiFileFormat( stream ); // throws IOException break; @@ -687,11 +687,11 @@ public class MidiSystem { public static MidiFileFormat getMidiFileFormat(URL url) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); MidiFileFormat format = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { format = reader.getMidiFileFormat( url ); // throws IOException break; @@ -733,11 +733,11 @@ public class MidiSystem { public static MidiFileFormat getMidiFileFormat(File file) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); MidiFileFormat format = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { format = reader.getMidiFileFormat( file ); // throws IOException break; @@ -788,11 +788,11 @@ public class MidiSystem { public static Sequence getSequence(InputStream stream) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); Sequence sequence = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { sequence = reader.getSequence( stream ); // throws IOException break; @@ -832,11 +832,11 @@ public class MidiSystem { public static Sequence getSequence(URL url) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); Sequence sequence = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { sequence = reader.getSequence( url ); // throws IOException break; @@ -876,11 +876,11 @@ public class MidiSystem { public static Sequence getSequence(File file) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); Sequence sequence = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { sequence = reader.getSequence( file ); // throws IOException break; @@ -905,13 +905,13 @@ public class MidiSystem { */ public static int[] getMidiFileTypes() { - List providers = getMidiFileWriters(); - Set allTypes = new HashSet(); + List providers = getMidiFileWriters(); + Set allTypes = new HashSet<>(); // gather from all the providers for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); int[] types = writer.getMidiFileTypes(); for (int j = 0; j < types.length; j++ ) { allTypes.add(new Integer(types[j])); @@ -919,9 +919,9 @@ public class MidiSystem { } int resultTypes[] = new int[allTypes.size()]; int index = 0; - Iterator iterator = allTypes.iterator(); + Iterator iterator = allTypes.iterator(); while (iterator.hasNext()) { - Integer integer = (Integer) iterator.next(); + Integer integer = iterator.next(); resultTypes[index++] = integer.intValue(); } return resultTypes; @@ -937,10 +937,10 @@ public class MidiSystem { */ public static boolean isFileTypeSupported(int fileType) { - List providers = getMidiFileWriters(); + List providers = getMidiFileWriters(); for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); if( writer.isFileTypeSupported(fileType)) { return true; } @@ -959,13 +959,13 @@ public class MidiSystem { */ public static int[] getMidiFileTypes(Sequence sequence) { - List providers = getMidiFileWriters(); - Set allTypes = new HashSet(); + List providers = getMidiFileWriters(); + Set allTypes = new HashSet<>(); // gather from all the providers for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); int[] types = writer.getMidiFileTypes(sequence); for (int j = 0; j < types.length; j++ ) { allTypes.add(new Integer(types[j])); @@ -973,9 +973,9 @@ public class MidiSystem { } int resultTypes[] = new int[allTypes.size()]; int index = 0; - Iterator iterator = allTypes.iterator(); + Iterator iterator = allTypes.iterator(); while (iterator.hasNext()) { - Integer integer = (Integer) iterator.next(); + Integer integer = iterator.next(); resultTypes[index++] = integer.intValue(); } return resultTypes; @@ -993,10 +993,10 @@ public class MidiSystem { */ public static boolean isFileTypeSupported(int fileType, Sequence sequence) { - List providers = getMidiFileWriters(); + List providers = getMidiFileWriters(); for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); if( writer.isFileTypeSupported(fileType,sequence)) { return true; } @@ -1020,12 +1020,12 @@ public class MidiSystem { */ public static int write(Sequence in, int fileType, OutputStream out) throws IOException { - List providers = getMidiFileWriters(); + List providers = getMidiFileWriters(); //$$fb 2002-04-17: Fix for 4635287: Standard MidiFileWriter cannot write empty Sequences int bytesWritten = -2; for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); if( writer.isFileTypeSupported( fileType, in ) ) { bytesWritten = writer.write(in, fileType, out); @@ -1054,12 +1054,12 @@ public class MidiSystem { */ public static int write(Sequence in, int type, File out) throws IOException { - List providers = getMidiFileWriters(); + List providers = getMidiFileWriters(); //$$fb 2002-04-17: Fix for 4635287: Standard MidiFileWriter cannot write empty Sequences int bytesWritten = -2; for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); if( writer.isFileTypeSupported( type, in ) ) { bytesWritten = writer.write(in, type, out); @@ -1075,24 +1075,24 @@ public class MidiSystem { // HELPER METHODS - - private static List getMidiDeviceProviders() { - return getProviders(MidiDeviceProvider.class); + @SuppressWarnings("unchecked") + private static List getMidiDeviceProviders() { + return (List) getProviders(MidiDeviceProvider.class); } - - private static List getSoundbankReaders() { - return getProviders(SoundbankReader.class); + @SuppressWarnings("unchecked") + private static List getSoundbankReaders() { + return (List) getProviders(SoundbankReader.class); } - - private static List getMidiFileWriters() { - return getProviders(MidiFileWriter.class); + @SuppressWarnings("unchecked") + private static List getMidiFileWriters() { + return (List) getProviders(MidiFileWriter.class); } - - private static List getMidiFileReaders() { - return getProviders(MidiFileReader.class); + @SuppressWarnings("unchecked") + private static List getMidiFileReaders() { + return (List) getProviders(MidiFileReader.class); } @@ -1109,7 +1109,7 @@ public class MidiSystem { * Sequencer.class, Receiver.class or Transmitter.class. * @throws MidiUnavalableException on failure. */ - private static MidiDevice getDefaultDeviceWrapper(Class deviceClass) + private static MidiDevice getDefaultDeviceWrapper(Class deviceClass) throws MidiUnavailableException{ try { return getDefaultDevice(deviceClass); @@ -1128,8 +1128,8 @@ public class MidiSystem { * Sequencer.class, Receiver.class or Transmitter.class. * @throws IllegalArgumentException on failure. */ - private static MidiDevice getDefaultDevice(Class deviceClass) { - List providers = getMidiDeviceProviders(); + private static MidiDevice getDefaultDevice(Class deviceClass) { + List providers = getMidiDeviceProviders(); String providerClassName = JDK13Services.getDefaultProviderClassName(deviceClass); String instanceName = JDK13Services.getDefaultInstanceName(deviceClass); MidiDevice device; @@ -1179,9 +1179,10 @@ public class MidiSystem { @return A MidiDeviceProvider of the requested class, or null if none is found. */ - private static MidiDeviceProvider getNamedProvider(String providerClassName, List providers) { + private static MidiDeviceProvider getNamedProvider(String providerClassName, + List providers) { for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); if (provider.getClass().getName().equals(providerClassName)) { return provider; } @@ -1200,7 +1201,7 @@ public class MidiSystem { */ private static MidiDevice getNamedDevice(String deviceName, MidiDeviceProvider provider, - Class deviceClass) { + Class deviceClass) { MidiDevice device; // try to get MIDI port device = getNamedDevice(deviceName, provider, deviceClass, @@ -1232,7 +1233,7 @@ public class MidiSystem { */ private static MidiDevice getNamedDevice(String deviceName, MidiDeviceProvider provider, - Class deviceClass, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { MidiDevice.Info[] infos = provider.getDeviceInfo(); @@ -1259,8 +1260,8 @@ public class MidiSystem { @return A Mixer matching the requirements, or null if none is found. */ private static MidiDevice getNamedDevice(String deviceName, - List providers, - Class deviceClass) { + List providers, + Class deviceClass) { MidiDevice device; // try to get MIDI port device = getNamedDevice(deviceName, providers, deviceClass, @@ -1292,12 +1293,12 @@ public class MidiSystem { @return A Mixer matching the requirements, or null if none is found. */ private static MidiDevice getNamedDevice(String deviceName, - List providers, - Class deviceClass, + List providers, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); MidiDevice device = getNamedDevice(deviceName, provider, deviceClass, allowSynthesizer, @@ -1318,7 +1319,7 @@ public class MidiSystem { appropriate device is found. */ private static MidiDevice getFirstDevice(MidiDeviceProvider provider, - Class deviceClass) { + Class deviceClass) { MidiDevice device; // try to get MIDI port device = getFirstDevice(provider, deviceClass, @@ -1348,7 +1349,7 @@ public class MidiSystem { appropriate device is found. */ private static MidiDevice getFirstDevice(MidiDeviceProvider provider, - Class deviceClass, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { MidiDevice.Info[] infos = provider.getDeviceInfo(); @@ -1371,8 +1372,8 @@ public class MidiSystem { @return A MidiDevice that is considered appropriate, or null if none is found. */ - private static MidiDevice getFirstDevice(List providers, - Class deviceClass) { + private static MidiDevice getFirstDevice(List providers, + Class deviceClass) { MidiDevice device; // try to get MIDI port device = getFirstDevice(providers, deviceClass, @@ -1402,12 +1403,12 @@ public class MidiSystem { @return A MidiDevice that is considered appropriate, or null if none is found. */ - private static MidiDevice getFirstDevice(List providers, - Class deviceClass, + private static MidiDevice getFirstDevice(List providers, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); MidiDevice device = getFirstDevice(provider, deviceClass, allowSynthesizer, allowSequencer); @@ -1441,11 +1442,11 @@ public class MidiSystem { rules given above, false otherwise. */ private static boolean isAppropriateDevice(MidiDevice device, - Class deviceClass, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { if (deviceClass.isInstance(device)) { - // This clause is for deviceClass being either Synthesizer + // This clause is for deviceClass being either Synthesizer // or Sequencer. return true; } else { @@ -1479,7 +1480,7 @@ public class MidiSystem { * @return a List of instances of providers for the requested service. * If no providers are available, a List of length 0 will be returned. */ - private static List getProviders(Class providerClass) { - return JDK13Services.getProviders(providerClass); + private static List getProviders(Class providerClass) { + return JDK13Services.getProviders(providerClass); } } diff --git a/jdk/src/share/classes/javax/sound/midi/SoundbankResource.java b/jdk/src/share/classes/javax/sound/midi/SoundbankResource.java index 87c0864a627..52ba8f78feb 100644 --- a/jdk/src/share/classes/javax/sound/midi/SoundbankResource.java +++ b/jdk/src/share/classes/javax/sound/midi/SoundbankResource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -83,7 +83,7 @@ public abstract class SoundbankResource { /** * The class used to represent the sample's data. */ - private final Class dataClass; + private final Class dataClass; /** diff --git a/jdk/src/share/classes/javax/sound/midi/Track.java b/jdk/src/share/classes/javax/sound/midi/Track.java index 4e54a8aa3dd..d9e0f438b6c 100644 --- a/jdk/src/share/classes/javax/sound/midi/Track.java +++ b/jdk/src/share/classes/javax/sound/midi/Track.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -66,10 +66,10 @@ public class Track { // TODO: use arrays for faster access // the list containing the events - private ArrayList eventsList = new ArrayList(); + private ArrayList eventsList = new ArrayList<>(); // use a hashset to detect duplicate events in add(MidiEvent) - private HashSet set = new HashSet(); + private HashSet set = new HashSet<>(); private MidiEvent eotEvent; @@ -108,7 +108,7 @@ public class Track { // get the last event MidiEvent lastEvent = null; if (eventsCount > 0) { - lastEvent = (MidiEvent) eventsList.get(eventsCount - 1); + lastEvent = eventsList.get(eventsCount - 1); } // sanity check that we have a correct end-of-track if (lastEvent != eotEvent) { @@ -148,7 +148,7 @@ public class Track { // tick order int i = eventsCount; for ( ; i > 0; i--) { - if (event.getTick() >= ((MidiEvent)eventsList.get(i-1)).getTick()) { + if (event.getTick() >= (eventsList.get(i-1)).getTick()) { break; } } @@ -220,7 +220,7 @@ public class Track { public MidiEvent get(int index) throws ArrayIndexOutOfBoundsException { try { synchronized(eventsList) { - return (MidiEvent)eventsList.get(index); + return eventsList.get(index); } } catch (IndexOutOfBoundsException ioobe) { throw new ArrayIndexOutOfBoundsException(ioobe.getMessage()); @@ -253,7 +253,7 @@ public class Track { long ret = 0; synchronized (eventsList) { if (eventsList.size() > 0) { - ret = ((MidiEvent)eventsList.get(eventsList.size() - 1)).getTick(); + ret = (eventsList.get(eventsList.size() - 1)).getTick(); } } return ret; diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java b/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java index 31a279d56ee..9c6ba5a3e4e 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java @@ -233,10 +233,11 @@ public class AudioFileFormat { * @see #getProperty(String) * @since 1.5 */ + @SuppressWarnings("unchecked") // Cast of result of clone public Map properties() { Map ret; if (properties == null) { - ret = new HashMap(0); + ret = new HashMap<>(0); } else { ret = (Map) (properties.clone()); } diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java b/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java index 9ea70f975f1..39264aacf84 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java @@ -388,10 +388,11 @@ public class AudioFormat { * @see #getProperty(String) * @since 1.5 */ + @SuppressWarnings("unchecked") // Cast of result of clone. public Map properties() { Map ret; if (properties == null) { - ret = new HashMap(0); + ret = new HashMap<>(0); } else { ret = (Map) (properties.clone()); } diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java b/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java index 7b5428b1c19..459ef997855 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java @@ -175,8 +175,8 @@ public class AudioSystem { */ public static Mixer.Info[] getMixerInfo() { - List infos = getMixerInfoList(); - Mixer.Info[] allInfos = (Mixer.Info[]) infos.toArray(new Mixer.Info[infos.size()]); + List infos = getMixerInfoList(); + Mixer.Info[] allInfos = infos.toArray(new Mixer.Info[infos.size()]); return allInfos; } @@ -195,12 +195,12 @@ public class AudioSystem { public static Mixer getMixer(Mixer.Info info) { Mixer mixer = null; - List providers = getMixerProviders(); + List providers = getMixerProviders(); for(int i = 0; i < providers.size(); i++ ) { try { - return ((MixerProvider)providers.get(i)).getMixer(info); + return providers.get(i).getMixer(info); } catch (IllegalArgumentException e) { } catch (NullPointerException e) { @@ -217,7 +217,7 @@ public class AudioSystem { if (info == null) { for(int i = 0; i < providers.size(); i++ ) { try { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); Mixer.Info[] infos = provider.getMixerInfo(); // start from 0 to last device (do not reverse this order) for (int ii = 0; ii < infos.length; ii++) { @@ -253,7 +253,7 @@ public class AudioSystem { */ public static Line.Info[] getSourceLineInfo(Line.Info info) { - Vector vector = new Vector(); + Vector vector = new Vector<>(); Line.Info[] currentInfoArray; Mixer mixer; @@ -273,7 +273,7 @@ public class AudioSystem { Line.Info[] returnedArray = new Line.Info[vector.size()]; for (int i = 0; i < returnedArray.length; i++) { - returnedArray[i] = (Line.Info)vector.get(i); + returnedArray[i] = vector.get(i); } return returnedArray; @@ -292,7 +292,7 @@ public class AudioSystem { */ public static Line.Info[] getTargetLineInfo(Line.Info info) { - Vector vector = new Vector(); + Vector vector = new Vector<>(); Line.Info[] currentInfoArray; Mixer mixer; @@ -312,7 +312,7 @@ public class AudioSystem { Line.Info[] returnedArray = new Line.Info[vector.size()]; for (int i = 0; i < returnedArray.length; i++) { - returnedArray[i] = (Line.Info)vector.get(i); + returnedArray[i] = vector.get(i); } return returnedArray; @@ -382,7 +382,7 @@ public class AudioSystem { */ public static Line getLine(Line.Info info) throws LineUnavailableException { LineUnavailableException lue = null; - List providers = getMixerProviders(); + List providers = getMixerProviders(); // 1: try from default mixer for this line class @@ -401,7 +401,7 @@ public class AudioSystem { // 2: if that doesn't work, try to find any mixing mixer for(int i = 0; i < providers.size(); i++) { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); Mixer.Info[] infos = provider.getMixerInfo(); for (int j = 0; j < infos.length; j++) { @@ -423,7 +423,7 @@ public class AudioSystem { // 3: if that didn't work, try to find any non-mixing mixer for(int i = 0; i < providers.size(); i++) { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); Mixer.Info[] infos = provider.getMixerInfo(); for (int j = 0; j < infos.length; j++) { try { @@ -700,14 +700,14 @@ public class AudioSystem { */ public static AudioFormat.Encoding[] getTargetEncodings(AudioFormat.Encoding sourceEncoding) { - List codecs = getFormatConversionProviders(); - Vector encodings = new Vector(); + List codecs = getFormatConversionProviders(); + Vector encodings = new Vector<>(); AudioFormat.Encoding encs[] = null; // gather from all the codecs for(int i=0; i codecs = getFormatConversionProviders(); + Vector encodings = new Vector<>(); int size = 0; int index = 0; @@ -745,7 +745,7 @@ public class AudioSystem { // gather from all the codecs for(int i=0; i codecs = getFormatConversionProviders(); for(int i=0; i codecs = getFormatConversionProviders(); for(int i = 0; i < codecs.size(); i++) { - FormatConversionProvider codec = (FormatConversionProvider) codecs.get(i); + FormatConversionProvider codec = codecs.get(i); if( codec.isConversionSupported( targetEncoding, sourceStream.getFormat() ) ) { return codec.getAudioInputStream( targetEncoding, sourceStream ); } @@ -825,8 +825,8 @@ public class AudioSystem { */ public static AudioFormat[] getTargetFormats(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) { - List codecs = getFormatConversionProviders(); - Vector formats = new Vector(); + List codecs = getFormatConversionProviders(); + Vector formats = new Vector<>(); int size = 0; int index = 0; @@ -835,7 +835,7 @@ public class AudioSystem { // gather from all the codecs for(int i=0; i codecs = getFormatConversionProviders(); for(int i=0; i codecs = getFormatConversionProviders(); for(int i = 0; i < codecs.size(); i++) { - FormatConversionProvider codec = (FormatConversionProvider) codecs.get(i); + FormatConversionProvider codec = codecs.get(i); if(codec.isConversionSupported(targetFormat,sourceStream.getFormat()) ) { return codec.getAudioInputStream(targetFormat,sourceStream); } @@ -931,11 +931,11 @@ public class AudioSystem { public static AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioFileFormat format = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { format = reader.getAudioFileFormat( stream ); // throws IOException break; @@ -966,11 +966,11 @@ public class AudioSystem { public static AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioFileFormat format = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { format = reader.getAudioFileFormat( url ); // throws IOException break; @@ -1001,11 +1001,11 @@ public class AudioSystem { public static AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioFileFormat format = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { format = reader.getAudioFileFormat( file ); // throws IOException break; @@ -1044,11 +1044,11 @@ public class AudioSystem { public static AudioInputStream getAudioInputStream(InputStream stream) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioInputStream audioStream = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { audioStream = reader.getAudioInputStream( stream ); // throws IOException break; @@ -1079,11 +1079,11 @@ public class AudioSystem { public static AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioInputStream audioStream = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { audioStream = reader.getAudioInputStream( url ); // throws IOException break; @@ -1114,11 +1114,11 @@ public class AudioSystem { public static AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioInputStream audioStream = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { audioStream = reader.getAudioInputStream( file ); // throws IOException break; @@ -1142,17 +1142,17 @@ public class AudioSystem { * array of length 0 is returned. */ public static AudioFileFormat.Type[] getAudioFileTypes() { - List providers = getAudioFileWriters(); - Set returnTypesSet = new HashSet(); + List providers = getAudioFileWriters(); + Set returnTypesSet = new HashSet<>(); for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); AudioFileFormat.Type[] fileTypes = writer.getAudioFileTypes(); for(int j=0; j < fileTypes.length; j++) { returnTypesSet.add(fileTypes[j]); } } - AudioFileFormat.Type returnTypes[] = (AudioFileFormat.Type[]) + AudioFileFormat.Type returnTypes[] = returnTypesSet.toArray(new AudioFileFormat.Type[0]); return returnTypes; } @@ -1167,10 +1167,10 @@ public class AudioSystem { */ public static boolean isFileTypeSupported(AudioFileFormat.Type fileType) { - List providers = getAudioFileWriters(); + List providers = getAudioFileWriters(); for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); if (writer.isFileTypeSupported(fileType)) { return true; } @@ -1188,17 +1188,17 @@ public class AudioSystem { * length 0 is returned. */ public static AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) { - List providers = getAudioFileWriters(); - Set returnTypesSet = new HashSet(); + List providers = getAudioFileWriters(); + Set returnTypesSet = new HashSet<>(); for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); AudioFileFormat.Type[] fileTypes = writer.getAudioFileTypes(stream); for(int j=0; j < fileTypes.length; j++) { returnTypesSet.add(fileTypes[j]); } } - AudioFileFormat.Type returnTypes[] = (AudioFileFormat.Type[]) + AudioFileFormat.Type returnTypes[] = returnTypesSet.toArray(new AudioFileFormat.Type[0]); return returnTypes; } @@ -1215,10 +1215,10 @@ public class AudioSystem { public static boolean isFileTypeSupported(AudioFileFormat.Type fileType, AudioInputStream stream) { - List providers = getAudioFileWriters(); + List providers = getAudioFileWriters(); for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); if(writer.isFileTypeSupported(fileType, stream)) { return true; } @@ -1248,12 +1248,12 @@ public class AudioSystem { public static int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException { - List providers = getAudioFileWriters(); + List providers = getAudioFileWriters(); int bytesWritten = 0; boolean flag = false; for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); try { bytesWritten = writer.write( stream, fileType, out ); // throws IOException flag = true; @@ -1288,12 +1288,12 @@ public class AudioSystem { public static int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException { - List providers = getAudioFileWriters(); + List providers = getAudioFileWriters(); int bytesWritten = 0; boolean flag = false; for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); try { bytesWritten = writer.write( stream, fileType, out ); // throws IOException flag = true; @@ -1315,8 +1315,9 @@ public class AudioSystem { /** * Obtains the set of MixerProviders on the system. */ - private static List getMixerProviders() { - return getProviders(MixerProvider.class); + @SuppressWarnings("unchecked") + private static List getMixerProviders() { + return (List) getProviders(MixerProvider.class); } /** @@ -1328,8 +1329,9 @@ public class AudioSystem { * format converters. If no format converters readers are available * on the system, an array of length 0 is returned. */ - private static List getFormatConversionProviders() { - return getProviders(FormatConversionProvider.class); + @SuppressWarnings("unchecked") + private static List getFormatConversionProviders() { + return (List) getProviders(FormatConversionProvider.class); } /** @@ -1341,8 +1343,9 @@ public class AudioSystem { * readers. If no audio file readers are available on the system, an * empty List is returned. */ - private static List getAudioFileReaders() { - return getProviders(AudioFileReader.class); + @SuppressWarnings("unchecked") + private static List getAudioFileReaders() { + return (List)getProviders(AudioFileReader.class); } /** @@ -1354,8 +1357,9 @@ public class AudioSystem { * writers. If no audio file writers are available on the system, an * empty List is returned. */ - private static List getAudioFileWriters() { - return getProviders(AudioFileWriter.class); + @SuppressWarnings("unchecked") + private static List getAudioFileWriters() { + return (List)getProviders(AudioFileWriter.class); } /** @@ -1368,8 +1372,8 @@ public class AudioSystem { * @return a Mixer that matches the requirements, or null if no default * mixer found */ - private static Mixer getDefaultMixer(List providers, Line.Info info) { - Class lineClass = info.getLineClass(); + private static Mixer getDefaultMixer(List providers, Line.Info info) { + Class lineClass = info.getLineClass(); String providerClassName = JDK13Services.getDefaultProviderClassName(lineClass); String instanceName = JDK13Services.getDefaultInstanceName(lineClass); Mixer mixer; @@ -1418,9 +1422,9 @@ public class AudioSystem { * @return A MixerProvider of the requested class, or null if none is found */ private static MixerProvider getNamedProvider(String providerClassName, - List providers) { + List providers) { for(int i = 0; i < providers.size(); i++) { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); if (provider.getClass().getName().equals(providerClassName)) { return provider; } @@ -1462,10 +1466,10 @@ public class AudioSystem { * @return A Mixer matching the requirements, or null if none is found */ private static Mixer getNamedMixer(String mixerName, - List providers, + List providers, Line.Info info) { for(int i = 0; i < providers.size(); i++) { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); Mixer mixer = getNamedMixer(mixerName, provider, info); if (mixer != null) { return mixer; @@ -1511,7 +1515,7 @@ public class AudioSystem { if (! mixer.isLineSupported(lineInfo)) { return false; } - Class lineClass = lineInfo.getLineClass(); + Class lineClass = lineInfo.getLineClass(); if (isMixingRequired && (SourceDataLine.class.isAssignableFrom(lineClass) || Clip.class.isAssignableFrom(lineClass))) { @@ -1524,22 +1528,22 @@ public class AudioSystem { /** * Like getMixerInfo, but return List. */ - private static List getMixerInfoList() { - List providers = getMixerProviders(); + private static List getMixerInfoList() { + List providers = getMixerProviders(); return getMixerInfoList(providers); } /** * Like getMixerInfo, but return List. */ - private static List getMixerInfoList(List providers) { - List infos = new ArrayList(); + private static List getMixerInfoList(List providers) { + List infos = new ArrayList<>(); Mixer.Info[] someInfos; // per-mixer Mixer.Info[] allInfos; // for all mixers for(int i = 0; i < providers.size(); i++ ) { - someInfos = ((MixerProvider)providers.get(i)).getMixerInfo(); + someInfos = providers.get(i).getMixerInfo(); for (int j = 0; j < someInfos.length; j++) { infos.add(someInfos[j]); @@ -1556,7 +1560,7 @@ public class AudioSystem { * @return a List of instances of providers for the requested service. If no * providers are available, a vector of length 0 will be returned. */ - private static List getProviders(Class providerClass) { + private static List getProviders(Class providerClass) { return JDK13Services.getProviders(providerClass); } } diff --git a/jdk/src/share/classes/javax/sound/sampled/Line.java b/jdk/src/share/classes/javax/sound/sampled/Line.java index 0b9d96c0b89..feb69fde185 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Line.java +++ b/jdk/src/share/classes/javax/sound/sampled/Line.java @@ -230,7 +230,7 @@ public interface Line extends AutoCloseable { /** * The class of the line described by the info object. */ - private final Class lineClass; + private final Class lineClass; /** * Constructs an info object that describes a line of the specified From 6733dcbb1cde2a502550311194806a78ba05a535 Mon Sep 17 00:00:00 2001 From: Petr Pchelko Date: Fri, 6 Jun 2014 13:52:49 +0400 Subject: [PATCH 051/192] 8044516: [macosx] ScreenPopupFactory uses native method that could be avoided Reviewed-by: anthony, serb --- .../com/apple/laf/ScreenPopupFactory.java | 21 ++------- .../native/com/apple/laf/ScreenPopupFactory.m | 44 ------------------- .../classes/javax/swing/PopupFactory.java | 11 +++++ .../classes/sun/swing/SwingAccessor.java | 35 +++++++++++++-- 4 files changed, 46 insertions(+), 65 deletions(-) delete mode 100644 jdk/src/macosx/native/com/apple/laf/ScreenPopupFactory.m diff --git a/jdk/src/macosx/classes/com/apple/laf/ScreenPopupFactory.java b/jdk/src/macosx/classes/com/apple/laf/ScreenPopupFactory.java index 1ab50a18679..bb2c0f1081b 100644 --- a/jdk/src/macosx/classes/com/apple/laf/ScreenPopupFactory.java +++ b/jdk/src/macosx/classes/com/apple/laf/ScreenPopupFactory.java @@ -29,18 +29,9 @@ import java.awt.*; import javax.swing.*; import sun.lwawt.macosx.CPlatformWindow; +import sun.swing.SwingAccessor; class ScreenPopupFactory extends PopupFactory { - static { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("osxui"); - return null; - } - }); - } - static final Float TRANSLUCENT = new Float(248f/255f); static final Float OPAQUE = new Float(1.0f); @@ -59,19 +50,13 @@ class ScreenPopupFactory extends PopupFactory { return (Window)w; } - /* - * Since we can't change the signature of PopupFactory, we have to call the - * private method getPopup(Component, Component, int, int, int) through JNI - * (see AquaLookAndFeel.m) - */ - native Popup _getHeavyWeightPopup(Component comp, Component invoker, int x, int y); - public Popup getPopup(final Component comp, final Component invoker, final int x, final int y) { if (invoker == null) throw new IllegalArgumentException("Popup.getPopup must be passed non-null contents"); final Popup popup; if (fIsActive) { - popup = _getHeavyWeightPopup(comp, invoker, x, y); + popup = SwingAccessor.getPopupFactoryAccessor() + .getHeavyWeightPopup(this, comp, invoker, x, y); } else { popup = super.getPopup(comp, invoker, x, y); } diff --git a/jdk/src/macosx/native/com/apple/laf/ScreenPopupFactory.m b/jdk/src/macosx/native/com/apple/laf/ScreenPopupFactory.m deleted file mode 100644 index 516ce45d5a0..00000000000 --- a/jdk/src/macosx/native/com/apple/laf/ScreenPopupFactory.m +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2011, 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. - */ - -#import "com_apple_laf_ScreenPopupFactory.h" -#import - -static JNF_CLASS_CACHE(sjc_PopupFactory, "javax/swing/PopupFactory"); -static JNF_MEMBER_CACHE(jm_getPopup, sjc_PopupFactory, "getPopup", "(Ljava/awt/Component;Ljava/awt/Component;III)Ljavax/swing/Popup;"); - -/* - * Class: com_apple_laf_ScreenPopupFactory - * Method: _getHeavyWeightPopup - * Signature: (Ljava/awt/Component;Ljava/awt/Component;II)Ljavax/swing/Popup; - */ -JNIEXPORT jobject /* javax.swing.Popup */ JNICALL Java_com_apple_laf_ScreenPopupFactory__1getHeavyWeightPopup -(JNIEnv *env, jobject screenPopupFactory, jobject comp, jobject invoker, jint x, jint y) { - jobject popup; -JNF_COCOA_ENTER(env); - popup = JNFCallObjectMethod(env, screenPopupFactory, jm_getPopup, comp, invoker, x, y, 2); -JNF_COCOA_EXIT(env); - return popup; -} diff --git a/jdk/src/share/classes/javax/swing/PopupFactory.java b/jdk/src/share/classes/javax/swing/PopupFactory.java index 695ef2bb76b..840d7d14962 100644 --- a/jdk/src/share/classes/javax/swing/PopupFactory.java +++ b/jdk/src/share/classes/javax/swing/PopupFactory.java @@ -27,6 +27,7 @@ package javax.swing; import sun.awt.EmbeddedFrame; import sun.awt.OSInfo; +import sun.swing.SwingAccessor; import java.applet.Applet; import java.awt.*; @@ -60,6 +61,16 @@ import static javax.swing.ClientPropertyKey.PopupFactory_FORCE_HEAVYWEIGHT_POPUP * @since 1.4 */ public class PopupFactory { + + static { + SwingAccessor.setPopupFactoryAccessor(new SwingAccessor.PopupFactoryAccessor() { + @Override + public Popup getHeavyWeightPopup(PopupFactory factory, Component owner, + Component contents, int ownerX, int ownerY) { + return factory.getPopup(owner, contents, ownerX, ownerY, HEAVY_WEIGHT_POPUP); + } + }); + } /** * The shared instanceof PopupFactory is per * AppContext. This is the key used in the diff --git a/jdk/src/share/classes/sun/swing/SwingAccessor.java b/jdk/src/share/classes/sun/swing/SwingAccessor.java index 797802abd8c..37aa744a69b 100644 --- a/jdk/src/share/classes/sun/swing/SwingAccessor.java +++ b/jdk/src/share/classes/sun/swing/SwingAccessor.java @@ -27,11 +27,10 @@ package sun.swing; import sun.misc.Unsafe; -import java.awt.Point; -import javax.swing.RepaintManager; +import java.awt.*; +import javax.swing.*; import javax.swing.text.JTextComponent; -import javax.swing.TransferHandler; /** * The SwingAccessor utility class. @@ -90,6 +89,14 @@ public final class SwingAccessor { void removeRepaintListener(RepaintManager rm, SwingUtilities2.RepaintListener l); } + /** + * An accessor for PopupFactory class. + */ + public interface PopupFactoryAccessor { + Popup getHeavyWeightPopup(PopupFactory factory, Component owner, Component contents, + int ownerX, int ownerY); + } + /** * The javax.swing.text.JTextComponent class accessor object. */ @@ -156,4 +163,26 @@ public final class SwingAccessor { } return repaintManagerAccessor; } + + /** + * The PopupFactory class accessor object. + */ + private static PopupFactoryAccessor popupFactoryAccessor; + + /** + * Retrieve the accessor object for the PopupFactory class. + */ + public static PopupFactoryAccessor getPopupFactoryAccessor() { + if (popupFactoryAccessor == null) { + unsafe.ensureClassInitialized(PopupFactory.class); + } + return popupFactoryAccessor; + } + + /** + * Set an Accessor object for the PopupFactory class. + */ + public static void setPopupFactoryAccessor(PopupFactoryAccessor popupFactoryAccessor) { + SwingAccessor.popupFactoryAccessor = popupFactoryAccessor; + } } From bfa90f6f301a1ecabe89ae5f17300d1f504a84c0 Mon Sep 17 00:00:00 2001 From: Petr Pchelko Date: Fri, 6 Jun 2014 14:52:07 +0400 Subject: [PATCH 052/192] 8041990: [macosx] Language specific keys does not work in applets when opened outside the browser Reviewed-by: alexsch, serb --- .../share/classes/java/awt/EventQueue.java | 5 + .../java/awt/event/InputMethodEvent.java | 35 +++++- .../share/classes/sun/awt/AWTAccessor.java | 7 +- jdk/test/java/awt/im/8041990/bug8041990.java | 104 ++++++++++++++++++ 4 files changed, 145 insertions(+), 6 deletions(-) create mode 100644 jdk/test/java/awt/im/8041990/bug8041990.java diff --git a/jdk/src/share/classes/java/awt/EventQueue.java b/jdk/src/share/classes/java/awt/EventQueue.java index 4164641392e..87bbace3ac8 100644 --- a/jdk/src/share/classes/java/awt/EventQueue.java +++ b/jdk/src/share/classes/java/awt/EventQueue.java @@ -214,6 +214,11 @@ public class EventQueue { FwDispatcher dispatcher) { eventQueue.setFwDispatcher(dispatcher); } + + @Override + public long getMostRecentEventTime(EventQueue eventQueue) { + return eventQueue.getMostRecentEventTimeImpl(); + } }); } diff --git a/jdk/src/share/classes/java/awt/event/InputMethodEvent.java b/jdk/src/share/classes/java/awt/event/InputMethodEvent.java index 104f10b8fea..ca214ed6e45 100644 --- a/jdk/src/share/classes/java/awt/event/InputMethodEvent.java +++ b/jdk/src/share/classes/java/awt/event/InputMethodEvent.java @@ -25,6 +25,10 @@ package java.awt.event; +import sun.awt.AWTAccessor; +import sun.awt.AppContext; +import sun.awt.SunToolkit; + import java.awt.AWTEvent; import java.awt.Component; import java.awt.EventQueue; @@ -217,8 +221,10 @@ public class InputMethodEvent extends AWTEvent { public InputMethodEvent(Component source, int id, AttributedCharacterIterator text, int committedCharacterCount, TextHitInfo caret, TextHitInfo visiblePosition) { - this(source, id, EventQueue.getMostRecentEventTime(), text, - committedCharacterCount, caret, visiblePosition); + this(source, id, + getMostRecentEventTimeForSource(source), + text, committedCharacterCount, + caret, visiblePosition); } /** @@ -258,8 +264,9 @@ public class InputMethodEvent extends AWTEvent { */ public InputMethodEvent(Component source, int id, TextHitInfo caret, TextHitInfo visiblePosition) { - this(source, id, EventQueue.getMostRecentEventTime(), null, - 0, caret, visiblePosition); + this(source, id, + getMostRecentEventTimeForSource(source), + null, 0, caret, visiblePosition); } /** @@ -411,7 +418,25 @@ public class InputMethodEvent extends AWTEvent { private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); if (when == 0) { - when = EventQueue.getMostRecentEventTime(); + when = getMostRecentEventTimeForSource(this.source); } } + + /** + * Get the most recent event time in the {@code EventQueue} which the {@code source} + * belongs to. + * + * @param source the source of the event + * @exception IllegalArgumentException if source is null. + * @return most recent event time in the {@code EventQueue} + */ + private static long getMostRecentEventTimeForSource(Object source) { + if (source == null) { + // throw the IllegalArgumentException to conform to EventObject spec + throw new IllegalArgumentException("null source"); + } + AppContext appContext = SunToolkit.targetToAppContext(source); + EventQueue eventQueue = SunToolkit.getSystemEventQueueImplPP(appContext); + return AWTAccessor.getEventQueueAccessor().getMostRecentEventTime(eventQueue); + } } diff --git a/jdk/src/share/classes/sun/awt/AWTAccessor.java b/jdk/src/share/classes/sun/awt/AWTAccessor.java index 1d60a1c332d..0bec70b332a 100644 --- a/jdk/src/share/classes/sun/awt/AWTAccessor.java +++ b/jdk/src/share/classes/sun/awt/AWTAccessor.java @@ -530,7 +530,12 @@ public final class AWTAccessor { /** * Sets the delegate for the EventQueue used by FX/AWT single threaded mode */ - public void setFwDispatcher(EventQueue eventQueue, FwDispatcher dispatcher); + void setFwDispatcher(EventQueue eventQueue, FwDispatcher dispatcher); + + /** + * Gets most recent event time in the EventQueue + */ + long getMostRecentEventTime(EventQueue eventQueue); } /* diff --git a/jdk/test/java/awt/im/8041990/bug8041990.java b/jdk/test/java/awt/im/8041990/bug8041990.java new file mode 100644 index 00000000000..ee813e6715c --- /dev/null +++ b/jdk/test/java/awt/im/8041990/bug8041990.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + @test + @bug 8041990 + @summary Language specific keys does not work in applets when opened outside the browser + @author Petr Pchelko +*/ + +import sun.awt.SunToolkit; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.InputMethodEvent; +import java.awt.font.TextHitInfo; +import java.text.AttributedString; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; + +public class bug8041990 { + private static JFrame frame; + private static JComponent component; + + public static void main(String[] args) throws Exception { + ThreadGroup stubTG = new ThreadGroup(getRootThreadGroup(), "Stub Thread Group"); + ThreadGroup swingTG = new ThreadGroup(getRootThreadGroup(), "SwingTG"); + try { + Thread stubThread = new Thread(stubTG, SunToolkit::createNewAppContext); + stubThread.start(); + stubThread.join(); + + CountDownLatch startSwingLatch = new CountDownLatch(1); + new Thread(swingTG, () -> { + SunToolkit.createNewAppContext(); + SwingUtilities.invokeLater(() -> { + frame = new JFrame(); + component = new JLabel("Test Text"); + frame.add(component); + frame.setBounds(100, 100, 100, 100); + frame.setVisible(true); + startSwingLatch.countDown(); + }); + }).start(); + startSwingLatch.await(); + + AtomicReference caughtException = new AtomicReference<>(); + Thread checkThread = new Thread(getRootThreadGroup(), () -> { + try { + // If the bug is present this will throw exception + new InputMethodEvent(component, + InputMethodEvent.CARET_POSITION_CHANGED, + TextHitInfo.leading(0), + TextHitInfo.trailing(0)); + } catch (Exception e) { + caughtException.set(e); + } + }); + checkThread.start(); + checkThread.join(); + + if (caughtException.get() != null) { + throw new RuntimeException("Failed. Caught exception!", caughtException.get()); + } + } finally { + new Thread(swingTG, () -> SwingUtilities.invokeLater(() -> { + if (frame != null) { + frame.dispose(); + } + })).start(); + } + } + + private static ThreadGroup getRootThreadGroup() { + ThreadGroup currentTG = Thread.currentThread().getThreadGroup(); + ThreadGroup parentTG = currentTG.getParent(); + while (parentTG != null) { + currentTG = parentTG; + parentTG = currentTG.getParent(); + } + return currentTG; + } +} From 52233220f23932d768e8562ac4d7f890fc337b72 Mon Sep 17 00:00:00 2001 From: Petr Pchelko Date: Fri, 6 Jun 2014 14:58:41 +0400 Subject: [PATCH 053/192] 8041464: [TEST_BUG] CustomClassLoaderTransferTest does not support OS X Reviewed-by: azvegint, serb --- .../AnotherInterface.java | 3 + .../CustomClassLoaderTransferTest.java | 63 +++++++++++++++++++ .../TransferableList.java | 30 +++++++++ .../awt/regtesthelpers/CopyClassFile.java | 34 ++++++++-- 4 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/AnotherInterface.java create mode 100644 jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/CustomClassLoaderTransferTest.java create mode 100644 jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/TransferableList.java diff --git a/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/AnotherInterface.java b/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/AnotherInterface.java new file mode 100644 index 00000000000..17c905e581b --- /dev/null +++ b/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/AnotherInterface.java @@ -0,0 +1,3 @@ +import java.io.*; + +public interface AnotherInterface extends Serializable {} diff --git a/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/CustomClassLoaderTransferTest.java b/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/CustomClassLoaderTransferTest.java new file mode 100644 index 00000000000..4468eafd8b4 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/CustomClassLoaderTransferTest.java @@ -0,0 +1,63 @@ +/* + @test + @bug 4932376 + @summary verifies that data transfer within one JVM works correctly if + the transfer data was created with a custom class loader. + @author das@sparc.spb.su area=datatransfer + @library ../../regtesthelpers + @build TransferableList AnotherInterface CopyClassFile CustomClassLoaderTransferTest + @run main CopyClassFile -r ListInterface subdir/ + @run main CopyClassFile -r TransferableList subdir/ + @run main CustomClassLoaderTransferTest +*/ + +import java.awt.*; +import java.awt.datatransfer.*; +import java.io.*; +import java.net.URL; +import java.net.URLClassLoader; + +public class CustomClassLoaderTransferTest { + public static class DFTransferable implements Transferable { + private final DataFlavor df; + private final Object obj; + public DFTransferable(DataFlavor df, Object obj) { + this.df = df; + this.obj = obj; + } + + @Override + public Object getTransferData(DataFlavor flavor) + throws UnsupportedFlavorException, IOException { + if (df.equals(flavor)) { + return obj; + } else { + throw new UnsupportedFlavorException(flavor); + } + } + + @Override + public DataFlavor[] getTransferDataFlavors(){ + return new DataFlavor[] { df }; + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return df.equals(flavor); + } + } + + public static void main(String[] args) throws Exception { + Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard(); + URL url = new File("./subdir/").toURL(); + ClassLoader classLoader = new URLClassLoader(new URL[] { url }, + CustomClassLoaderTransferTest.class.getClassLoader()); + Class clazz = Class.forName("TransferableList", true, classLoader); + DataFlavor df = new DataFlavor(clazz, "Transferable List"); + Object obj = clazz.newInstance(); + Transferable t = new DFTransferable(df, obj); + c.setContents(t, null); + Transferable ct = c.getContents(null); + ct.getTransferData(df); + } +} diff --git a/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/TransferableList.java b/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/TransferableList.java new file mode 100644 index 00000000000..8c28a160b8b --- /dev/null +++ b/jdk/test/java/awt/datatransfer/CustomClassLoaderTransferTest/TransferableList.java @@ -0,0 +1,30 @@ +import java.io.Serializable; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.ArrayList; + +public class TransferableList extends ArrayList { + private static class NullInvocationHandler implements InvocationHandler, Serializable { + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + throw new Error("UNIMPLEMENTED"); + } + } + + public TransferableList() { + try { + InvocationHandler handler = new NullInvocationHandler(); + Class proxyClass = Proxy.getProxyClass( + ListInterface.class.getClassLoader(), + new Class[] { ListInterface.class, AnotherInterface.class }); + AnotherInterface obj = (AnotherInterface) proxyClass. + getConstructor(new Class[]{InvocationHandler.class}). + newInstance(handler); + } catch (Exception e) { + e.printStackTrace(); + } + } +} + +interface ListInterface extends Serializable {} diff --git a/jdk/test/java/awt/regtesthelpers/CopyClassFile.java b/jdk/test/java/awt/regtesthelpers/CopyClassFile.java index 1ee6513638f..4db241d67eb 100644 --- a/jdk/test/java/awt/regtesthelpers/CopyClassFile.java +++ b/jdk/test/java/awt/regtesthelpers/CopyClassFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,8 @@ import java.util.Arrays; * * @build CopyClassFile * @run main CopyClassFile package.class dest_directory + * + * In case the source file should be removed add -r option */ public class CopyClassFile { @@ -48,13 +50,17 @@ public class CopyClassFile { private static String className; private static String classFile; + private static boolean removeSource = false; + public static void main(String[] args) throws Exception { - if (args.length != 2) { + if (args.length < 2) { throw new IllegalArgumentException("Illegal usage: class name and destination directory should be specified"); } - destinationDir = args[1]; - className = args[0]; + int classNameIndex = parseOptions(args); + + className = args[classNameIndex]; + destinationDir = args[classNameIndex + 1]; classFile = className.replaceAll("\\.", File.separator) + ".class"; URL url = cl.getResource(classFile); @@ -69,6 +75,21 @@ public class CopyClassFile { Arrays.stream(files).forEach(CopyClassFile::copyFile); } + private static int parseOptions(String[] args) { + int optionsEnd = 0; + while (args[optionsEnd].startsWith("-")) { + switch (args[optionsEnd].substring(1)) { + case "r" : + removeSource = true; + break; + default: + throw new RuntimeException("Unrecognized option passed to CopyClassFile: " + args[optionsEnd]); + } + optionsEnd++; + } + return optionsEnd; + } + private static String cutPackageName(String className) { int dotIndex = className.lastIndexOf(".") + 1; if (dotIndex <= 0) { @@ -87,6 +108,11 @@ public class CopyClassFile { try (InputStream is = new FileInputStream(f)) { Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING); } + + if (removeSource && !f.delete()) { + throw new RuntimeException("Failed to delete a file"); + } + } catch (IOException ex) { throw new RuntimeException("Could not copy file " + f, ex); } From 71b76d4073ca7f764b5bbc72dab0e678b392eac2 Mon Sep 17 00:00:00 2001 From: Christian Tornqvist Date: Fri, 6 Jun 2014 14:46:42 +0200 Subject: [PATCH 054/192] 8043492: ad_x86_64_misc.obj : error LNK2011: precompiled object not linked in; image may not run Added _build_pch_file.obj to LD_FLAGS and cleaned up support for older Visual Studio versions Reviewed-by: twisti, lfoltan, sla, kvn --- hotspot/make/windows/create.bat | 27 +---- hotspot/make/windows/makefiles/compile.make | 114 +----------------- hotspot/make/windows/makefiles/rules.make | 31 +---- hotspot/make/windows/makefiles/sa.make | 11 +- hotspot/make/windows/makefiles/sanity.make | 10 +- hotspot/make/windows/makefiles/vm.make | 4 +- .../make/windows/projectfiles/common/Makefile | 3 +- hotspot/src/share/vm/runtime/vm_version.cpp | 14 +-- 8 files changed, 19 insertions(+), 195 deletions(-) diff --git a/hotspot/make/windows/create.bat b/hotspot/make/windows/create.bat index a9a8acea6d2..fb0d450187a 100644 --- a/hotspot/make/windows/create.bat +++ b/hotspot/make/windows/create.bat @@ -1,6 +1,6 @@ @echo off REM -REM Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. +REM Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. REM DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. REM REM This code is free software; you can redistribute it and/or modify it @@ -81,33 +81,8 @@ REM figure out MSC version for /F %%i in ('sh %HotSpotWorkSpace%/make/windows/get_msc_ver.sh') do set %%i echo ************************************************************** -set ProjectFile=%HotSpotBuildSpace%\jvm.vcproj echo MSC_VER = "%MSC_VER%" -if "%MSC_VER%" == "1200" ( -set ProjectFile=%HotSpotBuildSpace%\jvm.dsp -echo Will generate VC6 project {unsupported} -) else ( -if "%MSC_VER%" == "1400" ( -echo Will generate VC8 {Visual Studio 2005} -) else ( -if "%MSC_VER%" == "1500" ( -echo Will generate VC9 {Visual Studio 2008} -) else ( -if "%MSC_VER%" == "1600" ( -echo Will generate VC10 {Visual Studio 2010} set ProjectFile=%HotSpotBuildSpace%\jvm.vcxproj -) else ( -if "%MSC_VER%" == "1700" ( -echo Will generate VC10 {compatible with Visual Studio 2012} -echo After opening in VS 2012, click "Update" when prompted. -set ProjectFile=%HotSpotBuildSpace%\jvm.vcxproj -) else ( -echo Will generate VC7 project {Visual Studio 2003 .NET} -) -) -) -) -) echo %ProjectFile% echo ************************************************************** diff --git a/hotspot/make/windows/makefiles/compile.make b/hotspot/make/windows/makefiles/compile.make index 9da2742335e..a4d1c0d4c3e 100644 --- a/hotspot/make/windows/makefiles/compile.make +++ b/hotspot/make/windows/makefiles/compile.make @@ -1,5 +1,5 @@ # -# Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -63,28 +63,20 @@ CXX_FLAGS=$(CXX_FLAGS) /Zi # Based on BUILDARCH we add some flags and select the default compiler name !if "$(BUILDARCH)" == "ia64" MACHINE=IA64 -DEFAULT_COMPILER_NAME=VS2003 CXX_FLAGS=$(CXX_FLAGS) /D "CC_INTERP" /D "_LP64" /D "IA64" !endif !if "$(BUILDARCH)" == "amd64" MACHINE=AMD64 -DEFAULT_COMPILER_NAME=VS2005 CXX_FLAGS=$(CXX_FLAGS) /D "_LP64" /D "AMD64" LP64=1 !endif !if "$(BUILDARCH)" == "i486" MACHINE=I386 -DEFAULT_COMPILER_NAME=VS2003 CXX_FLAGS=$(CXX_FLAGS) /D "IA32" !endif -# Sanity check, this is the default if not amd64, ia64, or i486 -!ifndef DEFAULT_COMPILER_NAME -CXX=ARCH_ERROR -!endif - CXX_FLAGS=$(CXX_FLAGS) /D "WIN32" /D "_WINDOWS" # Must specify this for sharedRuntimeTrig.cpp CXX_FLAGS=$(CXX_FLAGS) /D "VM_LITTLE_ENDIAN" @@ -112,6 +104,7 @@ CXX_FLAGS=$(CXX_FLAGS) /D TARGET_COMPILER_visCPP # 1500 is for VS2008 # 1600 is for VS2010 # 1700 is for VS2012 +# 1800 is for VS2013 # Do not confuse this MSC_VER with the predefined macro _MSC_VER that the # compiler provides, when MSC_VER==1399, _MSC_VER will be 1400. # Normally they are the same, but a pre-release of the VS2005 compilers @@ -119,35 +112,6 @@ CXX_FLAGS=$(CXX_FLAGS) /D TARGET_COMPILER_visCPP # closer to VS2003 in terms of option spellings, so we use 1399 for that # 1400 version that really isn't 1400. # See the file get_msc_ver.sh for more info. -!if "x$(MSC_VER)" == "x" -COMPILER_NAME=$(DEFAULT_COMPILER_NAME) -!else -!if "$(MSC_VER)" == "1200" -COMPILER_NAME=VC6 -!endif -!if "$(MSC_VER)" == "1300" -COMPILER_NAME=VS2003 -!endif -!if "$(MSC_VER)" == "1310" -COMPILER_NAME=VS2003 -!endif -!if "$(MSC_VER)" == "1399" -# Compiler might say 1400, but if it's 14.00.30701, it isn't really VS2005 -COMPILER_NAME=VS2003 -!endif -!if "$(MSC_VER)" == "1400" -COMPILER_NAME=VS2005 -!endif -!if "$(MSC_VER)" == "1500" -COMPILER_NAME=VS2008 -!endif -!if "$(MSC_VER)" == "1600" -COMPILER_NAME=VS2010 -!endif -!if "$(MSC_VER)" == "1700" -COMPILER_NAME=VS2012 -!endif -!endif # By default, we do not want to use the debug version of the msvcrt.dll file # but if MFC_DEBUG is defined in the environment it will be used. @@ -165,60 +129,6 @@ MS_RUNTIME_OPTION = $(MS_RUNTIME_OPTION) $(STATIC_CPPLIB_OPTION) !endif CXX_FLAGS=$(CXX_FLAGS) $(MS_RUNTIME_OPTION) -# How /GX option is spelled -GX_OPTION = /GX - -# Optimization settings for various versions of the compilers and types of -# builds. Three basic sets of settings: product, fastdebug, and debug. -# These get added into CXX_FLAGS as needed by other makefiles. -!if "$(COMPILER_NAME)" == "VC6" -PRODUCT_OPT_OPTION = /Ox /Os /Gy /GF -FASTDEBUG_OPT_OPTION = /Ox /Os /Gy /GF -DEBUG_OPT_OPTION = /Od -!endif - -!if "$(COMPILER_NAME)" == "VS2003" -PRODUCT_OPT_OPTION = /O2 /Oy- -FASTDEBUG_OPT_OPTION = /O2 /Oy- -DEBUG_OPT_OPTION = /Od -SAFESEH_FLAG = /SAFESEH -!endif - -!if "$(COMPILER_NAME)" == "VS2005" -PRODUCT_OPT_OPTION = /O2 /Oy- -FASTDEBUG_OPT_OPTION = /O2 /Oy- -DEBUG_OPT_OPTION = /Od -GX_OPTION = /EHsc -# This VS2005 compiler has /GS as a default and requires bufferoverflowU.lib -# on the link command line, otherwise we get missing __security_check_cookie -# externals at link time. Even with /GS-, you need bufferoverflowU.lib. -# NOTE: Currently we decided to not use /GS- -BUFFEROVERFLOWLIB = bufferoverflowU.lib -LD_FLAGS = /manifest $(LD_FLAGS) $(BUFFEROVERFLOWLIB) -# Manifest Tool - used in VS2005 and later to adjust manifests stored -# as resources inside build artifacts. -!if "x$(MT)" == "x" -MT=mt.exe -!endif -SAFESEH_FLAG = /SAFESEH -!endif - -!if "$(COMPILER_NAME)" == "VS2008" -PRODUCT_OPT_OPTION = /O2 /Oy- -FASTDEBUG_OPT_OPTION = /O2 /Oy- -DEBUG_OPT_OPTION = /Od -GX_OPTION = /EHsc -LD_FLAGS = /manifest $(LD_FLAGS) -MP_FLAG = /MP -# Manifest Tool - used in VS2005 and later to adjust manifests stored -# as resources inside build artifacts. -!if "x$(MT)" == "x" -MT=mt.exe -!endif -SAFESEH_FLAG = /SAFESEH -!endif - -!if "$(COMPILER_NAME)" == "VS2010" PRODUCT_OPT_OPTION = /O2 /Oy- FASTDEBUG_OPT_OPTION = /O2 /Oy- DEBUG_OPT_OPTION = /Od @@ -233,26 +143,6 @@ MT=mt.exe !if "$(BUILDARCH)" == "i486" LD_FLAGS = /SAFESEH $(LD_FLAGS) !endif -!endif - -!if "$(COMPILER_NAME)" == "VS2012" -PRODUCT_OPT_OPTION = /O2 /Oy- -FASTDEBUG_OPT_OPTION = /O2 /Oy- -DEBUG_OPT_OPTION = /Od -GX_OPTION = /EHsc -LD_FLAGS = /manifest $(LD_FLAGS) -MP_FLAG = /MP -# Manifest Tool - used in VS2005 and later to adjust manifests stored -# as resources inside build artifacts. -!if "x$(MT)" == "x" -MT=mt.exe -!endif -SAFESEH_FLAG = /SAFESEH -!endif - -!if "$(BUILDARCH)" == "i486" -LD_FLAGS = $(SAFESEH_FLAG) $(LD_FLAGS) -!endif CXX_FLAGS = $(CXX_FLAGS) $(MP_FLAG) diff --git a/hotspot/make/windows/makefiles/rules.make b/hotspot/make/windows/makefiles/rules.make index c5d565a2880..08a6a85e101 100644 --- a/hotspot/make/windows/makefiles/rules.make +++ b/hotspot/make/windows/makefiles/rules.make @@ -1,5 +1,5 @@ # -# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -49,35 +49,8 @@ BOOT_TARGET_CLASS_VERSION=6 JAVAC_FLAGS=-g -encoding ascii BOOTSTRAP_JAVAC_FLAGS=$(JAVAC_FLAGS) -source $(BOOT_SOURCE_LANGUAGE_VERSION) -target $(BOOT_TARGET_CLASS_VERSION) -ProjectFile=jvm.vcproj - -!if "$(MSC_VER)" == "1200" - -VcVersion=VC6 -ProjectFile=jvm.dsp - -!elseif "$(MSC_VER)" == "1400" - -VcVersion=VC8 - -!elseif "$(MSC_VER)" == "1500" - -VcVersion=VC9 - -!elseif "$(MSC_VER)" == "1600" - -VcVersion=VC10 -ProjectFile=jvm.vcxproj - -!elseif "$(MSC_VER)" == "1700" -# This is VS2012, but it loads VS10 projects just fine (and will +# VS2012 and VS2013 loads VS10 projects just fine (and will # upgrade them automatically to VS2012 format). - VcVersion=VC10 ProjectFile=jvm.vcxproj -!else - -VcVersion=VC7 - -!endif diff --git a/hotspot/make/windows/makefiles/sa.make b/hotspot/make/windows/makefiles/sa.make index 2208da9e3d8..13bb8130ef4 100644 --- a/hotspot/make/windows/makefiles/sa.make +++ b/hotspot/make/windows/makefiles/sa.make @@ -1,5 +1,5 @@ # -# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -85,14 +85,9 @@ checkAndBuildSA:: $(SAWINDBG) # will be useful to have the assertion checks in place !if "$(BUILDARCH)" == "ia64" -SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -YX -FD -c +SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -c !elseif "$(BUILDARCH)" == "amd64" -SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -YX -FD -c -!if "$(COMPILER_NAME)" == "VS2005" -# On amd64, VS2005 compiler requires bufferoverflowU.lib on the link command line, -# otherwise we get missing __security_check_cookie externals at link time. -SA_LD_FLAGS = bufferoverflowU.lib -!endif +SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -c !else SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -RTC1 -c !if "$(ENABLE_FULL_DEBUG_SYMBOLS)" == "1" diff --git a/hotspot/make/windows/makefiles/sanity.make b/hotspot/make/windows/makefiles/sanity.make index b502cfaa65f..515b0bb1b50 100644 --- a/hotspot/make/windows/makefiles/sanity.make +++ b/hotspot/make/windows/makefiles/sanity.make @@ -1,5 +1,5 @@ # -# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -27,9 +27,9 @@ all: checkCL checkLink checkCL: - @ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" if "$(MSC_VER)" NEQ "1700" \ - echo *** WARNING *** unrecognized cl.exe version $(MSC_VER) ($(RAW_MSC_VER)). Use FORCE_MSC_VER to override automatic detection. + @ if "$(MSC_VER)" NEQ "1600" if "$(MSC_VER)" NEQ "1700" if "$(MSC_VER)" NEQ "1800" \ + echo *** WARNING *** Unsupported cl.exe version detected: $(MSC_VER) ($(RAW_MSC_VER)), only 1600/1700/1800 (Visual Studio 2010/2012/2013) are supported. checkLink: - @ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" if "$(LD_VER)" NEQ "1100" \ - echo *** WARNING *** unrecognized link.exe version $(LD_VER) ($(RAW_LD_VER)). Use FORCE_LD_VER to override automatic detection. + @ if "$(LD_VER)" NEQ "1000" if "$(LD_VER)" NEQ "1100" if "$(LD_VER)" NEQ "1200" \ + echo *** WARNING *** Unsupported link.exe version detected: $(LD_VER) ($(RAW_LD_VER)), only 1000/1100/1200 (Visual Studio 2010/2012/2013) are supported. diff --git a/hotspot/make/windows/makefiles/vm.make b/hotspot/make/windows/makefiles/vm.make index e4caa13dea2..d8040f89ed8 100644 --- a/hotspot/make/windows/makefiles/vm.make +++ b/hotspot/make/windows/makefiles/vm.make @@ -1,5 +1,5 @@ # -# Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -132,7 +132,7 @@ CXX_DONT_USE_PCH=/D DONT_USE_PRECOMPILED_HEADER !if "$(USE_PRECOMPILED_HEADER)" != "0" CXX_USE_PCH=/Fp"vm.pch" /Yu"precompiled.hpp" -!if "$(COMPILER_NAME)" == "VS2012" +!if "$(MSC_VER)" > "1600" # VS2012 requires this object file to be listed: LD_FLAGS=$(LD_FLAGS) _build_pch_file.obj !endif diff --git a/hotspot/make/windows/projectfiles/common/Makefile b/hotspot/make/windows/projectfiles/common/Makefile index 51d4e6f1f11..1fc1350706e 100644 --- a/hotspot/make/windows/projectfiles/common/Makefile +++ b/hotspot/make/windows/projectfiles/common/Makefile @@ -1,5 +1,5 @@ # -# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -120,7 +120,6 @@ ReleaseOptions = -define HOTSPOT_RELEASE_VERSION=$(HOTSPOT_RELEASE_VERSION) -def ProjectCreatorIDEOptions = $(ProjectCreatorIDEOptions) $(ReleaseOptions) $(HOTSPOTBUILDSPACE)/$(ProjectFile): $(HOTSPOTBUILDSPACE)/classes/ProjectCreator.class - @if "$(MSC_VER)"=="1500" echo Make sure you have VS2008 SP1 or later, or you may see 'expanded command line too long' @$(RUN_JAVA) -Djava.class.path="$(HOTSPOTBUILDSPACE)/classes" ProjectCreator WinGammaPlatform$(VcVersion) $(ProjectCreatorIDEOptions) clean: diff --git a/hotspot/src/share/vm/runtime/vm_version.cpp b/hotspot/src/share/vm/runtime/vm_version.cpp index 5df7d221a2b..03fd43355bf 100644 --- a/hotspot/src/share/vm/runtime/vm_version.cpp +++ b/hotspot/src/share/vm/runtime/vm_version.cpp @@ -222,20 +222,12 @@ const char* Abstract_VM_Version::internal_vm_info_string() { #ifndef HOTSPOT_BUILD_COMPILER #ifdef _MSC_VER - #if _MSC_VER == 1100 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 5.0" - #elif _MSC_VER == 1200 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 6.0" - #elif _MSC_VER == 1310 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 7.1 (VS2003)" - #elif _MSC_VER == 1400 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 8.0 (VS2005)" - #elif _MSC_VER == 1500 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 9.0 (VS2008)" - #elif _MSC_VER == 1600 + #if _MSC_VER == 1600 #define HOTSPOT_BUILD_COMPILER "MS VC++ 10.0 (VS2010)" #elif _MSC_VER == 1700 #define HOTSPOT_BUILD_COMPILER "MS VC++ 11.0 (VS2012)" + #elif _MSC_VER == 1800 + #define HOTSPOT_BUILD_COMPILER "MS VC++ 12.0 (VS2013)" #else #define HOTSPOT_BUILD_COMPILER "unknown MS VC++:" XSTR(_MSC_VER) #endif From b3090f044ea742d7364668207bee89f27b936d4e Mon Sep 17 00:00:00 2001 From: Alexey Ivanov Date: Fri, 6 Jun 2014 17:51:32 +0400 Subject: [PATCH 055/192] 8039383: NPE when changing Windows theme Reviewed-by: pchelko, anthony --- .../plaf/windows/AnimationController.java | 15 +++--- .../swing/plaf/windows/WindowsComboBoxUI.java | 20 +++++--- .../plaf/windows/WindowsGraphicsUtils.java | 5 +- .../plaf/windows/WindowsIconFactory.java | 46 +++++++++++------- .../WindowsInternalFrameTitlePane.java | 13 ++--- .../plaf/windows/WindowsLookAndFeel.java | 8 ++-- .../swing/plaf/windows/WindowsMenuBarUI.java | 4 +- .../swing/plaf/windows/WindowsMenuItemUI.java | 6 +-- .../windows/WindowsPopupMenuSeparatorUI.java | 7 +-- .../plaf/windows/WindowsPopupMenuUI.java | 6 +-- .../plaf/windows/WindowsProgressBarUI.java | 13 +++-- .../swing/plaf/windows/WindowsSliderUI.java | 3 +- .../swing/plaf/windows/WindowsSpinnerUI.java | 5 +- .../plaf/windows/WindowsTableHeaderUI.java | 5 +- .../sun/java/swing/plaf/windows/XPStyle.java | 47 +++++++++++-------- .../classes/sun/awt/windows/ThemeReader.java | 6 +++ .../classes/sun/awt/windows/WToolkit.java | 29 +++++++++--- 17 files changed, 153 insertions(+), 85 deletions(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java index 8fec402dcea..70edf604df5 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -130,11 +130,14 @@ class AnimationController implements ActionListener, PropertyChangeListener { //one second seems plausible value duration = 1000; } else { - duration = XPStyle.getXP().getThemeTransitionDuration( - c, part, - normalizeState(oldState), - normalizeState(newState), - Prop.TRANSITIONDURATIONS); + XPStyle xp = XPStyle.getXP(); + duration = (xp != null) + ? xp.getThemeTransitionDuration( + c, part, + normalizeState(oldState), + normalizeState(newState), + Prop.TRANSITIONDURATIONS) + : 1000; } controller.startAnimation(c, part, oldState, newState, duration); } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java index 348b28a1a7b..dc7ae1bc511 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,7 @@ import java.awt.*; import static com.sun.java.swing.plaf.windows.TMSchema.Part; import static com.sun.java.swing.plaf.windows.TMSchema.State; import static com.sun.java.swing.plaf.windows.XPStyle.Skin; + import sun.swing.DefaultLookup; import sun.swing.StringUIClientPropertyKey; @@ -231,6 +232,9 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { private void paintXPComboBoxBackground(Graphics g, JComponent c) { XPStyle xp = XPStyle.getXP(); + if (xp == null) { + return; + } State state = getXPComboBoxState(c); Skin skin = null; if (! comboBox.isEditable() @@ -400,8 +404,9 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { * @return a button which represents the popup control */ protected JButton createArrowButton() { - if (XPStyle.getXP() != null) { - return new XPComboBoxButton(); + XPStyle xp = XPStyle.getXP(); + if (xp != null) { + return new XPComboBoxButton(xp); } else { return super.createArrowButton(); } @@ -409,9 +414,9 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { @SuppressWarnings("serial") // Superclass is not serializable across versions private class XPComboBoxButton extends XPStyle.GlyphButton { - public XPComboBoxButton() { + public XPComboBoxButton(XPStyle xp) { super(null, - (! XPStyle.getXP().isSkinDefined(comboBox, Part.CP_DROPDOWNBUTTONRIGHT)) + (! xp.isSkinDefined(comboBox, Part.CP_DROPDOWNBUTTONRIGHT)) ? Part.CP_DROPDOWNBUTTON : (comboBox.getComponentOrientation() == ComponentOrientation.RIGHT_TO_LEFT) ? Part.CP_DROPDOWNBUTTONLEFT @@ -424,10 +429,11 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { protected State getState() { State rv; rv = super.getState(); + XPStyle xp = XPStyle.getXP(); if (rv != State.DISABLED && comboBox != null && ! comboBox.isEditable() - && XPStyle.getXP().isSkinDefined(comboBox, - Part.CP_DROPDOWNBUTTONRIGHT)) { + && xp != null && xp.isSkinDefined(comboBox, + Part.CP_DROPDOWNBUTTONRIGHT)) { /* * for non editable ComboBoxes Vista seems to have the * same glyph for all non DISABLED states diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java index 63eb27b9b2d..8e168066d11 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -125,6 +125,9 @@ public class WindowsGraphicsUtils { static void paintXPText(AbstractButton b, Part part, State state, Graphics g, int x, int y, String text, int mnemIndex) { XPStyle xp = XPStyle.getXP(); + if (xp == null) { + return; + } Color textColor = b.getForeground(); if (textColor instanceof UIResource) { diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java index 0a4cfce44bf..d2018ea4e89 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java @@ -623,8 +623,8 @@ public class WindowsIconFactory implements Serializable @SuppressWarnings("serial") // Same-version serialization only private static class MenuArrowIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { - if (WindowsMenuItemUI.isVistaPainting()) { - XPStyle xp = XPStyle.getXP(); + XPStyle xp = XPStyle.getXP(); + if (xp != null && WindowsMenuItemUI.isVistaPainting()) { State state = State.NORMAL; if (c instanceof JMenuItem) { state = ((JMenuItem) c).getModel().isEnabled() @@ -657,16 +657,18 @@ public class WindowsIconFactory implements Serializable } } public int getIconWidth() { - if (WindowsMenuItemUI.isVistaPainting()) { - Skin skin = XPStyle.getXP().getSkin(null, Part.MP_POPUPSUBMENU); + XPStyle xp = XPStyle.getXP(); + if (xp != null && WindowsMenuItemUI.isVistaPainting()) { + Skin skin = xp.getSkin(null, Part.MP_POPUPSUBMENU); return skin.getWidth(); } else { return 4; } } public int getIconHeight() { - if (WindowsMenuItemUI.isVistaPainting()) { - Skin skin = XPStyle.getXP().getSkin(null, Part.MP_POPUPSUBMENU); + XPStyle xp = XPStyle.getXP(); + if (xp != null && WindowsMenuItemUI.isVistaPainting()) { + Skin skin = xp.getSkin(null, Part.MP_POPUPSUBMENU); return skin.getHeight(); } else { return 8; @@ -692,7 +694,8 @@ public class WindowsIconFactory implements Serializable } static int getIconWidth() { - return XPStyle.getXP().getSkin(null, Part.MP_POPUPCHECK).getWidth() + XPStyle xp = XPStyle.getXP(); + return ((xp != null) ? xp.getSkin(null, Part.MP_POPUPCHECK).getWidth() : 16) + 2 * OFFSET; } @@ -756,12 +759,17 @@ public class WindowsIconFactory implements Serializable Icon icon = getIcon(); int height = 0; if (icon != null) { - height = icon.getIconHeight() + 2 * OFFSET; + height = icon.getIconHeight(); } else { - Skin skin = - XPStyle.getXP().getSkin(null, Part.MP_POPUPCHECK); - height = skin.getHeight() + 2 * OFFSET; + XPStyle xp = XPStyle.getXP(); + if (xp != null) { + Skin skin = xp.getSkin(null, Part.MP_POPUPCHECK); + height = skin.getHeight(); + } else { + height = 16; + } } + height += 2 * OFFSET; return height; } @@ -809,14 +817,16 @@ public class WindowsIconFactory implements Serializable ? State.BULLETDISABLED : State.CHECKMARKDISABLED; } - Skin skin; XPStyle xp = XPStyle.getXP(); - skin = xp.getSkin(c, backgroundPart); - skin.paintSkin(g, x, y, - getIconWidth(), getIconHeight(), backgroundState); - if (icon == null) { - skin = xp.getSkin(c, part); - skin.paintSkin(g, x + OFFSET, y + OFFSET, state); + if (xp != null) { + Skin skin; + skin = xp.getSkin(c, backgroundPart); + skin.paintSkin(g, x, y, + getIconWidth(), getIconHeight(), backgroundState); + if (icon == null) { + skin = xp.getSkin(c, part); + skin.paintSkin(g, x + OFFSET, y + OFFSET, state); + } } } } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java index c654c5a7046..6210a93b738 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -86,14 +86,15 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane { } } else { buttonWidth += 2; - selectedTitleGradientColor = - UIManager.getColor("InternalFrame.activeTitleGradient"); - notSelectedTitleGradientColor = - UIManager.getColor("InternalFrame.inactiveTitleGradient"); Color activeBorderColor = UIManager.getColor("InternalFrame.activeBorderColor"); setBorder(BorderFactory.createLineBorder(activeBorderColor, 1)); } + // JDK-8039383: initialize these colors because getXP() may return null when theme is changed + selectedTitleGradientColor = + UIManager.getColor("InternalFrame.activeTitleGradient"); + notSelectedTitleGradientColor = + UIManager.getColor("InternalFrame.inactiveTitleGradient"); } protected void uninstallListeners() { @@ -388,7 +389,7 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane { public class WindowsTitlePaneLayout extends BasicInternalFrameTitlePane.TitlePaneLayout { private Insets captionMargin = null; private Insets contentMargin = null; - private XPStyle xp = XPStyle.getXP(); + private final XPStyle xp = XPStyle.getXP(); WindowsTitlePaneLayout() { if (xp != null) { diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index a6c1c895757..f4f326aa2f6 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -2327,8 +2327,9 @@ public class WindowsLookAndFeel extends BasicLookAndFeel } public Object getXPValue(UIDefaults table) { - Border xpBorder = XPStyle.getXP().getBorder(null, (Part)xpValue); - if (extraMargin != null) { + XPStyle xp = XPStyle.getXP(); + Border xpBorder = xp != null ? xp.getBorder(null, (Part)xpValue) : null; + if (xpBorder != null && extraMargin != null) { return new BorderUIResource. CompoundBorderUIResource(xpBorder, extraMargin); } else { @@ -2344,7 +2345,8 @@ public class WindowsLookAndFeel extends BasicLookAndFeel public Object getXPValue(UIDefaults table) { XPColorValueKey key = (XPColorValueKey)xpValue; - return XPStyle.getXP().getColor(key.skin, key.prop, null); + XPStyle xp = XPStyle.getXP(); + return xp != null ? xp.getColor(key.skin, key.prop, null) : null; } private static class XPColorValueKey { diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java index 73dcf802e33..68015c0752e 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java @@ -156,8 +156,8 @@ public class WindowsMenuBarUI extends BasicMenuBarUI @Override public void paint(Graphics g, JComponent c) { - if (WindowsMenuItemUI.isVistaPainting()) { - XPStyle xp = XPStyle.getXP(); + XPStyle xp = XPStyle.getXP(); + if (xp != null && WindowsMenuItemUI.isVistaPainting()) { Skin skin; skin = xp.getSkin(c, Part.MP_BARBACKGROUND); int width = c.getWidth(); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java index cac7af54aa7..8cc4fc420a0 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -109,7 +109,8 @@ public class WindowsMenuItemUI extends BasicMenuItemUI { static void paintBackground(WindowsMenuItemUIAccessor menuItemUI, Graphics g, JMenuItem menuItem, Color bgColor) { assert isVistaPainting(); - if (isVistaPainting()) { + XPStyle xp = XPStyle.getXP(); + if (xp != null && isVistaPainting()) { int menuWidth = menuItem.getWidth(); int menuHeight = menuItem.getHeight(); if (menuItem.isOpaque()) { @@ -118,7 +119,6 @@ public class WindowsMenuItemUI extends BasicMenuItemUI { g.fillRect(0,0, menuWidth, menuHeight); g.setColor(oldColor); } - XPStyle xp = XPStyle.getXP(); Part part = menuItemUI.getPart(menuItem); Skin skin = xp.getSkin(menuItem, part); skin.paintSkin(g, 0 , 0, diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java index 797aa5a7b6a..fc20e988459 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,7 +50,8 @@ public class WindowsPopupMenuSeparatorUI extends BasicPopupMenuSeparatorUI { public void paint(Graphics g, JComponent c) { Dimension s = c.getSize(); - if (WindowsMenuItemUI.isVistaPainting()) { + XPStyle xp = XPStyle.getXP(); + if (xp != null && WindowsMenuItemUI.isVistaPainting()) { int x = 1; Component parent = c.getParent(); if (parent instanceof JComponent) { @@ -67,7 +68,7 @@ public class WindowsPopupMenuSeparatorUI extends BasicPopupMenuSeparatorUI { x += WindowsPopupMenuUI.getGutterWidth(); } } - Skin skin = XPStyle.getXP().getSkin(c, Part.MP_POPUPSEPARATOR); + Skin skin = xp.getSkin(c, Part.MP_POPUPSEPARATOR); int skinHeight = skin.getHeight(); int y = (s.height - skinHeight) / 2; skin.paintSkin(g, x, y, s.width - x - 1, skinHeight, State.NORMAL); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java index 584641bcaf7..e3d9d96efc4 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -194,8 +194,8 @@ public class WindowsPopupMenuUI extends BasicPopupMenuUI { @Override public void paint(Graphics g, JComponent c) { - if (WindowsMenuItemUI.isVistaPainting()) { - XPStyle xp = XPStyle.getXP(); + XPStyle xp = XPStyle.getXP(); + if (xp != null && WindowsMenuItemUI.isVistaPainting()) { Skin skin = xp.getSkin(c, Part.MP_POPUPBACKGROUND); skin.paintSkin(g, 0, 0, c.getWidth(),c.getHeight(), State.NORMAL); int textOffset = getTextOffset(c); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java index ef5d176fa7b..45947fc2b7e 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -322,8 +322,9 @@ public class WindowsProgressBarUI extends BasicProgressBarUI private Rectangle getFullChunkBounds(Rectangle box) { boolean vertical = (progressBar.getOrientation() == JProgressBar.VERTICAL); XPStyle xp = XPStyle.getXP(); - int gap = xp.getInt(progressBar, Part.PP_PROGRESS, null, - Prop.PROGRESSSPACESIZE, 0); + int gap = (xp != null) ? xp.getInt(progressBar, Part.PP_PROGRESS, + null, Prop.PROGRESSSPACESIZE, 0) + : 0; if (!vertical) { int chunksize = box.width+gap; @@ -338,6 +339,9 @@ public class WindowsProgressBarUI extends BasicProgressBarUI boolean vertical, int bgwidth, int bgheight) { XPStyle xp = XPStyle.getXP(); + if (xp == null) { + return; + } // create a new graphics to keep drawing surface state Graphics2D gfx = (Graphics2D)g.create(); @@ -396,6 +400,9 @@ public class WindowsProgressBarUI extends BasicProgressBarUI private void paintXPBackground(Graphics g, boolean vertical, int barRectWidth, int barRectHeight) { XPStyle xp = XPStyle.getXP(); + if (xp == null) { + return; + } Part part = vertical ? Part.PP_BARVERT : Part.PP_BAR; Skin skin = xp.getSkin(progressBar, part); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java index dbfb7b81251..1bae3f8f441 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -215,7 +215,6 @@ public class WindowsSliderUI extends BasicSliderUI } private Part getXPThumbPart() { - XPStyle xp = XPStyle.getXP(); Part part; boolean vertical = (slider.getOrientation() == JSlider.VERTICAL); boolean leftToRight = slider.getComponentOrientation().isLeftToRight(); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java index ccc6d039b53..c17328e50cc 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,6 +63,9 @@ public class WindowsSpinnerUI extends BasicSpinnerUI { private void paintXPBackground(Graphics g, JComponent c) { XPStyle xp = XPStyle.getXP(); + if (xp == null) { + return; + } Skin skin = xp.getSkin(c, Part.EP_EDIT); State state = getXPState(c); skin.paintSkin(g, 0, 0, c.getWidth(), c.getHeight(), state); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java index 117e9d7b7b1..9cf37994589 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java @@ -91,9 +91,10 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI { this.column = column; this.hasRollover = (column == getRolloverColumn()); if (skin == null) { - skin = XPStyle.getXP().getSkin(header, Part.HP_HEADERITEM); + XPStyle xp = XPStyle.getXP(); + skin = (xp != null) ? xp.getSkin(header, Part.HP_HEADERITEM) : null; } - Insets margins = skin.getContentMargin(); + Insets margins = (skin != null) ? skin.getContentMargin() : null; Border border = null; int contentTop = 0; int contentLeft = 0; diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java index bc1404e9227..7765145eff1 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java @@ -52,6 +52,7 @@ import javax.swing.text.JTextComponent; import sun.awt.image.SunWritableRaster; import sun.awt.windows.ThemeReader; +import sun.awt.windows.WToolkit; import sun.security.action.GetPropertyAction; import sun.swing.CachedPainter; @@ -99,7 +100,7 @@ class XPStyle { if (themeActive == null) { Toolkit toolkit = Toolkit.getDefaultToolkit(); themeActive = - (Boolean)toolkit.getDesktopProperty("win.xpstyle.themeActive"); + (Boolean)toolkit.getDesktopProperty(WToolkit.XPSTYLE_THEME_ACTIVE); if (themeActive == null) { themeActive = Boolean.FALSE; } @@ -115,7 +116,7 @@ class XPStyle { } } } - return xp; + return ThemeReader.isXPStyleEnabled() ? xp : null; } static boolean isVista() { @@ -180,9 +181,10 @@ class XPStyle { * should probably be cached there instead of here. */ Dimension getDimension(Component c, Part part, State state, Prop prop) { - return ThemeReader.getPosition(part.getControlName(c), part.getValue(), - State.getValue(part, state), - prop.getValue()); + Dimension d = ThemeReader.getPosition(part.getControlName(c), part.getValue(), + State.getValue(part, state), + prop.getValue()); + return (d != null) ? d : new Dimension(); } /** Get a named Point (e.g. a location or an offset) value @@ -199,11 +201,7 @@ class XPStyle { Dimension d = ThemeReader.getPosition(part.getControlName(c), part.getValue(), State.getValue(part, state), prop.getValue()); - if (d != null) { - return new Point(d.width, d.height); - } else { - return null; - } + return (d != null) ? new Point(d.width, d.height) : new Point(); } /** Get a named Insets value from the current style @@ -217,9 +215,10 @@ class XPStyle { * The return value is already cached in those places. */ Insets getMargin(Component c, Part part, State state, Prop prop) { - return ThemeReader.getThemeMargins(part.getControlName(c), part.getValue(), - State.getValue(part, state), - prop.getValue()); + Insets insets = ThemeReader.getThemeMargins(part.getControlName(c), part.getValue(), + State.getValue(part, state), + prop.getValue()); + return (insets != null) ? insets : new Insets(0, 0, 0, 0); } @@ -509,16 +508,17 @@ class XPStyle { int boundingWidth = 100; int boundingHeight = 100; - return ThemeReader.getThemeBackgroundContentMargins( + Insets insets = ThemeReader.getThemeBackgroundContentMargins( part.getControlName(null), part.getValue(), 0, boundingWidth, boundingHeight); + return (insets != null) ? insets : new Insets(0, 0, 0, 0); } private int getWidth(State state) { if (size == null) { size = getPartSize(part, state); } - return size.width; + return (size != null) ? size.width : 0; } int getWidth() { @@ -529,7 +529,7 @@ class XPStyle { if (size == null) { size = getPartSize(part, state); } - return size.height; + return (size != null) ? size.height : 0; } int getHeight() { @@ -586,6 +586,9 @@ class XPStyle { * @param state which state to paint */ void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state) { + if (XPStyle.getXP() == null) { + return; + } if (ThemeReader.isGetThemeTransitionDurationDefined() && component instanceof JComponent && SwingUtilities.getAncestorOfClass(CellRendererPane.class, @@ -611,6 +614,9 @@ class XPStyle { * @param state which state to paint */ void paintSkinRaw(Graphics g, int dx, int dy, int dw, int dh, State state) { + if (XPStyle.getXP() == null) { + return; + } skinPainter.paint(null, g, dx, dy, dw, dh, this, state); } @@ -630,7 +636,7 @@ class XPStyle { void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state, boolean borderFill) { if(borderFill && "borderfill".equals(getTypeEnumName(component, part, - state, Prop.BGTYPE))) { + state, Prop.BGTYPE)) && XPStyle.getXP() == null) { return; } skinPainter.paint(null, g, dx, dy, dw, dh, this, state); @@ -684,7 +690,7 @@ class XPStyle { public GlyphButton(Component parent, Part part) { XPStyle xp = getXP(); - skin = xp.getSkin(parent, part); + skin = xp != null ? xp.getSkin(parent, part) : null; setBorder(null); setContentAreaFilled(false); setMinimumSize(new Dimension(5, 5)); @@ -709,13 +715,16 @@ class XPStyle { } public void paintComponent(Graphics g) { + if (XPStyle.getXP() == null || skin == null) { + return; + } Dimension d = getSize(); skin.paintSkin(g, 0, 0, d.width, d.height, getState()); } public void setPart(Component parent, Part part) { XPStyle xp = getXP(); - skin = xp.getSkin(parent, part); + skin = xp != null ? xp.getSkin(parent, part) : null; revalidate(); repaint(); } diff --git a/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java b/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java index 632489964e7..321e72ca182 100644 --- a/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java +++ b/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java @@ -61,6 +61,8 @@ public final class ThemeReader { private static final Lock readLock = readWriteLock.readLock(); private static final Lock writeLock = readWriteLock.writeLock(); + static volatile boolean xpStyleEnabled; + static void flush() { writeLock.lock(); try { @@ -76,6 +78,10 @@ public final class ThemeReader { public static native boolean isThemed(); + public static boolean isXPStyleEnabled() { + return xpStyleEnabled; + } + // this should be called only with writeLock held private static Long getThemeImpl(String widget) { Long theme = widgetToTheme.get(widget); diff --git a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java index 2a27c2df9cc..630d29e7b75 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java +++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java @@ -72,6 +72,9 @@ public final class WToolkit extends SunToolkit implements Runnable { private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WToolkit"); + // Desktop property which specifies whether XP visual styles are in effect + public static final String XPSTYLE_THEME_ACTIVE = "win.xpstyle.themeActive"; + static GraphicsConfiguration config; // System clipboard. @@ -894,7 +897,7 @@ public final class WToolkit extends SunToolkit implements Runnable { private synchronized void lazilyInitWProps() { if (wprops == null) { wprops = new WDesktopProperties(this); - updateProperties(); + updateProperties(wprops.getProperties()); } } @@ -929,21 +932,27 @@ public final class WToolkit extends SunToolkit implements Runnable { * Windows doesn't always send WM_SETTINGCHANGE when it should. */ private void windowsSettingChange() { + // JDK-8039383: Have to update the value of XPSTYLE_THEME_ACTIVE property + // as soon as possible to prevent NPE and other errors because theme data + // has become unavailable. + final Map props = getWProps(); + updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE)); + EventQueue.invokeLater(new Runnable() { @Override public void run() { - updateProperties(); + updateProperties(props); } }); } - private synchronized void updateProperties() { - if (null == wprops) { - // wprops has not been initialized, so we have nothing to update + private synchronized void updateProperties(final Map props) { + if (null == props) { return; } - Map props = wprops.getProperties(); + updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE)); + for (String propName : props.keySet()) { Object val = props.get(propName); if (log.isLoggable(PlatformLogger.Level.FINER)) { @@ -953,6 +962,14 @@ public final class WToolkit extends SunToolkit implements Runnable { } } + private synchronized Map getWProps() { + return (wprops != null) ? wprops.getProperties() : null; + } + + private void updateXPStyleEnabled(final Object dskProp) { + ThemeReader.xpStyleEnabled = Boolean.TRUE.equals(dskProp); + } + @Override public synchronized void addPropertyChangeListener(String name, PropertyChangeListener pcl) { if (name == null) { From b7b41fb0895d2b15df28fb8c3c2083de6a758c0b Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Mon, 9 Jun 2014 13:03:03 +0400 Subject: [PATCH 056/192] 8046245: JDK 9 client build failure on Solaris Reviewed-by: prr --- jdk/make/mapfiles/libawt/mapfile-vers | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/make/mapfiles/libawt/mapfile-vers b/jdk/make/mapfiles/libawt/mapfile-vers index b1c6a39ec1e..636c255c6c6 100644 --- a/jdk/make/mapfiles/libawt/mapfile-vers +++ b/jdk/make/mapfiles/libawt/mapfile-vers @@ -155,6 +155,7 @@ SUNWprivate_1.1 { g_CMpDataID; colorValueID; mul8table; + div8table; jvm; # ProcessPath entry points and data From 1510b7c75e2c6e3ab862653614f1e10c324265fb Mon Sep 17 00:00:00 2001 From: Staffan Larsen Date: Mon, 9 Jun 2014 11:03:09 +0200 Subject: [PATCH 057/192] 8044797: Building with clang gives: fatal error: file '...' has been modified since the precompiled header was built Reviewed-by: dholmes, dcubed --- hotspot/make/bsd/makefiles/vm.make | 1 + hotspot/make/linux/makefiles/vm.make | 1 + 2 files changed, 2 insertions(+) diff --git a/hotspot/make/bsd/makefiles/vm.make b/hotspot/make/bsd/makefiles/vm.make index 77dde8bc930..56beb6c6ba5 100644 --- a/hotspot/make/bsd/makefiles/vm.make +++ b/hotspot/make/bsd/makefiles/vm.make @@ -295,6 +295,7 @@ endif $(PRECOMPILED_HEADER): $(QUIETLY) echo Generating precompiled header $@ $(QUIETLY) mkdir -p $(PRECOMPILED_HEADER_DIR) + $(QUIETLY) rm -f $@ $(QUIETLY) $(COMPILE.CXX) $(DEPFLAGS) -x c++-header $(PRECOMPILED_HEADER_SRC) -o $@ $(COMPILE_DONE) # making the library: diff --git a/hotspot/make/linux/makefiles/vm.make b/hotspot/make/linux/makefiles/vm.make index bcf87c043ec..c91463aae13 100644 --- a/hotspot/make/linux/makefiles/vm.make +++ b/hotspot/make/linux/makefiles/vm.make @@ -290,6 +290,7 @@ LINK_VM = $(LINK_LIB.CC) $(PRECOMPILED_HEADER): $(QUIETLY) echo Generating precompiled header $@ $(QUIETLY) mkdir -p $(PRECOMPILED_HEADER_DIR) + $(QUIETLY) rm -f $@ $(QUIETLY) $(COMPILE.CXX) $(DEPFLAGS) -x c++-header $(PRECOMPILED_HEADER_SRC) -o $@ $(COMPILE_DONE) # making the library: From 5ecd91e84a5fd705d7a260400a75e5e5c53ac1cd Mon Sep 17 00:00:00 2001 From: Dmitriy Ermashov Date: Mon, 9 Jun 2014 14:59:45 +0400 Subject: [PATCH 058/192] 8044765: Move functional tests AWT_SystemTray/Automated to openjdk repository Reviewed-by: pchelko --- .../TrayIcon/ActionCommand/ActionCommand.java | 162 ++++++++++ .../ActionEventMask/ActionEventMask.java | 252 +++++++++++++++ .../GetTrayIconsTest/GetTrayIcons.java | 86 +++++ .../awt/TrayIcon/InterJVMTest/InterJVM.java | 86 +++++ .../TrayIcon/ModalityTest/ModalityTest.java | 302 ++++++++++++++++++ .../MouseEventMask/MouseEventMaskTest.java | 195 +++++++++++ .../MouseMovedTest/MouseMovedTest.java | 64 ++++ .../TrayIcon/PropertyChangeListenerTest.java | 201 ++++++++++++ .../FunctionalityCheck.java | 263 +++++++++++++++ .../FunctionalityCheck/tray.policy | 21 ++ .../NoPermissionTest/NoPermissionTest.java | 64 ++++ .../PermissionTest/PermissionTest.java | 50 +++ .../SecurityCheck/PermissionTest/tray.policy | 3 + .../awt/TrayIcon/SystemTrayIconHelper.java | 172 ++++++++++ .../SystemTrayInstanceTest.java | 71 ++++ .../TrayIconAddTest/TrayIconAddTest.java | 66 ++++ .../TrayIconEventModifiersTest.java | 275 ++++++++++++++++ .../TrayIconEvents/TrayIconEventsTest.java | 269 ++++++++++++++++ .../TrayIconMethodsTest.java | 159 +++++++++ .../TrayIconMouseTest/TrayIconMouseTest.java | 176 ++++++++++ .../TrayIconPopup/TrayIconPopupTest.java | 151 +++++++++ .../TrayIconRemoveTest.java | 72 +++++ .../TrayIconSizeTest/TrayIconSizeTest.java | 69 ++++ 23 files changed, 3229 insertions(+) create mode 100644 jdk/test/java/awt/TrayIcon/ActionCommand/ActionCommand.java create mode 100644 jdk/test/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java create mode 100644 jdk/test/java/awt/TrayIcon/GetTrayIconsTest/GetTrayIcons.java create mode 100644 jdk/test/java/awt/TrayIcon/InterJVMTest/InterJVM.java create mode 100644 jdk/test/java/awt/TrayIcon/ModalityTest/ModalityTest.java create mode 100644 jdk/test/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java create mode 100644 jdk/test/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java create mode 100644 jdk/test/java/awt/TrayIcon/PropertyChangeListenerTest.java create mode 100644 jdk/test/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java create mode 100644 jdk/test/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/tray.policy create mode 100644 jdk/test/java/awt/TrayIcon/SecurityCheck/NoPermissionTest/NoPermissionTest.java create mode 100644 jdk/test/java/awt/TrayIcon/SecurityCheck/PermissionTest/PermissionTest.java create mode 100644 jdk/test/java/awt/TrayIcon/SecurityCheck/PermissionTest/tray.policy create mode 100644 jdk/test/java/awt/TrayIcon/SystemTrayIconHelper.java create mode 100644 jdk/test/java/awt/TrayIcon/SystemTrayInstance/SystemTrayInstanceTest.java create mode 100644 jdk/test/java/awt/TrayIcon/TrayIconAddTest/TrayIconAddTest.java create mode 100644 jdk/test/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java create mode 100644 jdk/test/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java create mode 100644 jdk/test/java/awt/TrayIcon/TrayIconMethodsTest/TrayIconMethodsTest.java create mode 100644 jdk/test/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java create mode 100644 jdk/test/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java create mode 100644 jdk/test/java/awt/TrayIcon/TrayIconRemoveTest/TrayIconRemoveTest.java create mode 100644 jdk/test/java/awt/TrayIcon/TrayIconSizeTest/TrayIconSizeTest.java diff --git a/jdk/test/java/awt/TrayIcon/ActionCommand/ActionCommand.java b/jdk/test/java/awt/TrayIcon/ActionCommand/ActionCommand.java new file mode 100644 index 00000000000..5c5a17e0dbc --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/ActionCommand/ActionCommand.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check the return value of the getActionCommand method + * of the ActionEvent triggered when TrayIcon is double clicked + * (single clicked, on Mac) + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary ../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main ActionCommand + */ + +public class ActionCommand { + + TrayIcon icon; + ExtendedRobot robot; + + boolean actionPerformed = false; + Object actionLock = new Object(); + String actionCommand = null; + static boolean isMacOS = false; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (System.getProperty("os.name").toLowerCase().startsWith("win")) { + System.err.println("Test can fail if the icon hides to a tray icons pool " + + "in Windows 7, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true to " + + "avoid this problem. Or change behavior only for Java SE tray icon " + + "and rerun test."); + } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")){ + isMacOS = true; + } + + new ActionCommand().doTest(); + } + } + + void doTest() throws Exception { + robot = new ExtendedRobot(); + + EventQueue.invokeAndWait(() -> { + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), "Sample Icon"); + icon.addActionListener((event) -> { + actionPerformed = true; + actionCommand = event.getActionCommand(); + synchronized (actionLock) { + try { + actionLock.notifyAll(); + } catch (Exception e) { + } + } + }); + + if (icon.getActionCommand() != null) + throw new RuntimeException("FAIL: getActionCommand did not return null " + + "when no action command set " + icon.getActionCommand()); + + icon.setActionCommand("Sample Command"); + + if (! "Sample Command".equals(icon.getActionCommand())) + throw new RuntimeException("FAIL: getActionCommand did not return the correct value. " + + icon.getActionCommand() + " Expected: Sample Command"); + + try { + tray.add(icon); + } catch (AWTException e) { + throw new RuntimeException(e); + } + }); + + robot.waitForIdle(); + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(2000); + actionPerformed = false; + SystemTrayIconHelper.doubleClick(robot); + + if (! actionPerformed) { + synchronized (actionLock) { + try { + actionLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! actionPerformed) { + throw new RuntimeException("FAIL: ActionEvent not triggered when TrayIcon is "+(isMacOS? "" : "double ")+"clicked"); + } else if (! "Sample Command".equals(actionCommand)) { + throw new RuntimeException("FAIL: ActionEvent.getActionCommand did not return the correct " + + "value. Returned: " + actionCommand + " ; Expected: Sample Command"); + } + + EventQueue.invokeAndWait(() -> { + icon.setActionCommand(null); + if (icon.getActionCommand() != null) { + throw new RuntimeException("FAIL: ActionCommand set to null. getActionCommand did " + + "not return null " + icon.getActionCommand()); + } + }); + + robot.mouseMove(0, 0); + robot.waitForIdle(); + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(); + + actionPerformed = false; + actionCommand = null; + SystemTrayIconHelper.doubleClick(robot); + + if (! actionPerformed) { + synchronized (actionLock) { + try { + actionLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! actionPerformed) { + throw new RuntimeException("FAIL: ActionEvent not triggered when ActionCommand set to " + + "null and then TrayIcon is "+(isMacOS? "" : "double ")+ "clicked"); + } else if (actionCommand != null) { + throw new RuntimeException("FAIL: ActionEvent.getActionCommand did not return null " + + "when ActionCommand is set to null " + actionCommand); + } + + } +} diff --git a/jdk/test/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java b/jdk/test/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java new file mode 100644 index 00000000000..fb95874eadc --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check if ActionEvent triggered when a TrayIcon is double + * (single, on Mac) clicked is visible by an AWTEventListener + * added to the Toolkit. It also checks if all listeners are + * triggered when multiple AWTEventListeners and ActionListeners + * are added. + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary ../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main ActionEventMask + */ + +public class ActionEventMask { + + private Image image; + + TrayIcon icon; + ExtendedRobot robot; + + boolean actionPerformed = false; + boolean listenersInvoked = false; + Object actionLock = new Object(); + Object listenersLock = new Object(); + static boolean isMacOS = false; + static final int clickDelay = 50; + + ActionListener[] listeners; + boolean[] listenerStatus; + + Object lLock = new Object(); + boolean doTest, listenerAdded; + Button b1; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (System.getProperty("os.name").toLowerCase().startsWith("mac")) { + isMacOS = true; + } + new ActionEventMask().doTest(); + } + } + + public ActionEventMask() throws Exception { + EventQueue.invokeAndWait(this::initializeGUI); + } + + void initializeGUI() { + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), "Sample Icon"); + + Toolkit.getDefaultToolkit().addAWTEventListener(event -> { + if (doTest) { + System.out.println("ActionListener AWTEventListener"); + if (! icon.equals(event.getSource())) { + throw new RuntimeException("FAIL: ActionEvent not triggered for icon"); + } + actionPerformed = true; + synchronized (actionLock) { + try { + actionLock.notifyAll(); + } catch (Exception e) { + } + } + } + }, AWTEvent.ACTION_EVENT_MASK); + + try { + tray.add(icon); + } catch (AWTException e) { + throw new RuntimeException(e); + } + + listeners = new ActionListener[3]; + listenerStatus = new boolean[3]; + for (int i = 0; i < listeners.length; i++) { + final int index = i; + listeners[i] = event -> { + listenerStatus[index] = true; + System.out.println("ActionListener listeners[" + index + "]"); + for (int j = 0; j < listenerStatus.length; j++) { + if (! listenerStatus[j]) { + break; + } + listenersInvoked = true; + synchronized (listenersLock) { + try { + listenersLock.notifyAll(); + } catch (Exception e) { + } + } + } + }; + } + + Frame frame = new Frame("Test frame"); + b1 = new Button("Add ActionListener"); + b1.addActionListener(event -> { + for (int i = 0; i < listeners.length; i++) { + icon.addActionListener(listeners[i]); + } + listenerAdded = true; + synchronized (lLock) { + try { + lLock.notifyAll(); + } catch (Exception e) { + } + } + }); + frame.setLayout(new FlowLayout()); + frame.add(b1); + frame.setSize(200, 200); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent event) { + System.err.println("User closed the window"); + System.exit(1); + } + }); + frame.setVisible(true); + } + + private void doTest() throws Exception { + + robot = new ExtendedRobot(); + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(); + + actionPerformed = false; + doTest = true; + + if(isMacOS) { + robot.click(InputEvent.BUTTON3_MASK); + }else{ + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(clickDelay); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.delay(clickDelay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(clickDelay); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } + + if (! actionPerformed) { + synchronized (actionLock) { + try { + actionLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! actionPerformed) + throw new RuntimeException("FAIL: AWTEventListener not notified when TrayIcon " + + "is "+(isMacOS ? "" :"double ")+ "clicked"); + + doTest = false; + listenerAdded = false; + robot.mouseMove(b1.getLocationOnScreen().x + b1.getSize().width / 2, + b1.getLocationOnScreen().y + b1.getSize().height / 2); + robot.waitForIdle(); + robot.click(); + + if (! listenerAdded) { + synchronized (lLock) { + try { + lLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! listenerAdded) + throw new RuntimeException("FAIL: ActionListener could not be added at runtime. " + + "b1 did not trigger ActionEvent"); + + doTest = true; + actionPerformed = false; + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(); + + if(isMacOS) { + robot.click(InputEvent.BUTTON3_MASK); + }else{ + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(clickDelay); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.delay(clickDelay); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(clickDelay); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } + + if (! listenersInvoked) { + synchronized (listenersLock) { + try { + listenersLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! listenersInvoked) { + System.err.println("FAIL: All the listeners not invoked!"); + for (int i = 0; i < listenerStatus.length; i++) + throw new RuntimeException("Listener[" + i + "] invoked: " + listenerStatus[i]); + } + if (! actionPerformed) { + synchronized (actionLock) { + try { + actionLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! actionPerformed) + throw new RuntimeException("FAIL: AWTEventListener not notified when TrayIcon " + + "is "+(isMacOS? "" : "double ")+ "clicked. A set of listeners were added after it"); + + } +} diff --git a/jdk/test/java/awt/TrayIcon/GetTrayIconsTest/GetTrayIcons.java b/jdk/test/java/awt/TrayIcon/GetTrayIconsTest/GetTrayIcons.java new file mode 100644 index 00000000000..df6f01dd15c --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/GetTrayIconsTest/GetTrayIcons.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check the getTrayIcons method of the SystemTray + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main GetTrayIcons + */ + +public class GetTrayIcons { + + Image image; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + else + new GetTrayIcons().doTest(); + } + + GetTrayIcons() { + image = new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB); + } + + void doTest() throws Exception { + SystemTray tray = SystemTray.getSystemTray(); + TrayIcon[] icons = tray.getTrayIcons(); + if (icons == null || icons.length > 0) + throw new RuntimeException("FAIL: getTrayIcons() returned incorrect " + + "value when no icons are added " + icons); + + TrayIcon icon = new TrayIcon(image); + tray.add(icon); + + icons = tray.getTrayIcons(); + if (icons == null || icons.length != 1) + throw new RuntimeException("FAIL: getTrayIcons() returned incorrect value " + + "when one icon present " + icons); + + icon = new TrayIcon(image); + tray.add(icon); + + icons = tray.getTrayIcons(); + if (icons == null || icons.length != 2) + throw new RuntimeException("FAIL: getTrayIcons() returned incorrect value " + + "when two icons present " + icons); + + icons = tray.getTrayIcons(); + if (icons != null) { + for (int i = 0; i < icons.length; i++) { + tray.remove(icons[i]); + } + + TrayIcon[] newList = tray.getTrayIcons(); + + if (newList == null || newList.length != 0) + throw new RuntimeException("FAIL: Incorrect value returned by getTrayIcons " + + "after icons are added and then removed " + newList); + } + } +} diff --git a/jdk/test/java/awt/TrayIcon/InterJVMTest/InterJVM.java b/jdk/test/java/awt/TrayIcon/InterJVMTest/InterJVM.java new file mode 100644 index 00000000000..41b5d9a2028 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/InterJVMTest/InterJVM.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Check if TrayIcon added by a JVM is not visible + * in another JVM + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../regtesthelpers/process/ + * @build ProcessResults ProcessCommunicator + * @run main InterJVM + */ + +import test.java.awt.regtesthelpers.process.ProcessCommunicator; +import test.java.awt.regtesthelpers.process.ProcessResults; + +import java.awt.*; +import java.awt.image.BufferedImage; + +public class InterJVM { + + static String NEW_JVM = "-doTest"; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (args == null || args.length == 0) { + new InterJVM().addTrayIcon(); + } else { + if (args.length == 1 && NEW_JVM.equals(args[0])) + new InterJVM().doTest(); + } + } + } + + void doTest() throws Exception { + SystemTray tray = SystemTray.getSystemTray(); + try { + TrayIcon[] icons = tray.getTrayIcons(); + System.out.println(icons.length); + if (icons == null || icons.length != 0) + throw new RuntimeException("FAIL: getTrayIcons() returned incorrect " + + "value when two icons are added by a " + + "separate JVM: " + icons.length); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + void addTrayIcon() throws Exception { + + SystemTray tray = SystemTray.getSystemTray(); + TrayIcon icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB)); + tray.add(icon); + + new Robot().delay(2000); + + ProcessResults processResults = + ProcessCommunicator.executeChildProcess(this.getClass(), new String[]{NEW_JVM}); + + if (processResults.getExitValue() != 0) + throw new RuntimeException("\n"+processResults.getStdErr()); + } +} diff --git a/jdk/test/java/awt/TrayIcon/ModalityTest/ModalityTest.java b/jdk/test/java/awt/TrayIcon/ModalityTest/ModalityTest.java new file mode 100644 index 00000000000..2118457ee79 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/ModalityTest/ModalityTest.java @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check for MouseEvents with all mouse buttons + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary ../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main ModalityTest + */ +public class ModalityTest { + + TrayIcon icon; + ExtendedRobot robot; + Dialog d; + + boolean actionPerformed = false; + + private boolean dialogVisible = false; + private Object dialogLock = new Object(); + + Object actionLock = new Object(); + Object pressLock = new Object(); + Object releaseLock = new Object(); + Object clickLock = new Object(); + Object moveLock = new Object(); + static final int clickDelay = 50; + + boolean mousePressed = false; + boolean mouseReleased = false; + boolean mouseClicked = false; + boolean mouseMoved = false; + + int[] buttonTypes = { + InputEvent.BUTTON1_MASK, + InputEvent.BUTTON2_MASK, + InputEvent.BUTTON3_MASK + }; + + String[] buttonNames = { + "BUTTON1", + "BUTTON2", + "BUTTON3" + }; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (System.getProperty("os.name").toLowerCase().startsWith("win")) + System.err.println("Test can fail if the icon hides to a tray icons pool " + + "in Windows 7, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true " + + "to avoid this problem. Or change behavior only for Java SE tray " + + "icon and rerun test."); + + new ModalityTest().doTest(); + } + } + + public ModalityTest() throws Exception { + robot = new ExtendedRobot(); + EventQueue.invokeLater(this::initializeGUI); + } + + void initializeGUI() { + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), "Sample Icon"); + icon.addActionListener(event -> { + actionPerformed = true; + synchronized (actionLock) { + try { + actionLock.notifyAll(); + } catch (Exception e) { + } + } + }); + icon.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent event) { + mousePressed = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mousePressed"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mousePressed: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (pressLock) { + try { + pressLock.notifyAll(); + } catch (Exception e) { + } + } + } + + public void mouseReleased(MouseEvent event) { + mouseReleased = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseReleased"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseReleased: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (releaseLock) { + try { + releaseLock.notifyAll(); + } catch (Exception e) { + } + } + } + + public void mouseClicked(MouseEvent event) { + mouseClicked = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseClicked"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseClicked: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (clickLock) { + try { + clickLock.notifyAll(); + } catch (Exception e) { + } + } + } + }); + + icon.addMouseMotionListener(new MouseMotionAdapter() { + public void mouseMoved(MouseEvent event) { + mouseMoved = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseMoved"); + + if (!icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseMoved: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (moveLock) { + try { + moveLock.notifyAll(); + } catch (Exception e) { + } + } + } + }); + + try { + tray.add(icon); + } catch (AWTException e) { + throw new RuntimeException(e); + } + + d = new Dialog((Frame) null, "Modal Dialog"); + d.setLocation(200, 200); + d.setSize(100, 100); + d.setModalityType(Dialog.ModalityType.TOOLKIT_MODAL); + + dialogVisible = true; + synchronized (dialogLock) { + try { + dialogLock.notifyAll(); + } catch (Exception e) { + } + } + + d.setVisible(true); + } + + void doTest() throws Exception { + + if (! dialogVisible) { + synchronized (dialogLock) { + try { + dialogLock.wait(3000); + } catch (Exception e) { + } + } + } + + if (! dialogVisible) + throw new RuntimeException("ERROR: TIMEOUT: The thread in EDT not yet complete"); + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + if (! d.isVisible()) + throw new RuntimeException("FAIL: The modal dialog is not yet visible"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(2000); + + SystemTrayIconHelper.doubleClick(robot); + + if (! actionPerformed) { + synchronized (actionLock) { + try { + actionLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! actionPerformed) + throw new RuntimeException("FAIL: ActionEvent not triggered when TrayIcon is double clicked"); + + for (int i = 0; i < buttonTypes.length; i++) { + mousePressed = false; + robot.mousePress(buttonTypes[i]); + + if (! mousePressed) { + synchronized (pressLock) { + try { + pressLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mousePressed) + if (! SystemTrayIconHelper.skip(buttonTypes[i]) ) + throw new RuntimeException("FAIL: mousePressed not triggered when " + + buttonNames[i] + " pressed"); + + mouseReleased = false; + mouseClicked = false; + robot.mouseRelease(buttonTypes[i]); + + if (! mouseReleased) { + synchronized (releaseLock) { + try { + releaseLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mouseReleased) + throw new RuntimeException("FAIL: mouseReleased not triggered when " + + buttonNames[i] + " released"); + + if (! mouseClicked) { + synchronized (clickLock) { + try { + clickLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mouseClicked) + throw new RuntimeException("FAIL: mouseClicked not triggered when " + + buttonNames[i] + " pressed & released"); + } + + mouseMoved = false; + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.glide(iconPosition.x + 100, iconPosition.y); + + if (! mouseMoved) + if (! SystemTrayIconHelper.skip(0) ) + throw new RuntimeException("FAIL: mouseMoved not triggered even when mouse moved over the icon"); + } +} diff --git a/jdk/test/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java b/jdk/test/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java new file mode 100644 index 00000000000..e6c194ec69c --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check if MouseEvents triggered by TrayIcon are visible + * by an AWTEventListener added to the Toolkit. It also + * checks if all listeners are triggered when AWTEventListeners + * and MouseListeners are added. + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary ../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main MouseEventMaskTest + */ + +public class MouseEventMaskTest { + + TrayIcon icon; + Robot robot; + int[] buttonTypes = { + InputEvent.BUTTON1_MASK, + InputEvent.BUTTON2_MASK, + InputEvent.BUTTON3_MASK + }; + + String[] buttonNames = { + "BUTTON1", + "BUTTON2", + "BUTTON3" + }; + + boolean mouseEventTriggered = false; + boolean mouseMotionEventTriggered = false; + Object mouseEventLock = new Object(); + Object mouseMotionEventLock = new Object(); + boolean mouseMotionTest, mouseTest; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (System.getProperty("os.name").toLowerCase().startsWith("win")) { + System.err.println("Test can fail if the icon hides to a tray icons pool " + + "in Windows 7, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true " + + "to avoid this problem. Or change behavior only for Java SE tray " + + "icon and rerun test."); + } + new MouseEventMaskTest().doTest(); + } + } + + public MouseEventMaskTest() throws Exception{ + EventQueue.invokeAndWait(this::initializeGUI); + } + + void initializeGUI() { + + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), "Sample Icon"); + + Toolkit.getDefaultToolkit().addAWTEventListener(event -> { + if (mouseTest) { + if (! event.getSource().getClass().getName().contains("Canvas")) { + if (!icon.equals(event.getSource())) + throw new RuntimeException("FAIL: MouseEvent not triggered for icon " + event); + + mouseEventTriggered = true; + synchronized (mouseEventLock) { + try { + mouseEventLock.notifyAll(); + } catch (Exception e) { + } + } + } + } + }, AWTEvent.MOUSE_EVENT_MASK); + Toolkit.getDefaultToolkit().addAWTEventListener(event -> { + if (mouseMotionTest) { + if (! event.getSource().getClass().getName().contains("Canvas")) { + if (!icon.equals(event.getSource())) + throw new RuntimeException("FAIL: MouseMotionEvent not triggered for icon " + event); + + mouseMotionEventTriggered = true; + synchronized (mouseMotionEventLock) { + try { + mouseMotionEventLock.notifyAll(); + } catch (Exception e) { + } + } + } + } + }, AWTEvent.MOUSE_MOTION_EVENT_MASK); + + try { + tray.add(icon); + } catch (AWTException e) { + throw new RuntimeException(e); + } + } + + void doTest() throws Exception { + + robot = new Robot(); + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(); + + for (int i = 0; i < buttonTypes.length; i++) { + System.out.println("Verify button "+buttonTypes[i]); + mouseTest = true; + mouseEventTriggered = false; + robot.mousePress(buttonTypes[i]); + + if (! mouseEventTriggered) { + synchronized (mouseEventLock) { + try { + mouseEventLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mouseEventTriggered) + if (! SystemTrayIconHelper.skip(buttonTypes[i]) ) + throw new RuntimeException("FAIL: AWTEventListener not notified when " + + buttonNames[i] + " pressed on TrayIcon"); + + mouseEventTriggered = false; + robot.mouseRelease(buttonTypes[i]); + if (! mouseEventTriggered) { + synchronized (mouseEventLock) { + try { + mouseEventLock.wait(3000); + } catch (Exception e) { + } + } + } + + if (! mouseEventTriggered) + throw new RuntimeException("FAIL: AWTEventListener not notified when " + + buttonNames[i] + " released on TrayIcon"); + } + + mouseMotionTest = true; + mouseTest = false; + mouseMotionEventTriggered = false; + + for (int i = 0; i < 20; i++) { + robot.mouseMove(iconPosition.x + i, iconPosition.y); + robot.delay(25); + } + if (! mouseMotionEventTriggered) { + synchronized (mouseMotionEventLock) { + try { + mouseMotionEventLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mouseMotionEventTriggered) + if (! SystemTrayIconHelper.skip(0) ) + throw new RuntimeException("FAIL: AWTEventListener not notified when " + + "mouse moved"); + } +} diff --git a/jdk/test/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java b/jdk/test/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java new file mode 100644 index 00000000000..04d91f23859 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @bug 7153700 + * @summary Check for mouseMoved event for java.awt.TrayIcon + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary + * @build ExtendedRobot + * @run main MouseMovedTest + */ + +public class MouseMovedTest { + static volatile boolean moved; + + public static void main(String[] args) throws Exception { + moved = false; + + TrayIcon icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), "Test icon"); + icon.addMouseMotionListener(new MouseMotionAdapter() { + public void mouseMoved(MouseEvent event) { + moved = true; + System.out.println("Mouse moved"); + } + }); + SystemTray.getSystemTray().add(icon); + + ExtendedRobot robot = new ExtendedRobot(); + Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); + if (System.getProperty("os.name").toLowerCase().startsWith("win")) + robot.glide(size.width / 2, size.height-15, size.width, size.height-15, 1, 3); + else + robot.glide(size.width / 2, 13, size.width, 13, 1, 3); + robot.mouseMove(size.width/2, size.height/2); + + if (!moved) + throw new RuntimeException("Mouse moved action did not trigger"); + } +} diff --git a/jdk/test/java/awt/TrayIcon/PropertyChangeListenerTest.java b/jdk/test/java/awt/TrayIcon/PropertyChangeListenerTest.java new file mode 100644 index 00000000000..90bc1225ea3 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/PropertyChangeListenerTest.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +/* + * @test + * @summary Check if custom property change listener added + * to system tray works correctly + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main PropertyChangeListenerTest + */ + +public class PropertyChangeListenerTest implements PropertyChangeListener { + + Object property; + Object lock = new Object(); + boolean propertyChanged = false; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + new PropertyChangeListenerTest().doTest(); + } + } + + public void propertyChange(PropertyChangeEvent event) { + if (! "trayIcons".equals(event.getPropertyName())) + throw new RuntimeException("ERROR: PropertyName not matching. Event " + + "triggered for a different property\n"+ + "Property: " + event.getPropertyName()); + property = event.getNewValue(); + propertyChanged = true; + synchronized (lock) { + try { + lock.notifyAll(); + } catch (Exception e) { + } + } + } + + void doTest() throws Exception { + propertyChanged = false; + SystemTray tray = SystemTray.getSystemTray(); + + tray.addPropertyChangeListener(null, null); + tray.addPropertyChangeListener("trayIcons", null); + tray.addPropertyChangeListener("trayIcons", this); + + BufferedImage img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB); + Graphics g = img.createGraphics(); + g.setColor(Color.WHITE); + g.fillRect(0, 0, 32, 32); + g.setColor(Color.RED); + g.fillRect(6, 6, 20, 20); + g.dispose(); + + TrayIcon icon = new TrayIcon(img); + if (propertyChanged) + throw new RuntimeException("FAIL: spurious property events triggered"); + + propertyChanged = false; + tray.add(icon); + + if (! propertyChanged) { + synchronized (lock) { + try { + lock.wait(3000); + } catch (Exception e) { + } + } + } + if (! propertyChanged) { + throw new RuntimeException("FAIL: property event did not get triggered when tray icon added"); + } else { + if (! (property instanceof TrayIcon[])) { + throw new RuntimeException("FAIL: property is not TrayIcon[]. TrayIcon added."); + } else { + TrayIcon[] icons = (TrayIcon[]) property; + if (icons.length != 1 || ! icon.equals(icons[0])) { + throw new RuntimeException("FAIL: TrayIcon[] returned by the " + + "PropertyChangeEvent is incorrect. TrayIcon added.\n"+ + "icon[] length: " + icons.length); + } + } + } + + propertyChanged = false; + tray.remove(icon); + + if (! propertyChanged) { + synchronized (lock) { + try { + lock.wait(3000); + } catch (Exception e) { + } + } + } + if (! propertyChanged) { + throw new RuntimeException("FAIL: property event did not get triggered when tray icon removed"); + } else { + if (! (property instanceof TrayIcon[])) { + throw new RuntimeException("FAIL: property is not TrayIcon[]. TrayIcon removed."); + } else { + TrayIcon[] icons = (TrayIcon[]) property; + if (icons.length != 0) { + throw new RuntimeException("FAIL: TrayIcon[] returned by the " + + "PropertyChangeEvent is incorrect. TrayIcon removed.\n"+ + "icon[] length: " + icons.length); + } + } + } + + tray.removePropertyChangeListener("trayIcons", null); + tray.removePropertyChangeListener("trayIcons", this); + + propertyChanged = false; + tray.add(icon); + + Thread.sleep(3000); + if (propertyChanged) + throw new RuntimeException("FAIL: property listener notified even after " + + "removing the listener from SystemTray. TrayIcon added."); + + propertyChanged = false; + tray.remove(icon); + + Thread.sleep(3000); + if (propertyChanged) + throw new RuntimeException("FAIL: property listener notified even after " + + "removing the listener from SystemTray. TrayIcon removed."); + + tray.addPropertyChangeListener("someName", this); + + propertyChanged = false; + tray.add(icon); + + Thread.sleep(3000); + if (propertyChanged) + throw new RuntimeException("FAIL: property listener notified when " + + "listener added for a different property. TrayIcon added."); + + propertyChanged = false; + tray.remove(icon); + + Thread.sleep(3000); + if (propertyChanged) + throw new RuntimeException("FAIL: property listener notified when " + + "listener added for a different property. TrayIcon removed."); + + tray.addPropertyChangeListener("trayIcons", this); + tray.addPropertyChangeListener("trayIcons", this); + PropertyChangeListener listener = event -> { }; + tray.addPropertyChangeListener("trayIcons", listener); + tray.addPropertyChangeListener("sampleProp", event -> {}); + + if (tray.getPropertyChangeListeners("trayIcons").length != 3) { + throw new RuntimeException("FAIL: getPropertyChangeListeners did not return the " + + "correct value for trayIcons property. Expected: 3, " + + "Actual: " + tray.getPropertyChangeListeners("trayIcons").length); + } else if (! this.equals(tray.getPropertyChangeListeners("trayIcons")[0]) || + ! this.equals(tray.getPropertyChangeListeners("trayIcons")[1]) || + ! listener.equals(tray.getPropertyChangeListeners("trayIcons")[2])) { + throw new RuntimeException("FAIL: getPropertyChangeListeners did not return the " + + "expected listeners\n" + + "tray.getPropertyChangeListeners('trayIcons')[0] " + tray.getPropertyChangeListeners("trayIcons")[0]+"\n"+ + "tray.getPropertyChangeListeners('trayIcons')[1] " + tray.getPropertyChangeListeners("trayIcons")[1]+"\n"+ + "tray.getPropertyChangeListeners('trayIcons')[2] " + tray.getPropertyChangeListeners("trayIcons")[2]); + } + + if (tray.getPropertyChangeListeners("sampleProp").length != 1) + throw new RuntimeException("FAIL: getPropertyChangeListeners did not return the " + + "expected listener for 'sampleProp'"); + + } +} diff --git a/jdk/test/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java b/jdk/test/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java new file mode 100644 index 00000000000..5918ac3dfc0 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check for MouseEvents with all mouse buttons + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../../lib/testlibrary ../../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main/othervm/policy=tray.policy -Djava.security.manager FunctionalityCheck + */ + +public class FunctionalityCheck { + + TrayIcon icon; + ExtendedRobot robot; + + boolean actionPerformed = false; + Object actionLock = new Object(); + Object pressLock = new Object(); + Object releaseLock = new Object(); + Object clickLock = new Object(); + Object moveLock = new Object(); + + String caption = "Sample Icon"; + boolean mousePressed = false; + boolean mouseReleased = false; + boolean mouseClicked = false; + boolean mouseMoved = false; + + static final int[] buttonTypes = { + InputEvent.BUTTON1_MASK, + InputEvent.BUTTON2_MASK, + InputEvent.BUTTON3_MASK + }; + + static final String[] buttonNames = { + "BUTTON1", + "BUTTON2", + "BUTTON3" + }; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + new FunctionalityCheck().doTest(); + } + } + + FunctionalityCheck() throws Exception { + robot = new ExtendedRobot(); + EventQueue.invokeAndWait(this::initializeGUI); + } + + void initializeGUI() { + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), caption); + icon.addActionListener(event -> { + actionPerformed = true; + synchronized (actionLock) { + try { + actionLock.notifyAll(); + } catch (Exception e) { + } + } + }); + icon.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent event) { + mousePressed = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mousePressed"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mousePressed: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (pressLock) { + try { + pressLock.notifyAll(); + } catch (Exception e) { + } + } + } + + public void mouseReleased(MouseEvent event) { + mouseReleased = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseReleased"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseReleased: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (releaseLock) { + try { + releaseLock.notifyAll(); + } catch (Exception e) { + } + } + } + + public void mouseClicked(MouseEvent event) { + mouseClicked = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseClicked"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseClicked: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (clickLock) { + try { + clickLock.notifyAll(); + } catch (Exception e) { + } + } + } + }); + + icon.addMouseMotionListener(new MouseMotionAdapter() { + public void mouseMoved(MouseEvent event) { + mouseMoved = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseMoved"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseMoved: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (moveLock) { + try { + moveLock.notifyAll(); + } catch (Exception e) { + } + } + } + }); + + try { + tray.add(icon); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private void doTest() throws Exception { + + + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(2000); + + SystemTrayIconHelper.doubleClick(robot); + + if (! actionPerformed) { + synchronized (actionLock) { + try { + actionLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! actionPerformed) + throw new RuntimeException("FAIL: ActionEvent not triggered when TrayIcon is double clicked"); + + for (int i = 0; i < buttonTypes.length; i++) { + mousePressed = false; + robot.mousePress(buttonTypes[i]); + + if (! mousePressed) { + synchronized (pressLock) { + try { + pressLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mousePressed) + if (! SystemTrayIconHelper.skip(buttonTypes[i]) ) + throw new RuntimeException("FAIL: mousePressed not triggered when " + + buttonNames[i] + " pressed"); + + mouseReleased = false; + mouseClicked = false; + robot.mouseRelease(buttonTypes[i]); + + if (! mouseReleased) { + synchronized (releaseLock) { + try { + releaseLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mouseReleased) + if (! SystemTrayIconHelper.skip(buttonTypes[i]) ) + throw new RuntimeException("FAIL: mouseReleased not triggered when " + + buttonNames[i] + " released"); + + if (! mouseClicked) { + synchronized (clickLock) { + try { + clickLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mouseClicked) + throw new RuntimeException("FAIL: mouseClicked not triggered when " + + buttonNames[i] + " pressed & released"); + } + + mouseMoved = false; + robot.mouseMove(iconPosition.x + 100, iconPosition.y); + robot.glide(iconPosition.x, iconPosition.y); + + if (! mouseMoved) + if (! SystemTrayIconHelper.skip(0) ) + throw new RuntimeException("FAIL: mouseMoved not triggered even when mouse moved over the icon"); + } +} diff --git a/jdk/test/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/tray.policy b/jdk/test/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/tray.policy new file mode 100644 index 00000000000..845bfb8d80b --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/tray.policy @@ -0,0 +1,21 @@ +grant { + permission java.io.FilePermission "<>", "read, write, delete, execute"; + permission java.awt.AWTPermission "accessSystemTray"; + permission java.awt.AWTPermission "createRobot"; + permission java.util.PropertyPermission "resultsDir", "read"; + permission java.util.PropertyPermission "user.home", "read"; + permission java.util.PropertyPermission "os.name", "read"; + permission java.awt.AWTPermission "accessEventQueue"; + permission java.lang.RuntimePermission "setIO"; + permission java.lang.RuntimePermission "accessDeclaredMembers"; + permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.lwawt.macosx"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.awt.X11"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.awt"; + permission java.lang.RuntimePermission "loadLibrary.stl"; + permission java.util.PropertyPermission "java.home", "read"; + permission java.util.PropertyPermission "java.class.path", "read"; + permission java.awt.AWTPermission "readDisplayPixels"; + permission java.awt.AWTPermission "watchMousePointer"; +}; + diff --git a/jdk/test/java/awt/TrayIcon/SecurityCheck/NoPermissionTest/NoPermissionTest.java b/jdk/test/java/awt/TrayIcon/SecurityCheck/NoPermissionTest/NoPermissionTest.java new file mode 100644 index 00000000000..af172ae32ac --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/SecurityCheck/NoPermissionTest/NoPermissionTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check for SecurityException occurrence if no permissions for system tray granted + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main/othervm/policy=tray.policy -Djava.security.manager NoPermissionTest + */ + +public class NoPermissionTest { + + public static void main(String[] args) { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray is not supported on this platform. Marking the test passed"); + } else { + + BufferedImage im = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); + Graphics gr = im.createGraphics(); + gr.setColor(Color.white); + gr.fillRect(0, 0, 16, 16); + + try { + SystemTray.getSystemTray(); + throw new RuntimeException("FAIL: SecurityException not thrown by getSystemTray method"); + } catch (SecurityException ex) { + if (!ex.getMessage().matches(".+java.awt.AWTPermission.+accessSystemTray.*")) + throw new RuntimeException("FAIL: Security exception thrown due to unexpected reason"); + } + + try { + TrayIcon icon = new TrayIcon(im, "Caption"); + throw new RuntimeException("FAIL: SecurityException not thrown by TrayIcon constructor"); + } catch (SecurityException ex) { + if (!ex.getMessage().matches(".+java.awt.AWTPermission.+accessSystemTray.*")) + throw new RuntimeException("FAIL: Security exception thrown due to unexpected reason"); + } + } + } + +} diff --git a/jdk/test/java/awt/TrayIcon/SecurityCheck/PermissionTest/PermissionTest.java b/jdk/test/java/awt/TrayIcon/SecurityCheck/PermissionTest/PermissionTest.java new file mode 100644 index 00000000000..8de6187cd6b --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/SecurityCheck/PermissionTest/PermissionTest.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check for no Exception occurrence if permissions for system tray granted + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main/othervm/policy=tray.policy -Djava.security.manager PermissionTest + */ + +public class PermissionTest { + + public static void main(String[] args) { + + if (!SystemTray.isSupported()) { + System.out.println("SystemTray is not supported on this platform. Marking the test passed"); + } else { + BufferedImage im = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); + Graphics gr = im.createGraphics(); + gr.setColor(Color.white); + gr.fillRect(0, 0, 16, 16); + + SystemTray.getSystemTray(); + TrayIcon icon = new TrayIcon(im, "Caption"); + } + } +} diff --git a/jdk/test/java/awt/TrayIcon/SecurityCheck/PermissionTest/tray.policy b/jdk/test/java/awt/TrayIcon/SecurityCheck/PermissionTest/tray.policy new file mode 100644 index 00000000000..be273f8fdf4 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/SecurityCheck/PermissionTest/tray.policy @@ -0,0 +1,3 @@ +grant { + permission java.awt.AWTPermission "accessSystemTray"; +}; diff --git a/jdk/test/java/awt/TrayIcon/SystemTrayIconHelper.java b/jdk/test/java/awt/TrayIcon/SystemTrayIconHelper.java new file mode 100644 index 00000000000..a8f6e2f7cf5 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/SystemTrayIconHelper.java @@ -0,0 +1,172 @@ +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.Point2D; +import java.awt.image.BufferedImage; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; + +/* + * @summary This is a helper class to find the location of a system tray icon, + * and skip some OS specific cases in tests. + * @library ../../../../../lib/testlibrary + * @build ExtendedRobot SystemTrayIconHelper + */ +public class SystemTrayIconHelper { + + static Frame frame; + + /** + * Call this method if the tray icon need to be followed in an automated manner + * This method will be called by automated testcases + */ + static Point getTrayIconLocation(TrayIcon icon) throws Exception { + if (icon == null) { + return null; + } + + //This is added just in case the tray's native menu is visible. + //It has to be hidden if visible. For that, we are showing a Frame + //and clicking on it - the assumption is, the menu will + //be closed if another window is clicked + ExtendedRobot robot = new ExtendedRobot(); + try { + EventQueue.invokeAndWait(() -> { + frame = new Frame(); + frame.setSize(100, 100); + frame.setVisible(true); + }); + robot.mouseMove(frame.getLocationOnScreen().x + frame.getWidth() / 2, + frame.getLocationOnScreen().y + frame.getHeight() / 2); + robot.waitForIdle(); + robot.click(); + EventQueue.invokeAndWait(frame::dispose); + } catch (Exception e) { + return null; + } + + if (System.getProperty("os.name").startsWith("Win")) { + try { + // sun.awt.windows.WTrayIconPeer + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension iconSize = icon.getSize(); + + int width = (int) iconSize.getWidth(); + int height = (int) iconSize.getHeight(); + + // Some previously created icons may not be removed + // from tray until mouse move on it. So we glide + // through the whole tray bar. + robot.glide((int) screenSize.getWidth(), (int) (screenSize.getHeight()-15), 0, (int) (screenSize.getHeight() - 15), 1, 2); + + BufferedImage screen = robot.createScreenCapture(new Rectangle(screenSize)); + + for (int x = (int) (screenSize.getWidth()-width); x > 0; x--) { + for (int y = (int) (screenSize.getHeight()-height); y > (screenSize.getHeight()-50); y--) { + if (imagesEquals(((BufferedImage)icon.getImage()).getSubimage(0, 0, width, height), screen.getSubimage(x, y, width, height))) { + return new Point(x+5, y+5); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } else if (System.getProperty("os.name").startsWith("Mac")) { + Point2D point2d; + try { + // sun.lwawt.macosx.CTrayIcon + Field f_peer = getField( java.awt.TrayIcon.class, "peer"); + + Object peer = f_peer.get(icon); + Method m_getModel = peer.getClass().getDeclaredMethod( + "getModel"); + m_getModel.setAccessible(true); + long model = (Long) (m_getModel.invoke(peer, new Object[]{})); + Method m_getLocation = peer.getClass().getDeclaredMethod( + "nativeGetIconLocation", new Class[]{Long.TYPE}); + m_getLocation.setAccessible(true); + point2d = (Point2D)m_getLocation.invoke(peer, new Object[]{model}); + Point po = new Point((int)(point2d.getX()), (int)(point2d.getY())); + po.translate(10, -5); + return po; + }catch(Exception e) { + e.printStackTrace(); + return null; + } + } else { + try { + // sun.awt.X11.XTrayIconPeer + Field f_peer = getField(java.awt.TrayIcon.class, "peer"); + + Object peer = f_peer.get(icon); + Method m_getLOS = peer.getClass().getDeclaredMethod( + "getLocationOnScreen", new Class[]{}); + m_getLOS.setAccessible(true); + Point point = (Point)m_getLOS.invoke(peer, new Object[]{}); + point.translate(5, 5); + return point; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + return null; + } + + static Field getField(final Class clz, final String fieldName) { + Field res = null; + try { + res = (Field)AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + Field f = clz.getDeclaredField(fieldName); + f.setAccessible(true); + return f; + }); + } catch (PrivilegedActionException ex) { + ex.printStackTrace(); + } + return res; + } + + static boolean imagesEquals(BufferedImage img1, BufferedImage img2) { + for (int x = 0; x < img1.getWidth(); x++) { + for (int y = 0; y < img1.getHeight(); y++) { + if (img1.getRGB(x, y) != img2.getRGB(x, y)) + return false; + } + } + return true; + } + + static void doubleClick(Robot robot) { + if (System.getProperty("os.name").startsWith("Mac")) { + robot.mousePress(InputEvent.BUTTON3_MASK); + robot.delay(50); + robot.mouseRelease(InputEvent.BUTTON3_MASK); + } else { + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(50); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.delay(50); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(50); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } + } + + // Method for skipping some OS specific cases + static boolean skip(int button) { + if (System.getProperty("os.name").toLowerCase().startsWith("win")){ + if (button == InputEvent.BUTTON1_MASK){ + // See JDK-6827035 + return true; + } + } else if (System.getProperty("os.name").toLowerCase().contains("os x")){ + // See JDK-7153700 + return true; + } + return false; + } +} diff --git a/jdk/test/java/awt/TrayIcon/SystemTrayInstance/SystemTrayInstanceTest.java b/jdk/test/java/awt/TrayIcon/SystemTrayInstance/SystemTrayInstanceTest.java new file mode 100644 index 00000000000..d00d02e7484 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/SystemTrayInstance/SystemTrayInstanceTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; + +/* + * @test + * @summary Check the getSystemTray method of the SystemTray. Checks if + * a proper instance is returned in supported platforms and a proper + * exception is thrown in unsupported platforms + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main/othervm -DSystemTraySupport=TRUE SystemTrayInstanceTest + */ + +public class SystemTrayInstanceTest { + + private static boolean supported = false; + + public static void main(String[] args) throws Exception { + String sysTraySupport = System.getProperty("SystemTraySupport"); + if (sysTraySupport == null) + throw new RuntimeException("SystemTray support status unknown!"); + + if ("TRUE".equals(sysTraySupport)) { + System.out.println("System tray is supported on the platform under test"); + supported = true; + } + + new SystemTrayInstanceTest().doTest(); + } + + private void doTest() throws Exception { + boolean flag = SystemTray.isSupported(); + if (supported != flag) + throw new RuntimeException("FAIL: isSupported did not return the correct value"+ + (supported ? + "SystemTray is supported on the platform under test" : + "SystemTray is not supported on the platform under test") + + "SystemTray.isSupported() method returned " + flag); + + if (supported) { + SystemTray tray = SystemTray.getSystemTray(); + } else { + try { + SystemTray tray = SystemTray.getSystemTray(); + } catch (UnsupportedOperationException uoe) { + System.out.println("UnsupportedOperationException thrown correctly"); + } + } + } +} diff --git a/jdk/test/java/awt/TrayIcon/TrayIconAddTest/TrayIconAddTest.java b/jdk/test/java/awt/TrayIcon/TrayIconAddTest/TrayIconAddTest.java new file mode 100644 index 00000000000..1b12a27ca58 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/TrayIconAddTest/TrayIconAddTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; + + +/* + * @test + * @summary Tests the add method of the SystemTray. Checks if it + * throws proper exceptions in case of invalid arguments and adds the + * TrayIcon correctly in case of a proper argument + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main TrayIconAddTest + */ + +public class TrayIconAddTest { + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + new TrayIconAddTest().doTest(); + } + } + + void doTest() throws Exception { + SystemTray tray = SystemTray.getSystemTray(); + try { + tray.add(null); + } catch (NullPointerException npe) { + System.out.println("NullPointerException thrown correctly when add(null) called"); + } + + TrayIcon icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB)); + + tray.add(icon); + + try { + tray.add(icon); + } catch (IllegalArgumentException iae) { + System.out.println("IllegalArgumentException rightly thrown when tray icon is added twice"); + } + } +} diff --git a/jdk/test/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java b/jdk/test/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java new file mode 100644 index 00000000000..9cdce634a92 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; + + +/* + * @test + * @summary Check if MouseEvent has the proper modifiers when + * TrayIcon is clicked pressing the modifier keys + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary ../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main TrayIconEventModifiersTest + */ + +public class TrayIconEventModifiersTest { + + Image image; + + TrayIcon icon; + ExtendedRobot robot; + + Object mouseLock = new Object(); + + String caption = "Sample Icon"; + boolean mousePressed = false; + boolean mouseReleased = false; + boolean mouseClicked = false; + int modifiers, releaseModifiers, clickModifiers; + + int[] buttonTypes = { + InputEvent.BUTTON1_MASK, + InputEvent.BUTTON2_MASK, + InputEvent.BUTTON3_MASK + }; + + String[] buttonNames = { + "BUTTON1", + "BUTTON2", + "BUTTON3" + }; + + int[] buttonMasks = { + InputEvent.BUTTON1_DOWN_MASK, + InputEvent.BUTTON2_DOWN_MASK, + InputEvent.BUTTON3_DOWN_MASK + }; + + static int[] keyTypes = { + KeyEvent.VK_SHIFT, + KeyEvent.VK_CONTROL + }; + + static String[] keyNames = { + "SHIFT", + "CONTROL" + }; + + static int[] keyMasks = { + KeyEvent.SHIFT_DOWN_MASK, + KeyEvent.CTRL_DOWN_MASK + }; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (System.getProperty("os.name").toLowerCase().startsWith("win")) + System.err.println("Test can fail if the icon hides to a tray icons pool" + + "in Windows 7, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true " + + "to avoid this problem. Or change behavior only for Java SE tray " + + "icon and rerun test."); + + System.out.println(System.getProperty("os.arch")); + if (System.getProperty("os.name").indexOf("Sun") != -1 && + System.getProperty("os.arch").indexOf("sparc") != -1) { + keyTypes = new int[]{ + KeyEvent.VK_SHIFT, + KeyEvent.VK_CONTROL, + KeyEvent.VK_META + }; + + keyNames = new String[]{ + "SHIFT", + "CONTROL", + "META" + }; + keyMasks = new int[]{ + KeyEvent.SHIFT_DOWN_MASK, + KeyEvent.CTRL_DOWN_MASK, + KeyEvent.META_DOWN_MASK + }; + } + + new TrayIconEventModifiersTest().doTest(); + } + } + + public TrayIconEventModifiersTest() throws Exception { + robot = new ExtendedRobot(); + EventQueue.invokeAndWait(this::initializeGUI); + } + + private void initializeGUI() { + + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), caption); + icon.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent event) { + if (!icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mousePressed: MouseEvent.getSource " + + "did not return TrayIcon object"); + + mousePressed = true; + modifiers = event.getModifiersEx(); + System.out.println("Icon mousePressed " + modifiers); + synchronized (mouseLock) { + try { + mouseLock.notifyAll(); + } catch (Exception e) { + } + } + } + + public void mouseReleased(MouseEvent event) { + if (!icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseReleased: MouseEvent.getSource " + + "did not return TrayIcon object"); + + mouseReleased = true; + releaseModifiers = event.getModifiersEx(); + System.out.println("Icon mouseReleased " + releaseModifiers); + synchronized (mouseLock) { + try { + mouseLock.notifyAll(); + } catch (Exception e) { + } + } + } + + public void mouseClicked(MouseEvent event) { + if (!icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseClicked: MouseEvent.getSource " + + "did not return TrayIcon object"); + + mouseClicked = true; + clickModifiers = event.getModifiersEx(); + System.out.println("Icon mouseClickedd " + clickModifiers); + synchronized (mouseLock) { + try { + mouseLock.notifyAll(); + } catch (Exception e) { + } + } + } + }); + + try { + tray.add(icon); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + void doTest() throws Exception { + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(); + + for (int i = 0; i < buttonTypes.length; i++) { + for (int j = 0; j < keyTypes.length; j++) { + mousePressed = false; + + robot.keyPress(keyTypes[j]); + robot.mousePress(buttonTypes[i]); + + if (! mousePressed) { + synchronized (mouseLock) { + try { + mouseLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mousePressed) { + if (! SystemTrayIconHelper.skip(buttonTypes[i])) + throw new RuntimeException("FAIL: mousePressed not triggered when " + + keyNames[j] + " + " + buttonNames[i] + " pressed"); + } else { + int onMask = buttonMasks[i] | keyMasks[j]; + if ((modifiers & onMask) != onMask) { + throw new RuntimeException("FAIL: getModifiersEx did not return " + + "the correct value when " + keyNames[j] + " + " + + buttonNames[i] + " pressed"); + } + } + + mouseReleased = false; + mouseClicked = false; + robot.mouseRelease(buttonTypes[i]); + + if (! mouseReleased) { + synchronized (mouseLock) { + try { + mouseLock.wait(3000); + } catch (Exception e) { + } + } + } + + robot.waitForIdle(1000); + robot.keyRelease(keyTypes[j]); + robot.waitForIdle(1000); + + if (! mouseReleased) { + if (! SystemTrayIconHelper.skip(buttonTypes[i])) + throw new RuntimeException("FAIL: mouseReleased not triggered when " + + keyNames[j] + " + " + buttonNames[i] + " released"); + } else { + int onMask = keyMasks[j]; + if ((releaseModifiers & onMask) != onMask) + throw new RuntimeException("FAIL: getModifiersEx did not return " + + "the correct value when " + keyNames[j] + " + " + + buttonNames[i] + " released"); + } + if (! mouseClicked) { + throw new RuntimeException("FAIL: mouseClicked not triggered when " + + keyNames[j] + " + " + buttonNames[i] + + " pressed & released"); + } else { + int onMask = keyMasks[j]; + if ((clickModifiers & onMask) != onMask) + throw new RuntimeException("FAIL: getModifiersEx did not return " + + "the correct value when " + keyNames[j] + " + " + + buttonNames[i] + " pressed & released"); + } + robot.type(KeyEvent.VK_ESCAPE); + } + } + } +} + diff --git a/jdk/test/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java b/jdk/test/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java new file mode 100644 index 00000000000..c7c79ea6570 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + + +/* + * @test + * @summary Check for MouseEvents with all mouse buttons + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary ../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main TrayIconEventsTest + */ + +public class TrayIconEventsTest { + + TrayIcon icon; + ExtendedRobot robot; + + boolean actionPerformed = false; + Object actionLock = new Object(); + Object pressLock = new Object(); + Object releaseLock = new Object(); + Object clickLock = new Object(); + Object moveLock = new Object(); + + String caption = "Sample Icon"; + boolean mousePressed = false; + boolean mouseReleased = false; + boolean mouseClicked = false; + boolean mouseMoved = false; + + int[] buttonTypes = { + InputEvent.BUTTON1_MASK, + InputEvent.BUTTON2_MASK, + InputEvent.BUTTON3_MASK + }; + + String[] buttonNames = { + "BUTTON1", + "BUTTON2", + "BUTTON3" + }; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (System.getProperty("os.name").toLowerCase().startsWith("win")) + System.err.println("Test can fail if the icon hides to a tray icons pool " + + "in Windows 7, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true " + + "to avoid this problem. Or change behavior only for Java SE " + + "tray icon."); + new TrayIconEventsTest().doTest(); + } + } + + public TrayIconEventsTest() throws Exception { + robot = new ExtendedRobot(); + EventQueue.invokeAndWait(this::initializeGUI); + } + + private void initializeGUI(){ + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), caption); + icon.addActionListener(event -> { + actionPerformed = true; + synchronized (actionLock) { + try { + + actionLock.notifyAll(); + } catch (Exception e) { + } + } + }); + icon.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent event) { + mousePressed = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mousePressed"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mousePressed: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (pressLock) { + try { + pressLock.notifyAll(); + } catch (Exception e) { + } + } + } + + public void mouseReleased(MouseEvent event) { + mouseReleased = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseReleased"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseReleased: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (releaseLock) { + try { + releaseLock.notifyAll(); + } catch (Exception e) { + } + } + } + + public void mouseClicked(MouseEvent event) { + mouseClicked = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseClicked"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseClicked: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (clickLock) { + try { + clickLock.notifyAll(); + } catch (Exception e) { + } + } + } + }); + + icon.addMouseMotionListener(new MouseMotionAdapter() { + public void mouseMoved(MouseEvent event) { + mouseMoved = true; + Point p = event.getPoint(); + if (p.x != event.getX() || p.y != event.getY()) + throw new RuntimeException("FAIL: MouseEvent.getPoint() did " + + "not return the same value as getX/getY " + + "for mouseMoved"); + + if (! icon.equals(event.getSource())) + throw new RuntimeException("FAIL: mouseMoved: MouseEvent.getSource " + + "did not return TrayIcon object"); + + synchronized (moveLock) { + try { + moveLock.notifyAll(); + } catch (Exception e) { + } + } + } + }); + + try { + tray.add(icon); + } catch (AWTException e) { + throw new RuntimeException(e); + } + } + + void doTest() throws Exception { + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(2000); + + SystemTrayIconHelper.doubleClick(robot); + + if (! actionPerformed) { + synchronized (actionLock) { + try { + actionLock.wait(10000); + } catch (Exception e) { + } + } + } + if (! actionPerformed) + throw new RuntimeException("FAIL: ActionEvent not triggered when TrayIcon is double clicked"); + + for (int i = 0; i < buttonTypes.length; i++) { + mousePressed = false; + robot.mousePress(buttonTypes[i]); + + if (! mousePressed) { + synchronized (pressLock) { + try { + pressLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mousePressed) + if (! SystemTrayIconHelper.skip(buttonTypes[i]) ) + throw new RuntimeException("FAIL: mousePressed not triggered when " + + buttonNames[i] + " pressed"); + + mouseReleased = false; + mouseClicked = false; + robot.mouseRelease(buttonTypes[i]); + + if (! mouseReleased) { + synchronized (releaseLock) { + try { + releaseLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mouseReleased) + throw new RuntimeException("FAIL: mouseReleased not triggered when " + + buttonNames[i] + " released"); + + if (! mouseClicked) { + synchronized (clickLock) { + try { + clickLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! mouseClicked) + throw new RuntimeException("FAIL: mouseClicked not triggered when " + + buttonNames[i] + " pressed & released"); + } + + mouseMoved = false; + robot.mouseMove(iconPosition.x + 100, iconPosition.y); + robot.glide(iconPosition.x, iconPosition.y); + + if (! mouseMoved) + if (! SystemTrayIconHelper.skip(0) ) + throw new RuntimeException("FAIL: mouseMoved not triggered even when mouse moved over the icon"); + } +} diff --git a/jdk/test/java/awt/TrayIcon/TrayIconMethodsTest/TrayIconMethodsTest.java b/jdk/test/java/awt/TrayIcon/TrayIconMethodsTest/TrayIconMethodsTest.java new file mode 100644 index 00000000000..50c71310b7c --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/TrayIconMethodsTest/TrayIconMethodsTest.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check various methods of the TrayIcon - whether the methods + * return the proper values, throws the proper exceptions etc + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main TrayIconMethodsTest + */ + +public class TrayIconMethodsTest { + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + new TrayIconMethodsTest().doTest(); + } + } + + void doTest() throws Exception { + SystemTray tray = SystemTray.getSystemTray(); + + String toolTip = "Sample Icon"; + PopupMenu pm = new PopupMenu(); + pm.add(new MenuItem("Sample")); + + Image image = new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB); + TrayIcon icon = new TrayIcon(image, toolTip, pm); + + ActionListener al1 = event -> {}; + ActionListener al2 = event -> {}; + MouseMotionListener mml1 = new MouseMotionAdapter() {}; + MouseMotionListener mml2 = new MouseMotionAdapter() {}; + MouseListener ml1 = new MouseAdapter() {}; + MouseListener ml2 = new MouseAdapter() {}; + + icon.addActionListener(al1); + icon.addActionListener(al2); + icon.addMouseMotionListener(mml1); + icon.addMouseMotionListener(mml2); + icon.addMouseListener(ml1); + icon.addMouseListener(ml2); + tray.add(icon); + + ActionListener[] actionListeners = icon.getActionListeners(); + if (actionListeners == null || actionListeners.length != 2) + throw new RuntimeException("FAIL: getActionListeners did not return the correct value " + + "when there were two listeners present " + actionListeners); + + if (! isPresent(actionListeners, al1) || ! isPresent(actionListeners, al2)) + throw new RuntimeException("FAIL: All the action listeners added are not returned " + + "by the method"); + + MouseListener[] mouseListeners = icon.getMouseListeners(); + if (mouseListeners == null || mouseListeners.length != 2) + throw new RuntimeException("FAIL: getMouseListeners did not return the correct value " + + "when there were two listeners present " + mouseListeners); + + if (! isPresent(mouseListeners, ml1) || ! isPresent(mouseListeners, ml2)) + throw new RuntimeException("FAIL: All the mouse listeners added are not returned " + + "by the method"); + + MouseMotionListener[] mouseMotionListeners = icon.getMouseMotionListeners(); + if (mouseMotionListeners == null || mouseMotionListeners.length != 2) + throw new RuntimeException("FAIL: getMouseMotionListeners did not return the correct value " + + "when there were two listeners present " + mouseMotionListeners); + + if (! isPresent(mouseMotionListeners, mml1) || ! isPresent(mouseMotionListeners, mml2)) + throw new RuntimeException("FAIL: All the mouse motion listeners added are not returned " + + "by the method"); + + Image im = icon.getImage(); + if (! image.equals(im)) + throw new RuntimeException("FAIL: Images are not the same getImage()=" + im + + " Image=" + image); + + if (! pm.equals(icon.getPopupMenu())) + throw new RuntimeException("FAIL: PopupMenus are not the same getPopupMenu()=" + + icon.getPopupMenu() + " PopupMenu=" + pm); + + if (! toolTip.equals(icon.getToolTip())) + throw new RuntimeException("FAIL: ToolTips are not the same getToolTip()=" + + icon.getToolTip() + " ToolTip=" + toolTip); + + if (icon.isImageAutoSize()) + throw new RuntimeException("FAIL: Auto size property is true by default"); + + icon.setImageAutoSize(true); + if (! icon.isImageAutoSize()) + throw new RuntimeException("FAIL: Auto size property is not set to " + + "true by call to setImageAutoSize(true)"); + + icon.removeActionListener(al1); + icon.removeActionListener(al2); + actionListeners = icon.getActionListeners(); + if (actionListeners == null || actionListeners.length != 0) + throw new RuntimeException("FAIL: removeActionListener did not " + + "remove the ActionListeners added " + actionListeners); + + icon.removeMouseListener(ml1); + icon.removeMouseListener(ml2); + mouseListeners = icon.getMouseListeners(); + if (mouseListeners == null || mouseListeners.length != 0) + throw new RuntimeException("FAIL: removeMouseListener did not " + + "remove the MouseListeners added " + mouseListeners); + + icon.removeMouseMotionListener(mml1); + icon.removeMouseMotionListener(mml2); + mouseMotionListeners = icon.getMouseMotionListeners(); + if (mouseMotionListeners == null || mouseMotionListeners.length != 0) + throw new RuntimeException("FAIL: removeMouseMotionListener did not " + + "remove the MouseMotionListeners added " + mouseMotionListeners); + + try { + icon.setImage(null); + throw new RuntimeException("FAIL: setImage(null) did not throw NullPointerException"); + } catch (NullPointerException npe) { + } + } + + boolean isPresent(Object[] array, Object obj) { + if (array == null || array.length == 0 || obj == null) { + return false; + } + for (int i = 0; i < array.length; i++) { + if (obj.equals(array[i])) { + return true; + } + } + return false; + } +} diff --git a/jdk/test/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java b/jdk/test/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java new file mode 100644 index 00000000000..124ceba5399 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check if ActionEvent is triggered by a TrayIcon only when + * it is double clicked using mouse button 1 (or single clicked + * with button 3 (on Mac OS X)) + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary ../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main TrayIconMouseTest + */ + +public class TrayIconMouseTest { + + TrayIcon icon; + ExtendedRobot robot; + + boolean actionPerformed = false; + Object actionLock = new Object(); + static boolean isMacOS = false; + + String caption = "Sample Icon"; + + int[] buttonTypes = { + InputEvent.BUTTON1_MASK, + InputEvent.BUTTON2_MASK, + InputEvent.BUTTON3_MASK + }; + + String[] buttonNames = { + "BUTTON1", + "BUTTON2", + "BUTTON3" + }; + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (System.getProperty("os.name").toLowerCase().startsWith("mac")) { + isMacOS = true; + } + new TrayIconMouseTest().doTest(); + } + } + + TrayIconMouseTest() throws Exception{ + robot = new ExtendedRobot(); + EventQueue.invokeAndWait(this::initializeGUI); + } + + void initializeGUI() { + + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), caption); + icon.addActionListener(event -> { + actionPerformed = true; + synchronized (actionLock) { + try { + actionLock.notifyAll(); + } catch (Exception e) { + } + } + }); + try { + tray.add(icon); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private void doTest() throws Exception { + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(); + + for (int i = 0; i < buttonTypes.length; i++) { + actionPerformed = false; + robot.click(buttonTypes[i]); + robot.waitForIdle(2000); + + if (isMacOS && actionPerformed && i == 2) { + + }else if (isMacOS && i == 2) { + throw new RuntimeException("FAIL: ActionEvent NOT triggered when " + + buttonNames[i] + " is single clicked on Mac OS"); + }else if (actionPerformed) { + throw new RuntimeException("FAIL: ActionEvent triggered when " + + buttonNames[i] + " is single clicked"); + } + } + + if(!isMacOS) { + for (int i = 0; i < buttonTypes.length; i++) { + for (int j = 0; j < buttonTypes.length; j++) { + if (j != i) { + actionPerformed = false; + robot.mousePress(buttonTypes[i]); + robot.mousePress(buttonTypes[j]); + robot.mouseRelease(buttonTypes[j]); + robot.mouseRelease(buttonTypes[i]); + + robot.waitForIdle(); + + if (actionPerformed) + throw new RuntimeException("FAIL: ActionEvent triggered when " + + buttonNames[i] + " and " + buttonNames[j] + + " is clicked and released"); + } + } + } + + for (int i = 0; i < buttonTypes.length; i++) { + actionPerformed = false; + robot.mousePress(buttonTypes[i]); + robot.delay(50); + robot.mouseRelease(buttonTypes[i]); + robot.delay(50); + robot.mousePress(buttonTypes[i]); + robot.delay(50); + robot.mouseRelease(buttonTypes[i]); + + if (i == 0) { + if (! actionPerformed) { + synchronized (actionLock) { + try { + actionLock.wait(3000); + } catch (Exception e) { + } + } + } + if (! actionPerformed) + throw new RuntimeException("FAIL: ActionEvent not triggered when " + + buttonNames[i] + " is double clicked"); + } else { + robot.waitForIdle(); + + if (actionPerformed) + throw new RuntimeException("FAIL: ActionEvent triggered when " + + buttonNames[i] + " is double clicked"); + } + } + } + } +} diff --git a/jdk/test/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java b/jdk/test/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java new file mode 100644 index 00000000000..3aa48750d97 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.awt.*; +import java.awt.event.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Check if a JPopupMenu can be displayed when TrayIcon is + * right clicked. It uses a JWindow as the parent of the JPopupMenu + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @library ../../../../lib/testlibrary ../ + * @build ExtendedRobot SystemTrayIconHelper + * @run main TrayIconPopupTest + */ + +public class TrayIconPopupTest { + + TrayIcon icon; + ExtendedRobot robot; + + boolean actionPerformed = false; + Object actionLock = new Object(); + static final int ATTEMPTS = 50; + + PopupMenu popup; + Dialog window; + + public static void main(String[] args) throws Exception { + if (!SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + if (System.getProperty("os.name").toLowerCase().startsWith("win")) + System.err.println("Test can fail if the icon hides to a tray icons pool " + + "in Windows 7, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true " + + "to avoid this problem. Or change behavior only for Java SE " + + "tray icon."); + new TrayIconPopupTest().doTest(); + } + } + + TrayIconPopupTest() throws Exception { + robot = new ExtendedRobot(); + EventQueue.invokeAndWait(this::initializeGUI); + robot.waitForIdle(1000); + EventQueue.invokeAndWait( () -> window.setLocation(100, 100)); + robot.waitForIdle(1000); + } + + private void initializeGUI() { + window = new Dialog((Frame) null); + window.setSize(5, 5); + window.setVisible(true); + + popup = new PopupMenu(""); + + MenuItem item = new MenuItem("Sample"); + item.addActionListener(event -> { + actionPerformed = true; + + synchronized (actionLock) { + try { + actionLock.notifyAll(); + } catch (Exception e) { + } + } + }); + popup.add(item); + popup.add(new MenuItem("Item2")); + popup.add(new MenuItem("Item3")); + + window.add(popup); + + SystemTray tray = SystemTray.getSystemTray(); + icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), "Sample Icon"); + icon.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent event) { + if (event.isPopupTrigger()) { + popup.show(window, 0, 0); + } + } + + public void mouseReleased(MouseEvent event) { + if (event.isPopupTrigger()) { + popup.show(window, 0, 0); + } + } + }); + try { + tray.add(icon); + } catch (AWTException e) { + throw new RuntimeException(e); + } + } + + void doTest() throws Exception { + + Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); + if (iconPosition == null) + throw new RuntimeException("Unable to find the icon location!"); + + robot.mouseMove(iconPosition.x, iconPosition.y); + robot.waitForIdle(); + robot.mousePress(InputEvent.BUTTON3_MASK); + robot.delay(50); + robot.mouseRelease(InputEvent.BUTTON3_MASK); + robot.delay(1000); + + robot.mouseMove(window.getLocation().x + 10, window.getLocation().y + 10); + robot.mousePress(InputEvent.BUTTON3_MASK); + robot.delay(50); + robot.mouseRelease(InputEvent.BUTTON3_MASK); + + int attempts = 0; + while (!actionPerformed && attempts++ < ATTEMPTS) { + synchronized (actionLock) { + try { + actionLock.wait(3000); + } catch (Exception e) { + } + } + } + if (!actionPerformed) + throw new RuntimeException("FAIL: ActionEvent not triggered when " + + "JPopupMenu shown and menu item selected using keyboard"); + + } +} \ No newline at end of file diff --git a/jdk/test/java/awt/TrayIcon/TrayIconRemoveTest/TrayIconRemoveTest.java b/jdk/test/java/awt/TrayIcon/TrayIconRemoveTest/TrayIconRemoveTest.java new file mode 100644 index 00000000000..330cc4a9eec --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/TrayIconRemoveTest/TrayIconRemoveTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; + +/* + * @test + * @summary Test the remove method of the TrayIcon + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main TrayIconRemoveTest + */ + +public class TrayIconRemoveTest { + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + new TrayIconRemoveTest().doTest(); + } + } + + private void doTest() throws Exception { + Image image = new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB); + SystemTray tray = SystemTray.getSystemTray(); + tray.remove(null); + + TrayIcon icon1 = new TrayIcon(image); + tray.add(icon1); + + tray.remove(icon1); + + TrayIcon[] icons = tray.getTrayIcons(); + if (icons.length != 0) + throw new RuntimeException("FAIL: There are icons still present even after " + + "removing the added icon" + "\n"+ + "No. of icons present: " + icons.length); + + TrayIcon icon2 = new TrayIcon(image); + tray.remove(icon2); + + TrayIcon icon3 = new TrayIcon(image); + tray.add(icon3); + + TrayIcon newIcon = new TrayIcon(image); + tray.remove(newIcon); + + tray.remove(null); + } +} diff --git a/jdk/test/java/awt/TrayIcon/TrayIconSizeTest/TrayIconSizeTest.java b/jdk/test/java/awt/TrayIcon/TrayIconSizeTest/TrayIconSizeTest.java new file mode 100644 index 00000000000..eb769c459d8 --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/TrayIconSizeTest/TrayIconSizeTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.*; +import java.awt.image.BufferedImage; + + +/* + * @test + * @summary Test the methods TrayIcon.getSize and SystemTray.getTrayIconSize. + * There is no way to check whether the values returned are correct, + * so its checked whether the value is greater than a minimum + * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) + * @run main TrayIconSizeTest + */ + +public class TrayIconSizeTest { + + public static void main(String[] args) throws Exception { + if (! SystemTray.isSupported()) { + System.out.println("SystemTray not supported on the platform under test. " + + "Marking the test passed"); + } else { + new TrayIconSizeTest().doTest(); + } + } + + void doTest() throws Exception { + + SystemTray tray = SystemTray.getSystemTray(); + Dimension dim = tray.getTrayIconSize(); + + if (dim.width <= 5 || dim.height <= 5) + throw new RuntimeException("FAIL: value returned by getTrayIconSize is not correct: " + dim); + + TrayIcon icon = new TrayIcon(new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB)); + + if (! icon.getSize().equals(dim)) + throw new RuntimeException("FAIL: TrayIcon.getSize did not return the same value as " + + "getTrayIconSize when TrayIcon not added" + "\n" + + "SystemTray.getTrayIconSize(): " + dim + "\n" + + "TrayIcon.getSize(): " + icon.getSize()); + + tray.add(icon); + + if (icon.getSize().width <= 5 || icon.getSize().height <= 5) + throw new RuntimeException("FAIL: value returned by TrayIcon.getSize is not correct: " + icon.getSize()); + } +} From 48b2a7c0c73db372164e6a4f507bfdda7852ab21 Mon Sep 17 00:00:00 2001 From: Alexey Ivanov Date: Mon, 9 Jun 2014 18:10:49 +0400 Subject: [PATCH 059/192] 8046239: Build failure in 9-client on all non-Windows platforms Reviewed-by: anthony, serb, alexp --- .../classes/com/sun/java/swing/plaf/windows/XPStyle.java | 3 +-- jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java | 4 ++++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java index 7765145eff1..baeca8c29ca 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java @@ -52,7 +52,6 @@ import javax.swing.text.JTextComponent; import sun.awt.image.SunWritableRaster; import sun.awt.windows.ThemeReader; -import sun.awt.windows.WToolkit; import sun.security.action.GetPropertyAction; import sun.swing.CachedPainter; @@ -100,7 +99,7 @@ class XPStyle { if (themeActive == null) { Toolkit toolkit = Toolkit.getDefaultToolkit(); themeActive = - (Boolean)toolkit.getDesktopProperty(WToolkit.XPSTYLE_THEME_ACTIVE); + (Boolean)toolkit.getDesktopProperty("win.xpstyle.themeActive"); if (themeActive == null) { themeActive = Boolean.FALSE; } diff --git a/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java b/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java index 7445cc2f5ff..5bd2f7ec0b8 100644 --- a/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java +++ b/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java @@ -45,6 +45,10 @@ public final class ThemeReader { return false; } + public static boolean isXPStyleEnabled() { + return false; + } + public static void paintBackground(int[] buffer, String widget, int part, int state, int x, int y, int w, int h, int stride) { } From e89442e619c71598c72fa1f6328d04710c001377 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Mon, 9 Jun 2014 20:23:26 +0400 Subject: [PATCH 060/192] 8039901: jdk/src/share/classes/com/sun/media/sound/services/ appear not to be used Reviewed-by: amenkov, azvegint --- .../linux-i586/javax.sound.sampled.spi.MixerProvider | 6 ------ .../windows-i586/javax.sound.sampled.spi.MixerProvider | 6 ------ .../windows-ia64/javax.sound.sampled.spi.MixerProvider | 6 ------ 3 files changed, 18 deletions(-) delete mode 100644 jdk/src/share/classes/com/sun/media/sound/services/linux-i586/javax.sound.sampled.spi.MixerProvider delete mode 100644 jdk/src/share/classes/com/sun/media/sound/services/windows-i586/javax.sound.sampled.spi.MixerProvider delete mode 100644 jdk/src/share/classes/com/sun/media/sound/services/windows-ia64/javax.sound.sampled.spi.MixerProvider diff --git a/jdk/src/share/classes/com/sun/media/sound/services/linux-i586/javax.sound.sampled.spi.MixerProvider b/jdk/src/share/classes/com/sun/media/sound/services/linux-i586/javax.sound.sampled.spi.MixerProvider deleted file mode 100644 index 56b8f12b0fb..00000000000 --- a/jdk/src/share/classes/com/sun/media/sound/services/linux-i586/javax.sound.sampled.spi.MixerProvider +++ /dev/null @@ -1,6 +0,0 @@ -# service provider file for Linux: with DirectAudioDeviceProvider -# last mixer is default mixer -com.sun.media.sound.PortMixerProvider -com.sun.media.sound.SimpleInputDeviceProvider -com.sun.media.sound.DirectAudioDeviceProvider -com.sun.media.sound.HeadspaceMixerProvider diff --git a/jdk/src/share/classes/com/sun/media/sound/services/windows-i586/javax.sound.sampled.spi.MixerProvider b/jdk/src/share/classes/com/sun/media/sound/services/windows-i586/javax.sound.sampled.spi.MixerProvider deleted file mode 100644 index 7e39afe741a..00000000000 --- a/jdk/src/share/classes/com/sun/media/sound/services/windows-i586/javax.sound.sampled.spi.MixerProvider +++ /dev/null @@ -1,6 +0,0 @@ -# service provider file for Windows: with DirectAudioDeviceProvider -# last mixer is default mixer -com.sun.media.sound.PortMixerProvider -com.sun.media.sound.SimpleInputDeviceProvider -com.sun.media.sound.DirectAudioDeviceProvider -com.sun.media.sound.HeadspaceMixerProvider diff --git a/jdk/src/share/classes/com/sun/media/sound/services/windows-ia64/javax.sound.sampled.spi.MixerProvider b/jdk/src/share/classes/com/sun/media/sound/services/windows-ia64/javax.sound.sampled.spi.MixerProvider deleted file mode 100644 index cf3bc8acaa6..00000000000 --- a/jdk/src/share/classes/com/sun/media/sound/services/windows-ia64/javax.sound.sampled.spi.MixerProvider +++ /dev/null @@ -1,6 +0,0 @@ -# service provider file for Windows IA64: with DirectAudioDeviceProvider -# last mixer is default mixer -com.sun.media.sound.PortMixerProvider -com.sun.media.sound.SimpleInputDeviceProvider -com.sun.media.sound.DirectAudioDeviceProvider -com.sun.media.sound.HeadspaceMixerProvider From c6065994826726461eeca3a66c9c404f236d6b1c Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Mon, 9 Jun 2014 11:47:18 -0700 Subject: [PATCH 061/192] 8042870: Fix raw and unchecked warnings in sun.print Reviewed-by: prr --- .../sun/print/CustomMediaSizeName.java | 8 +- .../classes/sun/print/CustomMediaTray.java | 10 +-- .../share/classes/sun/print/DialogOwner.java | 3 +- .../share/classes/sun/print/PSPrinterJob.java | 34 ++++---- .../classes/sun/print/PSStreamPrintJob.java | 16 ++-- .../sun/print/PSStreamPrintService.java | 12 +-- .../share/classes/sun/print/PrintJob2D.java | 4 +- .../sun/print/PrintJobAttributeException.java | 8 +- .../classes/sun/print/PrinterJobWrapper.java | 3 +- .../classes/sun/print/RasterPrinterJob.java | 34 ++++---- .../classes/sun/print/ServiceDialog.java | 85 +++++++++---------- .../classes/sun/print/ServiceNotifier.java | 9 +- .../classes/sun/print/SunAlternateMedia.java | 3 +- .../classes/sun/print/SunMinMaxPage.java | 3 +- .../classes/sun/print/SunPageSelection.java | 3 +- .../sun/print/SunPrinterJobService.java | 2 +- .../classes/sun/print/CUPSPrinter.java | 30 +++---- .../classes/sun/print/IPPPrintService.java | 84 +++++++++--------- .../classes/sun/print/UnixPrintJob.java | 22 ++--- .../classes/sun/print/UnixPrintService.java | 17 ++-- .../sun/print/UnixPrintServiceLookup.java | 44 +++++----- .../classes/sun/print/Win32MediaTray.java | 12 +-- .../classes/sun/print/Win32PrintJob.java | 16 ++-- .../classes/sun/print/Win32PrintService.java | 65 +++++++------- .../sun/print/Win32PrintServiceLookup.java | 5 +- 25 files changed, 264 insertions(+), 268 deletions(-) diff --git a/jdk/src/share/classes/sun/print/CustomMediaSizeName.java b/jdk/src/share/classes/sun/print/CustomMediaSizeName.java index e1df990730c..2390495a703 100644 --- a/jdk/src/share/classes/sun/print/CustomMediaSizeName.java +++ b/jdk/src/share/classes/sun/print/CustomMediaSizeName.java @@ -33,8 +33,8 @@ import javax.print.attribute.standard.MediaSizeName; import java.util.ArrayList; class CustomMediaSizeName extends MediaSizeName { - private static ArrayList customStringTable = new ArrayList(); - private static ArrayList customEnumTable = new ArrayList(); + private static ArrayList customStringTable = new ArrayList<>(); + private static ArrayList customEnumTable = new ArrayList<>(); private String choiceName; private MediaSizeName mediaName; @@ -162,7 +162,7 @@ class CustomMediaSizeName extends MediaSizeName { */ protected String[] getStringTable() { String[] nameTable = new String[customStringTable.size()]; - return (String[])customStringTable.toArray(nameTable); + return customStringTable.toArray(nameTable); } /** @@ -170,7 +170,7 @@ class CustomMediaSizeName extends MediaSizeName { */ protected EnumSyntax[] getEnumValueTable() { MediaSizeName[] enumTable = new MediaSizeName[customEnumTable.size()]; - return (MediaSizeName[])customEnumTable.toArray(enumTable); + return customEnumTable.toArray(enumTable); } } diff --git a/jdk/src/share/classes/sun/print/CustomMediaTray.java b/jdk/src/share/classes/sun/print/CustomMediaTray.java index d74c806676f..7607cd8d118 100644 --- a/jdk/src/share/classes/sun/print/CustomMediaTray.java +++ b/jdk/src/share/classes/sun/print/CustomMediaTray.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,8 +31,8 @@ import javax.print.attribute.standard.Media; import java.util.ArrayList; class CustomMediaTray extends MediaTray { - private static ArrayList customStringTable = new ArrayList(); - private static ArrayList customEnumTable = new ArrayList(); + private static ArrayList customStringTable = new ArrayList<>(); + private static ArrayList customEnumTable = new ArrayList<>(); private String choiceName; private CustomMediaTray(int x) { @@ -79,7 +79,7 @@ class CustomMediaTray extends MediaTray { */ protected String[] getStringTable() { String[] nameTable = new String[customStringTable.size()]; - return (String[])customStringTable.toArray(nameTable); + return customStringTable.toArray(nameTable); } /** @@ -87,7 +87,7 @@ class CustomMediaTray extends MediaTray { */ protected EnumSyntax[] getEnumValueTable() { MediaTray[] enumTable = new MediaTray[customEnumTable.size()]; - return (MediaTray[])customEnumTable.toArray(enumTable); + return customEnumTable.toArray(enumTable); } } diff --git a/jdk/src/share/classes/sun/print/DialogOwner.java b/jdk/src/share/classes/sun/print/DialogOwner.java index 2551ed694a3..4704e0772c3 100644 --- a/jdk/src/share/classes/sun/print/DialogOwner.java +++ b/jdk/src/share/classes/sun/print/DialogOwner.java @@ -25,6 +25,7 @@ package sun.print; +import javax.print.attribute.Attribute; import javax.print.attribute.PrintRequestAttribute; import java.awt.Frame; @@ -72,7 +73,7 @@ public final class DialogOwner * @return Printing attribute class (category), an instance of class * {@link java.lang.Class java.lang.Class}. */ - public final Class getCategory() { + public final Class getCategory() { return DialogOwner.class; } diff --git a/jdk/src/share/classes/sun/print/PSPrinterJob.java b/jdk/src/share/classes/sun/print/PSPrinterJob.java index 325bfd8e718..09ae122d014 100644 --- a/jdk/src/share/classes/sun/print/PSPrinterJob.java +++ b/jdk/src/share/classes/sun/print/PSPrinterJob.java @@ -310,7 +310,7 @@ public class PSPrinterJob extends RasterPrinterJob { /** * A stack that represents the PostScript gstate stack. */ - ArrayList mGStateStack = new ArrayList(); + ArrayList mGStateStack = new ArrayList<>(); /** * The x coordinate of the current pen position. @@ -346,7 +346,7 @@ public class PSPrinterJob extends RasterPrinterJob { //enable priviledges so initProps can access system properties, // open the property file, etc. java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction() { public Object run() { mFontProps = initProps(); String osName = System.getProperty("os.name"); @@ -622,11 +622,11 @@ public class PSPrinterJob extends RasterPrinterJob { paperWidth + " "+ paperHeight+"]"); final PrintService pservice = getPrintService(); - Boolean isPS = (Boolean)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + Boolean isPS = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Boolean run() { try { - Class psClass = Class.forName("sun.print.IPPPrintService"); + Class psClass = Class.forName("sun.print.IPPPrintService"); if (psClass.isInstance(pservice)) { Method isPSMethod = psClass.getMethod("isPostscript", (Class[])null); @@ -660,11 +660,11 @@ public class PSPrinterJob extends RasterPrinterJob { // Inner class to run "privileged" to open the printer output stream. - private class PrinterOpener implements java.security.PrivilegedAction { + private class PrinterOpener implements java.security.PrivilegedAction { PrinterException pex; OutputStream result; - public Object run() { + public OutputStream run() { try { /* Write to a temporary file which will be spooled to @@ -687,7 +687,7 @@ public class PSPrinterJob extends RasterPrinterJob { // Inner class to run "privileged" to invoke the system print command - private class PrinterSpooler implements java.security.PrivilegedAction { + private class PrinterSpooler implements java.security.PrivilegedAction { PrinterException pex; private void handleProcessFailure(final Process failedProcess, @@ -753,7 +753,7 @@ public class PSPrinterJob extends RasterPrinterJob { mPSStream.close(); } java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction() { public Object run() { if (spoolFile != null && spoolFile.exists()) { @@ -812,7 +812,7 @@ public class PSPrinterJob extends RasterPrinterJob { * It will have the default PostScript gstate * attributes. */ - mGStateStack = new ArrayList(); + mGStateStack = new ArrayList<>(); mGStateStack.add(new GState()); mPSStream.println(PAGE_COMMENT + pageNumber + " " + pageNumber); @@ -825,13 +825,11 @@ public class PSPrinterJob extends RasterPrinterJob { paperWidth + " " + paperHeight + "]"); final PrintService pservice = getPrintService(); - Boolean isPS = - (Boolean)java.security.AccessController.doPrivileged( - - new java.security.PrivilegedAction() { - public Object run() { + Boolean isPS = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Boolean run() { try { - Class psClass = + Class psClass = Class.forName("sun.print.IPPPrintService"); if (psClass.isInstance(pservice)) { Method isPSMethod = @@ -1720,7 +1718,7 @@ public class PSPrinterJob extends RasterPrinterJob { */ private GState getGState() { int count = mGStateStack.size(); - return (GState) mGStateStack.get(count - 1); + return mGStateStack.get(count - 1); } /** diff --git a/jdk/src/share/classes/sun/print/PSStreamPrintJob.java b/jdk/src/share/classes/sun/print/PSStreamPrintJob.java index 7d1712d6f90..63118aa4841 100644 --- a/jdk/src/share/classes/sun/print/PSStreamPrintJob.java +++ b/jdk/src/share/classes/sun/print/PSStreamPrintJob.java @@ -66,9 +66,9 @@ import java.awt.print.*; public class PSStreamPrintJob implements CancelablePrintJob { - transient private Vector jobListeners; - transient private Vector attrListeners; - transient private Vector listenedAttributeSets; + transient private Vector jobListeners; + transient private Vector attrListeners; + transient private Vector listenedAttributeSets; private PSStreamPrintService service; private boolean fidelity; @@ -117,7 +117,7 @@ public class PSStreamPrintJob implements CancelablePrintJob { return; } if (jobListeners == null) { - jobListeners = new Vector(); + jobListeners = new Vector<>(); } jobListeners.add(listener); } @@ -191,7 +191,7 @@ public class PSStreamPrintJob implements CancelablePrintJob { PrintJobListener listener; PrintJobEvent event = new PrintJobEvent(this, reason); for (int i = 0; i < jobListeners.size(); i++) { - listener = (PrintJobListener)(jobListeners.elementAt(i)); + listener = jobListeners.elementAt(i); switch (reason) { case PrintJobEvent.JOB_CANCELED : @@ -230,8 +230,8 @@ public class PSStreamPrintJob implements CancelablePrintJob { return; } if (attrListeners == null) { - attrListeners = new Vector(); - listenedAttributeSets = new Vector(); + attrListeners = new Vector<>(); + listenedAttributeSets = new Vector<>(); } attrListeners.add(listener); if (attributes == null) { @@ -494,7 +494,7 @@ public class PSStreamPrintJob implements CancelablePrintJob { private void getAttributeValues(DocFlavor flavor) throws PrintException { Attribute attr; - Class category; + Class category; if (reqAttrSet.get(Fidelity.class) == Fidelity.FIDELITY_TRUE) { fidelity = true; diff --git a/jdk/src/share/classes/sun/print/PSStreamPrintService.java b/jdk/src/share/classes/sun/print/PSStreamPrintService.java index 92d27a026c1..3bfb7577e8e 100644 --- a/jdk/src/share/classes/sun/print/PSStreamPrintService.java +++ b/jdk/src/share/classes/sun/print/PSStreamPrintService.java @@ -62,7 +62,7 @@ import javax.print.attribute.standard.Sides; public class PSStreamPrintService extends StreamPrintService implements SunPrinterJobService { - private static final Class[] suppAttrCats = { + private static final Class[] suppAttrCats = { Chromaticity.class, Copies.class, Fidelity.class, @@ -108,7 +108,7 @@ public class PSStreamPrintService extends StreamPrintService return new PSStreamPrintJob(this); } - public boolean usesClass(Class c) { + public boolean usesClass(Class c) { return (c == sun.print.PSPrinterJob.class); } @@ -137,7 +137,9 @@ public class PSStreamPrintService extends StreamPrintService throw new IllegalArgumentException("Not a PrintServiceAttribute"); } if (category == ColorSupported.class) { - return (T)ColorSupported.SUPPORTED; + @SuppressWarnings("unchecked") + T tmp = (T)ColorSupported.SUPPORTED; + return tmp; } else { return null; } @@ -161,7 +163,7 @@ public class PSStreamPrintService extends StreamPrintService public Class[] getSupportedAttributeCategories() { - Class []cats = new Class[suppAttrCats.length]; + Class[] cats = new Class[suppAttrCats.length]; System.arraycopy(suppAttrCats, 0, cats, 0, cats.length); return cats; } @@ -401,7 +403,7 @@ public class PSStreamPrintService extends StreamPrintService throw new IllegalArgumentException(flavor + " is an unsupported flavor"); } - Class category = attr.getCategory(); + Class category = attr.getCategory(); if (!isAttributeCategorySupported(category)) { return false; } diff --git a/jdk/src/share/classes/sun/print/PrintJob2D.java b/jdk/src/share/classes/sun/print/PrintJob2D.java index ef5446dcd54..22f21fc34cd 100644 --- a/jdk/src/share/classes/sun/print/PrintJob2D.java +++ b/jdk/src/share/classes/sun/print/PrintJob2D.java @@ -1011,7 +1011,7 @@ public class PrintJob2D extends PrintJob implements Printable, Runnable { private String qid="noname"; - private ArrayList queue = new ArrayList(); + private ArrayList queue = new ArrayList<>(); MessageQ(String id) { qid = id; @@ -1055,7 +1055,7 @@ public class PrintJob2D extends PrintJob implements Printable, Runnable { while (g == null && queue != null) { if (queue.size() > 0) { - g = (Graphics2D) queue.remove(0); + g = queue.remove(0); notify(); } else { diff --git a/jdk/src/share/classes/sun/print/PrintJobAttributeException.java b/jdk/src/share/classes/sun/print/PrintJobAttributeException.java index 8919a1af1b8..d97be663517 100644 --- a/jdk/src/share/classes/sun/print/PrintJobAttributeException.java +++ b/jdk/src/share/classes/sun/print/PrintJobAttributeException.java @@ -34,19 +34,19 @@ class PrintJobAttributeException extends PrintException implements AttributeException { private Attribute attr; - private Class category; + private Class category; - PrintJobAttributeException(String s, Class cat, Attribute attrval) { + PrintJobAttributeException(String s, Class cat, Attribute attrval) { super(s); attr = attrval; category = cat; } - public Class[] getUnsupportedAttributes() { + public Class[] getUnsupportedAttributes() { if (category == null) { return null; } else { - Class [] cats = { category}; + Class[] cats = { category}; return cats; } } diff --git a/jdk/src/share/classes/sun/print/PrinterJobWrapper.java b/jdk/src/share/classes/sun/print/PrinterJobWrapper.java index 343da0baa77..69207bf2a23 100644 --- a/jdk/src/share/classes/sun/print/PrinterJobWrapper.java +++ b/jdk/src/share/classes/sun/print/PrinterJobWrapper.java @@ -26,6 +26,7 @@ package sun.print; import java.awt.print.PrinterJob; +import javax.print.attribute.Attribute; import javax.print.attribute.PrintRequestAttribute; public class PrinterJobWrapper implements PrintRequestAttribute { @@ -42,7 +43,7 @@ public class PrinterJobWrapper implements PrintRequestAttribute { return job; } - public final Class getCategory() { + public final Class getCategory() { return PrinterJobWrapper.class; } diff --git a/jdk/src/share/classes/sun/print/RasterPrinterJob.java b/jdk/src/share/classes/sun/print/RasterPrinterJob.java index dae42e789d9..f80970af362 100644 --- a/jdk/src/share/classes/sun/print/RasterPrinterJob.java +++ b/jdk/src/share/classes/sun/print/RasterPrinterJob.java @@ -273,7 +273,7 @@ public abstract class RasterPrinterJob extends PrinterJob { /** * List of areas & the graphics state for redrawing */ - private ArrayList redrawList = new ArrayList(); + private ArrayList redrawList = new ArrayList<>(); /* variables representing values extracted from an attribute set. @@ -712,10 +712,9 @@ public abstract class RasterPrinterJob extends PrinterJob { GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getDefaultConfiguration(); - PrintService service = - (PrintService)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + PrintService service = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public PrintService run() { PrintService service = getPrintService(); if (service == null) { ServiceDialog.showNoPrintService(gc); @@ -768,10 +767,9 @@ public abstract class RasterPrinterJob extends PrinterJob { int x = bounds.x+bounds.width/3; int y = bounds.y+bounds.height/3; - PrintService service = - (PrintService)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + PrintService service = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public PrintService run() { PrintService service = getPrintService(); if (service == null) { ServiceDialog.showNoPrintService(gc); @@ -793,7 +791,7 @@ public abstract class RasterPrinterJob extends PrinterJob { if (pageDialog.getStatus() == ServiceDialog.APPROVE) { PrintRequestAttributeSet newas = pageDialog.getAttributes(); - Class amCategory = SunAlternateMedia.class; + Class amCategory = SunAlternateMedia.class; if (attributes.containsKey(amCategory) && !newas.containsKey(amCategory)) { @@ -868,10 +866,9 @@ public abstract class RasterPrinterJob extends PrinterJob { GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getDefaultConfiguration(); - PrintService service = - (PrintService)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + PrintService service = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public PrintService run() { PrintService service = getPrintService(); if (service == null) { ServiceDialog.showNoPrintService(gc); @@ -894,10 +891,9 @@ public abstract class RasterPrinterJob extends PrinterJob { services[i] = spsFactories[i].getPrintService(null); } } else { - services = - (PrintService[])java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + services = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public PrintService[] run() { PrintService[] services = PrinterJob.lookupPrintServices(); return services; } @@ -2131,7 +2127,7 @@ public abstract class RasterPrinterJob extends PrinterJob { painter.print(pathGraphics, origPage, pageIndex); for (int i=0;i dstCategory = Destination.class; Destination dst = (Destination)asCurrent.get(dstCategory); if (dst == null) { @@ -463,7 +463,7 @@ public class ServiceDialog extends JDialog implements ActionListener { */ public static void initResource() { java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction() { public Object run() { try { messageRB = ResourceBundle.getBundle(strBundle); @@ -529,7 +529,7 @@ public class ServiceDialog extends JDialog implements ActionListener { /** * Returns the mnemonic as a KeyEvent.VK constant from the resource. */ - static Class _keyEventClazz = null; + static Class _keyEventClazz = null; private static int getVKMnemonic(String key) { String s = String.valueOf(getMnemonic(key)); if ( s == null || s.length() != 1) { @@ -554,9 +554,9 @@ public class ServiceDialog extends JDialog implements ActionListener { * Returns URL for image resource */ private static URL getImageResource(final String key) { - URL url = (URL)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + URL url = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public URL run() { URL url = ServiceDialog.class.getResource( "resources/" + key); return url; @@ -710,7 +710,7 @@ public class ServiceDialog extends JDialog implements ActionListener { private FilePermission printToFilePermission; private JButton btnProperties; private JCheckBox cbPrintToFile; - private JComboBox cbName; + private JComboBox cbName; private JLabel lblType, lblStatus, lblInfo; private ServiceUIFactory uiFactory; private boolean changedService = false; @@ -731,7 +731,7 @@ public class ServiceDialog extends JDialog implements ActionListener { for (int i = 0; i < psnames.length; i++) { psnames[i] = services[i].getName(); } - cbName = new JComboBox(psnames); + cbName = new JComboBox<>(psnames); cbName.setSelectedIndex(defaultServiceIndex); cbName.addItemListener(this); cbName.addPopupMenuListener(this); @@ -924,7 +924,7 @@ public class ServiceDialog extends JDialog implements ActionListener { } public void updateInfo() { - Class dstCategory = Destination.class; + Class dstCategory = Destination.class; boolean dstSupported = false; boolean dstSelected = false; boolean dstAllowed = filePermission ? @@ -1123,7 +1123,7 @@ public class ServiceDialog extends JDialog implements ActionListener { } public void updateInfo() { - Class prCategory = PageRanges.class; + Class prCategory = PageRanges.class; prSupported = false; if (psCurrent.isAttributeCategorySupported(prCategory) || @@ -1240,9 +1240,8 @@ public class ServiceDialog extends JDialog implements ActionListener { } public void updateInfo() { - Class cpCategory = Copies.class; - Class csCategory = CopiesSupported.class; - Class scCategory = SheetCollate.class; + Class cpCategory = Copies.class; + Class scCategory = SheetCollate.class; boolean cpSupported = false; scSupported = false; @@ -1525,7 +1524,7 @@ public class ServiceDialog extends JDialog implements ActionListener { float bm = bmTmpObj.floatValue(); /* adjust for orientation */ - Class orCategory = OrientationRequested.class; + Class orCategory = OrientationRequested.class; OrientationRequested or = (OrientationRequested)asCurrent.get(orCategory); @@ -1589,7 +1588,7 @@ public class ServiceDialog extends JDialog implements ActionListener { private MediaPrintableArea validateMargins(float lm, float rm, float tm, float bm) { - Class mpaCategory = MediaPrintableArea.class; + Class mpaCategory = MediaPrintableArea.class; MediaPrintableArea mpa; MediaPrintableArea mpaMax = null; MediaSize mediaSize = null; @@ -1671,7 +1670,7 @@ public class ServiceDialog extends JDialog implements ActionListener { return; } - Class mpaCategory = MediaPrintableArea.class; + Class mpaCategory = MediaPrintableArea.class; MediaPrintableArea mpa = (MediaPrintableArea)asCurrent.get(mpaCategory); MediaPrintableArea mpaMax = null; @@ -1845,7 +1844,7 @@ public class ServiceDialog extends JDialog implements ActionListener { * to the fields appropriate for the orientation. * Note: if orientation changes this method must be called. */ - Class orCategory = OrientationRequested.class; + Class orCategory = OrientationRequested.class; OrientationRequested or = (OrientationRequested)asCurrent.get(orCategory); @@ -1885,9 +1884,9 @@ public class ServiceDialog extends JDialog implements ActionListener { private final String strTitle = getMsg("border.media"); private JLabel lblSize, lblSource; - private JComboBox cbSize, cbSource; - private Vector sizes = new Vector(); - private Vector sources = new Vector(); + private JComboBox cbSize, cbSource; + private Vector sizes = new Vector<>(); + private Vector sources = new Vector<>(); private MarginsPanel pnlMargins = null; public MediaPanel() { @@ -1899,8 +1898,8 @@ public class ServiceDialog extends JDialog implements ActionListener { setLayout(gridbag); setBorder(BorderFactory.createTitledBorder(strTitle)); - cbSize = new JComboBox(); - cbSource = new JComboBox(); + cbSize = new JComboBox<>(); + cbSource = new JComboBox<>(); c.fill = GridBagConstraints.BOTH; c.insets = compInsets; @@ -1950,17 +1949,17 @@ public class ServiceDialog extends JDialog implements ActionListener { (cbSource.getSelectedIndex() >= 1)) { int src = cbSource.getSelectedIndex() - 1; - MediaTray mt = (MediaTray)sources.get(src); + MediaTray mt = sources.get(src); asCurrent.add(new SunAlternateMedia(mt)); } - asCurrent.add((MediaSizeName)sizes.get(index)); + asCurrent.add(sizes.get(index)); } } else if (source == cbSource) { int index = cbSource.getSelectedIndex(); if ((index >= 1) && (index < (sources.size() + 1))) { asCurrent.remove(SunAlternateMedia.class); - MediaTray newTray = (MediaTray)sources.get(index - 1); + MediaTray newTray = sources.get(index - 1); Media m = (Media)asCurrent.get(Media.class); if (m == null || m instanceof MediaTray) { asCurrent.add(newTray); @@ -1980,7 +1979,7 @@ public class ServiceDialog extends JDialog implements ActionListener { asCurrent.remove(SunAlternateMedia.class); if (cbSize.getItemCount() > 0) { int size = cbSize.getSelectedIndex(); - asCurrent.add((MediaSizeName)sizes.get(size)); + asCurrent.add(sizes.get(size)); } } } @@ -1997,8 +1996,8 @@ public class ServiceDialog extends JDialog implements ActionListener { pnlMargins = pnl; } public void updateInfo() { - Class mdCategory = Media.class; - Class amCategory = SunAlternateMedia.class; + Class mdCategory = Media.class; + Class amCategory = SunAlternateMedia.class; boolean mediaSupported = false; cbSize.removeItemListener(this); @@ -2025,10 +2024,10 @@ public class ServiceDialog extends JDialog implements ActionListener { Media medium = media[i]; if (medium instanceof MediaSizeName) { - sizes.add(medium); + sizes.add((MediaSizeName)medium); cbSize.addItem(getMediaName(medium.toString())); } else if (medium instanceof MediaTray) { - sources.add(medium); + sources.add((MediaTray)medium); cbSource.addItem(getMediaName(medium.toString())); } } @@ -2095,12 +2094,12 @@ public class ServiceDialog extends JDialog implements ActionListener { int selIndex = cbSize.getSelectedIndex(); if ((selIndex >= 0) && (selIndex < sizes.size())) { - asCurrent.add((MediaSizeName)sizes.get(selIndex)); + asCurrent.add(sizes.get(selIndex)); } selIndex = cbSource.getSelectedIndex(); if ((selIndex >= 1) && (selIndex < (sources.size()+1))) { - MediaTray mt = (MediaTray)sources.get(selIndex-1); + MediaTray mt = sources.get(selIndex-1); if (medium instanceof MediaTray) { asCurrent.add(mt); } else { @@ -2185,7 +2184,7 @@ public class ServiceDialog extends JDialog implements ActionListener { } public void updateInfo() { - Class orCategory = OrientationRequested.class; + Class orCategory = OrientationRequested.class; boolean pSupported = false; boolean lSupported = false; boolean rpSupported = false; @@ -2363,7 +2362,7 @@ public class ServiceDialog extends JDialog implements ActionListener { } public void updateInfo() { - Class chCategory = Chromaticity.class; + Class chCategory = Chromaticity.class; boolean monoSupported = false; boolean colorSupported = false; @@ -2458,7 +2457,7 @@ public class ServiceDialog extends JDialog implements ActionListener { } public void updateInfo() { - Class pqCategory = PrintQuality.class; + Class pqCategory = PrintQuality.class; boolean draftSupported = false; boolean normalSupported = false; boolean highSupported = false; @@ -2568,7 +2567,7 @@ public class ServiceDialog extends JDialog implements ActionListener { } public void updateInfo() { - Class sdCategory = Sides.class; + Class sdCategory = Sides.class; boolean osSupported = false; boolean tSupported = false; boolean dSupported = false; @@ -2725,10 +2724,10 @@ public class ServiceDialog extends JDialog implements ActionListener { public void focusGained(FocusEvent e) {} public void updateInfo() { - Class jsCategory = JobSheets.class; - Class jpCategory = JobPriority.class; - Class jnCategory = JobName.class; - Class unCategory = RequestingUserName.class; + Class jsCategory = JobSheets.class; + Class jpCategory = JobPriority.class; + Class jnCategory = JobName.class; + Class unCategory = RequestingUserName.class; boolean jsSupported = false; boolean jpSupported = false; boolean jnSupported = false; @@ -2817,9 +2816,9 @@ public class ServiceDialog extends JDialog implements ActionListener { { super(new FlowLayout(FlowLayout.LEADING)); final URL imgURL = getImageResource(img); - Icon icon = (Icon)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + Icon icon = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Icon run() { Icon icon = new ImageIcon(imgURL); return icon; } diff --git a/jdk/src/share/classes/sun/print/ServiceNotifier.java b/jdk/src/share/classes/sun/print/ServiceNotifier.java index 4fec7ee09e0..a6a6dbb6cdc 100644 --- a/jdk/src/share/classes/sun/print/ServiceNotifier.java +++ b/jdk/src/share/classes/sun/print/ServiceNotifier.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,14 +43,14 @@ import javax.print.event.PrintServiceAttributeListener; class ServiceNotifier extends Thread { private PrintService service; - private Vector listeners; + private Vector listeners; private boolean stop = false; private PrintServiceAttributeSet lastSet; ServiceNotifier(PrintService service) { super(service.getName() + " notifier"); this.service = service; - listeners = new Vector(); + listeners = new Vector<>(); try { setPriority(Thread.NORM_PRIORITY-1); setDaemon(true); @@ -128,8 +128,7 @@ class ServiceNotifier extends Thread { } if (psa != null && !psa.isEmpty()) { for (int i = 0; i < listeners.size() ; i++) { - listener = (PrintServiceAttributeListener) - listeners.elementAt(i); + listener = listeners.elementAt(i); attrs = new HashPrintServiceAttributeSet(psa); attrEvent = diff --git a/jdk/src/share/classes/sun/print/SunAlternateMedia.java b/jdk/src/share/classes/sun/print/SunAlternateMedia.java index 868af737969..a71104e33aa 100644 --- a/jdk/src/share/classes/sun/print/SunAlternateMedia.java +++ b/jdk/src/share/classes/sun/print/SunAlternateMedia.java @@ -25,6 +25,7 @@ package sun.print; +import javax.print.attribute.Attribute; import javax.print.attribute.PrintRequestAttribute; import javax.print.attribute.standard.Media; @@ -47,7 +48,7 @@ public class SunAlternateMedia implements PrintRequestAttribute { return media; } - public final Class getCategory() { + public final Class getCategory() { return SunAlternateMedia.class; } diff --git a/jdk/src/share/classes/sun/print/SunMinMaxPage.java b/jdk/src/share/classes/sun/print/SunMinMaxPage.java index 9381d29128e..24feefd76b2 100644 --- a/jdk/src/share/classes/sun/print/SunMinMaxPage.java +++ b/jdk/src/share/classes/sun/print/SunMinMaxPage.java @@ -25,6 +25,7 @@ package sun.print; +import javax.print.attribute.PrintRequestAttribute; import javax.print.attribute.PrintRequestAttribute; /* @@ -40,7 +41,7 @@ public final class SunMinMaxPage implements PrintRequestAttribute { } - public final Class getCategory() { + public final Class getCategory() { return SunMinMaxPage.class; } diff --git a/jdk/src/share/classes/sun/print/SunPageSelection.java b/jdk/src/share/classes/sun/print/SunPageSelection.java index b54d7ba55d2..7cfd54d9535 100644 --- a/jdk/src/share/classes/sun/print/SunPageSelection.java +++ b/jdk/src/share/classes/sun/print/SunPageSelection.java @@ -25,6 +25,7 @@ package sun.print; +import javax.print.attribute.Attribute; import javax.print.attribute.PrintRequestAttribute; /* @@ -43,7 +44,7 @@ public final class SunPageSelection implements PrintRequestAttribute { pages = value; } - public final Class getCategory() { + public final Class getCategory() { return SunPageSelection.class; } diff --git a/jdk/src/share/classes/sun/print/SunPrinterJobService.java b/jdk/src/share/classes/sun/print/SunPrinterJobService.java index af3d5027d23..6f7927ddef5 100644 --- a/jdk/src/share/classes/sun/print/SunPrinterJobService.java +++ b/jdk/src/share/classes/sun/print/SunPrinterJobService.java @@ -37,6 +37,6 @@ public interface SunPrinterJobService { * platform's built-in subclass of PrinterJob. * ie the same class as the caller. */ - public boolean usesClass(Class c); + public boolean usesClass(Class c); } diff --git a/jdk/src/solaris/classes/sun/print/CUPSPrinter.java b/jdk/src/solaris/classes/sun/print/CUPSPrinter.java index b70b398d5ee..a371f1aadd0 100644 --- a/jdk/src/solaris/classes/sun/print/CUPSPrinter.java +++ b/jdk/src/solaris/classes/sun/print/CUPSPrinter.java @@ -246,9 +246,9 @@ public class CUPSPrinter { IPPPrintService.getIPPConnection(url); if (urlConnection != null) { - OutputStream os = (OutputStream)java.security.AccessController. - doPrivileged(new java.security.PrivilegedAction() { - public Object run() { + OutputStream os = java.security.AccessController. + doPrivileged(new java.security.PrivilegedAction() { + public OutputStream run() { try { return urlConnection.getOutputStream(); } catch (Exception e) { @@ -274,10 +274,10 @@ public class CUPSPrinter { IPPPrintService.OP_CUPS_GET_DEFAULT, attCl)) { - HashMap defaultMap = null; + HashMap defaultMap = null; String[] printerInfo = new String[2]; InputStream is = urlConnection.getInputStream(); - HashMap[] responseMap = IPPPrintService.readIPPResponse( + HashMap[] responseMap = IPPPrintService.readIPPResponse( is); is.close(); @@ -309,13 +309,11 @@ public class CUPSPrinter { } - AttributeClass attribClass = (AttributeClass) - defaultMap.get("printer-name"); + AttributeClass attribClass = defaultMap.get("printer-name"); if (attribClass != null) { printerInfo[0] = attribClass.getStringValue(); - attribClass = (AttributeClass) - defaultMap.get("printer-uri-supported"); + attribClass = defaultMap.get("printer-uri-supported"); IPPPrintService.debug_println(debugPrefix+ "printer-uri-supported="+attribClass); if (attribClass != null) { @@ -348,9 +346,9 @@ public class CUPSPrinter { IPPPrintService.getIPPConnection(url); if (urlConnection != null) { - OutputStream os = (OutputStream)java.security.AccessController. - doPrivileged(new java.security.PrivilegedAction() { - public Object run() { + OutputStream os = java.security.AccessController. + doPrivileged(new java.security.PrivilegedAction() { + public OutputStream run() { try { return urlConnection.getOutputStream(); } catch (Exception e) { @@ -375,7 +373,7 @@ public class CUPSPrinter { IPPPrintService.OP_CUPS_GET_PRINTERS, attCl)) { InputStream is = urlConnection.getInputStream(); - HashMap[] responseMap = + HashMap[] responseMap = IPPPrintService.readIPPResponse(is); is.close(); @@ -386,9 +384,9 @@ public class CUPSPrinter { return null; } - ArrayList printerNames = new ArrayList(); + ArrayList printerNames = new ArrayList<>(); for (int i=0; i< responseMap.length; i++) { - AttributeClass attribClass = (AttributeClass) + AttributeClass attribClass = responseMap[i].get("printer-uri-supported"); if (attribClass != null) { @@ -396,7 +394,7 @@ public class CUPSPrinter { printerNames.add(nameStr); } } - return (String[])printerNames.toArray(new String[] {}); + return printerNames.toArray(new String[] {}); } else { os.close(); urlConnection.disconnect(); diff --git a/jdk/src/solaris/classes/sun/print/IPPPrintService.java b/jdk/src/solaris/classes/sun/print/IPPPrintService.java index 2134c71321e..47398220ccc 100644 --- a/jdk/src/solaris/classes/sun/print/IPPPrintService.java +++ b/jdk/src/solaris/classes/sun/print/IPPPrintService.java @@ -91,7 +91,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { private CUPSPrinter cps; private HttpURLConnection urlConnection = null; private DocFlavor[] supportedDocFlavors; - private Class[] supportedCats; + private Class[] supportedCats; private MediaTray[] mediaTrays; private MediaSizeName[] mediaSizeNames; private CustomMediaSizeName[] customMediaSizeNames; @@ -99,7 +99,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { private boolean isCupsPrinter; private boolean init; private Boolean isPS; - private HashMap getAttMap; + private HashMap getAttMap; private boolean pngImagesAdded = false; private boolean gifImagesAdded = false; private boolean jpgImagesAdded = false; @@ -424,8 +424,8 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { // use IPP to get all media, Media[] allMedia = getSupportedMedia(); - ArrayList sizeList = new ArrayList(); - ArrayList trayList = new ArrayList(); + ArrayList sizeList = new ArrayList<>(); + ArrayList trayList = new ArrayList<>(); for (int i=0; i docList = new HashSet<>(); int j; String hostEnc = DocFlavor.hostEncoding. toLowerCase(Locale.ENGLISH); @@ -970,8 +968,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { if ((getAttMap != null) && getAttMap.containsKey("media-supported")) { - AttributeClass attribClass = - (AttributeClass)getAttMap.get("media-supported"); + AttributeClass attribClass = getAttMap.get("media-supported"); if (attribClass != null) { String[] mediaVals = attribClass.getArrayOfStringValues(); @@ -990,23 +987,21 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { } - public synchronized Class[] getSupportedAttributeCategories() { + public synchronized Class[] getSupportedAttributeCategories() { if (supportedCats != null) { return supportedCats; } initAttributes(); - ArrayList catList = new ArrayList(); - Class cl; + ArrayList> catList = new ArrayList<>(); for (int i=0; i < printReqAttribDefault.length; i++) { PrintRequestAttribute pra = (PrintRequestAttribute)printReqAttribDefault[i]; if (getAttMap != null && getAttMap.containsKey(pra.getName()+"-supported")) { - cl = pra.getCategory(); - catList.add(cl); + catList.add(pra.getCategory()); } } @@ -1047,7 +1042,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { if (getAttMap != null && getAttMap.containsKey("color-supported")) { catList.add(Chromaticity.class); } - supportedCats = new Class[catList.size()]; + supportedCats = new Class[catList.size()]; catList.toArray(supportedCats); return supportedCats; } @@ -1085,7 +1080,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { return false; } - + @SuppressWarnings("unchecked") public synchronized T getAttribute(Class category) { @@ -1103,7 +1098,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { } else if (category == PrinterInfo.class) { PrinterInfo pInfo = new PrinterInfo(printer, null); AttributeClass ac = (getAttMap != null) ? - (AttributeClass)getAttMap.get(pInfo.getName()) + getAttMap.get(pInfo.getName()) : null; if (ac != null) { return (T)(new PrinterInfo(ac.getStringValue(), null)); @@ -1112,7 +1107,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { } else if (category == QueuedJobCount.class) { QueuedJobCount qjc = new QueuedJobCount(0); AttributeClass ac = (getAttMap != null) ? - (AttributeClass)getAttMap.get(qjc.getName()) + getAttMap.get(qjc.getName()) : null; if (ac != null) { qjc = new QueuedJobCount(ac.getIntValue()); @@ -1122,7 +1117,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { PrinterIsAcceptingJobs accJob = PrinterIsAcceptingJobs.ACCEPTING_JOBS; AttributeClass ac = (getAttMap != null) ? - (AttributeClass)getAttMap.get(accJob.getName()) + getAttMap.get(accJob.getName()) : null; if ((ac != null) && (ac.getByteValue() == 0)) { accJob = PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS; @@ -1131,7 +1126,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { } else if (category == ColorSupported.class) { ColorSupported cs = ColorSupported.SUPPORTED; AttributeClass ac = (getAttMap != null) ? - (AttributeClass)getAttMap.get(cs.getName()) + getAttMap.get(cs.getName()) : null; if ((ac != null) && (ac.getByteValue() == 0)) { cs = ColorSupported.NOT_SUPPORTED; @@ -1165,7 +1160,8 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { for (int i=0; i < serviceAttributes.length; i++) { String name = (String)serviceAttributes[i][1]; if (getAttMap != null && getAttMap.containsKey(name)) { - Class c = (Class)serviceAttributes[i][0]; + @SuppressWarnings("unchecked") + Class c = (Class)serviceAttributes[i][0]; PrintServiceAttribute psa = getAttribute(c); if (psa != null) { attrs.add(psa); @@ -1279,7 +1275,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { return false; } } - Class category = attr.getCategory(); + Class category = attr.getCategory(); if (!isAttributeCategorySupported(category)) { return false; } @@ -1397,7 +1393,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { } String attribName = catName+"-default"; AttributeClass attribClass = (getAttMap != null) ? - (AttributeClass)getAttMap.get(attribName) : null; + getAttMap.get(attribName) : null; if (category == Copies.class) { if (attribClass != null) { @@ -1600,7 +1596,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { } - public boolean usesClass(Class c) { + public boolean usesClass(Class c) { return (c == sun.print.PSPrinterJob.class); } @@ -1675,9 +1671,9 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { AttributeClass.TAG_URI, ""+myURI)}; - OutputStream os = (OutputStream)java.security.AccessController. - doPrivileged(new java.security.PrivilegedAction() { - public Object run() { + OutputStream os = java.security.AccessController. + doPrivileged(new java.security.PrivilegedAction() { + public OutputStream run() { try { return urlConnection.getOutputStream(); } catch (Exception e) { @@ -1696,7 +1692,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { if (success) { InputStream is = null; if ((is = urlConnection.getInputStream())!=null) { - HashMap[] responseMap = readIPPResponse(is); + HashMap[] responseMap = readIPPResponse(is); if (responseMap != null && responseMap.length > 0) { getAttMap = responseMap[0]; @@ -1771,7 +1767,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { } - public static HashMap[] readIPPResponse(InputStream inputStream) { + public static HashMap[] readIPPResponse(InputStream inputStream) { if (inputStream == null) { return null; @@ -1792,8 +1788,8 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { String attribStr = null; // assign default value byte valTagByte = AttributeClass.TAG_KEYWORD; - ArrayList respList = new ArrayList(); - HashMap responseMap = new HashMap(); + ArrayList> respList = new ArrayList<>(); + HashMap responseMap = new HashMap<>(); response[0] = ois.readByte(); @@ -1829,7 +1825,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { // if key exists, new HashMap if (responseMap.containsKey(attribStr)) { respList.add(responseMap); - responseMap = new HashMap(); + responseMap = new HashMap<>(); } // exclude those that are unknown @@ -1885,7 +1881,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { if ((counter != 0) && responseMap.containsKey(attribStr)) { respList.add(responseMap); - responseMap = new HashMap(); + responseMap = new HashMap<>(); } byte outArray[] = outObj.toByteArray(); @@ -1901,8 +1897,10 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { if ((responseMap != null) && (responseMap.size() > 0)) { respList.add(responseMap); } - return (HashMap[])respList.toArray( - new HashMap[respList.size()]); + @SuppressWarnings({"unchecked", "rawtypes"}) + HashMap[] tmp = + respList.toArray((HashMap[])new HashMap[respList.size()]); + return tmp; } else { debug_println(debugPrefix+ "readIPPResponse client error, IPP status code: 0x"+ diff --git a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java index 366a62f0e49..496dfb7abeb 100644 --- a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java +++ b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java @@ -90,9 +90,9 @@ import java.awt.print.*; public class UnixPrintJob implements CancelablePrintJob { private static String debugPrefix = "UnixPrintJob>> "; - transient private Vector jobListeners; - transient private Vector attrListeners; - transient private Vector listenedAttributeSets; + transient private Vector jobListeners; + transient private Vector attrListeners; + transient private Vector listenedAttributeSets; private PrintService service; private boolean fidelity; @@ -150,7 +150,7 @@ public class UnixPrintJob implements CancelablePrintJob { return; } if (jobListeners == null) { - jobListeners = new Vector(); + jobListeners = new Vector<>(); } jobListeners.add(listener); } @@ -238,7 +238,7 @@ public class UnixPrintJob implements CancelablePrintJob { PrintJobListener listener; PrintJobEvent event = new PrintJobEvent(this, reason); for (int i = 0; i < jobListeners.size(); i++) { - listener = (PrintJobListener)(jobListeners.elementAt(i)); + listener = jobListeners.elementAt(i); switch (reason) { case PrintJobEvent.JOB_CANCELED : @@ -273,8 +273,8 @@ public class UnixPrintJob implements CancelablePrintJob { return; } if (attrListeners == null) { - attrListeners = new Vector(); - listenedAttributeSets = new Vector(); + attrListeners = new Vector<>(); + listenedAttributeSets = new Vector<>(); } attrListeners.add(listener); if (attributes == null) { @@ -770,7 +770,7 @@ public class UnixPrintJob implements CancelablePrintJob { private void getAttributeValues(DocFlavor flavor) throws PrintException { Attribute attr; - Class category; + Class category; if (reqAttrSet.get(Fidelity.class) == Fidelity.FIDELITY_TRUE) { fidelity = true; @@ -941,11 +941,11 @@ public class UnixPrintJob implements CancelablePrintJob { // Inner class to run "privileged" to open the printer output stream. - private class PrinterOpener implements java.security.PrivilegedAction { + private class PrinterOpener implements java.security.PrivilegedAction { PrintException pex; OutputStream result; - public Object run() { + public OutputStream run() { try { if (mDestType == UnixPrintJob.DESTFILE) { spoolFile = new File(mDestination); @@ -971,7 +971,7 @@ public class UnixPrintJob implements CancelablePrintJob { // Inner class to run "privileged" to invoke the system print command - private class PrinterSpooler implements java.security.PrivilegedAction { + private class PrinterSpooler implements java.security.PrivilegedAction { PrintException pex; private void handleProcessFailure(final Process failedProcess, diff --git a/jdk/src/solaris/classes/sun/print/UnixPrintService.java b/jdk/src/solaris/classes/sun/print/UnixPrintService.java index bb9a6dfce58..ac60fa7ec38 100644 --- a/jdk/src/solaris/classes/sun/print/UnixPrintService.java +++ b/jdk/src/solaris/classes/sun/print/UnixPrintService.java @@ -148,7 +148,7 @@ public class UnixPrintService implements PrintService, AttributeUpdater, } /* let's try to support a few of these */ - private static final Class[] serviceAttrCats = { + private static final Class[] serviceAttrCats = { PrinterName.class, PrinterIsAcceptingJobs.class, QueuedJobCount.class, @@ -157,7 +157,7 @@ public class UnixPrintService implements PrintService, AttributeUpdater, /* it turns out to be inconvenient to store the other categories * separately because many attributes are in multiple categories. */ - private static final Class[] otherAttrCats = { + private static final Class[] otherAttrCats = { Chromaticity.class, Copies.class, Destination.class, @@ -278,7 +278,7 @@ public class UnixPrintService implements PrintService, AttributeUpdater, // and extra lines which have been added for remote printers. // 'protected' because this method is also used from UnixPrintServiceLookup. protected static String[] filterPrinterNamesAIX(String[] posPrinters) { - ArrayList printers = new ArrayList(); + ArrayList printers = new ArrayList<>(); String [] splitPart; for(int i = 0; i < posPrinters.length; i++) { @@ -295,7 +295,7 @@ public class UnixPrintService implements PrintService, AttributeUpdater, } } - return (String[])printers.toArray(new String[printers.size()]); + return printers.toArray(new String[printers.size()]); } private PrinterIsAcceptingJobs getPrinterIsAcceptingJobsAIX() { @@ -533,6 +533,7 @@ public class UnixPrintService implements PrintService, AttributeUpdater, } } + @SuppressWarnings("unchecked") public T getAttribute(Class category) { @@ -617,9 +618,9 @@ public class UnixPrintService implements PrintService, AttributeUpdater, return false; } - public Class[] getSupportedAttributeCategories() { + public Class[] getSupportedAttributeCategories() { int totalCats = otherAttrCats.length; - Class [] cats = new Class[totalCats]; + Class[] cats = new Class[totalCats]; System.arraycopy(otherAttrCats, 0, cats, 0, otherAttrCats.length); return cats; } @@ -967,7 +968,7 @@ public class UnixPrintService implements PrintService, AttributeUpdater, return false; } } - Class category = attr.getCategory(); + Class category = attr.getCategory(); if (!isAttributeCategorySupported(category)) { return false; } @@ -1078,7 +1079,7 @@ public class UnixPrintService implements PrintService, AttributeUpdater, return this.getClass().hashCode()+getName().hashCode(); } - public boolean usesClass(Class c) { + public boolean usesClass(Class c) { return (c == sun.print.PSPrinterJob.class); } diff --git a/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java b/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java index 7abed34489d..25b9da12842 100644 --- a/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java +++ b/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java @@ -69,7 +69,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup private String defaultPrinter; private PrintService defaultPrintService; private PrintService[] printServices; /* includes the default printer */ - private Vector lookupListeners = null; + private Vector lookupListeners = null; private static String debugPrefix = "UnixPrintServiceLookup>> "; private static boolean pollServices = true; private static final int DEFAULT_MINREFRESH = 120; // 2 minutes @@ -239,7 +239,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup } } - private int addPrintServiceToList(ArrayList printerList, PrintService ps) { + private int addPrintServiceToList(ArrayList printerList, PrintService ps) { int index = printerList.indexOf(ps); // Check if PrintService with same name is already in the list. if (CUPSPrinter.isCupsRunning() && index != -1) { @@ -253,7 +253,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup IPPPrintService.debug_println(debugPrefix+"duplicate PrintService, ignoring the new local printer: "+ps); return index; // Do not add this. } - PrintService oldPS = (PrintService)(printerList.get(index)); + PrintService oldPS = printerList.get(index); uri = oldPS.getAttribute(PrinterURI.class); if (uri.getURI().getHost().equals("localhost")) { IPPPrintService.debug_println(debugPrefix+"duplicate PrintService, removing existing local printer: "+oldPS); @@ -319,7 +319,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup return; } - ArrayList printerList = new ArrayList(); + ArrayList printerList = new ArrayList<>(); int defaultIndex = -1; for (int p=0; p 0) { @@ -411,9 +410,9 @@ public class UnixPrintServiceLookup extends PrintServiceLookup PrintServiceAttributeSet attributes) { Attribute [] attrs = attributes.toArray(); - Attribute serviceAttr; for (int i=0; i)attrs[i].getCategory()); if (serviceAttr == null || !serviceAttr.equals(attrs[i])) { return false; @@ -542,7 +541,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup } } else { /* specified service attributes don't include a name.*/ - Vector matchedServices = new Vector(); + Vector matchedServices = new Vector<>(); services = getPrintServices(); for (int i = 0; i< services.length; i++) { if (matchesAttributes(services[i], serviceSet)) { @@ -551,7 +550,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup } services = new PrintService[matchedServices.size()]; for (int i = 0; i< services.length; i++) { - services[i] = (PrintService)matchedServices.elementAt(i); + services[i] = matchedServices.elementAt(i); } return services; } @@ -591,7 +590,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup } if (CUPSPrinter.isCupsRunning()) { - ArrayList matchingServices = new ArrayList(); + ArrayList matchingServices = new ArrayList<>(); for (int i=0; i(); lookupListeners.add(listener); Thread lookupThread = new Thread(this); lookupThread.start(); @@ -733,8 +732,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup synchronized (this) { BackgroundLookupListener listener; for (int i=0; i printerNames = new ArrayList<>(); for (int i=0; i < names.length; i++) { if (!names[i].equals("_default") && !names[i].equals(defaultPrinter) && @@ -828,7 +826,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup printerNames.add(names[i]); } } - return (String[])printerNames.toArray(new String[printerNames.size()]); + return printerNames.toArray(new String[printerNames.size()]); } private String getDefaultPrinterNameAIX() { @@ -870,7 +868,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup } static String[] execCmd(final String command) { - ArrayList results = null; + ArrayList results = null; try { final String[] cmd = new String[3]; if (isSysV() || isAIX()) { @@ -883,9 +881,9 @@ public class UnixPrintServiceLookup extends PrintServiceLookup cmd[2] = "LC_ALL=C " + command; } - results = (ArrayList)AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public Object run() throws IOException { + results = AccessController.doPrivileged( + new PrivilegedExceptionAction>() { + public ArrayList run() throws IOException { Process proc; BufferedReader bufferedReader = null; @@ -907,7 +905,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup FileReader reader = new FileReader(f); bufferedReader = new BufferedReader(reader); String line; - ArrayList results = new ArrayList(); + ArrayList results = new ArrayList<>(); while ((line = bufferedReader.readLine()) != null) { results.add(line); @@ -932,7 +930,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup if (results == null) { return new String[0]; } else { - return (String[])results.toArray(new String[results.size()]); + return results.toArray(new String[results.size()]); } } diff --git a/jdk/src/windows/classes/sun/print/Win32MediaTray.java b/jdk/src/windows/classes/sun/print/Win32MediaTray.java index eed18007353..79198ec4655 100644 --- a/jdk/src/windows/classes/sun/print/Win32MediaTray.java +++ b/jdk/src/windows/classes/sun/print/Win32MediaTray.java @@ -50,8 +50,8 @@ public class Win32MediaTray extends MediaTray { static final Win32MediaTray FORMSOURCE = new Win32MediaTray(5, 15); //DMBIN_FORMSOURCE - private static ArrayList winStringTable = new ArrayList(); - private static ArrayList winEnumTable = new ArrayList(); + private static ArrayList winStringTable = new ArrayList<>(); + private static ArrayList winEnumTable = new ArrayList<>(); public int winID; private Win32MediaTray(int value, int id) { @@ -97,22 +97,22 @@ public class Win32MediaTray extends MediaTray { } protected String[] getStringTable() { - ArrayList completeList = new ArrayList(); + ArrayList completeList = new ArrayList<>(); for (int i=0; i < myStringTable.length; i++) { completeList.add(myStringTable[i]); } completeList.addAll(winStringTable); String[] nameTable = new String[completeList.size()]; - return (String[])completeList.toArray(nameTable); + return completeList.toArray(nameTable); } protected EnumSyntax[] getEnumValueTable() { - ArrayList completeList = new ArrayList(); + ArrayList completeList = new ArrayList<>(); for (int i=0; i < myEnumValueTable.length; i++) { completeList.add(myEnumValueTable[i]); } completeList.addAll(winEnumTable); MediaTray[] enumTable = new MediaTray[completeList.size()]; - return (MediaTray[])completeList.toArray(enumTable); + return completeList.toArray(enumTable); } } diff --git a/jdk/src/windows/classes/sun/print/Win32PrintJob.java b/jdk/src/windows/classes/sun/print/Win32PrintJob.java index 570d23a91d2..df8b9923a5e 100644 --- a/jdk/src/windows/classes/sun/print/Win32PrintJob.java +++ b/jdk/src/windows/classes/sun/print/Win32PrintJob.java @@ -79,9 +79,9 @@ import java.awt.print.*; public class Win32PrintJob implements CancelablePrintJob { - transient private Vector jobListeners; - transient private Vector attrListeners; - transient private Vector listenedAttributeSets; + transient private Vector jobListeners; + transient private Vector attrListeners; + transient private Vector listenedAttributeSets; private Win32PrintService service; private boolean fidelity; @@ -139,7 +139,7 @@ public class Win32PrintJob implements CancelablePrintJob { return; } if (jobListeners == null) { - jobListeners = new Vector(); + jobListeners = new Vector<>(); } jobListeners.add(listener); } @@ -227,7 +227,7 @@ public class Win32PrintJob implements CancelablePrintJob { PrintJobListener listener; PrintJobEvent event = new PrintJobEvent(this, reason); for (int i = 0; i < jobListeners.size(); i++) { - listener = (PrintJobListener)(jobListeners.elementAt(i)); + listener = jobListeners.elementAt(i); switch (reason) { case PrintJobEvent.JOB_COMPLETE : @@ -266,8 +266,8 @@ public class Win32PrintJob implements CancelablePrintJob { return; } if (attrListeners == null) { - attrListeners = new Vector(); - listenedAttributeSets = new Vector(); + attrListeners = new Vector<>(); + listenedAttributeSets = new Vector<>(); } attrListeners.add(listener); if (attributes == null) { @@ -670,7 +670,7 @@ public class Win32PrintJob implements CancelablePrintJob { fidelity = false; } - Class category; + Class category; Attribute [] attrs = reqAttrSet.toArray(); for (int i=0; i[] serviceAttrCats = { PrinterName.class, PrinterIsAcceptingJobs.class, QueuedJobCount.class, @@ -107,7 +107,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, /* it turns out to be inconvenient to store the other categories * separately because many attributes are in multiple categories. */ - private static Class[] otherAttrCats = { + private static Class[] otherAttrCats = { JobName.class, RequestingUserName.class, Copies.class, @@ -202,7 +202,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, private MediaPrintableArea[] mediaPrintables; private MediaTray[] mediaTrays; private PrinterResolution[] printRes; - private HashMap mpaMap; + private HashMap mpaMap; private int nCopies; private int prnCaps; private int[] defaultSettings; @@ -212,7 +212,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, private boolean mediaInitialized; private boolean mpaListInitialized; - private ArrayList idList; + private ArrayList idList; private MediaSize[] mediaSizes; private boolean isInvalid; @@ -279,7 +279,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, (idList.size() == mediaSizes.length)) { for (int i=0; i< idList.size(); i++) { if (mediaSizes[i].getMediaSizeName() == msn) { - return ((Integer)idList.get(i)).intValue(); + return idList.get(i).intValue(); } } } @@ -338,10 +338,11 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } } - private boolean addToUniqueList(ArrayList msnList, MediaSizeName mediaName) { + private boolean addToUniqueList(ArrayList msnList, + MediaSizeName mediaName) { MediaSizeName msn; for (int i=0; i< msnList.size(); i++) { - msn = (MediaSizeName)msnList.get(i); + msn = msnList.get(i); if (msn == mediaName) { return false; } @@ -360,9 +361,8 @@ public class Win32PrintService implements PrintService, AttributeUpdater, return; } - ArrayList msnList = new ArrayList(); + ArrayList msnList = new ArrayList<>(); ArrayList trailingWmsList = new ArrayList(); - ArrayList printableList = new ArrayList(); MediaSizeName mediaName; boolean added; boolean queryFailure = false; @@ -375,7 +375,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, // We remove from ID list any invalid mediaSize. Though this is rare, // it happens in HP 4050 German driver. - idList = new ArrayList(); + idList = new ArrayList<>(); for (int i=0; i < media.length; i++) { idList.add(Integer.valueOf(media[i])); } @@ -385,7 +385,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, for (int i = 0; i < idList.size(); i++) { // match Win ID with our predefined ID using table - mediaName = findWin32Media(((Integer)idList.get(i)).intValue()); + mediaName = findWin32Media(idList.get(i).intValue()); // Verify that this standard size is the same size as that // reported by the driver. This should be the case except when // the driver is mis-using a standard windows paper ID. @@ -420,7 +420,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, */ Win32MediaSize wms = Win32MediaSize.findMediaName(dmPaperNameList.get(i)); if ((wms == null) && (idList.size() == mediaSizes.length)) { - wms = new Win32MediaSize(dmPaperNameList.get(i), (Integer)idList.get(i)); + wms = new Win32MediaSize(dmPaperNameList.get(i), idList.get(i)); mediaSizes[i] = new MediaSize(mediaSizes[i].getX(MediaSize.MM), mediaSizes[i].getY(MediaSize.MM), MediaSize.MM, wms); } @@ -458,7 +458,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, // get from cached mapping of MPAs if (mpaMap != null && (mpaMap.get(msn) != null)) { MediaPrintableArea[] mpaArr = new MediaPrintableArea[1]; - mpaArr[0] = (MediaPrintableArea)mpaMap.get(msn); + mpaArr[0] = mpaMap.get(msn); return mpaArr; } } @@ -478,7 +478,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } if (mpaMap == null) { - mpaMap = new HashMap(); + mpaMap = new HashMap<>(); } for (int i=0; i < loopNames.length; i++) { @@ -532,10 +532,10 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } MediaPrintableArea[] mpaArr = new MediaPrintableArea[1]; // by this time, we've already gotten the desired MPA - mpaArr[0] = (MediaPrintableArea)mpaMap.get(msn); + mpaArr[0] = mpaMap.get(msn); return mpaArr; } else { - mediaPrintables = (MediaPrintableArea[])mpaMap.values().toArray(new MediaPrintableArea[0]); + mediaPrintables = mpaMap.values().toArray(new MediaPrintableArea[0]); mpaListInitialized = true; return mediaPrintables; } @@ -624,7 +624,8 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } - private MediaSize[] getMediaSizes(ArrayList idList, int[] media, ArrayList dmPaperNameList) { + private MediaSize[] getMediaSizes(ArrayList idList, int[] media, + ArrayList dmPaperNameList) { if (dmPaperNameList == null) { dmPaperNameList = new ArrayList(); } @@ -641,7 +642,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } int nMedia = mediaSz.length/2; - ArrayList msList = new ArrayList(); + ArrayList msList = new ArrayList<>(); for (int i = 0; i < nMedia; i++, ms=null) { wid = mediaSz[i*2]/10f; @@ -814,7 +815,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } else { int nRes = prnRes.length/2; - ArrayList arrList = new ArrayList(); + ArrayList arrList = new ArrayList<>(); PrinterResolution pr; for (int i=0; i T getAttribute(Class category) { @@ -1009,7 +1010,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } public Class[] getSupportedAttributeCategories() { - ArrayList categList = new ArrayList(otherAttrCats.length+3); + ArrayList> categList = new ArrayList<>(otherAttrCats.length+3); for (int i=0; i < otherAttrCats.length; i++) { categList.add(otherAttrCats[i]); } @@ -1033,7 +1034,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, categList.add(PrinterResolution.class); } - return (Class[])categList.toArray(new Class[categList.size()]); + return categList.toArray(new Class[categList.size()]); } public boolean @@ -1049,7 +1050,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, " is not an Attribute"); } - Class[] classList = getSupportedAttributeCategories(); + Class[] classList = getSupportedAttributeCategories(); for (int i = 0; i < classList.length; i++) { if (category.equals(classList[i])) { return true; @@ -1234,7 +1235,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } } - private boolean isPSDocAttr(Class category) { + private boolean isPSDocAttr(Class category) { if (category == OrientationRequested.class || category == Copies.class) { return true; } @@ -1475,7 +1476,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, if (attr == null) { throw new NullPointerException("null attribute"); } - Class category = attr.getCategory(); + Class category = attr.getCategory(); if (flavor != null) { if (!isDocFlavorSupported(flavor)) { throw new IllegalArgumentException(flavor + @@ -1700,7 +1701,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, return this.getClass().hashCode()+getName().hashCode(); } - public boolean usesClass(Class c) { + public boolean usesClass(Class c) { return (c == sun.awt.windows.WPrinterJob.class); } @@ -1722,8 +1723,8 @@ public class Win32PrintService implements PrintService, AttributeUpdater, @SuppressWarnings("serial") // JDK implementation class class Win32MediaSize extends MediaSizeName { - private static ArrayList winStringTable = new ArrayList(); - private static ArrayList winEnumTable = new ArrayList(); + private static ArrayList winStringTable = new ArrayList<>(); + private static ArrayList winEnumTable = new ArrayList<>(); private static MediaSize[] predefMedia; private int dmPaperID; // driver ID for this paper. @@ -1741,7 +1742,7 @@ class Win32MediaSize extends MediaSizeName { public static synchronized Win32MediaSize findMediaName(String name) { int nameIndex = winStringTable.indexOf(name); if (nameIndex != -1) { - return (Win32MediaSize)winEnumTable.get(nameIndex); + return winEnumTable.get(nameIndex); } return null; } @@ -1783,12 +1784,12 @@ class Win32MediaSize extends MediaSizeName { protected String[] getStringTable() { String[] nameTable = new String[winStringTable.size()]; - return (String[])winStringTable.toArray(nameTable); + return winStringTable.toArray(nameTable); } protected EnumSyntax[] getEnumValueTable() { MediaSizeName[] enumTable = new MediaSizeName[winEnumTable.size()]; - return (MediaSizeName[])winEnumTable.toArray(enumTable); + return winEnumTable.toArray(enumTable); } } diff --git a/jdk/src/windows/classes/sun/print/Win32PrintServiceLookup.java b/jdk/src/windows/classes/sun/print/Win32PrintServiceLookup.java index 06d4b0840dd..5a386d7f2ef 100644 --- a/jdk/src/windows/classes/sun/print/Win32PrintServiceLookup.java +++ b/jdk/src/windows/classes/sun/print/Win32PrintServiceLookup.java @@ -183,6 +183,7 @@ public class Win32PrintServiceLookup extends PrintServiceLookup { } } + @SuppressWarnings("unchecked") // Cast to Class boolean matchingService(PrintService service, PrintServiceAttributeSet serviceSet) { if (serviceSet != null) { @@ -246,7 +247,7 @@ public class Win32PrintServiceLookup extends PrintServiceLookup { if (services.length == 0) { return services; } else { - ArrayList matchingServices = new ArrayList(); + ArrayList matchingServices = new ArrayList<>(); for (int i=0; i Date: Mon, 9 Jun 2014 16:24:47 -0700 Subject: [PATCH 062/192] 8046271: Fix overrides lint warnings in Apple laf code Reviewed-by: alanb, prr --- .../macosx/classes/com/apple/laf/AquaFileSystemModel.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaFileSystemModel.java b/jdk/src/macosx/classes/com/apple/laf/AquaFileSystemModel.java index 37e627e8338..b0713215077 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaFileSystemModel.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaFileSystemModel.java @@ -366,6 +366,11 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi final SortableFile otherFile = (SortableFile)other; return otherFile.fFile.equals(fFile); } + + @Override + public int hashCode() { + return Objects.hashCode(fFile); + } } class LoadFilesThread extends Thread { From 70c76ec8c45b4e0d9bad4168a558a95a25b901eb Mon Sep 17 00:00:00 2001 From: Harold Seigel Date: Tue, 10 Jun 2014 14:04:37 -0400 Subject: [PATCH 063/192] 8044738: Check attribute_length of EnclosingMethod attribute Add check that attribute_length == 4. Reviewed-by: fparain, coleenp, lfoltan --- .../share/vm/classfile/classFileParser.cpp | 5 +- .../EnclosingMethodAttr/EnclMethTest.jcod | 115 ++++++++++++++++++ .../EnclosingMethodAttr/EnclMethodAttr.java | 47 +++++++ .../EnclosingMethodAttr/enclMethodAttr.jar | Bin 0 -> 738 bytes 4 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 hotspot/test/runtime/EnclosingMethodAttr/EnclMethTest.jcod create mode 100644 hotspot/test/runtime/EnclosingMethodAttr/EnclMethodAttr.java create mode 100644 hotspot/test/runtime/EnclosingMethodAttr/enclMethodAttr.jar diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp index 608b43ae150..c7fe1c7d5a2 100644 --- a/hotspot/src/share/vm/classfile/classFileParser.cpp +++ b/hotspot/src/share/vm/classfile/classFileParser.cpp @@ -2984,9 +2984,12 @@ void ClassFileParser::parse_classfile_attributes(ClassFileParser::ClassAnnotatio } else if (tag == vmSymbols::tag_enclosing_method()) { if (parsed_enclosingmethod_attribute) { classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK); - } else { + } else { parsed_enclosingmethod_attribute = true; } + guarantee_property(attribute_length == 4, + "Wrong EnclosingMethod attribute length %u in class file %s", + attribute_length, CHECK); cfs->guarantee_more(4, CHECK); // class_index, method_index enclosing_method_class_index = cfs->get_u2_fast(); enclosing_method_method_index = cfs->get_u2_fast(); diff --git a/hotspot/test/runtime/EnclosingMethodAttr/EnclMethTest.jcod b/hotspot/test/runtime/EnclosingMethodAttr/EnclMethTest.jcod new file mode 100644 index 00000000000..956b643b055 --- /dev/null +++ b/hotspot/test/runtime/EnclosingMethodAttr/EnclMethTest.jcod @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * This test has a EnclosingMethod attribute with an illegal + * attribute_length field value of 6. This should cause a + * java.lang.ClassFormatError exception to be thrown. + */ + +class EnclMethTest { + 0xCAFEBABE; + 0; // minor version + 52; // version + [22] { // Constant Pool + ; // first element is empty + Field #3 #14; // #1 at 0x0A + Method #4 #15; // #2 at 0x0F + class #16; // #3 at 0x14 + class #19; // #4 at 0x17 + Utf8 "this$0"; // #5 at 0x1A + Utf8 "La;"; // #6 at 0x23 + Utf8 "Synthetic"; // #7 at 0x29 + Utf8 ""; // #8 at 0x35 + Utf8 "(Ljava/lang/Object;)V"; // #9 at 0x3E + Utf8 "Code"; // #10 at 0x56 + Utf8 "LineNumberTable"; // #11 at 0x5D + Utf8 "SourceFile"; // #12 at 0x6F + Utf8 "a.java"; // #13 at 0x7C + NameAndType #5 #6; // #14 at 0x85 + NameAndType #8 #20; // #15 at 0x8A + Utf8 "EnclMethTest"; // #16 at 0x8F + Utf8 "Loc"; // #17 at 0x9E + Utf8 "InnerClasses"; // #18 at 0xA4 + Utf8 "java/lang/Object"; // #19 at 0xB3 + Utf8 "()V"; // #20 at 0xC6 + Utf8 "EnclosingMethod"; // #21 at 0xCC + } // Constant Pool + + 0x0000; // access + #3;// this_cpx + #4;// super_cpx + + [0] { // Interfaces + } // Interfaces + + [1] { // fields + { // Member at 0xE8 + 0x0000; // access + #5; // name_cpx + #6; // sig_cpx + [1] { // Attributes + Attr(#7, 0) { // Synthetic at 0xF0 + } // end Synthetic + } // Attributes + } // Member + } // fields + + [1] { // methods + { // Member at 0xF8 + 0x0001; // access + #8; // name_cpx + #20; // sig_cpx + [1] { // Attributes + Attr(#10, 17) { // Code at 0x0100 + 2; // max_stack + 2; // max_locals + Bytes[5]{ + 0x2AB70002B1; + }; + [0] { // Traps + } // end Traps + [0] { // Attributes + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [3] { // Attributes + Attr(#12, 2) { // SourceFile at 0x0119 + #13; + } // end SourceFile + ; + Attr(#18, 10) { // InnerClasses at 0x0121 + [1] { // InnerClasses + #3 #0 #17 0; // at 0x0131 + } + } // end InnerClasses + ; + Attr(#21, 6) { // EnclosingMethod at 0x0131 + // invalid length of EnclosingMethod attr: 6 (should be 4) !! + 0x0004000F; + } // end EnclosingMethod + } // Attributes +} // end class EnclMethTest diff --git a/hotspot/test/runtime/EnclosingMethodAttr/EnclMethodAttr.java b/hotspot/test/runtime/EnclosingMethodAttr/EnclMethodAttr.java new file mode 100644 index 00000000000..82b5424813f --- /dev/null +++ b/hotspot/test/runtime/EnclosingMethodAttr/EnclMethodAttr.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8044738 + * @library /testlibrary + * @summary Check attribute_length of EnclosingMethod attribute + * @run main EnclMethodAttr + */ + +import java.io.File; +import com.oracle.java.testlibrary.*; + +public class EnclMethodAttr { + + static final String testsrc = System.getProperty("test.src"); + + public static void main(String args[]) throws Throwable { + System.out.println("Regression test for bug 8044738"); + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + "-jar", testsrc + File.separator + "enclMethodAttr.jar"); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + output.shouldContain("java.lang.ClassFormatError: Wrong EnclosingMethod"); + } +} + diff --git a/hotspot/test/runtime/EnclosingMethodAttr/enclMethodAttr.jar b/hotspot/test/runtime/EnclosingMethodAttr/enclMethodAttr.jar new file mode 100644 index 0000000000000000000000000000000000000000..590e7ae37b641964ac60d566a76f73450aa3f57a GIT binary patch literal 738 zcmWIWW@Zs#;Nak3cwKkYg#ih0GO#fCx`sIFdiuHP|2xINz|0Wf&CUT*!30$nfK#&w zPz7AGucM!*n`>~0p0C?y-!rFuymj?1@_OrPojY@WbCAIm;|EWR^t^m^Jbf>gu43Vg zcqRE_nVMF{4{=qs=S#FKo{Nh<5m%kYFg5#A(NDFsXD_XutB8q5Ywmca`uxYTX(=rX zzE7S$dddWLox3TyHXpUyt#0niX6*jqscBeVUO0VC2 zxq1Jt|MU6x*XJ{sTSz-SFgVWO+7{R*>?9@i`22d#MIpwA3V!A}FK%A>Gc#`u=k}J5 zOYW>PH_e@T*Ju9fwd)SQdDLnUv16;6$kL6!GQUT?%v-u@TK=b{w@bI~GY?$yN~_HK zjpEcB$2A@A-P~1sWnpBdywWX0Kf8$4yIoiBxjxU}SAWWVm7wk$Z}x1QZE Date: Wed, 11 Jun 2014 10:53:27 +0400 Subject: [PATCH 064/192] 8046391: Hang displaying JFileChooser with Windows L&F Reviewed-by: anthony, serb --- .../plaf/windows/AnimationController.java | 15 +++--- .../swing/plaf/windows/WindowsComboBoxUI.java | 20 +++----- .../plaf/windows/WindowsGraphicsUtils.java | 5 +- .../plaf/windows/WindowsIconFactory.java | 46 ++++++++----------- .../WindowsInternalFrameTitlePane.java | 13 +++--- .../plaf/windows/WindowsLookAndFeel.java | 8 ++-- .../swing/plaf/windows/WindowsMenuBarUI.java | 4 +- .../swing/plaf/windows/WindowsMenuItemUI.java | 6 +-- .../windows/WindowsPopupMenuSeparatorUI.java | 7 ++- .../plaf/windows/WindowsPopupMenuUI.java | 6 +-- .../plaf/windows/WindowsProgressBarUI.java | 13 ++---- .../swing/plaf/windows/WindowsSliderUI.java | 3 +- .../swing/plaf/windows/WindowsSpinnerUI.java | 5 +- .../plaf/windows/WindowsTableHeaderUI.java | 5 +- .../sun/java/swing/plaf/windows/XPStyle.java | 44 ++++++++---------- .../classes/sun/awt/windows/ThemeReader.java | 4 -- .../classes/sun/awt/windows/ThemeReader.java | 6 --- .../classes/sun/awt/windows/WToolkit.java | 29 +++--------- 18 files changed, 84 insertions(+), 155 deletions(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java index 70edf604df5..8fec402dcea 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/AnimationController.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 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 @@ -130,14 +130,11 @@ class AnimationController implements ActionListener, PropertyChangeListener { //one second seems plausible value duration = 1000; } else { - XPStyle xp = XPStyle.getXP(); - duration = (xp != null) - ? xp.getThemeTransitionDuration( - c, part, - normalizeState(oldState), - normalizeState(newState), - Prop.TRANSITIONDURATIONS) - : 1000; + duration = XPStyle.getXP().getThemeTransitionDuration( + c, part, + normalizeState(oldState), + normalizeState(newState), + Prop.TRANSITIONDURATIONS); } controller.startAnimation(c, part, oldState, newState, duration); } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java index dc7ae1bc511..348b28a1a7b 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, 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 @@ -37,7 +37,6 @@ import java.awt.*; import static com.sun.java.swing.plaf.windows.TMSchema.Part; import static com.sun.java.swing.plaf.windows.TMSchema.State; import static com.sun.java.swing.plaf.windows.XPStyle.Skin; - import sun.swing.DefaultLookup; import sun.swing.StringUIClientPropertyKey; @@ -232,9 +231,6 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { private void paintXPComboBoxBackground(Graphics g, JComponent c) { XPStyle xp = XPStyle.getXP(); - if (xp == null) { - return; - } State state = getXPComboBoxState(c); Skin skin = null; if (! comboBox.isEditable() @@ -404,9 +400,8 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { * @return a button which represents the popup control */ protected JButton createArrowButton() { - XPStyle xp = XPStyle.getXP(); - if (xp != null) { - return new XPComboBoxButton(xp); + if (XPStyle.getXP() != null) { + return new XPComboBoxButton(); } else { return super.createArrowButton(); } @@ -414,9 +409,9 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { @SuppressWarnings("serial") // Superclass is not serializable across versions private class XPComboBoxButton extends XPStyle.GlyphButton { - public XPComboBoxButton(XPStyle xp) { + public XPComboBoxButton() { super(null, - (! xp.isSkinDefined(comboBox, Part.CP_DROPDOWNBUTTONRIGHT)) + (! XPStyle.getXP().isSkinDefined(comboBox, Part.CP_DROPDOWNBUTTONRIGHT)) ? Part.CP_DROPDOWNBUTTON : (comboBox.getComponentOrientation() == ComponentOrientation.RIGHT_TO_LEFT) ? Part.CP_DROPDOWNBUTTONLEFT @@ -429,11 +424,10 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { protected State getState() { State rv; rv = super.getState(); - XPStyle xp = XPStyle.getXP(); if (rv != State.DISABLED && comboBox != null && ! comboBox.isEditable() - && xp != null && xp.isSkinDefined(comboBox, - Part.CP_DROPDOWNBUTTONRIGHT)) { + && XPStyle.getXP().isSkinDefined(comboBox, + Part.CP_DROPDOWNBUTTONRIGHT)) { /* * for non editable ComboBoxes Vista seems to have the * same glyph for all non DISABLED states diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java index 8e168066d11..63eb27b9b2d 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsGraphicsUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, 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 @@ -125,9 +125,6 @@ public class WindowsGraphicsUtils { static void paintXPText(AbstractButton b, Part part, State state, Graphics g, int x, int y, String text, int mnemIndex) { XPStyle xp = XPStyle.getXP(); - if (xp == null) { - return; - } Color textColor = b.getForeground(); if (textColor instanceof UIResource) { diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java index d2018ea4e89..0a4cfce44bf 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java @@ -623,8 +623,8 @@ public class WindowsIconFactory implements Serializable @SuppressWarnings("serial") // Same-version serialization only private static class MenuArrowIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { - XPStyle xp = XPStyle.getXP(); - if (xp != null && WindowsMenuItemUI.isVistaPainting()) { + if (WindowsMenuItemUI.isVistaPainting()) { + XPStyle xp = XPStyle.getXP(); State state = State.NORMAL; if (c instanceof JMenuItem) { state = ((JMenuItem) c).getModel().isEnabled() @@ -657,18 +657,16 @@ public class WindowsIconFactory implements Serializable } } public int getIconWidth() { - XPStyle xp = XPStyle.getXP(); - if (xp != null && WindowsMenuItemUI.isVistaPainting()) { - Skin skin = xp.getSkin(null, Part.MP_POPUPSUBMENU); + if (WindowsMenuItemUI.isVistaPainting()) { + Skin skin = XPStyle.getXP().getSkin(null, Part.MP_POPUPSUBMENU); return skin.getWidth(); } else { return 4; } } public int getIconHeight() { - XPStyle xp = XPStyle.getXP(); - if (xp != null && WindowsMenuItemUI.isVistaPainting()) { - Skin skin = xp.getSkin(null, Part.MP_POPUPSUBMENU); + if (WindowsMenuItemUI.isVistaPainting()) { + Skin skin = XPStyle.getXP().getSkin(null, Part.MP_POPUPSUBMENU); return skin.getHeight(); } else { return 8; @@ -694,8 +692,7 @@ public class WindowsIconFactory implements Serializable } static int getIconWidth() { - XPStyle xp = XPStyle.getXP(); - return ((xp != null) ? xp.getSkin(null, Part.MP_POPUPCHECK).getWidth() : 16) + return XPStyle.getXP().getSkin(null, Part.MP_POPUPCHECK).getWidth() + 2 * OFFSET; } @@ -759,17 +756,12 @@ public class WindowsIconFactory implements Serializable Icon icon = getIcon(); int height = 0; if (icon != null) { - height = icon.getIconHeight(); + height = icon.getIconHeight() + 2 * OFFSET; } else { - XPStyle xp = XPStyle.getXP(); - if (xp != null) { - Skin skin = xp.getSkin(null, Part.MP_POPUPCHECK); - height = skin.getHeight(); - } else { - height = 16; - } + Skin skin = + XPStyle.getXP().getSkin(null, Part.MP_POPUPCHECK); + height = skin.getHeight() + 2 * OFFSET; } - height += 2 * OFFSET; return height; } @@ -817,16 +809,14 @@ public class WindowsIconFactory implements Serializable ? State.BULLETDISABLED : State.CHECKMARKDISABLED; } + Skin skin; XPStyle xp = XPStyle.getXP(); - if (xp != null) { - Skin skin; - skin = xp.getSkin(c, backgroundPart); - skin.paintSkin(g, x, y, - getIconWidth(), getIconHeight(), backgroundState); - if (icon == null) { - skin = xp.getSkin(c, part); - skin.paintSkin(g, x + OFFSET, y + OFFSET, state); - } + skin = xp.getSkin(c, backgroundPart); + skin.paintSkin(g, x, y, + getIconWidth(), getIconHeight(), backgroundState); + if (icon == null) { + skin = xp.getSkin(c, part); + skin.paintSkin(g, x + OFFSET, y + OFFSET, state); } } } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java index 6210a93b738..c654c5a7046 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2013, 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 @@ -86,15 +86,14 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane { } } else { buttonWidth += 2; + selectedTitleGradientColor = + UIManager.getColor("InternalFrame.activeTitleGradient"); + notSelectedTitleGradientColor = + UIManager.getColor("InternalFrame.inactiveTitleGradient"); Color activeBorderColor = UIManager.getColor("InternalFrame.activeBorderColor"); setBorder(BorderFactory.createLineBorder(activeBorderColor, 1)); } - // JDK-8039383: initialize these colors because getXP() may return null when theme is changed - selectedTitleGradientColor = - UIManager.getColor("InternalFrame.activeTitleGradient"); - notSelectedTitleGradientColor = - UIManager.getColor("InternalFrame.inactiveTitleGradient"); } protected void uninstallListeners() { @@ -389,7 +388,7 @@ public class WindowsInternalFrameTitlePane extends BasicInternalFrameTitlePane { public class WindowsTitlePaneLayout extends BasicInternalFrameTitlePane.TitlePaneLayout { private Insets captionMargin = null; private Insets contentMargin = null; - private final XPStyle xp = XPStyle.getXP(); + private XPStyle xp = XPStyle.getXP(); WindowsTitlePaneLayout() { if (xp != null) { diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index f4f326aa2f6..a6c1c895757 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -2327,9 +2327,8 @@ public class WindowsLookAndFeel extends BasicLookAndFeel } public Object getXPValue(UIDefaults table) { - XPStyle xp = XPStyle.getXP(); - Border xpBorder = xp != null ? xp.getBorder(null, (Part)xpValue) : null; - if (xpBorder != null && extraMargin != null) { + Border xpBorder = XPStyle.getXP().getBorder(null, (Part)xpValue); + if (extraMargin != null) { return new BorderUIResource. CompoundBorderUIResource(xpBorder, extraMargin); } else { @@ -2345,8 +2344,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel public Object getXPValue(UIDefaults table) { XPColorValueKey key = (XPColorValueKey)xpValue; - XPStyle xp = XPStyle.getXP(); - return xp != null ? xp.getColor(key.skin, key.prop, null) : null; + return XPStyle.getXP().getColor(key.skin, key.prop, null); } private static class XPColorValueKey { diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java index 68015c0752e..73dcf802e33 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuBarUI.java @@ -156,8 +156,8 @@ public class WindowsMenuBarUI extends BasicMenuBarUI @Override public void paint(Graphics g, JComponent c) { - XPStyle xp = XPStyle.getXP(); - if (xp != null && WindowsMenuItemUI.isVistaPainting()) { + if (WindowsMenuItemUI.isVistaPainting()) { + XPStyle xp = XPStyle.getXP(); Skin skin; skin = xp.getSkin(c, Part.MP_BARBACKGROUND); int width = c.getWidth(); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java index 8cc4fc420a0..cac7af54aa7 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsMenuItemUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -109,8 +109,7 @@ public class WindowsMenuItemUI extends BasicMenuItemUI { static void paintBackground(WindowsMenuItemUIAccessor menuItemUI, Graphics g, JMenuItem menuItem, Color bgColor) { assert isVistaPainting(); - XPStyle xp = XPStyle.getXP(); - if (xp != null && isVistaPainting()) { + if (isVistaPainting()) { int menuWidth = menuItem.getWidth(); int menuHeight = menuItem.getHeight(); if (menuItem.isOpaque()) { @@ -119,6 +118,7 @@ public class WindowsMenuItemUI extends BasicMenuItemUI { g.fillRect(0,0, menuWidth, menuHeight); g.setColor(oldColor); } + XPStyle xp = XPStyle.getXP(); Part part = menuItemUI.getPart(menuItem); Skin skin = xp.getSkin(menuItem, part); skin.paintSkin(g, 0 , 0, diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java index fc20e988459..797aa5a7b6a 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuSeparatorUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -50,8 +50,7 @@ public class WindowsPopupMenuSeparatorUI extends BasicPopupMenuSeparatorUI { public void paint(Graphics g, JComponent c) { Dimension s = c.getSize(); - XPStyle xp = XPStyle.getXP(); - if (xp != null && WindowsMenuItemUI.isVistaPainting()) { + if (WindowsMenuItemUI.isVistaPainting()) { int x = 1; Component parent = c.getParent(); if (parent instanceof JComponent) { @@ -68,7 +67,7 @@ public class WindowsPopupMenuSeparatorUI extends BasicPopupMenuSeparatorUI { x += WindowsPopupMenuUI.getGutterWidth(); } } - Skin skin = xp.getSkin(c, Part.MP_POPUPSEPARATOR); + Skin skin = XPStyle.getXP().getSkin(c, Part.MP_POPUPSEPARATOR); int skinHeight = skin.getHeight(); int y = (s.height - skinHeight) / 2; skin.paintSkin(g, x, y, s.width - x - 1, skinHeight, State.NORMAL); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java index e3d9d96efc4..584641bcaf7 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsPopupMenuUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -194,8 +194,8 @@ public class WindowsPopupMenuUI extends BasicPopupMenuUI { @Override public void paint(Graphics g, JComponent c) { - XPStyle xp = XPStyle.getXP(); - if (xp != null && WindowsMenuItemUI.isVistaPainting()) { + if (WindowsMenuItemUI.isVistaPainting()) { + XPStyle xp = XPStyle.getXP(); Skin skin = xp.getSkin(c, Part.MP_POPUPBACKGROUND); skin.paintSkin(g, 0, 0, c.getWidth(),c.getHeight(), State.NORMAL); int textOffset = getTextOffset(c); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java index 45947fc2b7e..ef5d176fa7b 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsProgressBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, 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 @@ -322,9 +322,8 @@ public class WindowsProgressBarUI extends BasicProgressBarUI private Rectangle getFullChunkBounds(Rectangle box) { boolean vertical = (progressBar.getOrientation() == JProgressBar.VERTICAL); XPStyle xp = XPStyle.getXP(); - int gap = (xp != null) ? xp.getInt(progressBar, Part.PP_PROGRESS, - null, Prop.PROGRESSSPACESIZE, 0) - : 0; + int gap = xp.getInt(progressBar, Part.PP_PROGRESS, null, + Prop.PROGRESSSPACESIZE, 0); if (!vertical) { int chunksize = box.width+gap; @@ -339,9 +338,6 @@ public class WindowsProgressBarUI extends BasicProgressBarUI boolean vertical, int bgwidth, int bgheight) { XPStyle xp = XPStyle.getXP(); - if (xp == null) { - return; - } // create a new graphics to keep drawing surface state Graphics2D gfx = (Graphics2D)g.create(); @@ -400,9 +396,6 @@ public class WindowsProgressBarUI extends BasicProgressBarUI private void paintXPBackground(Graphics g, boolean vertical, int barRectWidth, int barRectHeight) { XPStyle xp = XPStyle.getXP(); - if (xp == null) { - return; - } Part part = vertical ? Part.PP_BARVERT : Part.PP_BAR; Skin skin = xp.getSkin(progressBar, part); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java index 1bae3f8f441..dbfb7b81251 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSliderUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2005, 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 @@ -215,6 +215,7 @@ public class WindowsSliderUI extends BasicSliderUI } private Part getXPThumbPart() { + XPStyle xp = XPStyle.getXP(); Part part; boolean vertical = (slider.getOrientation() == JSlider.VERTICAL); boolean leftToRight = slider.getComponentOrientation().isLeftToRight(); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java index c17328e50cc..ccc6d039b53 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsSpinnerUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -63,9 +63,6 @@ public class WindowsSpinnerUI extends BasicSpinnerUI { private void paintXPBackground(Graphics g, JComponent c) { XPStyle xp = XPStyle.getXP(); - if (xp == null) { - return; - } Skin skin = xp.getSkin(c, Part.EP_EDIT); State state = getXPState(c); skin.paintSkin(g, 0, 0, c.getWidth(), c.getHeight(), state); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java index 9cf37994589..117e9d7b7b1 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java @@ -91,10 +91,9 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI { this.column = column; this.hasRollover = (column == getRolloverColumn()); if (skin == null) { - XPStyle xp = XPStyle.getXP(); - skin = (xp != null) ? xp.getSkin(header, Part.HP_HEADERITEM) : null; + skin = XPStyle.getXP().getSkin(header, Part.HP_HEADERITEM); } - Insets margins = (skin != null) ? skin.getContentMargin() : null; + Insets margins = skin.getContentMargin(); Border border = null; int contentTop = 0; int contentLeft = 0; diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java index baeca8c29ca..bc1404e9227 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/XPStyle.java @@ -115,7 +115,7 @@ class XPStyle { } } } - return ThemeReader.isXPStyleEnabled() ? xp : null; + return xp; } static boolean isVista() { @@ -180,10 +180,9 @@ class XPStyle { * should probably be cached there instead of here. */ Dimension getDimension(Component c, Part part, State state, Prop prop) { - Dimension d = ThemeReader.getPosition(part.getControlName(c), part.getValue(), - State.getValue(part, state), - prop.getValue()); - return (d != null) ? d : new Dimension(); + return ThemeReader.getPosition(part.getControlName(c), part.getValue(), + State.getValue(part, state), + prop.getValue()); } /** Get a named Point (e.g. a location or an offset) value @@ -200,7 +199,11 @@ class XPStyle { Dimension d = ThemeReader.getPosition(part.getControlName(c), part.getValue(), State.getValue(part, state), prop.getValue()); - return (d != null) ? new Point(d.width, d.height) : new Point(); + if (d != null) { + return new Point(d.width, d.height); + } else { + return null; + } } /** Get a named Insets value from the current style @@ -214,10 +217,9 @@ class XPStyle { * The return value is already cached in those places. */ Insets getMargin(Component c, Part part, State state, Prop prop) { - Insets insets = ThemeReader.getThemeMargins(part.getControlName(c), part.getValue(), - State.getValue(part, state), - prop.getValue()); - return (insets != null) ? insets : new Insets(0, 0, 0, 0); + return ThemeReader.getThemeMargins(part.getControlName(c), part.getValue(), + State.getValue(part, state), + prop.getValue()); } @@ -507,17 +509,16 @@ class XPStyle { int boundingWidth = 100; int boundingHeight = 100; - Insets insets = ThemeReader.getThemeBackgroundContentMargins( + return ThemeReader.getThemeBackgroundContentMargins( part.getControlName(null), part.getValue(), 0, boundingWidth, boundingHeight); - return (insets != null) ? insets : new Insets(0, 0, 0, 0); } private int getWidth(State state) { if (size == null) { size = getPartSize(part, state); } - return (size != null) ? size.width : 0; + return size.width; } int getWidth() { @@ -528,7 +529,7 @@ class XPStyle { if (size == null) { size = getPartSize(part, state); } - return (size != null) ? size.height : 0; + return size.height; } int getHeight() { @@ -585,9 +586,6 @@ class XPStyle { * @param state which state to paint */ void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state) { - if (XPStyle.getXP() == null) { - return; - } if (ThemeReader.isGetThemeTransitionDurationDefined() && component instanceof JComponent && SwingUtilities.getAncestorOfClass(CellRendererPane.class, @@ -613,9 +611,6 @@ class XPStyle { * @param state which state to paint */ void paintSkinRaw(Graphics g, int dx, int dy, int dw, int dh, State state) { - if (XPStyle.getXP() == null) { - return; - } skinPainter.paint(null, g, dx, dy, dw, dh, this, state); } @@ -635,7 +630,7 @@ class XPStyle { void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state, boolean borderFill) { if(borderFill && "borderfill".equals(getTypeEnumName(component, part, - state, Prop.BGTYPE)) && XPStyle.getXP() == null) { + state, Prop.BGTYPE))) { return; } skinPainter.paint(null, g, dx, dy, dw, dh, this, state); @@ -689,7 +684,7 @@ class XPStyle { public GlyphButton(Component parent, Part part) { XPStyle xp = getXP(); - skin = xp != null ? xp.getSkin(parent, part) : null; + skin = xp.getSkin(parent, part); setBorder(null); setContentAreaFilled(false); setMinimumSize(new Dimension(5, 5)); @@ -714,16 +709,13 @@ class XPStyle { } public void paintComponent(Graphics g) { - if (XPStyle.getXP() == null || skin == null) { - return; - } Dimension d = getSize(); skin.paintSkin(g, 0, 0, d.width, d.height, getState()); } public void setPart(Component parent, Part part) { XPStyle xp = getXP(); - skin = xp != null ? xp.getSkin(parent, part) : null; + skin = xp.getSkin(parent, part); revalidate(); repaint(); } diff --git a/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java b/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java index 5bd2f7ec0b8..7445cc2f5ff 100644 --- a/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java +++ b/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java @@ -45,10 +45,6 @@ public final class ThemeReader { return false; } - public static boolean isXPStyleEnabled() { - return false; - } - public static void paintBackground(int[] buffer, String widget, int part, int state, int x, int y, int w, int h, int stride) { } diff --git a/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java b/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java index 321e72ca182..632489964e7 100644 --- a/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java +++ b/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java @@ -61,8 +61,6 @@ public final class ThemeReader { private static final Lock readLock = readWriteLock.readLock(); private static final Lock writeLock = readWriteLock.writeLock(); - static volatile boolean xpStyleEnabled; - static void flush() { writeLock.lock(); try { @@ -78,10 +76,6 @@ public final class ThemeReader { public static native boolean isThemed(); - public static boolean isXPStyleEnabled() { - return xpStyleEnabled; - } - // this should be called only with writeLock held private static Long getThemeImpl(String widget) { Long theme = widgetToTheme.get(widget); diff --git a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java index 630d29e7b75..2a27c2df9cc 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java +++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java @@ -72,9 +72,6 @@ public final class WToolkit extends SunToolkit implements Runnable { private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WToolkit"); - // Desktop property which specifies whether XP visual styles are in effect - public static final String XPSTYLE_THEME_ACTIVE = "win.xpstyle.themeActive"; - static GraphicsConfiguration config; // System clipboard. @@ -897,7 +894,7 @@ public final class WToolkit extends SunToolkit implements Runnable { private synchronized void lazilyInitWProps() { if (wprops == null) { wprops = new WDesktopProperties(this); - updateProperties(wprops.getProperties()); + updateProperties(); } } @@ -932,27 +929,21 @@ public final class WToolkit extends SunToolkit implements Runnable { * Windows doesn't always send WM_SETTINGCHANGE when it should. */ private void windowsSettingChange() { - // JDK-8039383: Have to update the value of XPSTYLE_THEME_ACTIVE property - // as soon as possible to prevent NPE and other errors because theme data - // has become unavailable. - final Map props = getWProps(); - updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE)); - EventQueue.invokeLater(new Runnable() { @Override public void run() { - updateProperties(props); + updateProperties(); } }); } - private synchronized void updateProperties(final Map props) { - if (null == props) { + private synchronized void updateProperties() { + if (null == wprops) { + // wprops has not been initialized, so we have nothing to update return; } - updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE)); - + Map props = wprops.getProperties(); for (String propName : props.keySet()) { Object val = props.get(propName); if (log.isLoggable(PlatformLogger.Level.FINER)) { @@ -962,14 +953,6 @@ public final class WToolkit extends SunToolkit implements Runnable { } } - private synchronized Map getWProps() { - return (wprops != null) ? wprops.getProperties() : null; - } - - private void updateXPStyleEnabled(final Object dskProp) { - ThemeReader.xpStyleEnabled = Boolean.TRUE.equals(dskProp); - } - @Override public synchronized void addPropertyChangeListener(String name, PropertyChangeListener pcl) { if (name == null) { From 6f97a45429b17cb9ccb178586e795c32fe3af795 Mon Sep 17 00:00:00 2001 From: David Simms Date: Wed, 11 Jun 2014 12:09:12 +0200 Subject: [PATCH 065/192] 6311046: -Xcheck:jni should support checking of GetPrimitiveArrayCritical Wrapped memory with standard bounds checking "GuardedMemory". Reviewed-by: zgu, fparain, dcubed --- hotspot/src/share/vm/memory/guardedMemory.cpp | 161 +++++++++ hotspot/src/share/vm/memory/guardedMemory.hpp | 326 ++++++++++++++++++ hotspot/src/share/vm/prims/jni.cpp | 2 + hotspot/src/share/vm/prims/jniCheck.cpp | 163 +++++++-- hotspot/src/share/vm/runtime/os.cpp | 210 +++-------- 5 files changed, 671 insertions(+), 191 deletions(-) create mode 100644 hotspot/src/share/vm/memory/guardedMemory.cpp create mode 100644 hotspot/src/share/vm/memory/guardedMemory.hpp diff --git a/hotspot/src/share/vm/memory/guardedMemory.cpp b/hotspot/src/share/vm/memory/guardedMemory.cpp new file mode 100644 index 00000000000..763548fd35d --- /dev/null +++ b/hotspot/src/share/vm/memory/guardedMemory.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ +#include "precompiled.hpp" +#include "memory/allocation.hpp" +#include "memory/allocation.inline.hpp" +#include "memory/guardedMemory.hpp" +#include "runtime/os.hpp" + +void* GuardedMemory::wrap_copy(const void* ptr, const size_t len, const void* tag) { + size_t total_sz = GuardedMemory::get_total_size(len); + void* outerp = os::malloc(total_sz, mtInternal); + if (outerp != NULL) { + GuardedMemory guarded(outerp, len, tag); + void* innerp = guarded.get_user_ptr(); + memcpy(innerp, ptr, len); + return innerp; + } + return NULL; // OOM +} + +bool GuardedMemory::free_copy(void* p) { + if (p == NULL) { + return true; + } + GuardedMemory guarded((u_char*)p); + bool verify_ok = guarded.verify_guards(); + + /* always attempt to free, pass problem on to any nested memchecker */ + os::free(guarded.release_for_freeing()); + + return verify_ok; +} + +void GuardedMemory::print_on(outputStream* st) const { + if (_base_addr == NULL) { + st->print_cr("GuardedMemory(" PTR_FORMAT ") not associated to any memory", p2i(this)); + return; + } + st->print_cr("GuardedMemory(" PTR_FORMAT ") base_addr=" PTR_FORMAT + " tag=" PTR_FORMAT " user_size=" SIZE_FORMAT " user_data=" PTR_FORMAT, + p2i(this), p2i(_base_addr), p2i(get_tag()), get_user_size(), p2i(get_user_ptr())); + + Guard* guard = get_head_guard(); + st->print_cr(" Header guard @" PTR_FORMAT " is %s", p2i(guard), (guard->verify() ? "OK" : "BROKEN")); + guard = get_tail_guard(); + st->print_cr(" Trailer guard @" PTR_FORMAT " is %s", p2i(guard), (guard->verify() ? "OK" : "BROKEN")); + + u_char udata = *get_user_ptr(); + switch (udata) { + case uninitBlockPad: + st->print_cr(" User data appears unused"); + break; + case freeBlockPad: + st->print_cr(" User data appears to have been freed"); + break; + default: + st->print_cr(" User data appears to be in use"); + break; + } +} + +// test code... + +#ifndef PRODUCT + +static void guarded_memory_test_check(void* p, size_t sz, void* tag) { + assert(p != NULL, "NULL pointer given to check"); + u_char* c = (u_char*) p; + GuardedMemory guarded(c); + assert(guarded.get_tag() == tag, "Tag is not the same as supplied"); + assert(guarded.get_user_ptr() == c, "User pointer is not the same as supplied"); + assert(guarded.get_user_size() == sz, "User size is not the same as supplied"); + assert(guarded.verify_guards(), "Guard broken"); +} + +void GuardedMemory::test_guarded_memory() { + // Test the basic characteristics... + size_t total_sz = GuardedMemory::get_total_size(1); + assert(total_sz > 1 && total_sz >= (sizeof(GuardHeader) + 1 + sizeof(Guard)), "Unexpected size"); + u_char* basep = (u_char*) os::malloc(total_sz, mtInternal); + + GuardedMemory guarded(basep, 1, (void*)0xf000f000); + + assert(*basep == badResourceValue, "Expected guard in the form of badResourceValue"); + u_char* userp = guarded.get_user_ptr(); + assert(*userp == uninitBlockPad, "Expected uninitialized data in the form of uninitBlockPad"); + guarded_memory_test_check(userp, 1, (void*)0xf000f000); + + void* freep = guarded.release_for_freeing(); + assert((u_char*)freep == basep, "Expected the same pointer guard was "); + assert(*userp == freeBlockPad, "Expected user data to be free block padded"); + assert(!guarded.verify_guards(), "Expected failed"); + os::free(freep); + + // Test a number of odd sizes... + size_t sz = 0; + do { + void* p = os::malloc(GuardedMemory::get_total_size(sz), mtInternal); + void* up = guarded.wrap_with_guards(p, sz, (void*)1); + memset(up, 0, sz); + guarded_memory_test_check(up, sz, (void*)1); + os::free(guarded.release_for_freeing()); + sz = (sz << 4) + 1; + } while (sz < (256 * 1024)); + + // Test buffer overrun into head... + basep = (u_char*) os::malloc(GuardedMemory::get_total_size(1), mtInternal); + guarded.wrap_with_guards(basep, 1); + *basep = 0; + assert(!guarded.verify_guards(), "Expected failure"); + os::free(basep); + + // Test buffer overrun into tail with a number of odd sizes... + sz = 1; + do { + void* p = os::malloc(GuardedMemory::get_total_size(sz), mtInternal); + void* up = guarded.wrap_with_guards(p, sz, (void*)1); + memset(up, 0, sz + 1); // Buffer-overwrite (within guard) + assert(!guarded.verify_guards(), "Guard was not broken as expected"); + os::free(guarded.release_for_freeing()); + sz = (sz << 4) + 1; + } while (sz < (256 * 1024)); + + // Test wrap_copy/wrap_free... + assert(GuardedMemory::free_copy(NULL), "Expected free NULL to be OK"); + + const char* str = "Check my bounds out"; + size_t str_sz = strlen(str) + 1; + char* str_copy = (char*) GuardedMemory::wrap_copy(str, str_sz); + guarded_memory_test_check(str_copy, str_sz, NULL); + assert(strcmp(str, str_copy) == 0, "Not identical copy"); + assert(GuardedMemory::free_copy(str_copy), "Free copy failed to verify"); + + void* no_data = NULL; + void* no_data_copy = GuardedMemory::wrap_copy(no_data, 0); + assert(GuardedMemory::free_copy(no_data_copy), "Expected valid guards even for no data copy"); +} + +#endif // !PRODUCT + diff --git a/hotspot/src/share/vm/memory/guardedMemory.hpp b/hotspot/src/share/vm/memory/guardedMemory.hpp new file mode 100644 index 00000000000..dada10d84bf --- /dev/null +++ b/hotspot/src/share/vm/memory/guardedMemory.hpp @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#ifndef SHARE_VM_MEMORY_GUARDED_MEMORY_HPP +#define SHARE_VM_MEMORY_GUARDED_MEMORY_HPP + +#include "memory/allocation.hpp" +#include "utilities/globalDefinitions.hpp" + +/** + * Guarded memory for detecting buffer overrun. + * + * Allows allocations to be wrapped with padded bytes of a known byte pattern, + * that is a "guard". Guard patterns may be verified to detect buffer overruns. + * + * Primarily used by "debug malloc" and "checked JNI". + * + * Memory layout: + * + * |Offset | Content | Description | + * |------------------------------------------------------------ + * |base_addr | 0xABABABABABABABAB | Head guard | + * |+16 | | User data size | + * |+sizeof(uintptr_t) | | Tag word | + * |+sizeof(void*) | 0xF1 ( | User data | + * |+user_size | 0xABABABABABABABAB | Tail guard | + * ------------------------------------------------------------- + * + * Where: + * - guard padding uses "badResourceValue" (0xAB) + * - tag word is general purpose + * - user data + * -- initially padded with "uninitBlockPad" (0xF1), + * -- to "freeBlockPad" (0xBA), when freed + * + * Usage: + * + * * Allocations: one may wrap allocations with guard memory: + * + * Thing* alloc_thing() { + * void* mem = user_alloc_fn(GuardedMemory::get_total_size(sizeof(thing))); + * GuardedMemory guarded(mem, sizeof(thing)); + * return (Thing*) guarded.get_user_ptr(); + * } + * + * * Verify: memory guards are still in tact + * + * bool verify_thing(Thing* thing) { + * GuardedMemory guarded((void*)thing); + * return guarded.verify_guards(); + * } + * + * * Free: one may mark bytes as freed (further debugging support) + * + * void free_thing(Thing* thing) { + * GuardedMemory guarded((void*)thing); + * assert(guarded.verify_guards(), "Corrupt thing"); + * user_free_fn(guards.release_for_freeing(); + * } + * + */ +class GuardedMemory : StackObj { // Wrapper on stack + + // Private inner classes for memory layout... + +protected: + + /** + * Guard class for header and trailer known pattern to test for overwrites. + */ + class Guard { // Class for raw memory (no vtbl allowed) + friend class GuardedMemory; + protected: + enum { + GUARD_SIZE = 16 + }; + + u_char _guard[GUARD_SIZE]; + + public: + + void build() { + u_char* c = _guard; // Possibly unaligned if tail guard + u_char* end = c + GUARD_SIZE; + while (c < end) { + *c = badResourceValue; + c++; + } + } + + bool verify() const { + u_char* c = (u_char*) _guard; + u_char* end = c + GUARD_SIZE; + while (c < end) { + if (*c != badResourceValue) { + return false; + } + c++; + } + return true; + } + + }; // GuardedMemory::Guard + + /** + * Header guard and size + */ + class GuardHeader : Guard { + friend class GuardedMemory; + protected: + // Take care in modifying fields here, will effect alignment + // e.g. x86 ABI 16 byte stack alignment + union { + uintptr_t __unused_full_word1; + size_t _user_size; + }; + void* _tag; + public: + void set_user_size(const size_t usz) { _user_size = usz; } + size_t get_user_size() const { return _user_size; } + + void set_tag(const void* tag) { _tag = (void*) tag; } + void* get_tag() const { return _tag; } + + }; // GuardedMemory::GuardHeader + + // Guarded Memory... + + protected: + u_char* _base_addr; + + public: + + /** + * Create new guarded memory. + * + * Wraps, starting at the given "base_ptr" with guards. Use "get_user_ptr()" + * to return a pointer suitable for user data. + * + * @param base_ptr allocation wishing to be wrapped, must be at least "GuardedMemory::get_total_size()" bytes. + * @param user_size the size of the user data to be wrapped. + * @param tag optional general purpose tag. + */ + GuardedMemory(void* base_ptr, const size_t user_size, const void* tag = NULL) { + wrap_with_guards(base_ptr, user_size, tag); + } + + /** + * Wrap existing guarded memory. + * + * To use this constructor, one must have created guarded memory with + * "GuardedMemory(void*, size_t, void*)" (or indirectly via helper, e.g. "wrap_copy()"). + * + * @param user_p existing wrapped memory. + */ + GuardedMemory(void* userp) { + u_char* user_ptr = (u_char*) userp; + assert((uintptr_t)user_ptr > (sizeof(GuardHeader) + 0x1000), "Invalid pointer"); + _base_addr = (user_ptr - sizeof(GuardHeader)); + } + + /** + * Create new guarded memory. + * + * Wraps, starting at the given "base_ptr" with guards. Allows reuse of stack allocated helper. + * + * @param base_ptr allocation wishing to be wrapped, must be at least "GuardedMemory::get_total_size()" bytes. + * @param user_size the size of the user data to be wrapped. + * @param tag optional general purpose tag. + * + * @return user data pointer (inner pointer to supplied "base_ptr"). + */ + void* wrap_with_guards(void* base_ptr, size_t user_size, const void* tag = NULL) { + assert(base_ptr != NULL, "Attempt to wrap NULL with memory guard"); + _base_addr = (u_char*)base_ptr; + get_head_guard()->build(); + get_head_guard()->set_user_size(user_size); + get_tail_guard()->build(); + set_tag(tag); + set_user_bytes(uninitBlockPad); + assert(verify_guards(), "Expected valid memory guards"); + return get_user_ptr(); + } + + /** + * Verify head and tail guards. + * + * @return true if guards are intact, false would indicate a buffer overrun. + */ + bool verify_guards() const { + if (_base_addr != NULL) { + return (get_head_guard()->verify() && get_tail_guard()->verify()); + } + return false; + } + + /** + * Set the general purpose tag. + * + * @param tag general purpose tag. + */ + void set_tag(const void* tag) { get_head_guard()->set_tag(tag); } + + /** + * Return the general purpose tag. + * + * @return the general purpose tag, defaults to NULL. + */ + void* get_tag() const { return get_head_guard()->get_tag(); } + + /** + * Return the size of the user data. + * + * @return the size of the user data. + */ + size_t get_user_size() const { + assert(_base_addr, "Not wrapping any memory"); + return get_head_guard()->get_user_size(); + } + + /** + * Return the user data pointer. + * + * @return the user data pointer. + */ + u_char* get_user_ptr() const { + assert(_base_addr, "Not wrapping any memory"); + return _base_addr + sizeof(GuardHeader); + } + + /** + * Release the wrapped pointer for resource freeing. + * + * Pads the user data with "freeBlockPad", and dis-associates the helper. + * + * @return the original base pointer used to wrap the data. + */ + void* release_for_freeing() { + set_user_bytes(freeBlockPad); + return release(); + } + + /** + * Dis-associate the help from the original base address. + * + * @return the original base pointer used to wrap the data. + */ + void* release() { + void* p = (void*) _base_addr; + _base_addr = NULL; + return p; + } + + virtual void print_on(outputStream* st) const; + + protected: + GuardHeader* get_head_guard() const { return (GuardHeader*) _base_addr; } + Guard* get_tail_guard() const { return (Guard*) (get_user_ptr() + get_user_size()); }; + void set_user_bytes(u_char ch) { + memset(get_user_ptr(), ch, get_user_size()); + } + +public: + /** + * Return the total size required for wrapping the given user size. + * + * @return the total size required for wrapping the given user size. + */ + static size_t get_total_size(size_t user_size) { + size_t total_size = sizeof(GuardHeader) + user_size + sizeof(Guard); + assert(total_size > user_size, "Unexpected wrap-around"); + return total_size; + } + + // Helper functions... + + /** + * Wrap a copy of size "len" of "ptr". + * + * @param ptr the memory to be copied + * @param len the length of the copy + * @param tag optional general purpose tag (see GuardedMemory::get_tag()) + * + * @return guarded wrapped memory pointer to the user area, or NULL if OOM. + */ + static void* wrap_copy(const void* p, const size_t len, const void* tag = NULL); + + /** + * Free wrapped copy. + * + * Frees memory copied with "wrap_copy()". + * + * @param p memory returned by "wrap_copy()". + * + * @return true if guards were verified as intact. false indicates a buffer overrun. + */ + static bool free_copy(void* p); + + // Testing... +#ifndef PRODUCT + static void test_guarded_memory(void); +#endif +}; // GuardedMemory + +#endif // SHARE_VM_MEMORY_GUARDED_MEMORY_HPP diff --git a/hotspot/src/share/vm/prims/jni.cpp b/hotspot/src/share/vm/prims/jni.cpp index 6bbe5feb691..cdb53afe1b7 100644 --- a/hotspot/src/share/vm/prims/jni.cpp +++ b/hotspot/src/share/vm/prims/jni.cpp @@ -3858,6 +3858,7 @@ _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_GetDefaultJavaVMInitArgs(void *args_) { #if INCLUDE_ALL_GCS #include "gc_implementation/g1/heapRegionRemSet.hpp" #endif +#include "memory/guardedMemory.hpp" #include "utilities/quickSort.hpp" #include "utilities/ostream.hpp" #if INCLUDE_VM_STRUCTS @@ -3901,6 +3902,7 @@ void execute_internal_vm_tests() { run_unit_test(arrayOopDesc::test_max_array_length()); run_unit_test(CollectedHeap::test_is_in()); run_unit_test(QuickSort::test_quick_sort()); + run_unit_test(GuardedMemory::test_guarded_memory()); run_unit_test(AltHashing::test_alt_hash()); run_unit_test(test_loggc_filename()); run_unit_test(TestNewSize_test()); diff --git a/hotspot/src/share/vm/prims/jniCheck.cpp b/hotspot/src/share/vm/prims/jniCheck.cpp index 0d5ffab1cdc..446c23143ae 100644 --- a/hotspot/src/share/vm/prims/jniCheck.cpp +++ b/hotspot/src/share/vm/prims/jniCheck.cpp @@ -25,6 +25,7 @@ #include "precompiled.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmSymbols.hpp" +#include "memory/guardedMemory.hpp" #include "oops/instanceKlass.hpp" #include "oops/oop.inline.hpp" #include "oops/symbol.hpp" @@ -323,6 +324,74 @@ check_is_obj_array(JavaThread* thr, jarray jArray) { } } +/* + * Copy and wrap array elements for bounds checking. + * Remember the original elements (GuardedMemory::get_tag()) + */ +static void* check_jni_wrap_copy_array(JavaThread* thr, jarray array, + void* orig_elements) { + void* result; + IN_VM( + oop a = JNIHandles::resolve_non_null(array); + size_t len = arrayOop(a)->length() << + TypeArrayKlass::cast(a->klass())->log2_element_size(); + result = GuardedMemory::wrap_copy(orig_elements, len, orig_elements); + ) + return result; +} + +static void* check_wrapped_array(JavaThread* thr, const char* fn_name, + void* obj, void* carray, size_t* rsz) { + if (carray == NULL) { + tty->print_cr("%s: elements vector NULL" PTR_FORMAT, fn_name, p2i(obj)); + NativeReportJNIFatalError(thr, "Elements vector NULL"); + } + GuardedMemory guarded(carray); + void* orig_result = guarded.get_tag(); + if (!guarded.verify_guards()) { + tty->print_cr("ReleasePrimitiveArrayCritical: release array failed bounds " + "check, incorrect pointer returned ? array: " PTR_FORMAT " carray: " + PTR_FORMAT, p2i(obj), p2i(carray)); + guarded.print_on(tty); + NativeReportJNIFatalError(thr, "ReleasePrimitiveArrayCritical: " + "failed bounds check"); + } + if (orig_result == NULL) { + tty->print_cr("ReleasePrimitiveArrayCritical: unrecognized elements. array: " + PTR_FORMAT " carray: " PTR_FORMAT, p2i(obj), p2i(carray)); + guarded.print_on(tty); + NativeReportJNIFatalError(thr, "ReleasePrimitiveArrayCritical: " + "unrecognized elements"); + } + if (rsz != NULL) { + *rsz = guarded.get_user_size(); + } + return orig_result; +} + +static void* check_wrapped_array_release(JavaThread* thr, const char* fn_name, + void* obj, void* carray, jint mode) { + size_t sz; + void* orig_result = check_wrapped_array(thr, fn_name, obj, carray, &sz); + switch (mode) { + case 0: + memcpy(orig_result, carray, sz); + GuardedMemory::free_copy(carray); + break; + case JNI_COMMIT: + memcpy(orig_result, carray, sz); + break; + case JNI_ABORT: + GuardedMemory::free_copy(carray); + break; + default: + tty->print_cr("%s: Unrecognized mode %i releasing array " + PTR_FORMAT " elements " PTR_FORMAT, fn_name, mode, p2i(obj), p2i(carray)); + NativeReportJNIFatalError(thr, "Unrecognized array release mode"); + } + return orig_result; +} + oop jniCheck::validate_handle(JavaThread* thr, jobject obj) { if (JNIHandles::is_frame_handle(thr, obj) || JNIHandles::is_local_handle(thr, obj) || @@ -1314,7 +1383,7 @@ JNI_ENTRY_CHECKED(jsize, JNI_END // Arbitrary (but well-known) tag -const jint STRING_TAG = 0x47114711; +const void* STRING_TAG = (void*)0x47114711; JNI_ENTRY_CHECKED(const jchar *, checked_jni_GetStringChars(JNIEnv *env, @@ -1324,21 +1393,22 @@ JNI_ENTRY_CHECKED(const jchar *, IN_VM( checkString(thr, str); ) - jchar* newResult = NULL; + jchar* new_result = NULL; const jchar *result = UNCHECKED()->GetStringChars(env,str,isCopy); assert (isCopy == NULL || *isCopy == JNI_TRUE, "GetStringChars didn't return a copy as expected"); if (result != NULL) { size_t len = UNCHECKED()->GetStringLength(env,str) + 1; // + 1 for NULL termination - jint* tagLocation = (jint*) AllocateHeap(len * sizeof(jchar) + sizeof(jint), mtInternal); - *tagLocation = STRING_TAG; - newResult = (jchar*) (tagLocation + 1); - memcpy(newResult, result, len * sizeof(jchar)); + len *= sizeof(jchar); + new_result = (jchar*) GuardedMemory::wrap_copy(result, len, STRING_TAG); + if (new_result == NULL) { + vm_exit_out_of_memory(len, OOM_MALLOC_ERROR, "checked_jni_GetStringChars"); + } // Avoiding call to UNCHECKED()->ReleaseStringChars() since that will fire unexpected dtrace probes // Note that the dtrace arguments for the allocated memory will not match up with this solution. FreeHeap((char*)result); } functionExit(env); - return newResult; + return new_result; JNI_END JNI_ENTRY_CHECKED(void, @@ -1354,11 +1424,23 @@ JNI_ENTRY_CHECKED(void, UNCHECKED()->ReleaseStringChars(env,str,chars); } else { - jint* tagLocation = ((jint*) chars) - 1; - if (*tagLocation != STRING_TAG) { - NativeReportJNIFatalError(thr, "ReleaseStringChars called on something not allocated by GetStringChars"); - } - UNCHECKED()->ReleaseStringChars(env,str,(const jchar*)tagLocation); + GuardedMemory guarded((void*)chars); + if (guarded.verify_guards()) { + tty->print_cr("ReleaseStringChars: release chars failed bounds check. " + "string: " PTR_FORMAT " chars: " PTR_FORMAT, p2i(str), p2i(chars)); + guarded.print_on(tty); + NativeReportJNIFatalError(thr, "ReleaseStringChars: " + "release chars failed bounds check."); + } + if (guarded.get_tag() != STRING_TAG) { + tty->print_cr("ReleaseStringChars: called on something not allocated " + "by GetStringChars. string: " PTR_FORMAT " chars: " PTR_FORMAT, + p2i(str), p2i(chars)); + NativeReportJNIFatalError(thr, "ReleaseStringChars called on something " + "not allocated by GetStringChars"); + } + UNCHECKED()->ReleaseStringChars(env, str, + (const jchar*) guarded.release_for_freeing()); } functionExit(env); JNI_END @@ -1385,7 +1467,7 @@ JNI_ENTRY_CHECKED(jsize, JNI_END // Arbitrary (but well-known) tag - different than GetStringChars -const jint STRING_UTF_TAG = 0x48124812; +const void* STRING_UTF_TAG = (void*) 0x48124812; JNI_ENTRY_CHECKED(const char *, checked_jni_GetStringUTFChars(JNIEnv *env, @@ -1395,21 +1477,21 @@ JNI_ENTRY_CHECKED(const char *, IN_VM( checkString(thr, str); ) - char* newResult = NULL; + char* new_result = NULL; const char *result = UNCHECKED()->GetStringUTFChars(env,str,isCopy); assert (isCopy == NULL || *isCopy == JNI_TRUE, "GetStringUTFChars didn't return a copy as expected"); if (result != NULL) { size_t len = strlen(result) + 1; // + 1 for NULL termination - jint* tagLocation = (jint*) AllocateHeap(len + sizeof(jint), mtInternal); - *tagLocation = STRING_UTF_TAG; - newResult = (char*) (tagLocation + 1); - strcpy(newResult, result); + new_result = (char*) GuardedMemory::wrap_copy(result, len, STRING_UTF_TAG); + if (new_result == NULL) { + vm_exit_out_of_memory(len, OOM_MALLOC_ERROR, "checked_jni_GetStringUTFChars"); + } // Avoiding call to UNCHECKED()->ReleaseStringUTFChars() since that will fire unexpected dtrace probes // Note that the dtrace arguments for the allocated memory will not match up with this solution. FreeHeap((char*)result, mtInternal); } functionExit(env); - return newResult; + return new_result; JNI_END JNI_ENTRY_CHECKED(void, @@ -1425,11 +1507,23 @@ JNI_ENTRY_CHECKED(void, UNCHECKED()->ReleaseStringUTFChars(env,str,chars); } else { - jint* tagLocation = ((jint*) chars) - 1; - if (*tagLocation != STRING_UTF_TAG) { - NativeReportJNIFatalError(thr, "ReleaseStringUTFChars called on something not allocated by GetStringUTFChars"); - } - UNCHECKED()->ReleaseStringUTFChars(env,str,(const char*)tagLocation); + GuardedMemory guarded((void*)chars); + if (guarded.verify_guards()) { + tty->print_cr("ReleaseStringUTFChars: release chars failed bounds check. " + "string: " PTR_FORMAT " chars: " PTR_FORMAT, p2i(str), p2i(chars)); + guarded.print_on(tty); + NativeReportJNIFatalError(thr, "ReleaseStringUTFChars: " + "release chars failed bounds check."); + } + if (guarded.get_tag() != STRING_UTF_TAG) { + tty->print_cr("ReleaseStringUTFChars: called on something not " + "allocated by GetStringUTFChars. string: " PTR_FORMAT " chars: " + PTR_FORMAT, p2i(str), p2i(chars)); + NativeReportJNIFatalError(thr, "ReleaseStringUTFChars " + "called on something not allocated by GetStringUTFChars"); + } + UNCHECKED()->ReleaseStringUTFChars(env, str, + (const char*) guarded.release_for_freeing()); } functionExit(env); JNI_END @@ -1514,6 +1608,9 @@ JNI_ENTRY_CHECKED(ElementType *, \ ElementType *result = UNCHECKED()->Get##Result##ArrayElements(env, \ array, \ isCopy); \ + if (result != NULL) { \ + result = (ElementType *) check_jni_wrap_copy_array(thr, array, result); \ + } \ functionExit(env); \ return result; \ JNI_END @@ -1538,12 +1635,10 @@ JNI_ENTRY_CHECKED(void, \ check_primitive_array_type(thr, array, ElementTag); \ ASSERT_OOPS_ALLOWED; \ typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \ - /* cannot check validity of copy, unless every request is logged by - * checking code. Implementation of this check is deferred until a - * subsequent release. - */ \ ) \ - UNCHECKED()->Release##Result##ArrayElements(env,array,elems,mode); \ + ElementType* orig_result = (ElementType *) check_wrapped_array_release( \ + thr, "checked_jni_Release"#Result"ArrayElements", array, elems, mode); \ + UNCHECKED()->Release##Result##ArrayElements(env, array, orig_result, mode); \ functionExit(env); \ JNI_END @@ -1694,6 +1789,9 @@ JNI_ENTRY_CHECKED(void *, check_is_primitive_array(thr, array); ) void *result = UNCHECKED()->GetPrimitiveArrayCritical(env, array, isCopy); + if (result != NULL) { + result = check_jni_wrap_copy_array(thr, array, result); + } functionExit(env); return result; JNI_END @@ -1707,10 +1805,9 @@ JNI_ENTRY_CHECKED(void, IN_VM( check_is_primitive_array(thr, array); ) - /* The Hotspot JNI code does not use the parameters, so just check the - * array parameter as a minor sanity check - */ - UNCHECKED()->ReleasePrimitiveArrayCritical(env, array, carray, mode); + // Check the element array... + void* orig_result = check_wrapped_array_release(thr, "ReleasePrimitiveArrayCritical", array, carray, mode); + UNCHECKED()->ReleasePrimitiveArrayCritical(env, array, orig_result, mode); functionExit(env); JNI_END diff --git a/hotspot/src/share/vm/runtime/os.cpp b/hotspot/src/share/vm/runtime/os.cpp index 04c008431c7..dc5d664989b 100644 --- a/hotspot/src/share/vm/runtime/os.cpp +++ b/hotspot/src/share/vm/runtime/os.cpp @@ -32,6 +32,9 @@ #include "gc_implementation/shared/vmGCOperations.hpp" #include "interpreter/interpreter.hpp" #include "memory/allocation.inline.hpp" +#ifdef ASSERT +#include "memory/guardedMemory.hpp" +#endif #include "oops/oop.inline.hpp" #include "prims/jvm.h" #include "prims/jvm_misc.hpp" @@ -523,121 +526,20 @@ char *os::strdup(const char *str, MEMFLAGS flags) { } - -#ifdef ASSERT -#define space_before (MallocCushion + sizeof(double)) -#define space_after MallocCushion -#define size_addr_from_base(p) (size_t*)(p + space_before - sizeof(size_t)) -#define size_addr_from_obj(p) ((size_t*)p - 1) -// MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly -// NB: cannot be debug variable, because these aren't set from the command line until -// *after* the first few allocs already happened -#define MallocCushion 16 -#else -#define space_before 0 -#define space_after 0 -#define size_addr_from_base(p) should not use w/o ASSERT -#define size_addr_from_obj(p) should not use w/o ASSERT -#define MallocCushion 0 -#endif #define paranoid 0 /* only set to 1 if you suspect checking code has bug */ #ifdef ASSERT -inline size_t get_size(void* obj) { - size_t size = *size_addr_from_obj(obj); - if (size < 0) { - fatal(err_msg("free: size field of object #" PTR_FORMAT " was overwritten (" - SIZE_FORMAT ")", obj, size)); - } - return size; -} -u_char* find_cushion_backwards(u_char* start) { - u_char* p = start; - while (p[ 0] != badResourceValue || p[-1] != badResourceValue || - p[-2] != badResourceValue || p[-3] != badResourceValue) p--; - // ok, we have four consecutive marker bytes; find start - u_char* q = p - 4; - while (*q == badResourceValue) q--; - return q + 1; -} - -u_char* find_cushion_forwards(u_char* start) { - u_char* p = start; - while (p[0] != badResourceValue || p[1] != badResourceValue || - p[2] != badResourceValue || p[3] != badResourceValue) p++; - // ok, we have four consecutive marker bytes; find end of cushion - u_char* q = p + 4; - while (*q == badResourceValue) q++; - return q - MallocCushion; -} - -void print_neighbor_blocks(void* ptr) { - // find block allocated before ptr (not entirely crash-proof) - if (MallocCushion < 4) { - tty->print_cr("### cannot find previous block (MallocCushion < 4)"); - return; - } - u_char* start_of_this_block = (u_char*)ptr - space_before; - u_char* end_of_prev_block_data = start_of_this_block - space_after -1; - // look for cushion in front of prev. block - u_char* start_of_prev_block = find_cushion_backwards(end_of_prev_block_data); - ptrdiff_t size = *size_addr_from_base(start_of_prev_block); - u_char* obj = start_of_prev_block + space_before; - if (size <= 0 ) { - // start is bad; may have been confused by OS data in between objects - // search one more backwards - start_of_prev_block = find_cushion_backwards(start_of_prev_block); - size = *size_addr_from_base(start_of_prev_block); - obj = start_of_prev_block + space_before; - } - - if (start_of_prev_block + space_before + size + space_after == start_of_this_block) { - tty->print_cr("### previous object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size); - } else { - tty->print_cr("### previous object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size); - } - - // now find successor block - u_char* start_of_next_block = (u_char*)ptr + *size_addr_from_obj(ptr) + space_after; - start_of_next_block = find_cushion_forwards(start_of_next_block); - u_char* next_obj = start_of_next_block + space_before; - ptrdiff_t next_size = *size_addr_from_base(start_of_next_block); - if (start_of_next_block[0] == badResourceValue && - start_of_next_block[1] == badResourceValue && - start_of_next_block[2] == badResourceValue && - start_of_next_block[3] == badResourceValue) { - tty->print_cr("### next object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size); - } else { - tty->print_cr("### next object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size); +static void verify_memory(void* ptr) { + GuardedMemory guarded(ptr); + if (!guarded.verify_guards()) { + tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees); + tty->print_cr("## memory stomp:"); + guarded.print_on(tty); + fatal("memory stomping error"); } } - -void report_heap_error(void* memblock, void* bad, const char* where) { - tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees); - tty->print_cr("## memory stomp: byte at " PTR_FORMAT " %s object " PTR_FORMAT, bad, where, memblock); - print_neighbor_blocks(memblock); - fatal("memory stomping error"); -} - -void verify_block(void* memblock) { - size_t size = get_size(memblock); - if (MallocCushion) { - u_char* ptr = (u_char*)memblock - space_before; - for (int i = 0; i < MallocCushion; i++) { - if (ptr[i] != badResourceValue) { - report_heap_error(memblock, ptr+i, "in front of"); - } - } - u_char* end = (u_char*)memblock + size + space_after; - for (int j = -MallocCushion; j < 0; j++) { - if (end[j] != badResourceValue) { - report_heap_error(memblock, end+j, "after"); - } - } - } -} #endif // @@ -686,16 +588,18 @@ void* os::malloc(size_t size, MEMFLAGS memflags, address caller) { size = 1; } - const size_t alloc_size = size + space_before + space_after; - +#ifndef ASSERT + const size_t alloc_size = size; +#else + const size_t alloc_size = GuardedMemory::get_total_size(size); if (size > alloc_size) { // Check for rollover. return NULL; } +#endif NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap()); u_char* ptr; - if (MallocMaxTestWords > 0) { ptr = testMalloc(alloc_size); } else { @@ -703,28 +607,26 @@ void* os::malloc(size_t size, MEMFLAGS memflags, address caller) { } #ifdef ASSERT - if (ptr == NULL) return NULL; - if (MallocCushion) { - for (u_char* p = ptr; p < ptr + MallocCushion; p++) *p = (u_char)badResourceValue; - u_char* end = ptr + space_before + size; - for (u_char* pq = ptr+MallocCushion; pq < end; pq++) *pq = (u_char)uninitBlockPad; - for (u_char* q = end; q < end + MallocCushion; q++) *q = (u_char)badResourceValue; + if (ptr == NULL) { + return NULL; } - // put size just before data - *size_addr_from_base(ptr) = size; + // Wrap memory with guard + GuardedMemory guarded(ptr, size); + ptr = guarded.get_user_ptr(); #endif - u_char* memblock = ptr + space_before; - if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) { - tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock); + if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) { + tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr); breakpoint(); } - debug_only(if (paranoid) verify_block(memblock)); - if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock); + debug_only(if (paranoid) verify_memory(ptr)); + if (PrintMalloc && tty != NULL) { + tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr); + } - // we do not track MallocCushion memory - MemTracker::record_malloc((address)memblock, size, memflags, caller == 0 ? CALLER_PC : caller); + // we do not track guard memory + MemTracker::record_malloc((address)ptr, size, memflags, caller == 0 ? CALLER_PC : caller); - return memblock; + return ptr; } @@ -743,27 +645,32 @@ void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, address caller return ptr; #else if (memblock == NULL) { - return malloc(size, memflags, (caller == 0 ? CALLER_PC : caller)); + return os::malloc(size, memflags, (caller == 0 ? CALLER_PC : caller)); } if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) { tty->print_cr("os::realloc caught " PTR_FORMAT, memblock); breakpoint(); } - verify_block(memblock); + verify_memory(memblock); NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap()); - if (size == 0) return NULL; + if (size == 0) { + return NULL; + } // always move the block - void* ptr = malloc(size, memflags, caller == 0 ? CALLER_PC : caller); - if (PrintMalloc) tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr); + void* ptr = os::malloc(size, memflags, caller == 0 ? CALLER_PC : caller); + if (PrintMalloc) { + tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr); + } // Copy to new memory if malloc didn't fail if ( ptr != NULL ) { - memcpy(ptr, memblock, MIN2(size, get_size(memblock))); - if (paranoid) verify_block(ptr); + GuardedMemory guarded(memblock); + memcpy(ptr, memblock, MIN2(size, guarded.get_user_size())); + if (paranoid) verify_memory(ptr); if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) { tty->print_cr("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr); breakpoint(); } - free(memblock); + os::free(memblock); } return ptr; #endif @@ -771,6 +678,7 @@ void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, address caller void os::free(void *memblock, MEMFLAGS memflags) { + address trackp = (address) memblock; NOT_PRODUCT(inc_stat_counter(&num_frees, 1)); #ifdef ASSERT if (memblock == NULL) return; @@ -778,34 +686,20 @@ void os::free(void *memblock, MEMFLAGS memflags) { if (tty != NULL) tty->print_cr("os::free caught " PTR_FORMAT, memblock); breakpoint(); } - verify_block(memblock); + verify_memory(memblock); NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap()); - // Added by detlefs. - if (MallocCushion) { - u_char* ptr = (u_char*)memblock - space_before; - for (u_char* p = ptr; p < ptr + MallocCushion; p++) { - guarantee(*p == badResourceValue, - "Thing freed should be malloc result."); - *p = (u_char)freeBlockPad; - } - size_t size = get_size(memblock); - inc_stat_counter(&free_bytes, size); - u_char* end = ptr + space_before + size; - for (u_char* q = end; q < end + MallocCushion; q++) { - guarantee(*q == badResourceValue, - "Thing freed should be malloc result."); - *q = (u_char)freeBlockPad; - } - if (PrintMalloc && tty != NULL) + + GuardedMemory guarded(memblock); + size_t size = guarded.get_user_size(); + inc_stat_counter(&free_bytes, size); + memblock = guarded.release_for_freeing(); + if (PrintMalloc && tty != NULL) { fprintf(stderr, "os::free " SIZE_FORMAT " bytes --> " PTR_FORMAT "\n", size, (uintptr_t)memblock); - } else if (PrintMalloc && tty != NULL) { - // tty->print_cr("os::free %p", memblock); - fprintf(stderr, "os::free " PTR_FORMAT "\n", (uintptr_t)memblock); } #endif - MemTracker::record_free((address)memblock, memflags); + MemTracker::record_free(trackp, memflags); - ::free((char*)memblock - space_before); + ::free(memblock); } void os::init_random(long initval) { From b6a2f946f6c80c2dc54a3d315ea3dae5d30b6829 Mon Sep 17 00:00:00 2001 From: Harold Seigel Date: Wed, 11 Jun 2014 09:58:23 -0400 Subject: [PATCH 066/192] 8031819: Remove legacy jdk checks and code Delete old jdk specific code. Reviewed-by: dholmes, coleenp, zgu, lfoltan --- .../share/vm/classfile/classFileParser.cpp | 4 +- .../src/share/vm/classfile/classLoader.cpp | 98 +++---------------- .../src/share/vm/classfile/classLoader.hpp | 6 +- .../src/share/vm/classfile/javaClasses.cpp | 51 +++------- .../share/vm/classfile/systemDictionary.cpp | 2 - .../share/vm/classfile/systemDictionary.hpp | 23 +---- hotspot/src/share/vm/classfile/vmSymbols.hpp | 1 - .../src/share/vm/interpreter/linkResolver.cpp | 8 +- hotspot/src/share/vm/memory/universe.cpp | 8 -- hotspot/src/share/vm/oops/method.cpp | 3 +- hotspot/src/share/vm/prims/jvm.cpp | 44 --------- hotspot/src/share/vm/prims/unsafe.cpp | 62 +----------- hotspot/src/share/vm/runtime/arguments.cpp | 14 +-- hotspot/src/share/vm/runtime/java.hpp | 54 +--------- hotspot/src/share/vm/runtime/reflection.cpp | 81 ++------------- hotspot/src/share/vm/runtime/reflection.hpp | 3 - .../src/share/vm/runtime/reflectionUtils.cpp | 15 +-- .../src/share/vm/runtime/serviceThread.cpp | 5 +- hotspot/src/share/vm/runtime/thread.cpp | 78 ++++----------- hotspot/src/share/vm/runtime/vframe.cpp | 3 +- .../src/share/vm/runtime/vm_operations.cpp | 10 +- hotspot/src/share/vm/runtime/vm_version.cpp | 3 +- hotspot/src/share/vm/services/management.cpp | 12 +-- .../src/share/vm/services/threadService.cpp | 14 ++- 24 files changed, 95 insertions(+), 507 deletions(-) diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp index c7fe1c7d5a2..d72a50cbb52 100644 --- a/hotspot/src/share/vm/classfile/classFileParser.cpp +++ b/hotspot/src/share/vm/classfile/classFileParser.cpp @@ -4667,9 +4667,7 @@ bool ClassFileParser::has_illegal_visibility(jint flags) { } bool ClassFileParser::is_supported_version(u2 major, u2 minor) { - u2 max_version = - JDK_Version::is_gte_jdk17x_version() ? JAVA_MAX_SUPPORTED_VERSION : - (JDK_Version::is_gte_jdk16x_version() ? JAVA_6_VERSION : JAVA_1_5_VERSION); + u2 max_version = JAVA_MAX_SUPPORTED_VERSION; return (major >= JAVA_MIN_SUPPORTED_VERSION) && (major <= max_version) && ((major != max_version) || diff --git a/hotspot/src/share/vm/classfile/classLoader.cpp b/hotspot/src/share/vm/classfile/classLoader.cpp index 8366c8fc4ce..46d979ed1df 100644 --- a/hotspot/src/share/vm/classfile/classLoader.cpp +++ b/hotspot/src/share/vm/classfile/classLoader.cpp @@ -1126,7 +1126,7 @@ void ClassLoader::verify() { // JDK 1.3 version -typedef struct real_jzentry13 { /* Zip file entry */ +typedef struct real_jzentry { /* Zip file entry */ char *name; /* entry name */ jint time; /* modification time */ jint size; /* size of uncompressed data */ @@ -1135,9 +1135,9 @@ typedef struct real_jzentry13 { /* Zip file entry */ char *comment; /* optional zip file comment */ jbyte *extra; /* optional extra data */ jint pos; /* position of LOC header (if negative) or data */ -} real_jzentry13; +} real_jzentry; -typedef struct real_jzfile13 { /* Zip file */ +typedef struct real_jzfile { /* Zip file */ char *name; /* zip file name */ jint refs; /* number of active references */ jint fd; /* open file descriptor */ @@ -1148,42 +1148,14 @@ typedef struct real_jzfile13 { /* Zip file */ jint total; /* total number of entries */ unsigned short *table; /* Hash chain heads: indexes into entries */ jint tablelen; /* number of hash eads */ - real_jzfile13 *next; /* next zip file in search list */ + real_jzfile *next; /* next zip file in search list */ jzentry *cache; /* we cache the most recently freed jzentry */ /* Information on metadata names in META-INF directory */ char **metanames; /* array of meta names (may have null names) */ jint metacount; /* number of slots in metanames array */ /* If there are any per-entry comments, they are in the comments array */ char **comments; -} real_jzfile13; - -// JDK 1.2 version -typedef struct real_jzentry12 { /* Zip file entry */ - char *name; /* entry name */ - jint time; /* modification time */ - jint size; /* size of uncompressed data */ - jint csize; /* size of compressed data (zero if uncompressed) */ - jint crc; /* crc of uncompressed data */ - char *comment; /* optional zip file comment */ - jbyte *extra; /* optional extra data */ - jint pos; /* position of LOC header (if negative) or data */ - struct real_jzentry12 *next; /* next entry in hash table */ -} real_jzentry12; - -typedef struct real_jzfile12 { /* Zip file */ - char *name; /* zip file name */ - jint refs; /* number of active references */ - jint fd; /* open file descriptor */ - void *lock; /* read lock */ - char *comment; /* zip file comment */ - char *msg; /* zip error message */ - real_jzentry12 *entries; /* array of zip entries */ - jint total; /* total number of entries */ - real_jzentry12 **table; /* hash table of entries */ - jint tablelen; /* number of buckets */ - jzfile *next; /* next zip file in search list */ -} real_jzfile12; - +} real_jzfile; void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) { // For now we only compile all methods in all classes in zip/jar files @@ -1197,10 +1169,14 @@ bool ClassPathDirEntry::is_rt_jar() { } void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) { - if (JDK_Version::is_jdk12x_version()) { - compile_the_world12(loader, THREAD); - } else { - compile_the_world13(loader, THREAD); + real_jzfile* zip = (real_jzfile*) _zip; + tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name); + tty->cr(); + // Iterate over all entries in zip file + for (int n = 0; ; n++) { + real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n)); + if (ze == NULL) break; + ClassLoader::compile_the_world_in(ze->name, loader, CHECK); } if (HAS_PENDING_EXCEPTION) { if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) { @@ -1213,54 +1189,8 @@ void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) { } } -// Version that works for JDK 1.3.x -void ClassPathZipEntry::compile_the_world13(Handle loader, TRAPS) { - real_jzfile13* zip = (real_jzfile13*) _zip; - tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name); - tty->cr(); - // Iterate over all entries in zip file - for (int n = 0; ; n++) { - real_jzentry13 * ze = (real_jzentry13 *)((*GetNextEntry)(_zip, n)); - if (ze == NULL) break; - ClassLoader::compile_the_world_in(ze->name, loader, CHECK); - } -} - - -// Version that works for JDK 1.2.x -void ClassPathZipEntry::compile_the_world12(Handle loader, TRAPS) { - real_jzfile12* zip = (real_jzfile12*) _zip; - tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name); - tty->cr(); - // Iterate over all entries in zip file - for (int n = 0; ; n++) { - real_jzentry12 * ze = (real_jzentry12 *)((*GetNextEntry)(_zip, n)); - if (ze == NULL) break; - ClassLoader::compile_the_world_in(ze->name, loader, CHECK); - } -} - bool ClassPathZipEntry::is_rt_jar() { - if (JDK_Version::is_jdk12x_version()) { - return is_rt_jar12(); - } else { - return is_rt_jar13(); - } -} - -// JDK 1.3 version -bool ClassPathZipEntry::is_rt_jar13() { - real_jzfile13* zip = (real_jzfile13*) _zip; - int len = (int)strlen(zip->name); - // Check whether zip name ends in "rt.jar" - // This will match other archives named rt.jar as well, but this is - // only used for debugging. - return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0); -} - -// JDK 1.2 version -bool ClassPathZipEntry::is_rt_jar12() { - real_jzfile12* zip = (real_jzfile12*) _zip; + real_jzfile* zip = (real_jzfile*) _zip; int len = (int)strlen(zip->name); // Check whether zip name ends in "rt.jar" // This will match other archives named rt.jar as well, but this is diff --git a/hotspot/src/share/vm/classfile/classLoader.hpp b/hotspot/src/share/vm/classfile/classLoader.hpp index e03cfad1b57..2cfcde6387e 100644 --- a/hotspot/src/share/vm/classfile/classLoader.hpp +++ b/hotspot/src/share/vm/classfile/classLoader.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -111,11 +111,7 @@ class ClassPathZipEntry: public ClassPathEntry { void contents_do(void f(const char* name, void* context), void* context); // Debugging NOT_PRODUCT(void compile_the_world(Handle loader, TRAPS);) - NOT_PRODUCT(void compile_the_world12(Handle loader, TRAPS);) // JDK 1.2 version - NOT_PRODUCT(void compile_the_world13(Handle loader, TRAPS);) // JDK 1.3 version NOT_PRODUCT(bool is_rt_jar();) - NOT_PRODUCT(bool is_rt_jar12();) - NOT_PRODUCT(bool is_rt_jar13();) }; diff --git a/hotspot/src/share/vm/classfile/javaClasses.cpp b/hotspot/src/share/vm/classfile/javaClasses.cpp index 628ddf910b7..0e61ff9f391 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.cpp +++ b/hotspot/src/share/vm/classfile/javaClasses.cpp @@ -857,9 +857,7 @@ void java_lang_Class::compute_offsets() { } int java_lang_Class::classRedefinedCount(oop the_class_mirror) { - if (!JDK_Version::is_gte_jdk15x_version() - || classRedefinedCount_offset == -1) { - // The classRedefinedCount field is only present starting in 1.5. + if (classRedefinedCount_offset == -1) { // If we don't have an offset for it then just return -1 as a marker. return -1; } @@ -868,9 +866,7 @@ int java_lang_Class::classRedefinedCount(oop the_class_mirror) { } void java_lang_Class::set_classRedefinedCount(oop the_class_mirror, int value) { - if (!JDK_Version::is_gte_jdk15x_version() - || classRedefinedCount_offset == -1) { - // The classRedefinedCount field is only present starting in 1.5. + if (classRedefinedCount_offset == -1) { // If we don't have an offset for it then nothing to set. return; } @@ -1000,9 +996,7 @@ oop java_lang_Thread::inherited_access_control_context(oop java_thread) { jlong java_lang_Thread::stackSize(oop java_thread) { - // The stackSize field is only present starting in 1.4 if (_stackSize_offset > 0) { - assert(JDK_Version::is_gte_jdk14x_version(), "sanity check"); return java_thread->long_field(_stackSize_offset); } else { return 0; @@ -1078,7 +1072,7 @@ bool java_lang_Thread::set_park_event(oop java_thread, jlong ptr) { const char* java_lang_Thread::thread_status_name(oop java_thread) { - assert(JDK_Version::is_gte_jdk15x_version() && _thread_status_offset != 0, "Must have thread status"); + assert(_thread_status_offset != 0, "Must have thread status"); ThreadStatus status = (java_lang_Thread::ThreadStatus)java_thread->int_field(_thread_status_offset); switch (status) { case NEW : return "NEW"; @@ -1217,7 +1211,6 @@ void java_lang_Throwable::set_stacktrace(oop throwable, oop st_element_array) { } void java_lang_Throwable::clear_stacktrace(oop throwable) { - assert(JDK_Version::is_gte_jdk14x_version(), "should only be called in >= 1.4"); set_stacktrace(throwable, NULL); } @@ -1548,12 +1541,9 @@ void java_lang_Throwable::fill_in_stack_trace(Handle throwable, methodHandle met // Start out by clearing the backtrace for this object, in case the VM // runs out of memory while allocating the stack trace set_backtrace(throwable(), NULL); - if (JDK_Version::is_gte_jdk14x_version()) { - // New since 1.4, clear lazily constructed Java level stacktrace if - // refilling occurs - // This is unnecessary in 1.7+ but harmless - clear_stacktrace(throwable()); - } + // Clear lazily constructed Java level stacktrace if refilling occurs + // This is unnecessary in 1.7+ but harmless + clear_stacktrace(throwable()); int max_depth = MaxJavaStackTraceDepth; JavaThread* thread = (JavaThread*)THREAD; @@ -1739,13 +1729,9 @@ void java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(Handle t if (chunk_count >= max_chunks) break; } - // For Java 7+ we support the Throwable immutability protocol defined for Java 7. This support - // was missing in 7u0 so in 7u0 there is a workaround in the Throwable class. That workaround - // can be removed in a JDK using this JVM version - if (JDK_Version::is_gte_jdk17x_version()) { - java_lang_Throwable::set_stacktrace(throwable(), java_lang_Throwable::unassigned_stacktrace()); - assert(java_lang_Throwable::unassigned_stacktrace() != NULL, "not initialized"); - } + // We support the Throwable immutability protocol defined for Java 7. + java_lang_Throwable::set_stacktrace(throwable(), java_lang_Throwable::unassigned_stacktrace()); + assert(java_lang_Throwable::unassigned_stacktrace() != NULL, "not initialized"); } @@ -3022,8 +3008,7 @@ bool java_lang_ClassLoader::isAncestor(oop loader, oop cl) { // based on non-null field // Written to by java.lang.ClassLoader, vm only reads this field, doesn't set it bool java_lang_ClassLoader::parallelCapable(oop class_loader) { - if (!JDK_Version::is_gte_jdk17x_version() - || parallelCapable_offset == -1) { + if (parallelCapable_offset == -1) { // Default for backward compatibility is false return false; } @@ -3219,7 +3204,6 @@ void java_nio_Buffer::compute_offsets() { void java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(TRAPS) { if (_owner_offset != 0) return; - assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later"); SystemDictionary::load_abstract_ownable_synchronizer_klass(CHECK); Klass* k = SystemDictionary::abstract_ownable_synchronizer_klass(); compute_offset(_owner_offset, k, @@ -3309,15 +3293,10 @@ void JavaClasses::compute_offsets() { java_lang_reflect_Method::compute_offsets(); java_lang_reflect_Constructor::compute_offsets(); java_lang_reflect_Field::compute_offsets(); - if (JDK_Version::is_gte_jdk14x_version()) { - java_nio_Buffer::compute_offsets(); - } - if (JDK_Version::is_gte_jdk15x_version()) { - sun_reflect_ConstantPool::compute_offsets(); - sun_reflect_UnsafeStaticFieldAccessorImpl::compute_offsets(); - } - if (JDK_Version::is_gte_jdk18x_version()) - java_lang_reflect_Parameter::compute_offsets(); + java_nio_Buffer::compute_offsets(); + sun_reflect_ConstantPool::compute_offsets(); + sun_reflect_UnsafeStaticFieldAccessorImpl::compute_offsets(); + java_lang_reflect_Parameter::compute_offsets(); // generated interpreter code wants to know about the offsets we just computed: AbstractAssembler::update_delayed_values(); @@ -3502,7 +3481,7 @@ void JavaClasses::check_offsets() { // into merlin "for some time." Without it, the vm will fail with early // merlin builds. - if (CheckAssertionStatusDirectives && JDK_Version::is_gte_jdk14x_version()) { + if (CheckAssertionStatusDirectives) { const char* nm = "java/lang/AssertionStatusDirectives"; const char* sig = "[Ljava/lang/String;"; CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, classes, sig); diff --git a/hotspot/src/share/vm/classfile/systemDictionary.cpp b/hotspot/src/share/vm/classfile/systemDictionary.cpp index d09de41114d..9a6fa98908b 100644 --- a/hotspot/src/share/vm/classfile/systemDictionary.cpp +++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp @@ -1754,8 +1754,6 @@ void SystemDictionary::methods_do(void f(Method*)) { // Lazily load klasses void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) { - assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later"); - // if multiple threads calling this function, only one thread will load // the class. The other threads will find the loaded version once the // class is loaded. diff --git a/hotspot/src/share/vm/classfile/systemDictionary.hpp b/hotspot/src/share/vm/classfile/systemDictionary.hpp index 4e1b75dc241..f26a9d8c56e 100644 --- a/hotspot/src/share/vm/classfile/systemDictionary.hpp +++ b/hotspot/src/share/vm/classfile/systemDictionary.hpp @@ -139,14 +139,13 @@ class Ticks; do_klass(reflect_Constructor_klass, java_lang_reflect_Constructor, Pre ) \ \ /* NOTE: needed too early in bootstrapping process to have checks based on JDK version */ \ - /* Universe::is_gte_jdk14x_version() is not set up by this point. */ \ /* It's okay if this turns out to be NULL in non-1.4 JDKs. */ \ do_klass(reflect_MagicAccessorImpl_klass, sun_reflect_MagicAccessorImpl, Opt ) \ - do_klass(reflect_MethodAccessorImpl_klass, sun_reflect_MethodAccessorImpl, Opt_Only_JDK14NewRef) \ - do_klass(reflect_ConstructorAccessorImpl_klass, sun_reflect_ConstructorAccessorImpl, Opt_Only_JDK14NewRef) \ + do_klass(reflect_MethodAccessorImpl_klass, sun_reflect_MethodAccessorImpl, Pre ) \ + do_klass(reflect_ConstructorAccessorImpl_klass, sun_reflect_ConstructorAccessorImpl, Pre ) \ do_klass(reflect_DelegatingClassLoader_klass, sun_reflect_DelegatingClassLoader, Opt ) \ - do_klass(reflect_ConstantPool_klass, sun_reflect_ConstantPool, Opt_Only_JDK15 ) \ - do_klass(reflect_UnsafeStaticFieldAccessorImpl_klass, sun_reflect_UnsafeStaticFieldAccessorImpl, Opt_Only_JDK15 ) \ + do_klass(reflect_ConstantPool_klass, sun_reflect_ConstantPool, Opt ) \ + do_klass(reflect_UnsafeStaticFieldAccessorImpl_klass, sun_reflect_UnsafeStaticFieldAccessorImpl, Opt ) \ do_klass(reflect_CallerSensitive_klass, sun_reflect_CallerSensitive, Opt ) \ \ /* support for dynamic typing; it's OK if these are NULL in earlier JDKs */ \ @@ -169,7 +168,6 @@ class Ticks; \ /* It's NULL in non-1.4 JDKs. */ \ do_klass(StackTraceElement_klass, java_lang_StackTraceElement, Opt ) \ - /* Universe::is_gte_jdk14x_version() is not set up by this point. */ \ /* It's okay if this turns out to be NULL in non-1.4 JDKs. */ \ do_klass(nio_Buffer_klass, java_nio_Buffer, Opt ) \ \ @@ -209,10 +207,8 @@ class SystemDictionary : AllStatic { // Options after this point will use resolve_or_null instead. Opt, // preload tried; NULL if not present - Opt_Only_JDK14NewRef, // preload tried; use only with NewReflection - Opt_Only_JDK15, // preload tried; use only with JDK1.5+ OPTION_LIMIT, - CEIL_LG_OPTION_LIMIT = 4 // OPTION_LIMIT <= (1<is_anonymous() ? current_klass() : InstanceKlass::cast(current_klass())->host_klass(); - // As of the fix for 4486457 we disable verification for all of the - // dynamically-generated bytecodes associated with the 1.4 - // reflection implementation, not just those associated with - // sun/reflect/SerializationConstructorAccessor. - bool is_reflect = JDK_Version::is_gte_jdk14x_version() && - klass_to_check->is_subclass_of( + // Disable verification for the dynamically-generated reflection bytecodes. + bool is_reflect = klass_to_check->is_subclass_of( SystemDictionary::reflect_MagicAccessorImpl_klass()); if (!is_reflect && diff --git a/hotspot/src/share/vm/memory/universe.cpp b/hotspot/src/share/vm/memory/universe.cpp index 0250f1a1b8d..5053b46e8c8 100644 --- a/hotspot/src/share/vm/memory/universe.cpp +++ b/hotspot/src/share/vm/memory/universe.cpp @@ -1000,9 +1000,6 @@ void universe2_init() { } -// This function is defined in JVM.cpp -extern void initialize_converter_functions(); - bool universe_post_init() { assert(!is_init_completed(), "Error: initialization not yet completed!"); Universe::_fully_initialized = true; @@ -1144,11 +1141,6 @@ bool universe_post_init() { SystemDictionary::ProtectionDomain_klass(), m);; } - // The following is initializing converter functions for serialization in - // JVM.cpp. If we clean up the StrictMath code above we may want to find - // a better solution for this as well. - initialize_converter_functions(); - // This needs to be done before the first scavenge/gc, since // it's an input to soft ref clearing policy. { diff --git a/hotspot/src/share/vm/oops/method.cpp b/hotspot/src/share/vm/oops/method.cpp index 01ef61f2386..4549c68871f 100644 --- a/hotspot/src/share/vm/oops/method.cpp +++ b/hotspot/src/share/vm/oops/method.cpp @@ -1023,8 +1023,7 @@ bool Method::is_ignored_by_security_stack_walk() const { // This is Method.invoke() -- ignore it return true; } - if (JDK_Version::is_gte_jdk14x_version() && - method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) { + if (method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) { // This is an auxilary frame -- ignore it return true; } diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp index 5b96377b24a..69e45bd11f7 100644 --- a/hotspot/src/share/vm/prims/jvm.cpp +++ b/hotspot/src/share/vm/prims/jvm.cpp @@ -3923,50 +3923,6 @@ JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) { } -// Support for Serialization - -typedef jfloat (JNICALL *IntBitsToFloatFn )(JNIEnv* env, jclass cb, jint value); -typedef jdouble (JNICALL *LongBitsToDoubleFn)(JNIEnv* env, jclass cb, jlong value); -typedef jint (JNICALL *FloatToIntBitsFn )(JNIEnv* env, jclass cb, jfloat value); -typedef jlong (JNICALL *DoubleToLongBitsFn)(JNIEnv* env, jclass cb, jdouble value); - -static IntBitsToFloatFn int_bits_to_float_fn = NULL; -static LongBitsToDoubleFn long_bits_to_double_fn = NULL; -static FloatToIntBitsFn float_to_int_bits_fn = NULL; -static DoubleToLongBitsFn double_to_long_bits_fn = NULL; - - -void initialize_converter_functions() { - if (JDK_Version::is_gte_jdk14x_version()) { - // These functions only exist for compatibility with 1.3.1 and earlier - return; - } - - // called from universe_post_init() - assert( - int_bits_to_float_fn == NULL && - long_bits_to_double_fn == NULL && - float_to_int_bits_fn == NULL && - double_to_long_bits_fn == NULL , - "initialization done twice" - ); - // initialize - int_bits_to_float_fn = CAST_TO_FN_PTR(IntBitsToFloatFn , NativeLookup::base_library_lookup("java/lang/Float" , "intBitsToFloat" , "(I)F")); - long_bits_to_double_fn = CAST_TO_FN_PTR(LongBitsToDoubleFn, NativeLookup::base_library_lookup("java/lang/Double", "longBitsToDouble", "(J)D")); - float_to_int_bits_fn = CAST_TO_FN_PTR(FloatToIntBitsFn , NativeLookup::base_library_lookup("java/lang/Float" , "floatToIntBits" , "(F)I")); - double_to_long_bits_fn = CAST_TO_FN_PTR(DoubleToLongBitsFn, NativeLookup::base_library_lookup("java/lang/Double", "doubleToLongBits", "(D)J")); - // verify - assert( - int_bits_to_float_fn != NULL && - long_bits_to_double_fn != NULL && - float_to_int_bits_fn != NULL && - double_to_long_bits_fn != NULL , - "initialization failed" - ); -} - - - // Shared JNI/JVM entry points ////////////////////////////////////////////////////////////// jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init, Handle loader, Handle protection_domain, jboolean throwError, TRAPS) { diff --git a/hotspot/src/share/vm/prims/unsafe.cpp b/hotspot/src/share/vm/prims/unsafe.cpp index 4dd10cfca57..332f8fb74ab 100644 --- a/hotspot/src/share/vm/prims/unsafe.cpp +++ b/hotspot/src/share/vm/prims/unsafe.cpp @@ -185,64 +185,7 @@ jint Unsafe_invocation_key_to_method_slot(jint key) { // Get/SetObject must be special-cased, since it works with handles. -// The xxx140 variants for backward compatibility do not allow a full-width offset. -UNSAFE_ENTRY(jobject, Unsafe_GetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset)) - UnsafeWrapper("Unsafe_GetObject"); - if (obj == NULL) THROW_0(vmSymbols::java_lang_NullPointerException()); - GET_OOP_FIELD(obj, offset, v) - jobject ret = JNIHandles::make_local(env, v); -#if INCLUDE_ALL_GCS - // We could be accessing the referent field in a reference - // object. If G1 is enabled then we need to register a non-null - // referent with the SATB barrier. - if (UseG1GC) { - bool needs_barrier = false; - - if (ret != NULL) { - if (offset == java_lang_ref_Reference::referent_offset) { - oop o = JNIHandles::resolve_non_null(obj); - Klass* k = o->klass(); - if (InstanceKlass::cast(k)->reference_type() != REF_NONE) { - assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity"); - needs_barrier = true; - } - } - } - - if (needs_barrier) { - oop referent = JNIHandles::resolve(ret); - G1SATBCardTableModRefBS::enqueue(referent); - } - } -#endif // INCLUDE_ALL_GCS - return ret; -UNSAFE_END - -UNSAFE_ENTRY(void, Unsafe_SetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jobject x_h)) - UnsafeWrapper("Unsafe_SetObject"); - if (obj == NULL) THROW(vmSymbols::java_lang_NullPointerException()); - oop x = JNIHandles::resolve(x_h); - //SET_FIELD(obj, offset, oop, x); - oop p = JNIHandles::resolve(obj); - if (UseCompressedOops) { - if (x != NULL) { - // If there is a heap base pointer, we are obliged to emit a store barrier. - oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x); - } else { - narrowOop n = oopDesc::encode_heap_oop_not_null(x); - *(narrowOop*)index_oop_from_field_offset_long(p, offset) = n; - } - } else { - if (x != NULL) { - // If there is a heap base pointer, we are obliged to emit a store barrier. - oop_store((oop*)index_oop_from_field_offset_long(p, offset), x); - } else { - *(oop*)index_oop_from_field_offset_long(p, offset) = x; - } - } -UNSAFE_END - -// The normal variants allow a null base pointer with an arbitrary address. +// These functions allow a null base pointer with an arbitrary address. // But if the base pointer is non-null, the offset should make some sense. // That is, it should be in the range [0, MAX_OBJECT_SIZE]. UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) @@ -1350,9 +1293,6 @@ UNSAFE_END // These are the methods for 1.4.0 static JNINativeMethod methods_140[] = { - {CC"getObject", CC"("OBJ"I)"OBJ"", FN_PTR(Unsafe_GetObject140)}, - {CC"putObject", CC"("OBJ"I"OBJ")V", FN_PTR(Unsafe_SetObject140)}, - DECLARE_GETSETOOP_140(Boolean, Z), DECLARE_GETSETOOP_140(Byte, B), DECLARE_GETSETOOP_140(Short, S), diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 91e485e7aed..88f1bfb400f 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -222,10 +222,8 @@ void Arguments::init_version_specific_system_properties() { const char* spec_vendor = "Sun Microsystems Inc."; uint32_t spec_version = 0; - if (JDK_Version::is_gte_jdk17x_version()) { - spec_vendor = "Oracle Corporation"; - spec_version = JDK_Version::current().major_version(); - } + spec_vendor = "Oracle Corporation"; + spec_version = JDK_Version::current().major_version(); jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version); PropertyList_add(&_system_properties, @@ -3695,14 +3693,6 @@ jint Arguments::parse(const JavaVMInitArgs* args) { PrintGC = true; } - if (!JDK_Version::is_gte_jdk18x_version()) { - // To avoid changing the log format for 7 updates this flag is only - // true by default in JDK8 and above. - if (FLAG_IS_DEFAULT(PrintGCCause)) { - FLAG_SET_DEFAULT(PrintGCCause, false); - } - } - // Set object alignment values. set_object_alignment(); diff --git a/hotspot/src/share/vm/runtime/java.hpp b/hotspot/src/share/vm/runtime/java.hpp index e5bae38c171..02ac99ebb60 100644 --- a/hotspot/src/share/vm/runtime/java.hpp +++ b/hotspot/src/share/vm/runtime/java.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -197,58 +197,6 @@ class JDK_Version VALUE_OBJ_CLASS_SPEC { _runtime_version = version; } - // Convenience methods for queries on the current major/minor version - static bool is_jdk12x_version() { - return current().compare_major(2) == 0; - } - - static bool is_jdk13x_version() { - return current().compare_major(3) == 0; - } - - static bool is_jdk14x_version() { - return current().compare_major(4) == 0; - } - - static bool is_jdk15x_version() { - return current().compare_major(5) == 0; - } - - static bool is_jdk16x_version() { - return current().compare_major(6) == 0; - } - - static bool is_jdk17x_version() { - return current().compare_major(7) == 0; - } - - static bool is_jdk18x_version() { - return current().compare_major(8) == 0; - } - - static bool is_gte_jdk13x_version() { - return current().compare_major(3) >= 0; - } - - static bool is_gte_jdk14x_version() { - return current().compare_major(4) >= 0; - } - - static bool is_gte_jdk15x_version() { - return current().compare_major(5) >= 0; - } - - static bool is_gte_jdk16x_version() { - return current().compare_major(6) >= 0; - } - - static bool is_gte_jdk17x_version() { - return current().compare_major(7) >= 0; - } - - static bool is_gte_jdk18x_version() { - return current().compare_major(8) >= 0; - } }; #endif // SHARE_VM_RUNTIME_JAVA_HPP diff --git a/hotspot/src/share/vm/runtime/reflection.cpp b/hotspot/src/share/vm/runtime/reflection.cpp index 872d73c72e8..cc35fea494b 100644 --- a/hotspot/src/share/vm/runtime/reflection.cpp +++ b/hotspot/src/share/vm/runtime/reflection.cpp @@ -410,49 +410,6 @@ oop Reflection::array_component_type(oop mirror, TRAPS) { } -bool Reflection::reflect_check_access(Klass* field_class, AccessFlags acc, Klass* target_class, bool is_method_invoke, TRAPS) { - // field_class : declaring class - // acc : declared field access - // target_class : for protected - - // Check if field or method is accessible to client. Throw an - // IllegalAccessException and return false if not. - - // The "client" is the class associated with the nearest real frame - // getCallerClass already skips Method.invoke frames, so pass 0 in - // that case (same as classic). - ResourceMark rm(THREAD); - assert(THREAD->is_Java_thread(), "sanity check"); - Klass* client_class = ((JavaThread *)THREAD)->security_get_caller_class(is_method_invoke ? 0 : 1); - - if (client_class != field_class) { - if (!verify_class_access(client_class, field_class, false) - || !verify_field_access(client_class, - field_class, - field_class, - acc, - false)) { - THROW_(vmSymbols::java_lang_IllegalAccessException(), false); - } - } - - // Additional test for protected members: JLS 6.6.2 - - if (acc.is_protected()) { - if (target_class != client_class) { - if (!is_same_class_package(client_class, field_class)) { - if (!target_class->is_subclass_of(client_class)) { - THROW_(vmSymbols::java_lang_IllegalAccessException(), false); - } - } - } - } - - // Passed all tests - return true; -} - - bool Reflection::verify_class_access(Klass* current_class, Klass* new_class, bool classloader_only) { // Verify that current_class can access new_class. If the classloader_only // flag is set, we automatically allow any accesses in which current_class @@ -463,10 +420,9 @@ bool Reflection::verify_class_access(Klass* current_class, Klass* new_class, boo is_same_class_package(current_class, new_class)) { return true; } - // New (1.4) reflection implementation. Allow all accesses from - // sun/reflect/MagicAccessorImpl subclasses to succeed trivially. - if ( JDK_Version::is_gte_jdk14x_version() - && current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) { + // Allow all accesses from sun/reflect/MagicAccessorImpl subclasses to + // succeed trivially. + if (current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) { return true; } @@ -567,10 +523,9 @@ bool Reflection::verify_field_access(Klass* current_class, return true; } - // New (1.4) reflection implementation. Allow all accesses from - // sun/reflect/MagicAccessorImpl subclasses to succeed trivially. - if ( JDK_Version::is_gte_jdk14x_version() - && current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) { + // Allow all accesses from sun/reflect/MagicAccessorImpl subclasses to + // succeed trivially. + if (current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) { return true; } @@ -707,12 +662,10 @@ Handle Reflection::new_type(Symbol* signature, KlassHandle k, TRAPS) { oop Reflection::new_method(methodHandle method, bool for_constant_pool_access, TRAPS) { - // In jdk1.2.x, getMethods on an interface erroneously includes , thus the complicated assert. - // Also allow sun.reflect.ConstantPool to refer to methods as java.lang.reflect.Methods. + // Allow sun.reflect.ConstantPool to refer to methods as java.lang.reflect.Methods. assert(!method()->is_initializer() || - (for_constant_pool_access && method()->is_static()) || - (method()->name() == vmSymbols::class_initializer_name() - && method()->method_holder()->is_interface() && JDK_Version::is_jdk12x_version()), "should call new_constructor instead"); + (for_constant_pool_access && method()->is_static()), + "should call new_constructor instead"); instanceKlassHandle holder (THREAD, method->method_holder()); int slot = method->method_idnum(); @@ -978,22 +931,6 @@ oop Reflection::invoke(instanceKlassHandle klass, methodHandle reflected_method, reflected_method->signature())); } - // In the JDK 1.4 reflection implementation, the security check is - // done at the Java level - if (!JDK_Version::is_gte_jdk14x_version()) { - - // Access checking (unless overridden by Method) - if (!override) { - if (!(klass->is_public() && reflected_method->is_public())) { - bool access = Reflection::reflect_check_access(klass(), reflected_method->access_flags(), target_klass(), is_method_invoke, CHECK_NULL); - if (!access) { - return NULL; // exception - } - } - } - - } // !Universe::is_gte_jdk14x_version() - assert(ptypes->is_objArray(), "just checking"); int args_len = args.is_null() ? 0 : args->length(); // Check number of arguments diff --git a/hotspot/src/share/vm/runtime/reflection.hpp b/hotspot/src/share/vm/runtime/reflection.hpp index 5757cfc39f5..593ff7ecc49 100644 --- a/hotspot/src/share/vm/runtime/reflection.hpp +++ b/hotspot/src/share/vm/runtime/reflection.hpp @@ -44,9 +44,6 @@ class FieldStream; class Reflection: public AllStatic { private: - // Access checking - static bool reflect_check_access(Klass* field_class, AccessFlags acc, Klass* target_class, bool is_method_invoke, TRAPS); - // Conversion static Klass* basic_type_mirror_to_arrayklass(oop basic_type_mirror, TRAPS); static oop basic_type_arrayklass_to_mirror(Klass* basic_type_arrayklass, TRAPS); diff --git a/hotspot/src/share/vm/runtime/reflectionUtils.cpp b/hotspot/src/share/vm/runtime/reflectionUtils.cpp index 2ec82abc91a..331d5a750a0 100644 --- a/hotspot/src/share/vm/runtime/reflectionUtils.cpp +++ b/hotspot/src/share/vm/runtime/reflectionUtils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -76,15 +76,10 @@ void FilteredFieldsMap::initialize() { int offset; offset = java_lang_Throwable::get_backtrace_offset(); _filtered_fields->append(new FilteredField(SystemDictionary::Throwable_klass(), offset)); - // The latest version of vm may be used with old jdk. - if (JDK_Version::is_gte_jdk16x_version()) { - // The following class fields do not exist in - // previous version of jdk. - offset = sun_reflect_ConstantPool::oop_offset(); - _filtered_fields->append(new FilteredField(SystemDictionary::reflect_ConstantPool_klass(), offset)); - offset = sun_reflect_UnsafeStaticFieldAccessorImpl::base_offset(); - _filtered_fields->append(new FilteredField(SystemDictionary::reflect_UnsafeStaticFieldAccessorImpl_klass(), offset)); - } + offset = sun_reflect_ConstantPool::oop_offset(); + _filtered_fields->append(new FilteredField(SystemDictionary::reflect_ConstantPool_klass(), offset)); + offset = sun_reflect_UnsafeStaticFieldAccessorImpl::base_offset(); + _filtered_fields->append(new FilteredField(SystemDictionary::reflect_UnsafeStaticFieldAccessorImpl_klass(), offset)); } int FilteredFieldStream::field_count() { diff --git a/hotspot/src/share/vm/runtime/serviceThread.cpp b/hotspot/src/share/vm/runtime/serviceThread.cpp index 3c1224abb2c..eb7cb4a439c 100644 --- a/hotspot/src/share/vm/runtime/serviceThread.cpp +++ b/hotspot/src/share/vm/runtime/serviceThread.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,8 +41,7 @@ void ServiceThread::initialize() { instanceKlassHandle klass (THREAD, SystemDictionary::Thread_klass()); instanceHandle thread_oop = klass->allocate_instance_handle(CHECK); - const char* name = JDK_Version::is_gte_jdk17x_version() ? - "Service Thread" : "Low Memory Detector"; + const char* name = "Service Thread"; Handle string = java_lang_String::create_from_str(name, CHECK); diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp index e9e9d22f197..061509ae144 100644 --- a/hotspot/src/share/vm/runtime/thread.cpp +++ b/hotspot/src/share/vm/runtime/thread.cpp @@ -1738,55 +1738,26 @@ void JavaThread::exit(bool destroy_vm, ExitType exit_type) { CLEAR_PENDING_EXCEPTION; } - // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This - // has to be fixed by a runtime query method - if (!destroy_vm || JDK_Version::is_jdk12x_version()) { - // JSR-166: change call from from ThreadGroup.uncaughtException to - // java.lang.Thread.dispatchUncaughtException + if (!destroy_vm) { if (uncaught_exception.not_null()) { - Handle group(this, java_lang_Thread::threadGroup(threadObj())); - { - EXCEPTION_MARK; - // Check if the method Thread.dispatchUncaughtException() exists. If so - // call it. Otherwise we have an older library without the JSR-166 changes, - // so call ThreadGroup.uncaughtException() - KlassHandle recvrKlass(THREAD, threadObj->klass()); - CallInfo callinfo; - KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass()); - LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass, - vmSymbols::dispatchUncaughtException_name(), - vmSymbols::throwable_void_signature(), - KlassHandle(), false, false, THREAD); + EXCEPTION_MARK; + // Call method Thread.dispatchUncaughtException(). + KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass()); + JavaValue result(T_VOID); + JavaCalls::call_virtual(&result, + threadObj, thread_klass, + vmSymbols::dispatchUncaughtException_name(), + vmSymbols::throwable_void_signature(), + uncaught_exception, + THREAD); + if (HAS_PENDING_EXCEPTION) { + ResourceMark rm(this); + jio_fprintf(defaultStream::error_stream(), + "\nException: %s thrown from the UncaughtExceptionHandler" + " in thread \"%s\"\n", + pending_exception()->klass()->external_name(), + get_thread_name()); CLEAR_PENDING_EXCEPTION; - methodHandle method = callinfo.selected_method(); - if (method.not_null()) { - JavaValue result(T_VOID); - JavaCalls::call_virtual(&result, - threadObj, thread_klass, - vmSymbols::dispatchUncaughtException_name(), - vmSymbols::throwable_void_signature(), - uncaught_exception, - THREAD); - } else { - KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass()); - JavaValue result(T_VOID); - JavaCalls::call_virtual(&result, - group, thread_group, - vmSymbols::uncaughtException_name(), - vmSymbols::thread_throwable_void_signature(), - threadObj, // Arg 1 - uncaught_exception, // Arg 2 - THREAD); - } - if (HAS_PENDING_EXCEPTION) { - ResourceMark rm(this); - jio_fprintf(defaultStream::error_stream(), - "\nException: %s thrown from the UncaughtExceptionHandler" - " in thread \"%s\"\n", - pending_exception()->klass()->external_name(), - get_thread_name()); - CLEAR_PENDING_EXCEPTION; - } } } @@ -2848,7 +2819,7 @@ void JavaThread::print_on(outputStream *st) const { Thread::print_on(st); // print guess for valid stack memory region (assume 4K pages); helps lock debugging st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12)); - if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) { + if (thread_oop != NULL) { st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop)); } #ifndef PRODUCT @@ -3948,15 +3919,8 @@ bool Threads::destroy_vm() { } os::wait_for_keypress_at_exit(); - if (JDK_Version::is_jdk12x_version()) { - // We are the last thread running, so check if finalizers should be run. - // For 1.3 or later this is done in thread->invoke_shutdown_hooks() - HandleMark rm(thread); - Universe::run_finalizers_on_exit(); - } else { - // run Java level shutdown hooks - thread->invoke_shutdown_hooks(); - } + // run Java level shutdown hooks + thread->invoke_shutdown_hooks(); before_exit(thread); diff --git a/hotspot/src/share/vm/runtime/vframe.cpp b/hotspot/src/share/vm/runtime/vframe.cpp index 79da635c443..57900245436 100644 --- a/hotspot/src/share/vm/runtime/vframe.cpp +++ b/hotspot/src/share/vm/runtime/vframe.cpp @@ -480,9 +480,8 @@ void vframeStreamCommon::skip_prefixed_method_and_wrappers() { void vframeStreamCommon::skip_reflection_related_frames() { while (!at_end() && - (JDK_Version::is_gte_jdk14x_version() && (method()->method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass()) || - method()->method_holder()->is_subclass_of(SystemDictionary::reflect_ConstructorAccessorImpl_klass())))) { + method()->method_holder()->is_subclass_of(SystemDictionary::reflect_ConstructorAccessorImpl_klass()))) { next(); } } diff --git a/hotspot/src/share/vm/runtime/vm_operations.cpp b/hotspot/src/share/vm/runtime/vm_operations.cpp index d46e1f775ac..6f27fe3fecc 100644 --- a/hotspot/src/share/vm/runtime/vm_operations.cpp +++ b/hotspot/src/share/vm/runtime/vm_operations.cpp @@ -184,9 +184,7 @@ bool VM_PrintThreads::doit_prologue() { assert(Thread::current()->is_Java_thread(), "just checking"); // Make sure AbstractOwnableSynchronizer is loaded - if (JDK_Version::is_gte_jdk16x_version()) { - java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); - } + java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); // Get Heap_lock if concurrent locks will be dumped if (_print_concurrent_locks) { @@ -225,7 +223,7 @@ bool VM_FindDeadlocks::doit_prologue() { assert(Thread::current()->is_Java_thread(), "just checking"); // Load AbstractOwnableSynchronizer class - if (_concurrent_locks && JDK_Version::is_gte_jdk16x_version()) { + if (_concurrent_locks) { java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); } @@ -283,9 +281,7 @@ bool VM_ThreadDump::doit_prologue() { assert(Thread::current()->is_Java_thread(), "just checking"); // Load AbstractOwnableSynchronizer class before taking thread snapshots - if (JDK_Version::is_gte_jdk16x_version()) { - java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); - } + java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); if (_with_locked_synchronizers) { // Acquire Heap_lock to dump concurrent locks diff --git a/hotspot/src/share/vm/runtime/vm_version.cpp b/hotspot/src/share/vm/runtime/vm_version.cpp index 03fd43355bf..9fee996f687 100644 --- a/hotspot/src/share/vm/runtime/vm_version.cpp +++ b/hotspot/src/share/vm/runtime/vm_version.cpp @@ -160,8 +160,7 @@ const char* Abstract_VM_Version::vm_vendor() { #ifdef VENDOR return XSTR(VENDOR); #else - return JDK_Version::is_gte_jdk17x_version() ? - "Oracle Corporation" : "Sun Microsystems Inc."; + return "Oracle Corporation"; #endif } diff --git a/hotspot/src/share/vm/services/management.cpp b/hotspot/src/share/vm/services/management.cpp index dc901876104..2d6f2ff1d23 100644 --- a/hotspot/src/share/vm/services/management.cpp +++ b/hotspot/src/share/vm/services/management.cpp @@ -1229,10 +1229,8 @@ JVM_ENTRY(jint, jmm_GetThreadInfo(JNIEnv *env, jlongArray ids, jint maxDepth, jo "The length of the given ThreadInfo array does not match the length of the given array of thread IDs", -1); } - if (JDK_Version::is_gte_jdk16x_version()) { - // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots - java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_0); - } + // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots + java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_0); // Must use ThreadDumpResult to store the ThreadSnapshot. // GC may occur after the thread snapshots are taken but before @@ -1303,10 +1301,8 @@ JVM_END JVM_ENTRY(jobjectArray, jmm_DumpThreads(JNIEnv *env, jlongArray thread_ids, jboolean locked_monitors, jboolean locked_synchronizers)) ResourceMark rm(THREAD); - if (JDK_Version::is_gte_jdk16x_version()) { - // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots - java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_NULL); - } + // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots + java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_NULL); typeArrayOop ta = typeArrayOop(JNIHandles::resolve(thread_ids)); int num_threads = (ta != NULL ? ta->length() : 0); diff --git a/hotspot/src/share/vm/services/threadService.cpp b/hotspot/src/share/vm/services/threadService.cpp index 02156a2f3e2..21d87567eed 100644 --- a/hotspot/src/share/vm/services/threadService.cpp +++ b/hotspot/src/share/vm/services/threadService.cpp @@ -665,17 +665,15 @@ void ConcurrentLocksDump::dump_at_safepoint() { // dump all locked concurrent locks assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); - if (JDK_Version::is_gte_jdk16x_version()) { - ResourceMark rm; + ResourceMark rm; - GrowableArray* aos_objects = new GrowableArray(INITIAL_ARRAY_SIZE); + GrowableArray* aos_objects = new GrowableArray(INITIAL_ARRAY_SIZE); - // Find all instances of AbstractOwnableSynchronizer - HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(), + // Find all instances of AbstractOwnableSynchronizer + HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(), aos_objects); - // Build a map of thread to its owned AQS locks - build_map(aos_objects); - } + // Build a map of thread to its owned AQS locks + build_map(aos_objects); } From d9b63bdbdd02b9ad8e5cf90a811b2759e191104d Mon Sep 17 00:00:00 2001 From: David Simms Date: Wed, 11 Jun 2014 18:34:09 +0200 Subject: [PATCH 067/192] 8043224: -Xcheck:jni improvements to exception checking and excessive local refs Warning when not checking exceptions from function that require so, also when local refs expand beyond capacity. Reviewed-by: zgu, coleenp, hseigel --- hotspot/src/share/vm/memory/guardedMemory.hpp | 6 +- hotspot/src/share/vm/prims/jniCheck.cpp | 269 +++++++++++------- hotspot/src/share/vm/runtime/jniHandles.cpp | 7 + hotspot/src/share/vm/runtime/jniHandles.hpp | 10 +- hotspot/src/share/vm/runtime/thread.cpp | 1 + hotspot/src/share/vm/runtime/thread.hpp | 9 + 6 files changed, 201 insertions(+), 101 deletions(-) diff --git a/hotspot/src/share/vm/memory/guardedMemory.hpp b/hotspot/src/share/vm/memory/guardedMemory.hpp index dada10d84bf..0d37bb03361 100644 --- a/hotspot/src/share/vm/memory/guardedMemory.hpp +++ b/hotspot/src/share/vm/memory/guardedMemory.hpp @@ -235,7 +235,7 @@ protected: * @return the size of the user data. */ size_t get_user_size() const { - assert(_base_addr, "Not wrapping any memory"); + assert(_base_addr != NULL, "Not wrapping any memory"); return get_head_guard()->get_user_size(); } @@ -245,7 +245,7 @@ protected: * @return the user data pointer. */ u_char* get_user_ptr() const { - assert(_base_addr, "Not wrapping any memory"); + assert(_base_addr != NULL, "Not wrapping any memory"); return _base_addr + sizeof(GuardHeader); } @@ -281,7 +281,7 @@ protected: memset(get_user_ptr(), ch, get_user_size()); } -public: + public: /** * Return the total size required for wrapping the given user size. * diff --git a/hotspot/src/share/vm/prims/jniCheck.cpp b/hotspot/src/share/vm/prims/jniCheck.cpp index 446c23143ae..de9b4e56a86 100644 --- a/hotspot/src/share/vm/prims/jniCheck.cpp +++ b/hotspot/src/share/vm/prims/jniCheck.cpp @@ -53,6 +53,8 @@ # include "jniTypes_ppc.hpp" #endif +// Complain every extra number of unplanned local refs +#define CHECK_JNI_LOCAL_REF_CAP_WARN_THRESHOLD 32 // Heap objects are allowed to be directly referenced only in VM code, // not in native code. @@ -168,12 +170,42 @@ static void NativeReportJNIWarning(JavaThread* thr, const char *msg) { * SUPPORT FUNCTIONS */ +/** + * Check whether or not a programmer has actually checked for exceptions. According + * to the JNI Specification ("jni/spec/design.html#java_exceptions"): + * + * There are two cases where the programmer needs to check for exceptions without + * being able to first check an error code: + * + * - The JNI functions that invoke a Java method return the result of the Java method. + * The programmer must call ExceptionOccurred() to check for possible exceptions + * that occurred during the execution of the Java method. + * + * - Some of the JNI array access functions do not return an error code, but may + * throw an ArrayIndexOutOfBoundsException or ArrayStoreException. + * + * In all other cases, a non-error return value guarantees that no exceptions have been thrown. + */ static inline void -functionEnterCritical(JavaThread* thr) -{ +check_pending_exception(JavaThread* thr) { if (thr->has_pending_exception()) { NativeReportJNIWarning(thr, "JNI call made with exception pending"); } + if (thr->is_pending_jni_exception_check()) { + IN_VM( + tty->print_cr("WARNING in native method: JNI call made without checking exceptions when required to from %s", + thr->get_pending_jni_exception_check()); + thr->print_stack(); + ) + thr->clear_pending_jni_exception_check(); // Just complain once + } +} + + +static inline void +functionEnterCritical(JavaThread* thr) +{ + check_pending_exception(thr); } static inline void @@ -187,9 +219,7 @@ functionEnter(JavaThread* thr) if (thr->in_critical()) { tty->print_cr("%s", warn_other_function_in_critical); } - if (thr->has_pending_exception()) { - NativeReportJNIWarning(thr, "JNI call made with exception pending"); - } + check_pending_exception(thr); } static inline void @@ -201,9 +231,20 @@ functionEnterExceptionAllowed(JavaThread* thr) } static inline void -functionExit(JNIEnv *env) +functionExit(JavaThread* thr) { - /* nothing to do at this time */ + JNIHandleBlock* handles = thr->active_handles(); + size_t planned_capacity = handles->get_planned_capacity(); + size_t live_handles = handles->get_number_of_live_handles(); + if (live_handles > planned_capacity) { + IN_VM( + tty->print_cr("WARNING: JNI local refs: %zu, exceeds capacity: %zu", + live_handles, planned_capacity); + thr->print_stack(); + ) + // Complain just the once, reset to current + warn threshold + handles->set_planned_capacity(live_handles + CHECK_JNI_LOCAL_REF_CAP_WARN_THRESHOLD); + } } static inline void @@ -508,7 +549,7 @@ JNI_ENTRY_CHECKED(jclass, jniCheck::validate_object(thr, loader); ) jclass result = UNCHECKED()->DefineClass(env, name, loader, buf, len); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -520,7 +561,7 @@ JNI_ENTRY_CHECKED(jclass, jniCheck::validate_class_descriptor(thr, name); ) jclass result = UNCHECKED()->FindClass(env, name); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -532,7 +573,7 @@ JNI_ENTRY_CHECKED(jmethodID, jniCheck::validate_object(thr, method); ) jmethodID result = UNCHECKED()->FromReflectedMethod(env, method); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -544,7 +585,7 @@ JNI_ENTRY_CHECKED(jfieldID, jniCheck::validate_object(thr, field); ) jfieldID result = UNCHECKED()->FromReflectedField(env, field); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -560,7 +601,7 @@ JNI_ENTRY_CHECKED(jobject, ) jobject result = UNCHECKED()->ToReflectedMethod(env, cls, methodID, isStatic); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -572,7 +613,7 @@ JNI_ENTRY_CHECKED(jclass, jniCheck::validate_class(thr, sub, true); ) jclass result = UNCHECKED()->GetSuperclass(env, sub); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -586,7 +627,7 @@ JNI_ENTRY_CHECKED(jboolean, jniCheck::validate_class(thr, sup, true); ) jboolean result = UNCHECKED()->IsAssignableFrom(env, sub, sup); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -601,7 +642,7 @@ JNI_ENTRY_CHECKED(jobject, ) jobject result = UNCHECKED()->ToReflectedField(env, cls, fieldID, isStatic); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -619,7 +660,7 @@ JNI_ENTRY_CHECKED(jint, } ) jint result = UNCHECKED()->Throw(env, obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -634,15 +675,16 @@ JNI_ENTRY_CHECKED(jint, jniCheck::validate_throwable_klass(thr, k); ) jint result = UNCHECKED()->ThrowNew(env, clazz, msg); - functionExit(env); + functionExit(thr); return result; JNI_END JNI_ENTRY_CHECKED(jthrowable, checked_jni_ExceptionOccurred(JNIEnv *env)) + thr->clear_pending_jni_exception_check(); functionEnterExceptionAllowed(thr); jthrowable result = UNCHECKED()->ExceptionOccurred(env); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -650,22 +692,24 @@ JNI_ENTRY_CHECKED(void, checked_jni_ExceptionDescribe(JNIEnv *env)) functionEnterExceptionAllowed(thr); UNCHECKED()->ExceptionDescribe(env); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, checked_jni_ExceptionClear(JNIEnv *env)) + thr->clear_pending_jni_exception_check(); functionEnterExceptionAllowed(thr); UNCHECKED()->ExceptionClear(env); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, checked_jni_FatalError(JNIEnv *env, const char *msg)) + thr->clear_pending_jni_exception_check(); functionEnter(thr); UNCHECKED()->FatalError(env, msg); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jint, @@ -675,7 +719,10 @@ JNI_ENTRY_CHECKED(jint, if (capacity < 0) NativeReportJNIFatalError(thr, "negative capacity"); jint result = UNCHECKED()->PushLocalFrame(env, capacity); - functionExit(env); + if (result == JNI_OK) { + thr->active_handles()->set_planned_capacity(capacity + CHECK_JNI_LOCAL_REF_CAP_WARN_THRESHOLD); + } + functionExit(thr); return result; JNI_END @@ -684,7 +731,7 @@ JNI_ENTRY_CHECKED(jobject, jobject result)) functionEnterExceptionAllowed(thr); jobject res = UNCHECKED()->PopLocalFrame(env, result); - functionExit(env); + functionExit(thr); return res; JNI_END @@ -698,7 +745,7 @@ JNI_ENTRY_CHECKED(jobject, } ) jobject result = UNCHECKED()->NewGlobalRef(env,lobj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -714,7 +761,7 @@ JNI_ENTRY_CHECKED(void, } ) UNCHECKED()->DeleteGlobalRef(env,gref); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -729,7 +776,7 @@ JNI_ENTRY_CHECKED(void, "Invalid local JNI handle passed to DeleteLocalRef"); ) UNCHECKED()->DeleteLocalRef(env, obj); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jboolean, @@ -750,7 +797,7 @@ JNI_ENTRY_CHECKED(jboolean, } ) jboolean result = UNCHECKED()->IsSameObject(env,obj1,obj2); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -764,7 +811,7 @@ JNI_ENTRY_CHECKED(jobject, } ) jobject result = UNCHECKED()->NewLocalRef(env, ref); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -776,7 +823,10 @@ JNI_ENTRY_CHECKED(jint, NativeReportJNIFatalError(thr, "negative capacity"); } jint result = UNCHECKED()->EnsureLocalCapacity(env, capacity); - functionExit(env); + if (result == JNI_OK) { + thr->active_handles()->set_planned_capacity(capacity + CHECK_JNI_LOCAL_REF_CAP_WARN_THRESHOLD); + } + functionExit(thr); return result; JNI_END @@ -788,7 +838,7 @@ JNI_ENTRY_CHECKED(jobject, jniCheck::validate_class(thr, clazz, false); ) jobject result = UNCHECKED()->AllocObject(env,clazz); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -806,7 +856,7 @@ JNI_ENTRY_CHECKED(jobject, va_start(args, methodID); jobject result = UNCHECKED()->NewObjectV(env,clazz,methodID,args); va_end(args); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -821,7 +871,7 @@ JNI_ENTRY_CHECKED(jobject, jniCheck::validate_jmethod_id(thr, methodID); ) jobject result = UNCHECKED()->NewObjectV(env,clazz,methodID,args); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -836,7 +886,7 @@ JNI_ENTRY_CHECKED(jobject, jniCheck::validate_jmethod_id(thr, methodID); ) jobject result = UNCHECKED()->NewObjectA(env,clazz,methodID,args); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -848,7 +898,7 @@ JNI_ENTRY_CHECKED(jclass, jniCheck::validate_object(thr, obj); ) jclass result = UNCHECKED()->GetObjectClass(env,obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -862,7 +912,7 @@ JNI_ENTRY_CHECKED(jboolean, jniCheck::validate_class(thr, clazz, true); ) jboolean result = UNCHECKED()->IsInstanceOf(env,obj,clazz); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -876,7 +926,7 @@ JNI_ENTRY_CHECKED(jmethodID, jniCheck::validate_class(thr, clazz, false); ) jmethodID result = UNCHECKED()->GetMethodID(env,clazz,name,sig); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -895,7 +945,8 @@ JNI_ENTRY_CHECKED(ResultType, \ ResultType result =UNCHECKED()->Call##Result##MethodV(env, obj, methodID, \ args); \ va_end(args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Call"#Result"Method"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -910,7 +961,8 @@ JNI_ENTRY_CHECKED(ResultType, \ ) \ ResultType result = UNCHECKED()->Call##Result##MethodV(env, obj, methodID,\ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Call"#Result"MethodV"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -925,7 +977,8 @@ JNI_ENTRY_CHECKED(ResultType, \ ) \ ResultType result = UNCHECKED()->Call##Result##MethodA(env, obj, methodID,\ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Call"#Result"MethodA"); \ + functionExit(thr); \ return result; \ JNI_END @@ -952,7 +1005,8 @@ JNI_ENTRY_CHECKED(void, va_start(args,methodID); UNCHECKED()->CallVoidMethodV(env,obj,methodID,args); va_end(args); - functionExit(env); + thr->set_pending_jni_exception_check("CallVoidMethod"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -965,7 +1019,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_call_object(thr, obj, methodID); ) UNCHECKED()->CallVoidMethodV(env,obj,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallVoidMethodV"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -978,7 +1033,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_call_object(thr, obj, methodID); ) UNCHECKED()->CallVoidMethodA(env,obj,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallVoidMethodA"); + functionExit(thr); JNI_END #define WRAPPER_CallNonvirtualMethod(ResultType, Result) \ @@ -1001,7 +1057,8 @@ JNI_ENTRY_CHECKED(ResultType, \ methodID,\ args); \ va_end(args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallNonvirtual"#Result"Method"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -1021,7 +1078,8 @@ JNI_ENTRY_CHECKED(ResultType, \ clazz, \ methodID,\ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallNonvirtual"#Result"MethodV"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -1041,7 +1099,8 @@ JNI_ENTRY_CHECKED(ResultType, \ clazz, \ methodID,\ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallNonvirtual"#Result"MethodA"); \ + functionExit(thr); \ return result; \ JNI_END @@ -1070,7 +1129,8 @@ JNI_ENTRY_CHECKED(void, va_start(args,methodID); UNCHECKED()->CallNonvirtualVoidMethodV(env,obj,clazz,methodID,args); va_end(args); - functionExit(env); + thr->set_pending_jni_exception_check("CallNonvirtualVoidMethod"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1085,7 +1145,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_call_class(thr, clazz, methodID); ) UNCHECKED()->CallNonvirtualVoidMethodV(env,obj,clazz,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallNonvirtualVoidMethodV"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1100,7 +1161,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_call_class(thr, clazz, methodID); ) UNCHECKED()->CallNonvirtualVoidMethodA(env,obj,clazz,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallNonvirtualVoidMethodA"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jfieldID, @@ -1113,7 +1175,7 @@ JNI_ENTRY_CHECKED(jfieldID, jniCheck::validate_class(thr, clazz, false); ) jfieldID result = UNCHECKED()->GetFieldID(env,clazz,name,sig); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1127,7 +1189,7 @@ JNI_ENTRY_CHECKED(ReturnType, \ checkInstanceFieldID(thr, fieldID, obj, FieldType); \ ) \ ReturnType result = UNCHECKED()->Get##Result##Field(env,obj,fieldID); \ - functionExit(env); \ + functionExit(thr); \ return result; \ JNI_END @@ -1152,7 +1214,7 @@ JNI_ENTRY_CHECKED(void, \ checkInstanceFieldID(thr, fieldID, obj, FieldType); \ ) \ UNCHECKED()->Set##Result##Field(env,obj,fieldID,val); \ - functionExit(env); \ + functionExit(thr); \ JNI_END WRAPPER_SetField(jobject, Object, T_OBJECT) @@ -1176,7 +1238,7 @@ JNI_ENTRY_CHECKED(jmethodID, jniCheck::validate_class(thr, clazz, false); ) jmethodID result = UNCHECKED()->GetStaticMethodID(env,clazz,name,sig); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1198,7 +1260,8 @@ JNI_ENTRY_CHECKED(ReturnType, \ methodID, \ args); \ va_end(args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallStatic"#Result"Method"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -1216,7 +1279,8 @@ JNI_ENTRY_CHECKED(ReturnType, \ clazz, \ methodID, \ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallStatic"#Result"MethodV"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -1234,7 +1298,8 @@ JNI_ENTRY_CHECKED(ReturnType, \ clazz, \ methodID, \ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallStatic"#Result"MethodA"); \ + functionExit(thr); \ return result; \ JNI_END @@ -1262,7 +1327,8 @@ JNI_ENTRY_CHECKED(void, va_start(args,methodID); UNCHECKED()->CallStaticVoidMethodV(env,cls,methodID,args); va_end(args); - functionExit(env); + thr->set_pending_jni_exception_check("CallStaticVoidMethod"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1276,7 +1342,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_class(thr, cls, false); ) UNCHECKED()->CallStaticVoidMethodV(env,cls,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallStaticVoidMethodV"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1290,7 +1357,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_class(thr, cls, false); ) UNCHECKED()->CallStaticVoidMethodA(env,cls,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallStaticVoidMethodA"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jfieldID, @@ -1303,7 +1371,7 @@ JNI_ENTRY_CHECKED(jfieldID, jniCheck::validate_class(thr, clazz, false); ) jfieldID result = UNCHECKED()->GetStaticFieldID(env,clazz,name,sig); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1320,7 +1388,7 @@ JNI_ENTRY_CHECKED(ReturnType, \ ReturnType result = UNCHECKED()->GetStatic##Result##Field(env, \ clazz, \ fieldID); \ - functionExit(env); \ + functionExit(thr); \ return result; \ JNI_END @@ -1346,7 +1414,7 @@ JNI_ENTRY_CHECKED(void, \ checkStaticFieldID(thr, fieldID, clazz, FieldType); \ ) \ UNCHECKED()->SetStatic##Result##Field(env,clazz,fieldID,value); \ - functionExit(env); \ + functionExit(thr); \ JNI_END WRAPPER_SetStaticField(jobject, Object, T_OBJECT) @@ -1366,7 +1434,7 @@ JNI_ENTRY_CHECKED(jstring, jsize len)) functionEnter(thr); jstring result = UNCHECKED()->NewString(env,unicode,len); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1378,7 +1446,7 @@ JNI_ENTRY_CHECKED(jsize, checkString(thr, str); ) jsize result = UNCHECKED()->GetStringLength(env,str); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1407,7 +1475,7 @@ JNI_ENTRY_CHECKED(const jchar *, // Note that the dtrace arguments for the allocated memory will not match up with this solution. FreeHeap((char*)result); } - functionExit(env); + functionExit(thr); return new_result; JNI_END @@ -1442,7 +1510,7 @@ JNI_ENTRY_CHECKED(void, UNCHECKED()->ReleaseStringChars(env, str, (const jchar*) guarded.release_for_freeing()); } - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jstring, @@ -1450,7 +1518,7 @@ JNI_ENTRY_CHECKED(jstring, const char *utf)) functionEnter(thr); jstring result = UNCHECKED()->NewStringUTF(env,utf); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1462,7 +1530,7 @@ JNI_ENTRY_CHECKED(jsize, checkString(thr, str); ) jsize result = UNCHECKED()->GetStringUTFLength(env,str); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1490,7 +1558,7 @@ JNI_ENTRY_CHECKED(const char *, // Note that the dtrace arguments for the allocated memory will not match up with this solution. FreeHeap((char*)result, mtInternal); } - functionExit(env); + functionExit(thr); return new_result; JNI_END @@ -1525,7 +1593,7 @@ JNI_ENTRY_CHECKED(void, UNCHECKED()->ReleaseStringUTFChars(env, str, (const char*) guarded.release_for_freeing()); } - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jsize, @@ -1536,7 +1604,7 @@ JNI_ENTRY_CHECKED(jsize, check_is_array(thr, array); ) jsize result = UNCHECKED()->GetArrayLength(env,array); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1547,7 +1615,7 @@ JNI_ENTRY_CHECKED(jobjectArray, jobject init)) functionEnter(thr); jobjectArray result = UNCHECKED()->NewObjectArray(env,len,clazz,init); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1560,7 +1628,8 @@ JNI_ENTRY_CHECKED(jobject, check_is_obj_array(thr, array); ) jobject result = UNCHECKED()->GetObjectArrayElement(env,array,index); - functionExit(env); + thr->set_pending_jni_exception_check("GetObjectArrayElement"); + functionExit(thr); return result; JNI_END @@ -1574,7 +1643,8 @@ JNI_ENTRY_CHECKED(void, check_is_obj_array(thr, array); ) UNCHECKED()->SetObjectArrayElement(env,array,index,val); - functionExit(env); + thr->set_pending_jni_exception_check("SetObjectArrayElement"); + functionExit(thr); JNI_END #define WRAPPER_NewScalarArray(Return, Result) \ @@ -1583,7 +1653,7 @@ JNI_ENTRY_CHECKED(Return, \ jsize len)) \ functionEnter(thr); \ Return result = UNCHECKED()->New##Result##Array(env,len); \ - functionExit(env); \ + functionExit(thr); \ return (Return) result; \ JNI_END @@ -1611,7 +1681,7 @@ JNI_ENTRY_CHECKED(ElementType *, \ if (result != NULL) { \ result = (ElementType *) check_jni_wrap_copy_array(thr, array, result); \ } \ - functionExit(env); \ + functionExit(thr); \ return result; \ JNI_END @@ -1639,7 +1709,7 @@ JNI_ENTRY_CHECKED(void, \ ElementType* orig_result = (ElementType *) check_wrapped_array_release( \ thr, "checked_jni_Release"#Result"ArrayElements", array, elems, mode); \ UNCHECKED()->Release##Result##ArrayElements(env, array, orig_result, mode); \ - functionExit(env); \ + functionExit(thr); \ JNI_END WRAPPER_ReleaseScalarArrayElements(T_BOOLEAN,jboolean, Boolean, bool) @@ -1663,7 +1733,8 @@ JNI_ENTRY_CHECKED(void, \ check_primitive_array_type(thr, array, ElementTag); \ ) \ UNCHECKED()->Get##Result##ArrayRegion(env,array,start,len,buf); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Get"#Result"ArrayRegion"); \ + functionExit(thr); \ JNI_END WRAPPER_GetScalarArrayRegion(T_BOOLEAN, jboolean, Boolean) @@ -1687,7 +1758,8 @@ JNI_ENTRY_CHECKED(void, \ check_primitive_array_type(thr, array, ElementTag); \ ) \ UNCHECKED()->Set##Result##ArrayRegion(env,array,start,len,buf); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Set"#Result"ArrayRegion"); \ + functionExit(thr); \ JNI_END WRAPPER_SetScalarArrayRegion(T_BOOLEAN, jboolean, Boolean) @@ -1706,7 +1778,7 @@ JNI_ENTRY_CHECKED(jint, jint nMethods)) functionEnter(thr); jint result = UNCHECKED()->RegisterNatives(env,clazz,methods,nMethods); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1715,7 +1787,7 @@ JNI_ENTRY_CHECKED(jint, jclass clazz)) functionEnter(thr); jint result = UNCHECKED()->UnregisterNatives(env,clazz); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1727,7 +1799,7 @@ JNI_ENTRY_CHECKED(jint, jniCheck::validate_object(thr, obj); ) jint result = UNCHECKED()->MonitorEnter(env,obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1739,7 +1811,7 @@ JNI_ENTRY_CHECKED(jint, jniCheck::validate_object(thr, obj); ) jint result = UNCHECKED()->MonitorExit(env,obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1748,7 +1820,7 @@ JNI_ENTRY_CHECKED(jint, JavaVM **vm)) functionEnter(thr); jint result = UNCHECKED()->GetJavaVM(env,vm); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1763,7 +1835,8 @@ JNI_ENTRY_CHECKED(void, checkString(thr, str); ) UNCHECKED()->GetStringRegion(env, str, start, len, buf); - functionExit(env); + thr->set_pending_jni_exception_check("GetStringRegion"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1777,7 +1850,8 @@ JNI_ENTRY_CHECKED(void, checkString(thr, str); ) UNCHECKED()->GetStringUTFRegion(env, str, start, len, buf); - functionExit(env); + thr->set_pending_jni_exception_check("GetStringUTFRegion"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void *, @@ -1792,7 +1866,7 @@ JNI_ENTRY_CHECKED(void *, if (result != NULL) { result = check_jni_wrap_copy_array(thr, array, result); } - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1808,7 +1882,7 @@ JNI_ENTRY_CHECKED(void, // Check the element array... void* orig_result = check_wrapped_array_release(thr, "ReleasePrimitiveArrayCritical", array, carray, mode); UNCHECKED()->ReleasePrimitiveArrayCritical(env, array, orig_result, mode); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(const jchar*, @@ -1820,7 +1894,7 @@ JNI_ENTRY_CHECKED(const jchar*, checkString(thr, string); ) const jchar *result = UNCHECKED()->GetStringCritical(env, string, isCopy); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1836,7 +1910,7 @@ JNI_ENTRY_CHECKED(void, * string parameter as a minor sanity check */ UNCHECKED()->ReleaseStringCritical(env, str, chars); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jweak, @@ -1849,7 +1923,7 @@ JNI_ENTRY_CHECKED(jweak, } ) jweak result = UNCHECKED()->NewWeakGlobalRef(env, obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1858,14 +1932,15 @@ JNI_ENTRY_CHECKED(void, jweak ref)) functionEnterExceptionAllowed(thr); UNCHECKED()->DeleteWeakGlobalRef(env, ref); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jboolean, checked_jni_ExceptionCheck(JNIEnv *env)) + thr->clear_pending_jni_exception_check(); functionEnterExceptionAllowed(thr); jboolean result = UNCHECKED()->ExceptionCheck(env); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1875,7 +1950,7 @@ JNI_ENTRY_CHECKED(jobject, jlong capacity)) functionEnter(thr); jobject result = UNCHECKED()->NewDirectByteBuffer(env, address, capacity); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1884,7 +1959,7 @@ JNI_ENTRY_CHECKED(void *, jobject buf)) functionEnter(thr); void* result = UNCHECKED()->GetDirectBufferAddress(env, buf); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1893,7 +1968,7 @@ JNI_ENTRY_CHECKED(jlong, jobject buf)) functionEnter(thr); jlong result = UNCHECKED()->GetDirectBufferCapacity(env, buf); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1906,7 +1981,7 @@ JNI_ENTRY_CHECKED(jobjectRefType, jniCheck::validate_object(thr, obj); ) jobjectRefType result = UNCHECKED()->GetObjectRefType(env, obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1915,7 +1990,7 @@ JNI_ENTRY_CHECKED(jint, checked_jni_GetVersion(JNIEnv *env)) functionEnter(thr); jint result = UNCHECKED()->GetVersion(env); - functionExit(env); + functionExit(thr); return result; JNI_END diff --git a/hotspot/src/share/vm/runtime/jniHandles.cpp b/hotspot/src/share/vm/runtime/jniHandles.cpp index 7ff38335029..9ce7ce8ae44 100644 --- a/hotspot/src/share/vm/runtime/jniHandles.cpp +++ b/hotspot/src/share/vm/runtime/jniHandles.cpp @@ -298,6 +298,7 @@ JNIHandleBlock* JNIHandleBlock::allocate_block(Thread* thread) { block->_top = 0; block->_next = NULL; block->_pop_frame_link = NULL; + block->_planned_capacity = block_size_in_oops; // _last, _free_list & _allocate_before_rebuild initialized in allocate_handle debug_only(block->_last = NULL); debug_only(block->_free_list = NULL); @@ -531,6 +532,12 @@ int JNIHandleBlock::length() const { return result; } +const size_t JNIHandleBlock::get_number_of_live_handles() { + CountHandleClosure counter; + oops_do(&counter); + return counter.count(); +} + // This method is not thread-safe, i.e., must be called while holding a lock on the // structure. long JNIHandleBlock::memory_usage() const { diff --git a/hotspot/src/share/vm/runtime/jniHandles.hpp b/hotspot/src/share/vm/runtime/jniHandles.hpp index 1bd97c3cf09..069a1f35cfa 100644 --- a/hotspot/src/share/vm/runtime/jniHandles.hpp +++ b/hotspot/src/share/vm/runtime/jniHandles.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -112,6 +112,9 @@ class JNIHandleBlock : public CHeapObj { oop* _free_list; // Handle free list int _allocate_before_rebuild; // Number of blocks to allocate before rebuilding free list + // Check JNI, "planned capacity" for current frame (or push/ensure) + size_t _planned_capacity; + #ifndef PRODUCT JNIHandleBlock* _block_list_link; // Link for list below static JNIHandleBlock* _block_list; // List of all allocated blocks (for debugging only) @@ -152,6 +155,11 @@ class JNIHandleBlock : public CHeapObj { // Traversal of weak handles. Unreachable oops are cleared. void weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f); + // Checked JNI support + void set_planned_capacity(size_t planned_capacity) { _planned_capacity = planned_capacity; } + const size_t get_planned_capacity() { return _planned_capacity; } + const size_t get_number_of_live_handles(); + // Debugging bool chain_contains(jobject handle) const; // Does this block or following blocks contain handle bool contains(jobject handle) const; // Does this block contain handle diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp index 061509ae144..e3ab1725a1d 100644 --- a/hotspot/src/share/vm/runtime/thread.cpp +++ b/hotspot/src/share/vm/runtime/thread.cpp @@ -1448,6 +1448,7 @@ void JavaThread::initialize() { _thread_stat = new ThreadStatistics(); _blocked_on_compilation = false; _jni_active_critical = 0; + _pending_jni_exception_check_fn = NULL; _do_not_unlock_if_synchronized = false; _cached_monitor_info = NULL; _parker = Parker::Allocate(this) ; diff --git a/hotspot/src/share/vm/runtime/thread.hpp b/hotspot/src/share/vm/runtime/thread.hpp index a5f0a92246d..64bed4610b0 100644 --- a/hotspot/src/share/vm/runtime/thread.hpp +++ b/hotspot/src/share/vm/runtime/thread.hpp @@ -915,6 +915,9 @@ class JavaThread: public Thread { // support for JNI critical regions jint _jni_active_critical; // count of entries into JNI critical region + // Checked JNI: function name requires exception check + char* _pending_jni_exception_check_fn; + // For deadlock detection. int _depth_first_number; @@ -1400,6 +1403,12 @@ class JavaThread: public Thread { assert(_jni_active_critical >= 0, "JNI critical nesting problem?"); } + // Checked JNI, is the programmer required to check for exceptions, specify which function name + bool is_pending_jni_exception_check() const { return _pending_jni_exception_check_fn != NULL; } + void clear_pending_jni_exception_check() { _pending_jni_exception_check_fn = NULL; } + const char* get_pending_jni_exception_check() const { return _pending_jni_exception_check_fn; } + void set_pending_jni_exception_check(const char* fn_name) { _pending_jni_exception_check_fn = (char*) fn_name; } + // For deadlock detection int depth_first_number() { return _depth_first_number; } void set_depth_first_number(int dfn) { _depth_first_number = dfn; } From f829432469a75b7aa115a853a6a1ea021dd3f492 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Wed, 11 Jun 2014 13:25:15 -0700 Subject: [PATCH 068/192] 8043549: Fix raw and unchecked lint warnings in javax.swing.text.* Reviewed-by: prr --- .../javax/swing/text/AbstractDocument.java | 8 +++--- .../javax/swing/text/AbstractWriter.java | 2 +- .../javax/swing/text/DateFormatter.java | 6 ++-- .../javax/swing/text/DefaultFormatter.java | 4 +-- .../swing/text/DefaultStyledDocument.java | 13 +++++---- .../javax/swing/text/ElementIterator.java | 2 +- .../classes/javax/swing/text/GapContent.java | 16 ++++++----- .../classes/javax/swing/text/GlyphView.java | 2 +- .../swing/text/InternationalFormatter.java | 28 ++++++++++--------- .../javax/swing/text/JTextComponent.java | 1 + .../javax/swing/text/NumberFormatter.java | 11 ++++---- .../javax/swing/text/ParagraphView.java | 2 +- .../javax/swing/text/SimpleAttributeSet.java | 11 ++++---- .../javax/swing/text/StringContent.java | 12 ++++---- .../javax/swing/text/StyleContext.java | 14 +++++----- .../classes/javax/swing/text/TextAction.java | 4 +-- .../javax/swing/text/html/AccessibleHTML.java | 2 +- .../classes/javax/swing/text/html/CSS.java | 6 ++-- .../javax/swing/text/html/FormView.java | 21 +++++++++----- .../javax/swing/text/html/HTMLDocument.java | 22 ++++++++++----- .../javax/swing/text/html/HTMLEditorKit.java | 4 +-- .../javax/swing/text/html/HTMLWriter.java | 18 ++++++------ .../javax/swing/text/html/ImageView.java | 7 +++-- .../swing/text/html/MinimalHTMLWriter.java | 4 +-- .../swing/text/html/MuxingAttributeSet.java | 8 +++--- .../javax/swing/text/html/ObjectView.java | 8 +++--- .../swing/text/html/OptionListModel.java | 5 ++-- .../javax/swing/text/html/StyleSheet.java | 21 +++++++++----- .../javax/swing/text/html/parser/DTD.java | 1 + .../swing/text/rtf/MockAttributeSet.java | 4 +-- .../javax/swing/text/rtf/RTFGenerator.java | 10 +++---- .../javax/swing/text/rtf/RTFReader.java | 26 ++++++++++------- 32 files changed, 172 insertions(+), 131 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java index a7a109f8c91..e42d549791a 100644 --- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java +++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java @@ -1809,7 +1809,7 @@ public abstract class AbstractDocument implements Document, Serializable { if (getAttributeCount() > 0) { out.println(""); // dump the attributes - Enumeration names = attributes.getAttributeNames(); + Enumeration names = attributes.getAttributeNames(); while (names.hasMoreElements()) { Object name = names.nextElement(); indent(out, indentAmount + 1); @@ -2193,7 +2193,7 @@ public abstract class AbstractDocument implements Document, Serializable { * Enumeration. * @return the children of the receiver as an Enumeration */ - public abstract Enumeration children(); + public abstract Enumeration children(); // --- serialization --------------------------------------------- @@ -2456,7 +2456,7 @@ public abstract class AbstractDocument implements Document, Serializable { * Enumeration. * @return the children of the receiver */ - public Enumeration children() { + public Enumeration children() { if(nchildren == 0) return null; @@ -2610,7 +2610,7 @@ public abstract class AbstractDocument implements Document, Serializable { * Enumeration. * @return the children of the receiver */ - public Enumeration children() { + public Enumeration children() { return null; } diff --git a/jdk/src/share/classes/javax/swing/text/AbstractWriter.java b/jdk/src/share/classes/javax/swing/text/AbstractWriter.java index f2f7f746ee4..cfe619b801f 100644 --- a/jdk/src/share/classes/javax/swing/text/AbstractWriter.java +++ b/jdk/src/share/classes/javax/swing/text/AbstractWriter.java @@ -668,7 +668,7 @@ public abstract class AbstractWriter { */ protected void writeAttributes(AttributeSet attr) throws IOException { - Enumeration names = attr.getAttributeNames(); + Enumeration names = attr.getAttributeNames(); while (names.hasMoreElements()) { Object name = names.nextElement(); write(" " + name + "=" + attr.getAttribute(name)); diff --git a/jdk/src/share/classes/javax/swing/text/DateFormatter.java b/jdk/src/share/classes/javax/swing/text/DateFormatter.java index e935053bfc8..b82788fb6a2 100644 --- a/jdk/src/share/classes/javax/swing/text/DateFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/DateFormatter.java @@ -108,8 +108,8 @@ public class DateFormatter extends InternationalFormatter { /** * Returns the field that will be adjusted by adjustValue. */ - Object getAdjustField(int start, Map attributes) { - Iterator attrs = attributes.keySet().iterator(); + Object getAdjustField(int start, Map attributes) { + Iterator attrs = attributes.keySet().iterator(); while (attrs.hasNext()) { Object key = attrs.next(); @@ -127,7 +127,7 @@ public class DateFormatter extends InternationalFormatter { * Adjusts the Date if FieldPosition identifies a known calendar * field. */ - Object adjustValue(Object value, Map attributes, Object key, + Object adjustValue(Object value, Map attributes, Object key, int direction) throws BadLocationException, ParseException { if (key != null) { diff --git a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java index 0a4df2c0a1d..ee9cda6e85f 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java @@ -246,12 +246,12 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter } } if (vc != null) { - Constructor cons; + Constructor cons; try { ReflectUtil.checkPackageAccess(vc); SwingUtilities2.checkAccess(vc.getModifiers()); - cons = vc.getConstructor(new Class[]{String.class}); + cons = vc.getConstructor(new Class[]{String.class}); } catch (NoSuchMethodException nsme) { cons = null; diff --git a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java index a5ce0633f74..78788cbfad1 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java @@ -1048,8 +1048,9 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc styleChangeListener = createStyleChangeListener(); } if (styleChangeListener != null && styles != null) { - Enumeration styleNames = styles.getStyleNames(); - Vector v = (Vector)listeningStyles.clone(); + Enumeration styleNames = styles.getStyleNames(); + @SuppressWarnings("unchecked") + Vector