提交 882537f3 编写于 作者: L lana

Merge

......@@ -3385,7 +3385,7 @@ with JRE 8, JDK 8, and OpenJDK 8.
included with JRE 8, JDK 8, and OpenJDK 8.
Apache Commons Math 3.2
Apache Derby 10.10.1.3
Apache Derby 10.11.1.2
Apache Jakarta BCEL 5.1
Apache Jakarta Regexp 1.4
Apache Santuario XML Security for Java 1.5.4
......
......@@ -1280,12 +1280,12 @@ public class AquaFileChooserUI extends FileChooserUI {
filters = (FileFilter[]) e.getNewValue();
fireContentsChanged(this, -1, -1);
} else if (prop == JFileChooser.FILE_FILTER_CHANGED_PROPERTY) {
fireContentsChanged(this, -1, -1);
setSelectedItem(e.getNewValue());
}
}
public void setSelectedItem(Object filter) {
if(filter != null) {
if (filter != null && !containsFileFilter(filter)) {
getFileChooser().setFileFilter((FileFilter) filter);
fireContentsChanged(this, -1, -1);
}
......@@ -1333,6 +1333,10 @@ public class AquaFileChooserUI extends FileChooserUI {
}
}
private boolean containsFileFilter(Object fileFilter) {
return Objects.equals(fileFilter, getFileChooser().getFileFilter());
}
/**
* Acts when FilterComboBox has changed the selected item.
*/
......@@ -1342,7 +1346,10 @@ public class AquaFileChooserUI extends FileChooserUI {
}
public void actionPerformed(final ActionEvent e) {
getFileChooser().setFileFilter((FileFilter)filterComboBox.getSelectedItem());
Object selectedFilter = filterComboBox.getSelectedItem();
if (!containsFileFilter(selectedFilter)) {
getFileChooser().setFileFilter((FileFilter) selectedFilter);
}
}
}
......
......@@ -1285,7 +1285,7 @@ class GTKFileChooserUI extends SynthFileChooserUI {
/**
* Render different filters
*/
public class FilterComboBoxRenderer extends DefaultListCellRenderer implements UIResource {
public class FilterComboBoxRenderer extends DefaultListCellRenderer {
public String getName() {
// As SynthComboBoxRenderer's are asked for a size BEFORE they
// are parented getName is overriden to force the name to be
......
......@@ -111,7 +111,6 @@ public final class Connection implements Runnable {
private static final boolean debug = false;
private static final int dump = 0; // > 0 r, > 1 rw
public static final long DEFAULT_READ_TIMEOUT_MILLIS = 15 * 1000; // 15 second timeout;
final private Thread worker; // Initialized in constructor
......@@ -460,10 +459,13 @@ public final class Connection implements Runnable {
// will be woken up before readTimeout only if reply is
// available
ldr.wait(readTimeout);
waited = true;
} else {
ldr.wait(DEFAULT_READ_TIMEOUT_MILLIS);
// no timeout is set so we wait infinitely until
// a response is received
// http://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP
ldr.wait();
}
waited = true;
} else {
break;
}
......
......@@ -293,6 +293,7 @@ public final class SplashScreen {
*/
public Graphics2D createGraphics() throws IllegalStateException {
synchronized (SplashScreen.class) {
checkVisible();
if (image==null) {
// get unscaled splash image size
Dimension dim = _getBounds(splashPtr).getSize();
......@@ -419,4 +420,4 @@ public final class SplashScreen {
private native static boolean _setImageData(long SplashPtr, byte[] data);
private native static float _getScaleFactor(long SplashPtr);
};
}
/*
* Copyright (c) 1996, 2006, 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
......@@ -44,7 +44,7 @@ import java.util.EventListener;
*
* @see KeyAdapter
* @see KeyEvent
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/keylistener.html">Tutorial: Writing a Key Listener</a>
* @see <a href="https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html">Tutorial: Writing a Key Listener</a>
*
* @since 1.1
*/
......
......@@ -689,6 +689,8 @@ public final class Class<T> implements java.io.Serializable,
ClassLoader getClassLoader0() { return classLoader; }
// Initialized in JVM not by private constructor
// This field is filtered from reflection access, i.e. getDeclaredField
// will throw NoSuchFieldException
private final ClassLoader classLoader;
/**
......
......@@ -584,7 +584,10 @@ public final class System {
* <tr><td><code>java.compiler</code></td>
* <td>Name of JIT compiler to use</td></tr>
* <tr><td><code>java.ext.dirs</code></td>
* <td>Path of extension directory or directories</td></tr>
* <td>Path of extension directory or directories
* <b>Deprecated.</b> <i>This property, and the mechanism
* which implements it, may be removed in a future
* release.</i> </td></tr>
* <tr><td><code>os.name</code></td>
* <td>Operating system name</td></tr>
* <tr><td><code>os.arch</code></td>
......
......@@ -140,13 +140,6 @@ public class AccessibleObject implements AnnotatedElement {
throw new SecurityException("Cannot make a java.lang.Class" +
" constructor accessible");
}
} else if (obj instanceof Field && flag == true) {
Field f = (Field)obj;
if (f.getDeclaringClass() == Class.class &&
f.getName().equals("classLoader")) {
throw new SecurityException("Cannot make java.lang.Class.classLoader" +
" accessible");
}
}
obj.override = flag;
}
......
......@@ -25,7 +25,6 @@
package java.util;
import java.net.NetworkInterface;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
......@@ -140,11 +139,10 @@ public final class SplittableRandom {
* other cases, this split must be performed in a thread-safe
* manner, so we use an AtomicLong to represent the seed rather
* than use an explicit SplittableRandom. To bootstrap the
* defaultGen, we start off using a seed based on current time and
* network interface address unless the java.util.secureRandomSeed
* property is set. This serves as a slimmed-down (and insecure)
* variant of SecureRandom that also avoids stalls that may occur
* when using /dev/random.
* defaultGen, we start off using a seed based on current time
* unless the java.util.secureRandomSeed property is set. This
* serves as a slimmed-down (and insecure) variant of SecureRandom
* that also avoids stalls that may occur when using /dev/random.
*
* It is a relatively simple matter to apply the basic design here
* to use 128 bit seeds. However, emulating 128bit arithmetic and
......@@ -237,34 +235,7 @@ public final class SplittableRandom {
s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
return s;
}
long h = 0L;
try {
Enumeration<NetworkInterface> ifcs =
NetworkInterface.getNetworkInterfaces();
boolean retry = false; // retry once if getHardwareAddress is null
while (ifcs.hasMoreElements()) {
NetworkInterface ifc = ifcs.nextElement();
if (!ifc.isVirtual()) { // skip fake addresses
byte[] bs = ifc.getHardwareAddress();
if (bs != null) {
int n = bs.length;
int m = Math.min(n >>> 1, 4);
for (int i = 0; i < m; ++i)
h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
if (m < 4)
h = (h << 8) ^ bs[n-1-m];
h = mix64(h);
break;
}
else if (!retry)
retry = true;
else
break;
}
}
} catch (Exception ignore) {
}
return (h ^ mix64(System.currentTimeMillis()) ^
return (mix64(System.currentTimeMillis()) ^
mix64(System.nanoTime()));
}
......
......@@ -36,8 +36,6 @@
package java.util.concurrent;
import java.io.ObjectStreamField;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Random;
import java.util.Spliterator;
import java.util.concurrent.atomic.AtomicInteger;
......@@ -147,34 +145,7 @@ public class ThreadLocalRandom extends Random {
s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
return s;
}
long h = 0L;
try {
Enumeration<NetworkInterface> ifcs =
NetworkInterface.getNetworkInterfaces();
boolean retry = false; // retry once if getHardwareAddress is null
while (ifcs.hasMoreElements()) {
NetworkInterface ifc = ifcs.nextElement();
if (!ifc.isVirtual()) { // skip fake addresses
byte[] bs = ifc.getHardwareAddress();
if (bs != null) {
int n = bs.length;
int m = Math.min(n >>> 1, 4);
for (int i = 0; i < m; ++i)
h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
if (m < 4)
h = (h << 8) ^ bs[n-1-m];
h = mix64(h);
break;
}
else if (!retry)
retry = true;
else
break;
}
}
} catch (Exception ignore) {
}
return (h ^ mix64(System.currentTimeMillis()) ^
return (mix64(System.currentTimeMillis()) ^
mix64(System.nanoTime()));
}
......
......@@ -550,8 +550,8 @@ public class Attributes implements Map<Object,Object>, Cloneable {
* <code>Name</code> object for <code>Class-Path</code>
* manifest attribute. Bundled extensions can use this attribute
* to find other JAR files containing needed classes.
* @see <a href="../../../../technotes/guides/extensions/spec.html#bundled">
* Extensions Specification</a>
* @see <a href="../../../../technotes/guides/jar/jar.html#classpath">
* JAR file specification</a>
*/
public static final Name CLASS_PATH = new Name("Class-Path");
......@@ -567,8 +567,8 @@ public class Attributes implements Map<Object,Object>, Cloneable {
/**
* <code>Name</code> object for <code>Sealed</code> manifest attribute
* used for sealing.
* @see <a href="../../../../technotes/guides/extensions/spec.html#sealing">
* Extension Sealing</a>
* @see <a href="../../../../technotes/guides/jar/jar.html#sealing">
* Package Sealing</a>
*/
public static final Name SEALED = new Name("Sealed");
......@@ -591,9 +591,12 @@ public class Attributes implements Map<Object,Object>, Cloneable {
/**
* <code>Name</code> object for <code>Extension-Name</code> manifest attribute
* used for declaring dependencies on installed extensions.
* @deprecated Extension mechanism will be removed in a future release.
* Use class path instead.
* @see <a href="../../../../technotes/guides/extensions/spec.html#dependency">
* Installed extension dependency</a>
*/
@Deprecated
public static final Name EXTENSION_INSTALLATION = new Name("Extension-Installation");
/**
......@@ -623,17 +626,23 @@ public class Attributes implements Map<Object,Object>, Cloneable {
/**
* <code>Name</code> object for <code>Implementation-Vendor-Id</code>
* manifest attribute used for package versioning.
* @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779">
* Java Product Versioning Specification</a>
* @deprecated Extension mechanism will be removed in a future release.
* Use class path instead.
* @see <a href="../../../../technotes/guides/extensions/versioning.html#applet">
* Optional Package Versioning</a>
*/
@Deprecated
public static final Name IMPLEMENTATION_VENDOR_ID = new Name("Implementation-Vendor-Id");
/**
* <code>Name</code> object for <code>Implementation-URL</code>
* manifest attribute used for package versioning.
* @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779">
* Java Product Versioning Specification</a>
* @deprecated Extension mechanism will be removed in a future release.
* Use class path instead.
* @see <a href="../../../../technotes/guides/extensions/versioning.html#applet">
* Optional Package Versioning</a>
*/
@Deprecated
public static final Name IMPLEMENTATION_URL = new Name("Implementation-URL");
/**
......
......@@ -502,11 +502,11 @@ public class LogManager {
JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess();
if (sm != null && javaAwtAccess != null) {
// for each applet, it has its own LoggerContext isolated from others
final Object ecx = javaAwtAccess.getAppletContext();
if (ecx != null) {
synchronized (javaAwtAccess) {
// find the AppContext of the applet code
// will be null if we are in the main app context.
final Object ecx = javaAwtAccess.getAppletContext();
if (ecx != null) {
if (contextsMap == null) {
contextsMap = new WeakHashMap<>();
}
......
......@@ -1308,8 +1308,8 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible {
*/
public void actionPerformed(ActionEvent e) {
ComboBoxEditor editor = getEditor();
if ((editor != null) && (e != null)
&& (editor.getEditorComponent() == e.getSource())) {
if ((editor != null) && (e != null) && (editor == e.getSource()
|| editor.getEditorComponent() == e.getSource())) {
setPopupVisible(false);
getModel().setSelectedItem(editor.getItem());
String oldCommand = getActionCommand();
......
......@@ -274,7 +274,7 @@ public abstract class DataTransferer {
* instead, null will be returned.
*/
public static synchronized DataTransferer getInstance() {
return ((SunToolkit) Toolkit.getDefaultToolkit()).getDataTransferer();
return ((ComponentFactory) Toolkit.getDefaultToolkit()).getDataTransferer();
}
/**
......
......@@ -364,8 +364,53 @@ public class DrawImage implements DrawImagePipe
int sx1, int sy1, int sx2, int sy2,
Color bgColor)
{
final AffineTransform itx;
try {
itx = tx.createInverse();
} catch (final NoninvertibleTransformException ignored) {
// Non-invertible transform means no output
return;
}
/*
* Find the maximum bounds on the destination that will be
* affected by the transformed source. First, transform all
* four corners of the source and then min and max the resulting
* destination coordinates of the transformed corners.
* Note that tx already has the offset to sx1,sy1 accounted
* for so we use the box (0, 0, sx2-sx1, sy2-sy1) as the
* source coordinates.
*/
final double[] coords = new double[8];
/* corner: UL UR LL LR */
/* index: 0 1 2 3 4 5 6 7 */
/* coord: (0, 0), (w, 0), (0, h), (w, h) */
coords[2] = coords[6] = sx2 - sx1;
coords[5] = coords[7] = sy2 - sy1;
tx.transform(coords, 0, coords, 0, 4);
double ddx1, ddy1, ddx2, ddy2;
ddx1 = ddx2 = coords[0];
ddy1 = ddy2 = coords[1];
for (int i = 2; i < coords.length; i += 2) {
double d = coords[i];
if (ddx1 > d) ddx1 = d;
else if (ddx2 < d) ddx2 = d;
d = coords[i+1];
if (ddy1 > d) ddy1 = d;
else if (ddy2 < d) ddy2 = d;
}
Region clip = sg.getCompClip();
SurfaceData dstData = sg.surfaceData;
final int dx1 = Math.max((int) Math.floor(ddx1), clip.lox);
final int dy1 = Math.max((int) Math.floor(ddy1), clip.loy);
final int dx2 = Math.min((int) Math.ceil(ddx2), clip.hix);
final int dy2 = Math.min((int) Math.ceil(ddy2), clip.hiy);
if (dx2 <= dx1 || dy2 <= dy1) {
// empty destination means no output
return;
}
final SurfaceData dstData = sg.surfaceData;
SurfaceData srcData = dstData.getSourceSurfaceData(img,
SunGraphics2D.TRANSFORM_GENERIC,
sg.imageComp,
......@@ -429,56 +474,13 @@ public class DrawImage implements DrawImagePipe
// assert(helper != null);
}
AffineTransform itx;
try {
itx = tx.createInverse();
} catch (NoninvertibleTransformException e) {
// Non-invertible transform means no output
return;
}
/*
* Find the maximum bounds on the destination that will be
* affected by the transformed source. First, transform all
* four corners of the source and then min and max the resulting
* destination coordinates of the transformed corners.
* Note that tx already has the offset to sx1,sy1 accounted
* for so we use the box (0, 0, sx2-sx1, sy2-sy1) as the
* source coordinates.
*/
double coords[] = new double[8];
/* corner: UL UR LL LR */
/* index: 0 1 2 3 4 5 6 7 */
/* coord: (0, 0), (w, 0), (0, h), (w, h) */
coords[2] = coords[6] = sx2 - sx1;
coords[5] = coords[7] = sy2 - sy1;
tx.transform(coords, 0, coords, 0, 4);
double ddx1, ddy1, ddx2, ddy2;
ddx1 = ddx2 = coords[0];
ddy1 = ddy2 = coords[1];
for (int i = 2; i < coords.length; i += 2) {
double d = coords[i];
if (ddx1 > d) ddx1 = d;
else if (ddx2 < d) ddx2 = d;
d = coords[i+1];
if (ddy1 > d) ddy1 = d;
else if (ddy2 < d) ddy2 = d;
}
int dx1 = (int) Math.floor(ddx1);
int dy1 = (int) Math.floor(ddy1);
int dx2 = (int) Math.ceil(ddx2);
int dy2 = (int) Math.ceil(ddy2);
SurfaceType dstType = dstData.getSurfaceType();
MaskBlit maskblit;
Blit blit;
if (sg.compositeState <= SunGraphics2D.COMP_ALPHA) {
/* NOTE: We either have, or we can make,
* a MaskBlit for any alpha composite type
*/
maskblit = MaskBlit.getFromCache(SurfaceType.IntArgbPre,
sg.imageComp,
dstType);
MaskBlit maskblit = MaskBlit.getFromCache(SurfaceType.IntArgbPre,
sg.imageComp, dstType);
/* NOTE: We can only use the native TransformHelper
* func to go directly to the dest if both the helper
......@@ -496,25 +498,17 @@ public class DrawImage implements DrawImagePipe
null, 0, 0);
return;
}
blit = null;
} else {
/* NOTE: We either have, or we can make,
* a Blit for any composite type, even Custom
*/
maskblit = null;
blit = Blit.getFromCache(SurfaceType.IntArgbPre,
sg.imageComp,
dstType);
}
// We need to transform to a temp image and then copy
// just the pieces that are valid data to the dest.
BufferedImage tmpimg = new BufferedImage(dx2-dx1, dy2-dy1,
final int w = dx2 - dx1;
final int h = dy2 - dy1;
BufferedImage tmpimg = new BufferedImage(w, h,
BufferedImage.TYPE_INT_ARGB_PRE);
SurfaceData tmpData = SurfaceData.getPrimarySurfaceData(tmpimg);
SurfaceType tmpType = tmpData.getSurfaceType();
MaskBlit tmpmaskblit =
MaskBlit.getFromCache(SurfaceType.IntArgbPre,
MaskBlit tmpmaskblit = MaskBlit.getFromCache(SurfaceType.IntArgbPre,
CompositeType.SrcNoEa,
tmpType);
/*
......@@ -531,7 +525,7 @@ public class DrawImage implements DrawImagePipe
*
* edges thus has to be h*2+2 in length
*/
int edges[] = new int[(dy2-dy1)*2+2];
final int[] edges = new int[h * 2 + 2];
// It is important that edges[0]=edges[1]=0 when we call
// Transform in case it must return early and we would
// not want to render anything on an error condition.
......@@ -539,35 +533,17 @@ public class DrawImage implements DrawImagePipe
AlphaComposite.Src, null,
itx, interpType,
sx1, sy1, sx2, sy2,
0, 0, dx2-dx1, dy2-dy1,
0, 0, w, h,
edges, dx1, dy1);
/*
* Now copy the results, scanline by scanline, into the dest.
* The edges array helps us minimize the work.
final Region region = Region.getInstance(dx1, dy1, dx2, dy2, edges);
clip = clip.getIntersection(region);
/* NOTE: We either have, or we can make,
* a Blit for any composite type, even Custom
*/
int index = 2;
for (int y = edges[0]; y < edges[1]; y++) {
int relx1 = edges[index++];
int relx2 = edges[index++];
if (relx1 >= relx2) {
continue;
}
if (maskblit != null) {
maskblit.MaskBlit(tmpData, dstData,
sg.composite, clip,
relx1, y,
dx1+relx1, dy1+y,
relx2 - relx1, 1,
null, 0, 0);
} else {
blit.Blit(tmpData, dstData,
sg.composite, clip,
relx1, y,
dx1+relx1, dy1+y,
relx2 - relx1, 1);
}
}
final Blit blit = Blit.getFromCache(tmpType, sg.imageComp, dstType);
blit.Blit(tmpData, dstData, sg.composite, clip, 0, 0, dx1, dy1, w, h);
}
// Render an image using only integer translation
......
......@@ -30,6 +30,8 @@ import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.RectangularShape;
import sun.java2d.loops.TransformHelper;
/**
* This class encapsulates a definition of a two dimensional region which
* consists of a number of Y ranges each containing multiple X bands.
......@@ -160,6 +162,15 @@ public class Region {
this.hiy = hiy;
}
private Region(int lox, int loy, int hix, int hiy, int[] bands, int end) {
this.lox = lox;
this.loy = loy;
this.hix = hix;
this.hiy = hiy;
this.bands = bands;
this.endIndex = end;
}
/**
* Returns a Region object covering the pixels which would be
* touched by a fill or clip operation on a Graphics implementation
......@@ -255,6 +266,44 @@ public class Region {
}
}
/**
* Returns a Region object with a rectangle of interest specified by the
* indicated rectangular area in lox, loy, hix, hiy and edges array, which
* is located relative to the rectangular area. Edges array - 0,1 are y
* range, 2N,2N+1 are x ranges, 1 per y range.
*
* @see TransformHelper
*/
static Region getInstance(final int lox, final int loy, final int hix,
final int hiy, final int[] edges) {
final int y1 = edges[0];
final int y2 = edges[1];
if (hiy <= loy || hix <= lox || y2 <= y1) {
return EMPTY_REGION;
}
// rowsNum * (3 + 1 * 2)
final int[] bands = new int[(y2 - y1) * 5];
int end = 0;
int index = 2;
for (int y = y1; y < y2; ++y) {
final int spanlox = Math.max(clipAdd(lox, edges[index++]), lox);
final int spanhix = Math.min(clipAdd(lox, edges[index++]), hix);
if (spanlox < spanhix) {
final int spanloy = Math.max(clipAdd(loy, y), loy);
final int spanhiy = Math.min(clipAdd(spanloy, 1), hiy);
if (spanloy < spanhiy) {
bands[end++] = spanloy;
bands[end++] = spanhiy;
bands[end++] = 1; // 1 span per row
bands[end++] = spanlox;
bands[end++] = spanhix;
}
}
}
return end != 0 ? new Region(lox, loy, hix, hiy, bands, end)
: EMPTY_REGION;
}
/**
* Returns a Region object with a rectangle of interest specified
* by the indicated Rectangle object.
......
......@@ -46,6 +46,7 @@ public class Reflection {
map.put(Reflection.class,
new String[] {"fieldFilterMap", "methodFilterMap"});
map.put(System.class, new String[] {"security"});
map.put(Class.class, new String[] {"classLoader"});
fieldFilterMap = map;
methodFilterMap = new HashMap<>();
......
......@@ -674,6 +674,9 @@ OGLBlitLoops_Blit(JNIEnv *env,
viaTexture = JNI_TRUE;
break;
#endif
case OGLC_VENDOR_INTEL:
viaTexture = JNI_TRUE;
break;
default:
// just use the glDrawPixels() codepath
viaTexture = JNI_FALSE;
......
......@@ -917,8 +917,8 @@ OGLContext_GetExtensionInfo(JNIEnv *env, jint *caps)
vcap = OGLC_VENDOR_ATI;
} else if (strncmp(vendor, "NVIDIA", 6) == 0) {
vcap = OGLC_VENDOR_NVIDIA;
} else if (strncmp(vendor, "Sun", 3) == 0) {
vcap = OGLC_VENDOR_SUN;
} else if (strncmp(vendor, "Intel", 5) == 0) {
vcap = OGLC_VENDOR_INTEL;
}
// REMIND: new in 7 - check if needs fixing
*caps |= ((vcap & OGLC_VCAP_MASK) << OGLC_VCAP_OFFSET);
......
......@@ -152,7 +152,7 @@ typedef struct {
#define OGLC_VENDOR_OTHER 0
#define OGLC_VENDOR_ATI 1
#define OGLC_VENDOR_NVIDIA 2
#define OGLC_VENDOR_SUN 3
#define OGLC_VENDOR_INTEL 3
#define OGLC_VCAP_MASK 0x3
#define OGLC_VCAP_OFFSET 24
......
......@@ -102,11 +102,11 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
static TreeMap winMap = new TreeMap();
static HashMap specialPeerMap = new HashMap();
static HashMap winToDispatcher = new HashMap();
private static long _display;
static UIDefaults uidefaults;
static X11GraphicsEnvironment localEnv;
static X11GraphicsDevice device;
static final X11GraphicsConfig config;
static final X11GraphicsEnvironment localEnv;
private static final X11GraphicsDevice device;
private static final X11GraphicsConfig config;
private static final long display;
static int awt_multiclick_time;
static boolean securityWarningEnabled;
......@@ -117,15 +117,16 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
static {
initSecurityWarning();
if (GraphicsEnvironment.isHeadless()) {
localEnv = null;
device = null;
config = null;
display = 0;
} else {
localEnv = (X11GraphicsEnvironment) GraphicsEnvironment
.getLocalGraphicsEnvironment();
device = (X11GraphicsDevice) localEnv.getDefaultScreenDevice();
config = (X11GraphicsConfig) (device.getDefaultConfiguration());
if (device != null) {
_display = device.getDisplay();
}
config = (X11GraphicsConfig) device.getDefaultConfiguration();
display = device.getDisplay();
setupModifierMap();
initIDs();
setBackingStoreType();
......@@ -196,10 +197,18 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
}
}
static Object displayLock = new Object();
/**
* Returns the X11 Display of the default screen device.
*
* @return X11 Display
* @throws AWTError thrown if local GraphicsEnvironment is null, which
* means we are in the headless environment
*/
public static long getDisplay() {
return _display;
if (localEnv == null) {
throw new AWTError("Local GraphicsEnvironment must not be null");
}
return display;
}
public static long getDefaultRootWindow() {
......
......@@ -28,167 +28,440 @@
* @summary Timeout tests for ldap
*/
import com.sun.jndi.ldap.Connection;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import java.io.*;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.List;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class LdapTimeoutTest {
static volatile int passed = 0, failed = 0;
static void pass() {passed++;}
static void fail() {failed++; Thread.dumpStack();}
abstract class LdapTest implements Callable {
public static void main(String[] args) throws Exception {
ServerSocket serverSock = new ServerSocket(0);
Server s = new Server(serverSock);
s.start();
Thread.sleep(200);
Hashtable env;
TestServer server;
ScheduledExecutorService killSwitchPool;
boolean passed = false;
private int HANGING_TEST_TIMEOUT = 20_000;
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:" +
serverSock.getLocalPort());
public LdapTest (TestServer server, Hashtable env) {
this.server = server;
this.env = env;
}
env.put(Context.SECURITY_AUTHENTICATION,"simple");
public LdapTest(TestServer server, Hashtable env,
ScheduledExecutorService killSwitchPool)
{
this(server, env);
this.killSwitchPool = killSwitchPool;
}
env.put(Context.SECURITY_PRINCIPAL, "user");
env.put(Context.SECURITY_CREDENTIALS, "password");
public abstract void performOp(InitialContext ctx) throws NamingException;
public abstract void handleNamingException(
NamingException e, long start, long end);
InitialContext ctx = null;
try {
new LdapTimeoutTest().deadServerNoTimeout(env);
public void pass() {
this.passed = true;
}
env.put("com.sun.jndi.ldap.connect.timeout", "10");
env.put("com.sun.jndi.ldap.read.timeout", "3000");
new LdapTimeoutTest().ldapReadTimeoutTest(env, false);
new LdapTimeoutTest().ldapReadTimeoutTest(env, true);
new LdapTimeoutTest().simpleAuthConnectTest(env);
} finally {
s.interrupt();
public void fail() {
throw new RuntimeException("Test failed");
}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");
boolean shutItDown(InitialContext ctx) {
try {
if (ctx != null) ctx.close();
return true;
} catch (NamingException ex) {
return false;
}
}
void ldapReadTimeoutTest(Hashtable env, boolean ssl) {
public Boolean call() {
InitialContext ctx = null;
if (ssl) env.put(Context.SECURITY_PROTOCOL, "ssl");
ScheduledFuture killer = null;
long start = System.nanoTime();
try {
while(!server.accepting())
Thread.sleep(200); // allow the server to start up
Thread.sleep(200); // to be sure
// if this is a hanging test, scheduled a thread to
// interrupt after a certain time
if (killSwitchPool != null) {
final Thread current = Thread.currentThread();
killer = killSwitchPool.schedule(
new Callable<Void>() {
public Void call() throws Exception {
current.interrupt();
return null;
}
}, HANGING_TEST_TIMEOUT, MILLISECONDS);
}
env.put(Context.PROVIDER_URL, "ldap://localhost:" +
server.getLocalPort());
try {
ctx = new InitialDirContext(env);
performOp(ctx);
fail();
} catch (NamingException e) {
long end = System.nanoTime();
System.out.println(this.getClass().toString() + " - elapsed: "
+ NANOSECONDS.toMillis(end - start));
handleNamingException(e, start, end);
} finally {
if (killer != null && !killer.isDone())
killer.cancel(true);
shutItDown(ctx);
server.close();
}
return passed;
} catch (IOException|InterruptedException e) {
throw new RuntimeException(e);
}
}
}
abstract class ReadServerTest extends LdapTest {
public ReadServerTest(Hashtable env) throws IOException {
super(new BindableServer(), env);
}
public ReadServerTest(Hashtable env,
ScheduledExecutorService killSwitchPool)
throws IOException
{
super(new BindableServer(), env, killSwitchPool);
}
public void performOp(InitialContext ctx) throws NamingException {
SearchControls scl = new SearchControls();
scl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer = ((InitialDirContext)ctx)
.search("ou=People,o=JNDITutorial", "(objectClass=*)", scl);
// shouldn't reach here
fail();
} catch (NamingException e) {
if (ssl) {
if (e.getCause() instanceof SocketTimeoutException) {
pass();
} else if (e.getCause() instanceof InterruptedIOException) {
Thread.interrupted();
fail();
}
}
abstract class DeadServerTest extends LdapTest {
public DeadServerTest(Hashtable env) throws IOException {
super(new DeadServer(), env);
}
public DeadServerTest(Hashtable env,
ScheduledExecutorService killSwitchPool)
throws IOException
{
super(new DeadServer(), env, killSwitchPool);
}
public void performOp(InitialContext ctx) throws NamingException {}
}
class DeadServerNoTimeoutTest extends DeadServerTest {
public DeadServerNoTimeoutTest(Hashtable env,
ScheduledExecutorService killSwitchPool)
throws IOException
{
super(env, killSwitchPool);
}
public void handleNamingException(NamingException e, long start, long end) {
if (e instanceof InterruptedNamingException) Thread.interrupted();
if (NANOSECONDS.toMillis(end - start) < LdapTimeoutTest.MIN_TIMEOUT) {
System.err.printf("DeadServerNoTimeoutTest fail: timeout should be " +
"at least %s ms, actual time is %s ms%n",
LdapTimeoutTest.MIN_TIMEOUT,
NANOSECONDS.toMillis(end - start));
fail();
} else {
pass();
}
} finally {
if (!shutItDown(ctx)) fail();
}
}
class DeadServerTimeoutTest extends DeadServerTest {
public DeadServerTimeoutTest(Hashtable env) throws IOException {
super(env);
}
void simpleAuthConnectTest(Hashtable env) {
InitialContext ctx = null;
long start = System.nanoTime();
try {
ctx = new InitialDirContext(env);
// shouldn't reach here
System.err.println("Fail: InitialDirContext succeeded");
fail();
} catch (NamingException e) {
long end = System.nanoTime();
if (e.getCause() instanceof SocketTimeoutException) {
public void handleNamingException(NamingException e, long start, long end)
{
// non SSL connect will timeout via readReply using connectTimeout
if (NANOSECONDS.toMillis(end - start) < 2_900) {
pass();
} else {
System.err.println("Fail: Waited too long");
fail();
}
} else if (e.getCause() instanceof InterruptedIOException) {
Thread.interrupted();
fail();
}
}
class DeadServerTimeoutSSLTest extends DeadServerTest {
public DeadServerTimeoutSSLTest(Hashtable env) throws IOException {
super(env);
}
public void handleNamingException(NamingException e, long start, long end) {
if (e.getCause() instanceof SocketTimeoutException) {
// SSL connect will timeout via readReply using
// SocketTimeoutException
pass();
} else {
fail();
}
} finally {
if (!shutItDown(ctx)) fail();
}
}
class ReadServerNoTimeoutTest extends ReadServerTest {
public ReadServerNoTimeoutTest(Hashtable env,
ScheduledExecutorService killSwitchPool)
throws IOException
{
super(env, killSwitchPool);
}
void deadServerNoTimeout(Hashtable env) {
InitialContext ctx = null;
long start = System.currentTimeMillis();
try {
ctx = new InitialDirContext(env);
SearchControls scl = new SearchControls();
scl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer = ((InitialDirContext)ctx)
.search("ou=People,o=JNDITutorial", "(objectClass=*)", scl);
// shouldn't reach here
public void handleNamingException(NamingException e, long start, long end) {
if (e instanceof InterruptedNamingException) Thread.interrupted();
if (NANOSECONDS.toMillis(end - start) < LdapTimeoutTest.MIN_TIMEOUT) {
System.err.printf("ReadServerNoTimeoutTest fail: timeout should be " +
"at least %s ms, actual time is %s ms%n",
LdapTimeoutTest.MIN_TIMEOUT,
NANOSECONDS.toMillis(end - start));
fail();
} catch (NamingException e) {
long elapsed = System.currentTimeMillis() - start;
if (elapsed < Connection.DEFAULT_READ_TIMEOUT_MILLIS) {
System.err.printf("fail: timeout should be at least %s ms, " +
"actual time is %s ms%n",
Connection.DEFAULT_READ_TIMEOUT_MILLIS, elapsed);
e.printStackTrace();
} else {
pass();
}
}
}
class ReadServerTimeoutTest extends ReadServerTest {
public ReadServerTimeoutTest(Hashtable env) throws IOException {
super(env);
}
public void handleNamingException(NamingException e, long start, long end) {
if (NANOSECONDS.toMillis(end - start) < 2_900) {
fail();
} else {
pass();
}
} finally {
if (!shutItDown(ctx)) fail();
}
}
class TestServer extends Thread {
ServerSocket serverSock;
boolean accepting = false;
public TestServer() throws IOException {
this.serverSock = new ServerSocket(0);
start();
}
boolean shutItDown(InitialContext ctx) {
public int getLocalPort() {
return serverSock.getLocalPort();
}
public boolean accepting() {
return accepting;
}
public void close() throws IOException {
serverSock.close();
}
}
class BindableServer extends TestServer {
public BindableServer() throws IOException {
super();
}
private byte[] bindResponse = {
0x30, 0x0C, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0A,
0x01, 0x00, 0x04, 0x00, 0x04, 0x00
};
public void run() {
try {
if (ctx != null) ctx.close();
return true;
} catch (NamingException ex) {
return false;
accepting = true;
Socket socket = serverSock.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// Read the LDAP BindRequest
while (in.read() != -1) {
in.skip(in.available());
break;
}
// Write an LDAP BindResponse
out.write(bindResponse);
out.flush();
} catch (IOException e) {
// ignore
}
}
}
static class Server extends Thread {
final ServerSocket serverSock;
class DeadServer extends TestServer {
Server(ServerSocket serverSock) {
this.serverSock = serverSock;
public DeadServer() throws IOException {
super();
}
public void run() {
while(true) {
try {
accepting = true;
Socket socket = serverSock.accept();
} catch (IOException e) {}
} catch (Exception e) {
break;
}
}
}
}
public class LdapTimeoutTest {
private static final ExecutorService testPool =
Executors.newFixedThreadPool(3);
private static final ScheduledExecutorService killSwitchPool =
Executors.newScheduledThreadPool(3);
public static int MIN_TIMEOUT = 18_000;
static Hashtable createEnv() {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
return env;
}
public static void main(String[] args) throws Exception {
InitialContext ctx = null;
List<Future> results = new ArrayList<>();
try {
// run the DeadServerTest with no timeouts set
// this should get stuck indefinitely, so we need to kill
// it after a timeout
System.out.println("Running connect timeout test with 20s kill switch");
Hashtable env = createEnv();
results.add(
testPool.submit(new DeadServerNoTimeoutTest(env, killSwitchPool)));
// run the ReadServerTest with connect timeout set
// this should get stuck indefinitely so we need to kill
// it after a timeout
System.out.println("Running read timeout test with 10ms connect timeout & 20s kill switch");
Hashtable env1 = createEnv();
env1.put("com.sun.jndi.ldap.connect.timeout", "10");
results.add(testPool.submit(
new ReadServerNoTimeoutTest(env1, killSwitchPool)));
// run the ReadServerTest with no timeouts set
// this should get stuck indefinitely, so we need to kill
// it after a timeout
System.out.println("Running read timeout test with 20s kill switch");
Hashtable env2 = createEnv();
results.add(testPool.submit(
new ReadServerNoTimeoutTest(env2, killSwitchPool)));
// run the DeadServerTest with connect / read timeouts set
// this should exit after the connect timeout expires
System.out.println("Running connect timeout test with 10ms connect timeout, 3000ms read timeout");
Hashtable env3 = createEnv();
env3.put("com.sun.jndi.ldap.connect.timeout", "10");
env3.put("com.sun.jndi.ldap.read.timeout", "3000");
results.add(testPool.submit(new DeadServerTimeoutTest(env3)));
// run the ReadServerTest with connect / read timeouts set
// this should exit after the connect timeout expires
System.out.println("Running read timeout test with 10ms connect timeout, 3000ms read timeout");
Hashtable env4 = createEnv();
env4.put("com.sun.jndi.ldap.connect.timeout", "10");
env4.put("com.sun.jndi.ldap.read.timeout", "3000");
results.add(testPool.submit(new ReadServerTimeoutTest(env4)));
// run the DeadServerTest with connect timeout set
// this should exit after the connect timeout expires
System.out.println("Running connect timeout test with 10ms connect timeout");
Hashtable env5 = createEnv();
env5.put("com.sun.jndi.ldap.connect.timeout", "10");
results.add(testPool.submit(new DeadServerTimeoutTest(env5)));
// 8000487: Java JNDI connection library on ldap conn is
// not honoring configured timeout
System.out.println("Running simple auth connection test");
Hashtable env6 = createEnv();
env6.put("com.sun.jndi.ldap.connect.timeout", "10");
env6.put("com.sun.jndi.ldap.read.timeout", "3000");
env6.put(Context.SECURITY_AUTHENTICATION, "simple");
env6.put(Context.SECURITY_PRINCIPAL, "user");
env6.put(Context.SECURITY_CREDENTIALS, "password");
results.add(testPool.submit(new DeadServerTimeoutTest(env6)));
boolean testFailed = false;
for (Future test : results) {
while (!test.isDone()) {
if ((Boolean) test.get() == false)
testFailed = true;
}
}
//
// Running this test serially as it seems to tickle a problem
// on older kernels
//
// run the DeadServerTest with connect / read timeouts set
// and ssl enabled
// this should exit with a SocketTimeoutException as the root cause
// it should also use the connect timeout instead of the read timeout
System.out.println("Running connect timeout test with 10ms connect timeout, 3000ms read timeout & SSL");
Hashtable sslenv = createEnv();
sslenv.put("com.sun.jndi.ldap.connect.timeout", "10");
sslenv.put("com.sun.jndi.ldap.read.timeout", "3000");
sslenv.put(Context.SECURITY_PROTOCOL, "ssl");
testFailed = (new DeadServerTimeoutSSLTest(sslenv).call()) ? false : true;
if (testFailed) {
throw new AssertionError("some tests failed");
}
} finally {
LdapTimeoutTest.killSwitchPool.shutdown();
LdapTimeoutTest.testPool.shutdown();
}
}
}
/*
* 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.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferShort;
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_INT_ARGB;
/**
* @test
* @bug 8059942
* @summary Tests rotated clip when unmanaged image is drawn to VI.
* Results of the blit to compatibleImage are used for comparison.
* @author Sergey Bylokhov
*/
public final class IncorrectUnmanagedImageRotatedClip {
public static void main(final String[] args) throws IOException {
BufferedImage bi = makeUnmanagedBI();
fill(bi);
test(bi);
}
private static void test(final BufferedImage bi) throws IOException {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsConfiguration gc = ge.getDefaultScreenDevice()
.getDefaultConfiguration();
VolatileImage vi = gc.createCompatibleVolatileImage(500, 200,
TRANSLUCENT);
BufferedImage gold = gc.createCompatibleImage(500, 200, TRANSLUCENT);
// draw to compatible Image
draw(bi, gold);
// draw to volatile image
int attempt = 0;
BufferedImage snapshot;
while (true) {
if (++attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
vi.validate(gc);
if (vi.validate(gc) != VolatileImage.IMAGE_OK) {
continue;
}
draw(bi, vi);
snapshot = vi.getSnapshot();
if (vi.contentsLost()) {
continue;
}
break;
}
// validate images
for (int x = 0; x < gold.getWidth(); ++x) {
for (int y = 0; y < gold.getHeight(); ++y) {
if (gold.getRGB(x, y) != snapshot.getRGB(x, y)) {
ImageIO.write(gold, "png", new File("gold.png"));
ImageIO.write(snapshot, "png", new File("bi.png"));
throw new RuntimeException("Test failed.");
}
}
}
}
private static void draw(final BufferedImage from,final Image to) {
final Graphics2D g2d = (Graphics2D) to.getGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.setColor(Color.ORANGE);
g2d.fillRect(0, 0, to.getWidth(null), to.getHeight(null));
g2d.rotate(Math.toRadians(45));
g2d.clip(new Rectangle(41, 42, 43, 44));
g2d.drawImage(from, 50, 50, Color.blue, null);
g2d.dispose();
}
private static BufferedImage makeUnmanagedBI() {
final BufferedImage bi = new BufferedImage(500, 200, TYPE_INT_ARGB);
final DataBuffer db = bi.getRaster().getDataBuffer();
if (db instanceof DataBufferInt) {
((DataBufferInt) db).getData();
} else if (db instanceof DataBufferShort) {
((DataBufferShort) db).getData();
} else if (db instanceof DataBufferByte) {
((DataBufferByte) db).getData();
} else {
try {
bi.setAccelerationPriority(0.0f);
} catch (final Throwable ignored) {
}
}
return bi;
}
private static void fill(final Image image) {
final 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();
}
}
/*
* 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.lang.reflect.Field;
import java.lang.reflect.ReflectPermission;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @test
* @bug 8065552
* @summary test that all fields returned by getDeclaredFields() can be
* set accessible if the right permission is granted; this test
* also verifies that Class.classLoader final private field is
* hidden from reflection access.
* @run main/othervm ClassDeclaredFieldsTest UNSECURE
* @run main/othervm ClassDeclaredFieldsTest SECURE
*
* @author danielfuchs
*/
public class ClassDeclaredFieldsTest {
// Test with or without a security manager
public static enum TestCase {
UNSECURE, SECURE;
public void run() throws Exception {
System.out.println("Running test case: " + name());
Configure.setUp(this);
test(this);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
System.out.println(System.getProperty("java.version"));
if (args == null || args.length == 0) {
args = new String[] { "SECURE" };
} else if (args.length != 1) {
throw new IllegalArgumentException("Only one arg expected: "
+ Arrays.asList(args));
}
TestCase.valueOf(args[0]).run();
}
static void test(TestCase test) {
for (Field f : Class.class.getDeclaredFields()) {
f.setAccessible(true);
System.out.println("Field "+f.getName()+" is now accessible.");
if (f.getName().equals("classLoader")) {
throw new RuntimeException("Found "+f.getName()+" field!");
}
}
try {
Class.class.getDeclaredField("classLoader");
throw new RuntimeException("Expected NoSuchFieldException for"
+ " 'classLoader' field not raised");
} catch(NoSuchFieldException x) {
System.out.println("Got expected exception: " + x);
}
System.out.println("Passed "+test);
}
// A helper class to configure the security manager for the test,
// and bypass it when needed.
static class Configure {
static Policy policy = null;
static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() {
@Override
protected AtomicBoolean initialValue() {
return new AtomicBoolean(false);
}
};
static void setUp(TestCase test) {
switch (test) {
case SECURE:
if (policy == null && System.getSecurityManager() != null) {
throw new IllegalStateException("SecurityManager already set");
} else if (policy == null) {
policy = new SimplePolicy(TestCase.SECURE, allowAll);
Policy.setPolicy(policy);
System.setSecurityManager(new SecurityManager());
}
if (System.getSecurityManager() == null) {
throw new IllegalStateException("No SecurityManager.");
}
if (policy == null) {
throw new IllegalStateException("policy not configured");
}
break;
case UNSECURE:
if (System.getSecurityManager() != null) {
throw new IllegalStateException("SecurityManager already set");
}
break;
default:
throw new InternalError("No such testcase: " + test);
}
}
static void doPrivileged(Runnable run) {
allowAll.get().set(true);
try {
run.run();
} finally {
allowAll.get().set(false);
}
}
}
// A Helper class to build a set of permissions.
final static class PermissionsBuilder {
final Permissions perms;
public PermissionsBuilder() {
this(new Permissions());
}
public PermissionsBuilder(Permissions perms) {
this.perms = perms;
}
public PermissionsBuilder add(Permission p) {
perms.add(p);
return this;
}
public PermissionsBuilder addAll(PermissionCollection col) {
if (col != null) {
for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
perms.add(e.nextElement());
}
}
return this;
}
public Permissions toPermissions() {
final PermissionsBuilder builder = new PermissionsBuilder();
builder.addAll(perms);
return builder.perms;
}
}
// Policy for the test...
public static class SimplePolicy extends Policy {
final Permissions permissions;
final Permissions allPermissions;
final ThreadLocal<AtomicBoolean> allowAll; // actually: this should be in a thread locale
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
this.allowAll = allowAll;
// we don't actually need any permission to create our
// FileHandlers because we're passing invalid parameters
// which will make the creation fail...
permissions = new Permissions();
permissions.add(new RuntimePermission("accessDeclaredMembers"));
permissions.add(new ReflectPermission("suppressAccessChecks"));
// these are used for configuring the test itself...
allPermissions = new Permissions();
allPermissions.add(new java.security.AllPermission());
}
@Override
public boolean implies(ProtectionDomain domain, Permission permission) {
if (allowAll.get().get()) return allPermissions.implies(permission);
return permissions.implies(permission);
}
@Override
public PermissionCollection getPermissions(CodeSource codesource) {
return new PermissionsBuilder().addAll(allowAll.get().get()
? allPermissions : permissions).toPermissions();
}
@Override
public PermissionCollection getPermissions(ProtectionDomain domain) {
return new PermissionsBuilder().addAll(allowAll.get().get()
? allPermissions : permissions).toPermissions();
}
}
}
......@@ -2246,9 +2246,10 @@ public class Basic {
fail("Test failed: Process exited prematurely");
}
long end = System.nanoTime();
// give waitFor(timeout) a wide berth (200ms)
// Old AIX machines my need a little longer.
if ((end - start) > 200000000L * (AIX.is() ? 2 : 1))
// give waitFor(timeout) a wide berth (2s)
System.out.printf(" waitFor process: delta: %d%n",(end - start) );
if ((end - start) > TimeUnit.SECONDS.toNanos(2))
fail("Test failed: waitFor took too long (" + (end - start) + "ns)");
p.destroy();
......@@ -2272,19 +2273,23 @@ public class Basic {
final Process p = new ProcessBuilder(childArgs).start();
long start = System.nanoTime();
p.waitFor(1000, TimeUnit.MILLISECONDS);
p.waitFor(10, TimeUnit.MILLISECONDS);
long end = System.nanoTime();
if ((end - start) < 500000000)
if ((end - start) < TimeUnit.MILLISECONDS.toNanos(10))
fail("Test failed: waitFor didn't take long enough (" + (end - start) + "ns)");
p.destroy();
start = System.nanoTime();
p.waitFor(1000, TimeUnit.MILLISECONDS);
p.waitFor(8, TimeUnit.SECONDS);
end = System.nanoTime();
if ((end - start) > 900000000)
fail("Test failed: waitFor took too long on a dead process. (" + (end - start) + "ns)");
int exitValue = p.exitValue();
if ((end - start) > TimeUnit.SECONDS.toNanos(7))
fail("Test failed: waitFor took too long on a dead process. (" + (end - start) + "ns)"
+ ", exitValue: " + exitValue);
} catch (Throwable t) { unexpected(t); }
//----------------------------------------------------------------
......
......@@ -26,12 +26,12 @@
* @bug 8046703
* @summary Test verifies that lambda forms are garbage collected
* @author kshefov
* @ignore 8057020
* @library /lib/testlibrary/jsr292 /lib/testlibrary
* @ignore 8057020
* @build TestMethods
* @build LambdaFormTestCase
* @build LFGarbageCollectedTest
* @run main/othervm/timeout=600 -DtestLimit=150 LFGarbageCollectedTest
* @run main/othervm LFGarbageCollectedTest
*/
import java.lang.invoke.MethodHandle;
......
......@@ -31,7 +31,7 @@
* @build LambdaFormTestCase
* @build LFCachingTestCase
* @build LFMultiThreadCachingTest
* @run main/othervm/timeout=300 LFMultiThreadCachingTest
* @run main/othervm LFMultiThreadCachingTest
*/
import java.lang.invoke.MethodHandle;
......
......@@ -31,7 +31,7 @@
* @build LambdaFormTestCase
* @build LFCachingTestCase
* @build LFSingleThreadCachingTest
* @run main/othervm/timeout=300 LFSingleThreadCachingTest
* @run main/othervm LFSingleThreadCachingTest
*/
import java.lang.invoke.MethodHandle;
......
......@@ -27,6 +27,8 @@ import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.function.Function;
import jdk.testlibrary.Utils;
import jdk.testlibrary.TimeLimitedRunner;
/**
* Lambda forms caching test case class. Contains all necessary test routines to
......@@ -41,6 +43,7 @@ public abstract class LambdaFormTestCase {
private final static String INTERNAL_FORM_METHOD_NAME = "internalForm";
private static final double ITERATIONS_TO_CODE_CACHE_SIZE_RATIO
= 45 / (128.0 * 1024 * 1024);
private static final long TIMEOUT = Helper.IS_THOROUGH ? 0L : (long) (Utils.adjustTimeout(Utils.DEFAULT_TEST_TIMEOUT) * 0.9);
/**
* Reflection link to {@code j.l.i.MethodHandle.internalForm} method. It is
......@@ -59,6 +62,11 @@ public abstract class LambdaFormTestCase {
}
private final TestMethods testMethod;
private static long totalIterations = 0L;
private static long doneIterations = 0L;
private static boolean passed = true;
private static int testCounter = 0;
private static int failCounter = 0;
/**
* Test case constructor. Generates test cases with random method types for
......@@ -88,13 +96,10 @@ public abstract class LambdaFormTestCase {
* @param testMethods list of test methods
*/
public static void runTests(Function<TestMethods, LambdaFormTestCase> ctor, Collection<TestMethods> testMethods) {
boolean passed = true;
int testCounter = 0;
int failCounter = 0;
long testCaseNum = testMethods.size();
long iterations = Math.max(1, Helper.TEST_LIMIT / testCaseNum);
totalIterations = Math.max(1, Helper.TEST_LIMIT / testCaseNum);
System.out.printf("Number of iterations according to -DtestLimit is %d (%d cases)%n",
iterations, iterations * testCaseNum);
totalIterations, totalIterations * testCaseNum);
HotSpotDiagnosticMXBean hsDiagBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
long codeCacheSize = Long.parseLong(
hsDiagBean.getVMOption("ReservedCodeCacheSize").getValue());
......@@ -103,14 +108,18 @@ public abstract class LambdaFormTestCase {
* ITERATIONS_TO_CODE_CACHE_SIZE_RATIO);
System.out.printf("Number of iterations limited by code cache size is %d (%d cases)%n",
iterationsByCodeCacheSize, iterationsByCodeCacheSize * testCaseNum);
if (iterations > iterationsByCodeCacheSize) {
iterations = iterationsByCodeCacheSize;
if (totalIterations > iterationsByCodeCacheSize) {
totalIterations = iterationsByCodeCacheSize;
}
System.out.printf("Number of iterations is set to %d (%d cases)%n",
iterations, iterations * testCaseNum);
totalIterations, totalIterations * testCaseNum);
System.out.flush();
for (long i = 0; i < iterations; i++) {
System.err.println(String.format("Iteration %d:", i));
TimeLimitedRunner runner = new TimeLimitedRunner(TIMEOUT, 4.0d,
() -> {
if (doneIterations >= totalIterations) {
return false;
}
System.err.println(String.format("Iteration %d:", doneIterations));
for (TestMethods testMethod : testMethods) {
LambdaFormTestCase testCase = ctor.apply(testMethod);
try {
......@@ -126,6 +135,15 @@ public abstract class LambdaFormTestCase {
}
testCounter++;
}
doneIterations++;
return true;
});
try {
runner.call();
} catch (Throwable t) {
t.printStackTrace();
System.err.println("FAILED");
throw new Error("Unexpected error!");
}
if (!passed) {
throw new Error(String.format("%d of %d test cases FAILED! %n"
......
/*
* Copyright (c) 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
* 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.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* @test
* @bug 8065991
* @summary check that when LogManager is initialized, a deadlock similar
* to that described in 8065709 will not occur.
* @run main/othervm LogManagerAppContextDeadlock UNSECURE
* @run main/othervm LogManagerAppContextDeadlock SECURE
*
* @author danielfuchs
*/
public class LogManagerAppContextDeadlock {
public static final Semaphore sem = new Semaphore(0);
public static final Semaphore sem2 = new Semaphore(0);
public static final Semaphore sem3 = new Semaphore(-2);
public static volatile boolean goOn = true;
public static volatile Exception thrown;
// Emulate EventQueue
static class FakeEventQueue {
static final Logger logger = Logger.getLogger("foo");
}
// Emulate AppContext
static class FakeAppContext {
final static AtomicInteger numAppContexts = new AtomicInteger(0);
static final class FakeAppContextLock {}
static final FakeAppContextLock lock = new FakeAppContextLock();
static volatile FakeAppContext appContext;
final FakeEventQueue queue;
FakeAppContext() {
appContext = this;
numAppContexts.incrementAndGet();
// release sem2 to let Thread t2 call Logger.getLogger().
sem2.release();
try {
// Wait until we JavaAWTAccess is called by LogManager.
// Thread 2 will call Logger.getLogger() which will
// trigger a call to JavaAWTAccess - which will release
// sem, thus ensuring that Thread #2 is where we want it.
sem.acquire();
System.out.println("Sem acquired: Thread #2 has called JavaAWTAccess");
} catch(InterruptedException x) {
Thread.interrupted();
}
queue = new FakeEventQueue();
}
static FakeAppContext getAppContext() {
synchronized (lock) {
if (numAppContexts.get() == 0) {
return new FakeAppContext();
}
return appContext;
}
}
static {
sun.misc.SharedSecrets.setJavaAWTAccess(new sun.misc.JavaAWTAccess() {
@Override
public Object getAppletContext() {
if (numAppContexts.get() == 0) return null;
// We are in JavaAWTAccess, we can release sem and let
// FakeAppContext constructor proceeed.
System.out.println("Releasing Sem");
sem.release();
return getAppContext();
}
});
}
}
// Test with or without a security manager
public static enum TestCase {
UNSECURE, SECURE;
public void run() throws Exception {
System.out.println("Running test case: " + name());
Configure.setUp(this);
test(this);
}
}
public static void test(TestCase test) throws Exception {
Thread t1 = new Thread() {
@Override
public void run() {
sem3.release();
System.out.println("FakeAppContext.getAppContext()");
FakeAppContext.getAppContext();
System.out.println("Done: FakeAppContext.getAppContext()");
}
};
t1.setDaemon(true);
t1.start();
Thread t2 = new Thread() {
public void run() {
sem3.release();
try {
// Wait until Thread1 is in FakeAppContext constructor
sem2.acquire();
System.out.println("Sem2 acquired: Thread #1 will be waiting to acquire Sem");
} catch (InterruptedException ie) {
Thread.interrupted();
}
System.out.println("Logger.getLogger(name).info(name)");
Logger.getLogger(test.name());//.info(name);
System.out.println("Done: Logger.getLogger(name).info(name)");
}
};
t2.setDaemon(true);
t2.start();
System.out.println("Should exit now...");
Thread detector = new DeadlockDetector();
detector.start();
// Wait for the 3 threads to start
sem3.acquire();
// Now wait for t1 & t2 to finish, or for a deadlock to be detected.
while (goOn && (t1.isAlive() || t2.isAlive())) {
if (t2.isAlive()) t2.join(1000);
if (test == TestCase.UNSECURE && System.getSecurityManager() == null) {
// if there's no security manager, AppContext.getAppContext() is
// not called - so Thread t2 will not end up calling
// sem.release(). In that case we must release the semaphore here
// so that t1 can proceed.
if (LogManager.getLogManager().getLogger(TestCase.UNSECURE.name()) != null) {
// means Thread t2 has created the logger
sem.release();
}
}
if (t1.isAlive()) t1.join(1000);
}
if (thrown != null) {
throw thrown;
}
}
// Thrown by the deadlock detector
static final class DeadlockException extends RuntimeException {
public DeadlockException(String message) {
super(message);
}
@Override
public void printStackTrace() {
}
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
args = new String[] { "SECURE" };
}
// If we don't initialize LogManager here, there will be
// a deadlock.
// See <https://bugs.openjdk.java.net/browse/JDK-8065709?focusedCommentId=13582038&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-13582038>
// for more details.
Logger.getLogger("main").info("starting...");
try {
TestCase.valueOf(args[0]).run();
System.out.println("Test "+args[0]+" Passed");
} catch(Throwable t) {
System.err.println("Test " + args[0] +" failed: " + t);
t.printStackTrace();
}
}
// Called by the deadlock detector when a deadlock is found.
static void fail(Exception x) {
x.printStackTrace();
if (thrown == null) {
thrown = x;
}
goOn = false;
}
// A thread that detect deadlocks.
final static class DeadlockDetector extends Thread {
public DeadlockDetector() {
this.setDaemon(true);
}
@Override
public void run() {
sem3.release();
Configure.doPrivileged(this::loop);
}
public void loop() {
while(goOn) {
try {
long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
ids = ids == null ? new long[0] : ids;
if (ids.length == 1) {
throw new RuntimeException("Found 1 deadlocked thread: "+ids[0]);
} else if (ids.length > 0) {
ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(ids, Integer.MAX_VALUE);
System.err.println("Found "+ids.length+" deadlocked threads: ");
for (ThreadInfo inf : infos) {
System.err.println(inf);
}
throw new DeadlockException("Found "+ids.length+" deadlocked threads");
}
Thread.sleep(100);
} catch(InterruptedException | RuntimeException x) {
fail(x);
}
}
}
}
// A helper class to configure the security manager for the test,
// and bypass it when needed.
static class Configure {
static Policy policy = null;
static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() {
@Override
protected AtomicBoolean initialValue() {
return new AtomicBoolean(false);
}
};
static void setUp(TestCase test) {
switch (test) {
case SECURE:
if (policy == null && System.getSecurityManager() != null) {
throw new IllegalStateException("SecurityManager already set");
} else if (policy == null) {
policy = new SimplePolicy(TestCase.SECURE, allowAll);
Policy.setPolicy(policy);
System.setSecurityManager(new SecurityManager());
}
if (System.getSecurityManager() == null) {
throw new IllegalStateException("No SecurityManager.");
}
if (policy == null) {
throw new IllegalStateException("policy not configured");
}
break;
case UNSECURE:
if (System.getSecurityManager() != null) {
throw new IllegalStateException("SecurityManager already set");
}
break;
default:
new InternalError("No such testcase: " + test);
}
}
static void doPrivileged(Runnable run) {
allowAll.get().set(true);
try {
run.run();
} finally {
allowAll.get().set(false);
}
}
}
// A Helper class to build a set of permissions.
final static class PermissionsBuilder {
final Permissions perms;
public PermissionsBuilder() {
this(new Permissions());
}
public PermissionsBuilder(Permissions perms) {
this.perms = perms;
}
public PermissionsBuilder add(Permission p) {
perms.add(p);
return this;
}
public PermissionsBuilder addAll(PermissionCollection col) {
if (col != null) {
for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
perms.add(e.nextElement());
}
}
return this;
}
public Permissions toPermissions() {
final PermissionsBuilder builder = new PermissionsBuilder();
builder.addAll(perms);
return builder.perms;
}
}
// Policy for the test...
public static class SimplePolicy extends Policy {
final Permissions permissions;
final Permissions allPermissions;
final ThreadLocal<AtomicBoolean> allowAll; // actually: this should be in a thread locale
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
this.allowAll = allowAll;
// we don't actually need any permission to create our
// FileHandlers because we're passing invalid parameters
// which will make the creation fail...
permissions = new Permissions();
permissions.add(new RuntimePermission("accessClassInPackage.sun.misc"));
// these are used for configuring the test itself...
allPermissions = new Permissions();
allPermissions.add(new java.security.AllPermission());
}
@Override
public boolean implies(ProtectionDomain domain, Permission permission) {
if (allowAll.get().get()) return allPermissions.implies(permission);
return permissions.implies(permission);
}
@Override
public PermissionCollection getPermissions(CodeSource codesource) {
return new PermissionsBuilder().addAll(allowAll.get().get()
? allPermissions : permissions).toPermissions();
}
@Override
public PermissionCollection getPermissions(ProtectionDomain domain) {
return new PermissionsBuilder().addAll(allowAll.get().get()
? allPermissions : permissions).toPermissions();
}
}
}
/*
* Copyright (c) 2004, 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
......@@ -26,7 +26,7 @@
* @bug 4981829
* @summary Test that the counter monitor, when running in difference mode,
* emits a notification every time the threshold is exceeded.
* @author Luis-Miguel Alventosa
* @author Luis-Miguel Alventosa, Shanliang JIANG
* @run clean CounterMonitorTest
* @run build CounterMonitorTest
* @run main CounterMonitorTest
......@@ -50,23 +50,31 @@ public class CounterMonitorTest implements NotificationListener {
private boolean notifyFlag = true;
// granularity period
private int granularityperiod = 500;
private int granularityperiod = 10;
// counter values
private int[] values = new int[] {4, 6, 9, 11};
// derived gauge
private volatile int derivedGauge = 2;
// flag to notify that a message has been received
private volatile boolean messageReceived = false;
private volatile Object observedValue = null;
// MBean class
public class StdObservedObject implements StdObservedObjectMBean {
public Object getNbObjects() {
echo(">>> StdObservedObject.getNbObjects: " + count);
synchronized(CounterMonitorTest.class) {
observedValue = count;
CounterMonitorTest.class.notifyAll();
}
return count;
}
public void setNbObjects(Object n) {
echo(">>> StdObservedObject.setNbObjects: " + n);
count = n;
}
private Object count= null;
private volatile Object count= null;
}
// MBean interface
......@@ -166,18 +174,18 @@ public class CounterMonitorTest implements NotificationListener {
Attribute attrib = new Attribute("NbObjects", data);
server.setAttribute(stdObsObjName, attrib);
// Wait for granularity period (multiplied by 2 for sure)
//
Thread.sleep(granularityperiod * 2);
waitObservation(data);
// Loop through the values
//
for (int i = 0; i < values.length; i++) {
data = new Integer(values[i]);
echo(">>> Set data = " + data.intValue());
while (derivedGauge++ < 10) {
System.out.print(">>> Set data from " + data.intValue());
data = new Integer(data.intValue() + derivedGauge);
echo(" to " + data.intValue());
attrib = new Attribute("NbObjects", data);
server.setAttribute(stdObsObjName, attrib);
waitObservation(data);
echo("\tdoWait in Counter Monitor");
doWait();
......@@ -214,6 +222,20 @@ public class CounterMonitorTest implements NotificationListener {
}
}
private void waitObservation(Object value) {
synchronized (CounterMonitorTest.class) {
while (value != observedValue) {
try {
CounterMonitorTest.class.wait();
} catch (InterruptedException e) {
System.err.println("Got unexpected exception: " + e);
e.printStackTrace();
break;
}
}
}
}
/*
* Print message
*/
......
<html>
<!--
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 8029536
@author Sergey Bylokhov
@run applet/manual=yesno FileFilterDescription.html
-->
<body>
<applet code="FileFilterDescription.class" width=200 height=200></applet>
Follow the instructions below.
1) Check that current filter in the opened JFileChooser is a "CustomFileFilter".
2) Close the JFileChooser.
3) Test will repeat steps 1 - 2 for all supported look and feels.
4) If it's true for all look and feels then the test passed, otherwise it failed.
</body>
</html>
/*
* 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.applet.Applet;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
public final class FileFilterDescription extends Applet {
@Override
public void init() {
}
@Override
public void start() {
try {
test();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void test() throws Exception {
final UIManager.LookAndFeelInfo[] infos = UIManager
.getInstalledLookAndFeels();
for (final UIManager.LookAndFeelInfo info : infos) {
SwingUtilities.invokeAndWait(() -> {
final JFileChooser chooser = new JFileChooser();
setLookAndFeel(info);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(new CustomFileFilter());
SwingUtilities.updateComponentTreeUI(chooser);
chooser.showDialog(null, "Open");
});
}
}
private static void setLookAndFeel(final UIManager.LookAndFeelInfo info) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (ClassNotFoundException | InstantiationException |
UnsupportedLookAndFeelException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static class CustomFileFilter extends FileFilter {
@Override
public boolean accept(final File f) {
return false;
}
@Override
public String getDescription() {
return "CustomFileFilter";
}
}
}
\ No newline at end of file
/*
* 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 jdk.testlibrary;
import java.util.Objects;
import java.util.concurrent.Callable;
/**
* Auxiliary class to run target w/ given timeout.
*/
public class TimeLimitedRunner implements Callable<Void> {
private final long stoptime;
private final long timeout;
private final double factor;
private final Callable<Boolean> target;
/**
* @param timeout a timeout. zero means no time limitation
* @param factor a multiplier used to estimate next iteration time
* @param target a target to run
* @throws NullPointerException if target is null
* @throws IllegalArgumentException if timeout is negative or
factor isn't positive
*/
public TimeLimitedRunner(long timeout, double factor,
Callable<Boolean> target) {
Objects.requireNonNull(target, "target must not be null");
if (timeout < 0) {
throw new IllegalArgumentException("timeout[" + timeout + "] < 0");
}
if (factor <= 0d) {
throw new IllegalArgumentException("factor[" + factor + "] <= 0");
}
this.stoptime = System.currentTimeMillis() + timeout;
this.timeout = timeout;
this.factor = factor;
this.target = target;
}
/**
* Runs @{linkplan target} while it returns true and timeout isn't exceeded
*/
@Override
public Void call() throws Exception {
long maxDuration = 0L;
long iterStart = System.currentTimeMillis();
if (timeout != 0 && iterStart > stoptime) {
return null;
}
while (target.call()) {
if (timeout != 0) {
long iterDuration = System.currentTimeMillis() - iterStart;
maxDuration = Math.max(maxDuration, iterDuration);
iterStart = System.currentTimeMillis();
if (iterStart + (maxDuration * factor) > stoptime) {
System.out.println("Not enough time to continue execution. "
+ "Interrupted.");
break;
}
}
}
return null;
}
}
......@@ -35,6 +35,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.concurrent.TimeUnit;
/**
* Common library for various test helper functions.
......@@ -67,6 +68,12 @@ public final class Utils {
TIMEOUT_FACTOR = Double.parseDouble(toFactor);
}
/**
* Returns the value of JTREG default test timeout in milliseconds
* converted to {@code long}.
*/
public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120);
private Utils() {
// Private constructor to prevent class instantiation
}
......@@ -259,4 +266,14 @@ public final class Utils {
throw t;
}
}
/**
* Adjusts the provided timeout value for the TIMEOUT_FACTOR
* @param tOut the timeout value to be adjusted
* @return The timeout value adjusted for the value of "test.timeout.factor"
* system property
*/
public static long adjustTimeout(long tOut) {
return Math.round(tOut * Utils.TIMEOUT_FACTOR);
}
}
......@@ -277,9 +277,6 @@ public class bug8024061 {
try {
Transferable t = dtde.getTransferable();
Object data = t.getTransferData(DropObjectFlavor);
if (data != null) {
throw new Exception("getTransferData returned non-null");
}
} catch (Exception e) {
dragEnterException = e;
e.printStackTrace();
......
......@@ -37,13 +37,13 @@ import static java.lang.System.out;
public class StreamingRetry implements Runnable {
static final int ACCEPT_TIMEOUT = 20 * 1000; // 20 seconds
ServerSocket ss;
volatile ServerSocket ss;
public static void main(String[] args) throws IOException {
public static void main(String[] args) throws Exception {
(new StreamingRetry()).instanceMain();
}
void instanceMain() throws IOException {
void instanceMain() throws Exception {
out.println("Test with default method");
test(null);
out.println("Test with POST method");
......@@ -54,12 +54,13 @@ public class StreamingRetry implements Runnable {
if (failed > 0) throw new RuntimeException("Some tests failed");
}
void test(String method) throws IOException {
void test(String method) throws Exception {
ss = new ServerSocket(0);
ss.setSoTimeout(ACCEPT_TIMEOUT);
int port = ss.getLocalPort();
(new Thread(this)).start();
Thread otherThread = new Thread(this);
otherThread.start();
try {
URL url = new URL("http://localhost:" + port + "/");
......@@ -77,6 +78,7 @@ public class StreamingRetry implements Runnable {
//expected.printStackTrace();
} finally {
ss.close();
otherThread.join();
}
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册