提交 b9d203cc 编写于 作者: A amurillo

Merge

......@@ -384,7 +384,7 @@ $(JDK_OUTPUTDIR)/classes/META-INF/services/com.sun.tools.xjc.Plugin:
JAVAC_FLAGS := -cp $(JDK_OUTPUTDIR)/classes, \
SRC := $(JDK_OUTPUTDIR)/gensrc_ab/32bit, \
BIN := $(JDK_OUTPUTDIR)/classes_ab/32bit, \
HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers))
HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers_ab/32))
$(BUILD_ACCESSBRIDGE_32): $(BUILD_JDK)
......@@ -393,7 +393,7 @@ $(JDK_OUTPUTDIR)/classes/META-INF/services/com.sun.tools.xjc.Plugin:
JAVAC_FLAGS := -cp $(JDK_OUTPUTDIR)/classes, \
SRC := $(JDK_OUTPUTDIR)/gensrc_ab/legacy, \
BIN := $(JDK_OUTPUTDIR)/classes_ab/legacy, \
HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers))
HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers_ab/legacy))
$(BUILD_ACCESSBRIDGE_LEGACY): $(BUILD_JDK)
......@@ -404,7 +404,7 @@ $(JDK_OUTPUTDIR)/classes/META-INF/services/com.sun.tools.xjc.Plugin:
JAVAC_FLAGS := -cp $(JDK_OUTPUTDIR)/classes, \
SRC := $(JDK_OUTPUTDIR)/gensrc_ab/64bit, \
BIN := $(JDK_OUTPUTDIR)/classes_ab/64bit, \
HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers))
HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers_ab/64))
$(BUILD_ACCESSBRIDGE_64): $(BUILD_JDK)
......
......@@ -134,7 +134,8 @@ endif
define SetupAccessBridge
# Parameter 1 Suffix
# Parameter 2 Machine
# Parameter 3 ACCESSBRIDGE_ARCH_ suffix
# Parameter 3 ACCESSBRIDGE_ARCH_ suffix and name of directory where gensrc headers
# are found.
$(call SetupNativeCompilation,BUILD_JAWTACCESSBRIDGE$1, \
LIBRARY = JAWTAccessBridge$1, \
......@@ -144,7 +145,8 @@ endif
LANG := C++, \
OPTIMIZATION := LOW, \
CFLAGS := $(CFLAGS_JDKLIB) \
-DACCESSBRIDGE_ARCH_$3, \
-DACCESSBRIDGE_ARCH_$3 \
-I$(JDK_OUTPUTDIR)/gensrc_headers_ab/$3, \
LDFLAGS := $(LDFLAGS_JDKLIB) kernel32.lib user32.lib gdi32.lib \
winspool.lib jawt.lib comdlg32.lib advapi32.lib shell32.lib \
ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib \
......@@ -170,7 +172,8 @@ endif
LANG := C++, \
OPTIMIZATION := LOW, \
CFLAGS := $(CFLAGS_JDKLIB) \
-DACCESSBRIDGE_ARCH_$3, \
-DACCESSBRIDGE_ARCH_$3 \
-I$(JDK_OUTPUTDIR)/gensrc_headers_ab/$3, \
LDFLAGS := $(LDFLAGS_JDKLIB) kernel32.lib user32.lib gdi32.lib \
winspool.lib comdlg32.lib advapi32.lib shell32.lib \
ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib \
......@@ -194,7 +197,8 @@ endif
LANG := C++, \
OPTIMIZATION := LOW, \
CFLAGS := $(filter-out -MD, $(CFLAGS_JDKLIB)) -MT \
-DACCESSBRIDGE_ARCH_$3, \
-DACCESSBRIDGE_ARCH_$3 \
-I$(JDK_OUTPUTDIR)/gensrc_headers_ab/$3, \
LDFLAGS := $(LDFLAGS_JDKLIB) kernel32.lib user32.lib gdi32.lib \
winspool.lib comdlg32.lib advapi32.lib shell32.lib \
ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib \
......@@ -215,7 +219,7 @@ endif
ifeq ($(OPENJDK_TARGET_CPU_BITS), 32)
$(eval $(call SetupAccessBridge,-32,I386,32))
$(eval $(call SetupAccessBridge,,I386,LEGACY))
$(eval $(call SetupAccessBridge,,I386,legacy))
else
$(eval $(call SetupAccessBridge,-64,X64,64))
endif
......
......@@ -77,14 +77,72 @@ public final class CFont extends PhysicalFont {
}
private static native long createNativeFont(final String nativeFontName,
final int style,
final boolean isFakeItalic);
final int style);
private static native void disposeNativeFont(final long nativeFontPtr);
private boolean isFakeItalic;
private String nativeFontName;
private long nativeFontPtr;
private native float getWidthNative(final long nativeFontPtr);
private native float getWeightNative(final long nativeFontPtr);
private int fontWidth = -1;
private int fontWeight = -1;
@Override
public int getWidth() {
if (fontWidth == -1) {
// Apple use a range of -1 -> +1, where 0.0 is normal
// OpenType uses a % range from 50% -> 200% where 100% is normal
// and maps these onto the integer values 1->9.
// Since that is what Font2D.getWidth() expects, remap to that.
float fw = getWidthNative(getNativeFontPtr());
if (fw == 0.0) { // short cut the common case
fontWidth = Font2D.FWIDTH_NORMAL;
return fontWidth;
}
fw += 1.0; fw *= 100.0;
if (fw <= 50.0) {
fontWidth = 1;
} else if (fw <= 62.5) {
fontWidth = 2;
} else if (fw <= 75.0) {
fontWidth = 3;
} else if (fw <= 87.5) {
fontWidth = 4;
} else if (fw <= 100.0) {
fontWidth = 5;
} else if (fw <= 112.5) {
fontWidth = 6;
} else if (fw <= 125.0) {
fontWidth = 7;
} else if (fw <= 150.0) {
fontWidth = 8;
} else {
fontWidth = 9;
}
}
return fontWidth;
}
@Override
public int getWeight() {
if (fontWeight == -1) {
// Apple use a range of -1 -> +1, where 0 is medium/regular
// Map this on to the OpenType range of 100->900 where
// 500 is medium/regular.
// We'll actually map to 0->1000 but that's close enough.
float fw = getWeightNative(getNativeFontPtr());
if (fw == 0) {
return Font2D.FWEIGHT_NORMAL;
}
fw += 1.0; fw *= 500;
fontWeight = (int)fw;
}
return fontWeight;
}
// this constructor is called from CFontWrapper.m
public CFont(String name) {
this(name, name);
......@@ -94,10 +152,11 @@ public final class CFont extends PhysicalFont {
handle = new Font2DHandle(this);
fullName = name;
familyName = inFamilyName;
nativeFontName = inFamilyName;
nativeFontName = fullName;
setStyle();
}
/* Called from CFontManager too */
public CFont(CFont other, String logicalFamilyName) {
handle = new Font2DHandle(this);
fullName = logicalFamilyName;
......@@ -109,6 +168,7 @@ public final class CFont extends PhysicalFont {
public CFont createItalicVariant() {
CFont font = new CFont(this, familyName);
font.nativeFontName = fullName;
font.fullName =
fullName + (style == Font.BOLD ? "" : "-") + "Italic-Derived";
font.style |= Font.ITALIC;
......@@ -118,7 +178,7 @@ public final class CFont extends PhysicalFont {
protected synchronized long getNativeFontPtr() {
if (nativeFontPtr == 0L) {
nativeFontPtr = createNativeFont(nativeFontName, style, isFakeItalic);
nativeFontPtr = createNativeFont(nativeFontName, style);
}
return nativeFontPtr;
}
......
......@@ -252,13 +252,42 @@ public final class CFontManager extends SunFontManager {
final CFont font = new CFont(fontName, fontFamilyName);
registerGenericFont(font);
}
if ((font.getStyle() & Font.ITALIC) == 0) {
registerGenericFont(font.createItalicVariant(), true);
void registerItalicDerived() {
FontFamily[] famArr = FontFamily.getAllFontFamilies();
for (int i=0; i<famArr.length; i++) {
FontFamily family = famArr[i];
Font2D f2dPlain = family.getFont(Font.PLAIN);
if (f2dPlain != null && !(f2dPlain instanceof CFont)) continue;
Font2D f2dBold = family.getFont(Font.BOLD);
if (f2dBold != null && !(f2dBold instanceof CFont)) continue;
Font2D f2dItalic = family.getFont(Font.ITALIC);
if (f2dItalic != null && !(f2dItalic instanceof CFont)) continue;
Font2D f2dBoldItalic = family.getFont(Font.BOLD|Font.ITALIC);
if (f2dBoldItalic != null && !(f2dBoldItalic instanceof CFont)) continue;
CFont plain = (CFont)f2dPlain;
CFont bold = (CFont)f2dBold;
CFont italic = (CFont)f2dItalic;
CFont boldItalic = (CFont)f2dBoldItalic;
if (bold == null) bold = plain;
if (plain == null && bold == null) continue;
if (italic != null && boldItalic != null) continue;
if (plain != null && italic == null) {
registerGenericFont(plain.createItalicVariant(), true);
}
if (bold != null && boldItalic == null) {
registerGenericFont(bold.createItalicVariant(), true);
}
}
}
Object waitForFontsToBeLoaded = new Object();
private boolean loadedAllFonts = false;
public void loadFonts()
{
synchronized(waitForFontsToBeLoaded)
......@@ -267,7 +296,11 @@ public final class CFontManager extends SunFontManager {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Object>() {
public Object run() {
loadNativeFonts();
if (!loadedAllFonts) {
loadNativeFonts();
registerItalicDerived();
loadedAllFonts = true;
}
return null;
}
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -23,7 +23,6 @@
* questions.
*/
package sun.lwawt;
import java.awt.Component;
......@@ -40,7 +39,6 @@ import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
/**
* Lightweight implementation of {@link TextAreaPeer}. Delegates most of the
......@@ -75,12 +73,13 @@ final class LWTextAreaPeer
super.initializeImpl();
final int visibility = getTarget().getScrollbarVisibility();
synchronized (getDelegateLock()) {
getTextComponent().setWrapStyleWord(true);
setScrollBarVisibility(visibility);
}
}
@Override
JTextComponent getTextComponent() {
JTextArea getTextComponent() {
return getDelegate().getView();
}
......@@ -165,7 +164,7 @@ final class LWTextAreaPeer
// JTextArea.replaceRange() is called.
final Document document = getTextComponent().getDocument();
document.removeDocumentListener(this);
getDelegate().getView().replaceRange(text, start, end);
getTextComponent().replaceRange(text, start, end);
revalidate();
postEvent(new TextEvent(getTarget(), TextEvent.TEXT_VALUE_CHANGED));
document.addDocumentListener(this);
......
......@@ -366,8 +366,7 @@ public final class LWCToolkit extends LWToolkit {
protected void initializeDesktopProperties() {
super.initializeDesktopProperties();
Map <Object, Object> fontHints = new HashMap<>();
fontHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
fontHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
fontHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
desktopProperties.put(SunToolkit.DESKTOPFONTHINTS, fontHints);
desktopProperties.put("awt.mouse.numButtons", BUTTONS);
......
......@@ -23,6 +23,7 @@
* questions.
*/
#import <Cocoa/Cocoa.h>
#import <JavaNativeFoundation/JavaNativeFoundation.h>
#import "sun_lwawt_macosx_CFRetainedResource.h"
......@@ -37,7 +38,10 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CFRetainedResource_nativeCFRelease
(JNIEnv *env, jclass clazz, jlong ptr, jboolean releaseOnAppKitThread)
{
if (releaseOnAppKitThread) {
[JNFRunLoop performOnMainThreadWaiting:NO withBlock:^(){
// Releasing resources on the main AppKit message loop only
// Releasing resources on the nested loops may cause dangling
// pointers after the nested loop is exited
[NSApp postRunnableEvent:^(){
CFRelease(jlong_to_ptr(ptr));
}];
} else {
......
/*
* 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
......@@ -124,61 +124,6 @@ JNF_COCOA_ENTER(env);
JNF_COCOA_EXIT(env);
}
static JNF_CLASS_CACHE(jc_Component, "java/awt/Component");
static JNF_MEMBER_CACHE(jf_Component_appContext, jc_Component, "appContext", "Lsun/awt/AppContext;");
static JNF_CLASS_CACHE(jc_MenuComponent, "java/awt/MenuComponent");
static JNF_MEMBER_CACHE(jf_MenuComponent_appContext, jc_MenuComponent, "appContext", "Lsun/awt/AppContext;");
/*
* Class: sun_awt_SunToolkit
* Method: getAppContext
* Signature: (Ljava/awt/Object;)Lsun/awt/AppContext;
*/
JNIEXPORT jobject JNICALL
Java_sun_awt_SunToolkit_getAppContext
(JNIEnv *env, jclass cls, jobject obj)
{
jobject appContext = NULL;
JNF_COCOA_ENTER(env);
if (JNFIsInstanceOf(env, obj, &jc_Component)) {
appContext = JNFGetObjectField(env, obj, jf_Component_appContext);
} else if (JNFIsInstanceOf(env, obj, &jc_MenuComponent)) {
appContext = JNFGetObjectField(env, obj, jf_MenuComponent_appContext);
}
JNF_COCOA_EXIT(env);
return appContext;
}
/*
* Class: sun_awt_SunToolkit
* Method: setAppContext
* Signature: (Ljava/lang/Object;Lsun/awt/AppContext;)Z
*/
JNIEXPORT jboolean JNICALL
Java_sun_awt_SunToolkit_setAppContext
(JNIEnv *env, jclass cls, jobject obj, jobject appContext)
{
jboolean isComponent;
JNF_COCOA_ENTER(env);
if (JNFIsInstanceOf(env, obj, &jc_Component)) {
JNFSetObjectField(env, obj, jf_Component_appContext, appContext);
isComponent = JNI_TRUE;
} else if (JNFIsInstanceOf(env, obj, &jc_MenuComponent)) {
JNFSetObjectField(env, obj, jf_MenuComponent_appContext, appContext);
isComponent = JNI_FALSE;
}
JNF_COCOA_EXIT(env);
return isComponent;
}
/*
* Class: sun_lwawt_macosx_LWCToolkit
* Method: beep
......@@ -339,8 +284,10 @@ JNF_COCOA_ENTER(env);
beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.010]];
if (processEvents) {
//We do not spin a runloop here as date is nil, so does not matter which mode to use
// Processing all events excluding NSApplicationDefined which need to be processed
// on the main loop only (those events are intended for disposing resources)
NSEvent *event;
if ((event = [NSApp nextEventMatchingMask:NSAnyEventMask
if ((event = [NSApp nextEventMatchingMask:(NSAnyEventMask & ~NSApplicationDefined)
untilDate:nil
inMode:NSDefaultRunLoopMode
dequeue:YES]) != nil) {
......
......@@ -35,15 +35,11 @@
#import "AWTStrike.h"
#import "CoreTextSupport.h"
#define DEBUG
@implementation AWTFont
- (id) initWithFont:(NSFont *)font isFakeItalic:(BOOL)isFakeItalic {
- (id) initWithFont:(NSFont *)font {
self = [super init];
if (self) {
fIsFakeItalic = isFakeItalic;
fFont = [font retain];
fNativeCGFont = CTFontCopyGraphicsFont((CTFontRef)font, NULL);
}
......@@ -72,7 +68,6 @@
+ (AWTFont *) awtFontForName:(NSString *)name
style:(int)style
isFakeItalic:(BOOL)isFakeItalic
{
// create font with family & size
NSFont *nsFont = [NSFont fontWithName:name size:1.0];
......@@ -95,7 +90,7 @@
nsFont = [[NSFontManager sharedFontManager] convertFont:nsFont toHaveTrait:NSBoldFontMask];
}
return [[[AWTFont alloc] initWithFont:nsFont isFakeItalic:isFakeItalic] autorelease];
return [[[AWTFont alloc] initWithFont:nsFont] autorelease];
}
+ (NSFont *) nsFontForJavaFont:(jobject)javaFont env:(JNIEnv *)env {
......@@ -354,7 +349,7 @@ JNF_COCOA_EXIT(env);
JNIEXPORT jlong JNICALL
Java_sun_font_CFont_createNativeFont
(JNIEnv *env, jclass clazz,
jstring nativeFontName, jint style, jboolean isFakeItalic)
jstring nativeFontName, jint style)
{
AWTFont *awtFont = nil;
......@@ -362,8 +357,7 @@ JNF_COCOA_ENTER(env);
awtFont =
[AWTFont awtFontForName:JNFJavaToNSString(env, nativeFontName)
style:style
isFakeItalic:isFakeItalic]; // autoreleased
style:style]; // autoreleased
if (awtFont) {
CFRetain(awtFont); // GC
......@@ -374,6 +368,52 @@ JNF_COCOA_EXIT(env);
return ptr_to_jlong(awtFont);
}
/*
* Class: sun_font_CFont
* Method: getWidthNative
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL
Java_sun_font_CFont_getWidthNative
(JNIEnv *env, jobject cfont, jlong awtFontPtr)
{
float widthVal;
JNF_COCOA_ENTER(env);
AWTFont *awtFont = (AWTFont *)jlong_to_ptr(awtFontPtr);
NSFont* nsFont = awtFont->fFont;
NSFontDescriptor *fontDescriptor = nsFont.fontDescriptor;
NSDictionary *fontTraits = [fontDescriptor objectForKey : NSFontTraitsAttribute];
NSNumber *width = [fontTraits objectForKey : NSFontWidthTrait];
widthVal = (float)[width floatValue];
JNF_COCOA_EXIT(env);
return (jfloat)widthVal;
}
/*
* Class: sun_font_CFont
* Method: getWeightNative
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL
Java_sun_font_CFont_getWeightNative
(JNIEnv *env, jobject cfont, jlong awtFontPtr)
{
float weightVal;
JNF_COCOA_ENTER(env);
AWTFont *awtFont = (AWTFont *)jlong_to_ptr(awtFontPtr);
NSFont* nsFont = awtFont->fFont;
NSFontDescriptor *fontDescriptor = nsFont.fontDescriptor;
NSDictionary *fontTraits = [fontDescriptor objectForKey : NSFontTraitsAttribute];
NSNumber *weight = [fontTraits objectForKey : NSFontWeightTrait];
weightVal = (float)[weight floatValue];
JNF_COCOA_EXIT(env);
return (jfloat)weightVal;
}
/*
* Class: sun_font_CFont
* Method: disposeNativeFont
......
......@@ -311,21 +311,26 @@ JNF_COCOA_ENTER(env);
jlong *glyphInfos =
(*env)->GetPrimitiveArrayCritical(env, glyphInfoLongArray, NULL);
if (glyphInfos != NULL) {
jint *rawGlyphCodes =
(*env)->GetPrimitiveArrayCritical(env, glyphCodes, NULL);
jint *rawGlyphCodes =
(*env)->GetPrimitiveArrayCritical(env, glyphCodes, NULL);
@try {
if (rawGlyphCodes != NULL && glyphInfos != NULL) {
CGGlyphImages_GetGlyphImagePtrs(glyphInfos, awtStrike,
rawGlyphCodes, len);
}
}
@finally {
if (rawGlyphCodes != NULL) {
CGGlyphImages_GetGlyphImagePtrs(glyphInfos, awtStrike,
rawGlyphCodes, len);
(*env)->ReleasePrimitiveArrayCritical(env, glyphCodes,
rawGlyphCodes, JNI_ABORT);
(*env)->ReleasePrimitiveArrayCritical(env, glyphCodes,
rawGlyphCodes, JNI_ABORT);
}
if (glyphInfos != NULL) {
// Do not use JNI_COMMIT, as that will not free the buffer copy
// when +ProtectJavaHeap is on.
(*env)->ReleasePrimitiveArrayCritical(env, glyphInfoLongArray,
glyphInfos, 0);
}
// Do not use JNI_COMMIT, as that will not free the buffer copy
// when +ProtectJavaHeap is on.
(*env)->ReleasePrimitiveArrayCritical(env, glyphInfoLongArray,
glyphInfos, 0);
}
JNF_COCOA_EXIT(env);
......
......@@ -195,19 +195,41 @@ DUMP_GLYPHINFO(const GlyphInfo *info)
#pragma mark --- Font Rendering Mode Descriptors ---
static Int32 reverseGamma = 0;
static UInt8 reverseGammaLut[256] = { 0 };
static inline UInt8* getReverseGammaLut() {
if (reverseGamma == 0) {
// initialize gamma lut
double gamma;
int i;
const char* pGammaEnv = getenv("J2D_LCD_REVERSE_GAMMA");
if (pGammaEnv != NULL) {
reverseGamma = atol(pGammaEnv);
}
if (reverseGamma < 100 || reverseGamma > 250) {
reverseGamma = 180;
}
gamma = 100.0 / reverseGamma;
for (i = 0; i < 256; i++) {
double x = ((double)i) / 255.0;
reverseGammaLut[i] = (UInt8)(255 * pow(x, gamma));
}
}
return reverseGammaLut;
}
static inline void
CGGI_CopyARGBPixelToRGBPixel(const UInt32 p, UInt8 *dst)
{
#if __LITTLE_ENDIAN__
*(dst + 2) = 0xFF - (p >> 24 & 0xFF);
*(dst + 1) = 0xFF - (p >> 16 & 0xFF);
*(dst) = 0xFF - (p >> 8 & 0xFF);
#else
*(dst) = 0xFF - (p >> 16 & 0xFF);
*(dst + 1) = 0xFF - (p >> 8 & 0xFF);
*(dst + 2) = 0xFF - (p & 0xFF);
#endif
UInt8* lut = getReverseGammaLut();
*(dst + 0) = lut[0xFF - (p >> 16 & 0xFF)]; // red
*(dst + 1) = lut[0xFF - (p >> 8 & 0xFF)]; // green
*(dst + 2) = lut[0xFF - (p & 0xFF)]; // blue
}
static void
......@@ -222,17 +244,14 @@ CGGI_CopyImageFromCanvasToRGBInfo(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
size_t height = info->height;
size_t y;
// fill empty glyph image with black-on-white glyph
for (y = 0; y < height; y++) {
size_t destRow = y * destRowWidth * 3;
size_t srcRow = y * srcRowWidth;
size_t x;
for (x = 0; x < destRowWidth; x++) {
// size_t x3 = x * 3;
// UInt32 p = src[srcRow + x];
// dest[destRow + x3] = 0xFF - (p >> 16 & 0xFF);
// dest[destRow + x3 + 1] = 0xFF - (p >> 8 & 0xFF);
// dest[destRow + x3 + 2] = 0xFF - (p & 0xFF);
CGGI_CopyARGBPixelToRGBPixel(src[srcRow + x],
dest + destRow + x * 3);
}
......@@ -260,13 +279,9 @@ CGGI_CopyImageFromCanvasToRGBInfo(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
//}
static inline UInt8
CGGI_ConvertPixelToGreyBit(UInt32 p)
CGGI_ConvertBWPixelToByteGray(UInt32 p)
{
#ifdef __LITTLE_ENDIAN__
return 0xFF - ((p >> 24 & 0xFF) + (p >> 16 & 0xFF) + (p >> 8 & 0xFF)) / 3;
#else
return 0xFF - ((p >> 16 & 0xFF) + (p >> 8 & 0xFF) + (p & 0xFF)) / 3;
#endif
return 0xFF - (((p >> 24 & 0xFF) + (p >> 16 & 0xFF) + (p >> 8 & 0xFF)) / 3);
}
static void
......@@ -281,14 +296,15 @@ CGGI_CopyImageFromCanvasToAlphaInfo(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
size_t height = info->height;
size_t y;
// fill empty glyph image with black-on-white glyph
for (y = 0; y < height; y++) {
size_t destRow = y * destRowWidth;
size_t srcRow = y * srcRowWidth;
size_t x;
for (x = 0; x < destRowWidth; x++) {
UInt32 p = src[srcRow + x];
dest[destRow + x] = CGGI_ConvertPixelToGreyBit(p);
dest[destRow + x] = CGGI_ConvertBWPixelToByteGray(p);
}
}
}
......@@ -316,13 +332,11 @@ CGGI_GetRenderingMode(const AWTStrike *strike)
{
CGGI_RenderingMode mode;
mode.cgFontMode = strike->fStyle;
NSException *e = nil;
switch (strike->fAAStyle) {
case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_DEFAULT:
case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_OFF:
case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_ON:
case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_GASP:
default:
mode.glyphDescriptor = &grey;
break;
case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_HRGB:
......@@ -331,6 +345,17 @@ CGGI_GetRenderingMode(const AWTStrike *strike)
case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_VBGR:
mode.glyphDescriptor = &rgb;
break;
case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_GASP:
case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_DEFAULT:
default:
/* we expect that text antialiasing hint has been already
* evaluated. Report an error if we get 'unevaluated' hint here.
*/
e = [NSException
exceptionWithName:@"IllegalArgumentException"
reason:@"Invalid hint value"
userInfo:nil];
@throw e;
}
return mode;
......@@ -345,7 +370,8 @@ CGGI_GetRenderingMode(const AWTStrike *strike)
*/
static inline void
CGGI_InitCanvas(CGGI_GlyphCanvas *canvas,
const vImagePixelCount width, const vImagePixelCount height)
const vImagePixelCount width, const vImagePixelCount height,
const CGGI_RenderingMode* mode)
{
// our canvas is *always* 4-byte ARGB
size_t bytesPerRow = width * sizeof(UInt32);
......@@ -356,19 +382,26 @@ CGGI_InitCanvas(CGGI_GlyphCanvas *canvas,
canvas->image->height = height;
canvas->image->rowBytes = bytesPerRow;
canvas->image->data = (void *)calloc(byteCount, sizeof(UInt32));
canvas->image->data = (void *)calloc(byteCount, sizeof(UInt8));
if (canvas->image->data == NULL) {
[[NSException exceptionWithName:NSMallocException
reason:@"Failed to allocate memory for the buffer which backs the CGContext for glyph strikes." userInfo:nil] raise];
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
uint32_t bmpInfo = kCGImageAlphaPremultipliedFirst;
if (mode->glyphDescriptor == &rgb) {
bmpInfo |= kCGBitmapByteOrder32Host;
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
canvas->context = CGBitmapContextCreate(canvas->image->data,
width, height, 8, bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedFirst);
bmpInfo);
// set foreground color
CGContextSetRGBFillColor(canvas->context, 0.0f, 0.0f, 0.0f, 1.0f);
CGContextSetFontSize(canvas->context, 1);
CGContextSaveGState(canvas->context);
......@@ -404,7 +437,9 @@ CGGI_FreeCanvas(CGGI_GlyphCanvas *canvas)
* Quick and easy inline to check if this canvas is big enough.
*/
static inline void
CGGI_SizeCanvas(CGGI_GlyphCanvas *canvas, const vImagePixelCount width, const vImagePixelCount height, const JRSFontRenderingStyle style)
CGGI_SizeCanvas(CGGI_GlyphCanvas *canvas, const vImagePixelCount width,
const vImagePixelCount height,
const CGGI_RenderingMode* mode)
{
if (canvas->image != NULL &&
width < canvas->image->width &&
......@@ -418,8 +453,9 @@ CGGI_SizeCanvas(CGGI_GlyphCanvas *canvas, const vImagePixelCount width, const vI
CGGI_FreeCanvas(canvas);
CGGI_InitCanvas(canvas,
width * CGGI_GLYPH_CANVAS_SLACK,
height * CGGI_GLYPH_CANVAS_SLACK);
JRSFontSetRenderingStyleOnContext(canvas->context, style);
height * CGGI_GLYPH_CANVAS_SLACK,
mode);
JRSFontSetRenderingStyleOnContext(canvas->context, mode->cgFontMode);
}
/*
......@@ -443,6 +479,7 @@ CGGI_ClearCanvas(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
Pixel_8888 opaqueWhite = { 0xFF, 0xFF, 0xFF, 0xFF };
#endif
// clear canvas background and set foreground color
vImageBufferFill_ARGB8888(&canvasRectToClear, opaqueWhite, kvImageNoFlags);
}
......@@ -577,7 +614,7 @@ CGGI_CreateImageForUnicode
GlyphInfo *info = CGGI_CreateNewGlyphInfoFrom(advance, bbox, strike, mode);
// fix the context size, just in case the substituted character is unexpectedly large
CGGI_SizeCanvas(canvas, info->width, info->height, mode->cgFontMode);
CGGI_SizeCanvas(canvas, info->width, info->height, mode);
// align the transform for the real CoreText strike
CGContextSetTextMatrix(canvas->context, strike->fAltTx);
......@@ -653,8 +690,11 @@ CGGI_FillImagesForGlyphsWithSizedCanvas(CGGI_GlyphCanvas *canvas,
#endif
}
static NSString *threadLocalCanvasKey =
@"Java CoreGraphics Text Renderer Cached Canvas";
static NSString *threadLocalAACanvasKey =
@"Java CoreGraphics Text Renderer Cached Canvas for AA";
static NSString *threadLocalLCDCanvasKey =
@"Java CoreGraphics Text Renderer Cached Canvas for LCD";
/*
* This is the maximum length and height times the above slack squared
......@@ -678,25 +718,28 @@ CGGI_FillImagesForGlyphs(jlong *glyphInfos, const AWTStrike *strike,
CGGI_GLYPH_CANVAS_MAX*CGGI_GLYPH_CANVAS_MAX*CGGI_GLYPH_CANVAS_SLACK*CGGI_GLYPH_CANVAS_SLACK)
{
CGGI_GlyphCanvas *tmpCanvas = [[CGGI_GlyphCanvas alloc] init];
CGGI_InitCanvas(tmpCanvas, maxWidth, maxHeight);
CGGI_InitCanvas(tmpCanvas, maxWidth, maxHeight, mode);
CGGI_FillImagesForGlyphsWithSizedCanvas(tmpCanvas, strike,
mode, glyphInfos, uniChars,
glyphs, len);
mode, glyphInfos, uniChars,
glyphs, len);
CGGI_FreeCanvas(tmpCanvas);
[tmpCanvas release];
return;
}
NSMutableDictionary *threadDict =
[[NSThread currentThread] threadDictionary];
CGGI_GlyphCanvas *canvas = [threadDict objectForKey:threadLocalCanvasKey];
NSString* theKey = (mode->glyphDescriptor == &rgb) ?
threadLocalLCDCanvasKey : threadLocalAACanvasKey;
CGGI_GlyphCanvas *canvas = [threadDict objectForKey:theKey];
if (canvas == nil) {
canvas = [[CGGI_GlyphCanvas alloc] init];
[threadDict setObject:canvas forKey:threadLocalCanvasKey];
[threadDict setObject:canvas forKey:theKey];
}
CGGI_SizeCanvas(canvas, maxWidth, maxHeight, mode->cgFontMode);
CGGI_SizeCanvas(canvas, maxWidth, maxHeight, mode);
CGGI_FillImagesForGlyphsWithSizedCanvas(canvas, strike, mode,
glyphInfos, uniChars, glyphs, len);
}
......
......@@ -37,6 +37,7 @@
- (void) registerWithProcessManager;
- (void) setDockIconWithEnv:(JNIEnv *)env;
- (void) postDummyEvent;
- (void) postRunnableEvent:(void (^)())block;
- (void) waitForDummyEvent;
+ (void) runAWTLoopWithApp:(NSApplication*)app;
......
......@@ -338,9 +338,13 @@ AWT_ASSERT_APPKIT_THREAD;
- (void)sendEvent:(NSEvent *)event
{
if ([event type] == NSApplicationDefined && TS_EQUAL([event timestamp], dummyEventTimestamp)) {
if ([event type] == NSApplicationDefined && TS_EQUAL([event timestamp], dummyEventTimestamp) && [event subtype] == 0) {
[seenDummyEventLock lockWhenCondition:NO];
[seenDummyEventLock unlockWithCondition:YES];
} else if ([event type] == NSApplicationDefined && [event subtype] == 777) {
void (^block)() = (void (^)()) [event data1];
block();
[block release];
} else if ([event type] == NSKeyUp && ([event modifierFlags] & NSCommandKeyMask)) {
// Cocoa won't send us key up event when releasing a key while Cmd is down,
// so we have to do it ourselves.
......@@ -350,6 +354,33 @@ AWT_ASSERT_APPKIT_THREAD;
}
}
/*
* Posts the block to the AppKit event queue which will be executed
* on the main AppKit loop.
* While running nested loops this event will be ignored.
*/
- (void)postRunnableEvent:(void (^)())block
{
void (^copy)() = [block copy];
NSInteger encode = (NSInteger) copy;
[copy retain];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined
location: NSMakePoint(0,0)
modifierFlags: 0
timestamp: 0
windowNumber: 0
context: nil
subtype: 777
data1: encode
data2: 0];
[NSApp postEvent: event atStart: NO];
[pool drain];
}
- (void)postDummyEvent {
seenDummyEventLock = [[NSConditionLock alloc] initWithCondition:NO];
dummyEventTimestamp = [NSProcessInfo processInfo].systemUptime;
......
......@@ -439,9 +439,14 @@ public final class Connection implements Runnable {
BerDecoder readReply(LdapRequest ldr)
throws IOException, NamingException {
BerDecoder rber;
boolean waited = false;
while (((rber = ldr.getReplyBer()) == null) && !waited) {
// Track down elapsed time to workaround spurious wakeups
long elapsedMilli = 0;
long elapsedNano = 0;
while (((rber = ldr.getReplyBer()) == null) &&
(readTimeout <= 0 || elapsedMilli < readTimeout))
{
try {
// If socket closed, don't even try
synchronized (this) {
......@@ -455,11 +460,15 @@ public final class Connection implements Runnable {
rber = ldr.getReplyBer();
if (rber == null) {
if (readTimeout > 0) { // Socket read timeout is specified
long beginNano = System.nanoTime();
// will be woken up before readTimeout only if reply is
// will be woken up before readTimeout if reply is
// available
ldr.wait(readTimeout);
waited = true;
ldr.wait(readTimeout - elapsedMilli);
elapsedNano += (System.nanoTime() - beginNano);
elapsedMilli += elapsedNano / 1000_000;
elapsedNano %= 1000_000;
} else {
// no timeout is set so we wait infinitely until
// a response is received
......@@ -476,7 +485,7 @@ public final class Connection implements Runnable {
}
}
if ((rber == null) && waited) {
if ((rber == null) && (elapsedMilli >= readTimeout)) {
abandonRequest(ldr, null);
throw new NamingException("LDAP response read timed out, timeout used:"
+ readTimeout + "ms." );
......
......@@ -1301,6 +1301,25 @@ public abstract class Component implements ImageObserver, MenuContainer,
return visible && (parent == null || parent.isRecursivelyVisible());
}
/**
* Determines the bounds of a visible part of the component relative to its
* parent.
*
* @return the visible part of bounds
*/
private Rectangle getRecursivelyVisibleBounds() {
final Component container = getContainer();
final Rectangle bounds = getBounds();
if (container == null) {
// we are top level window or haven't a container, return our bounds
return bounds;
}
// translate the container's bounds to our coordinate space
final Rectangle parentsBounds = container.getRecursivelyVisibleBounds();
parentsBounds.setLocation(0, 0);
return parentsBounds.intersection(bounds);
}
/**
* Translates absolute coordinates into coordinates in the coordinate
* space of this component.
......@@ -1473,7 +1492,7 @@ public abstract class Component implements ImageObserver, MenuContainer,
ComponentPeer peer = this.peer;
if (peer != null) {
peer.setEnabled(true);
if (visible) {
if (visible && !getRecursivelyVisibleBounds().isEmpty()) {
updateCursorImmediately();
}
}
......@@ -1522,7 +1541,7 @@ public abstract class Component implements ImageObserver, MenuContainer,
ComponentPeer peer = this.peer;
if (peer != null) {
peer.setEnabled(false);
if (visible) {
if (visible && !getRecursivelyVisibleBounds().isEmpty()) {
updateCursorImmediately();
}
}
......
......@@ -44,6 +44,7 @@ import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.HashSet;
import java.util.Set;
......@@ -100,7 +101,7 @@ public class Container extends Component {
* @see #add
* @see #getComponents
*/
private java.util.List<Component> component = new java.util.ArrayList<Component>();
private java.util.List<Component> component = new ArrayList<>();
/**
* Layout manager for this container.
......@@ -2545,28 +2546,24 @@ public class Container extends Component {
if (!contains(x, y)) {
return null;
}
Component lightweight = null;
synchronized (getTreeLock()) {
// Two passes: see comment in sun.awt.SunGraphicsCallback
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null &&
!(comp.peer instanceof LightweightPeer)) {
if (comp.contains(x - comp.x, y - comp.y)) {
// Optimized version of two passes:
// see comment in sun.awt.SunGraphicsCallback
for (final Component comp : component) {
if (comp.contains(x - comp.x, y - comp.y)) {
if (!comp.isLightweight()) {
// return heavyweight component as soon as possible
return comp;
}
}
}
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null &&
comp.peer instanceof LightweightPeer) {
if (comp.contains(x - comp.x, y - comp.y)) {
return comp;
if (lightweight == null) {
// save and return later the first lightweight component
lightweight = comp;
}
}
}
}
return this;
return lightweight != null ? lightweight : this;
}
/**
......@@ -2670,52 +2667,54 @@ public class Container extends Component {
return null;
}
final Component findComponentAtImpl(int x, int y, boolean ignoreEnabled){
checkTreeLock();
final Component findComponentAtImpl(int x, int y, boolean ignoreEnabled) {
// checkTreeLock(); commented for a performance reason
if (!(contains(x, y) && visible && (ignoreEnabled || enabled))) {
return null;
}
// Two passes: see comment in sun.awt.SunGraphicsCallback
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null &&
!(comp.peer instanceof LightweightPeer)) {
if (comp instanceof Container) {
comp = ((Container)comp).findComponentAtImpl(x - comp.x,
y - comp.y,
ignoreEnabled);
} else {
comp = comp.getComponentAt(x - comp.x, y - comp.y);
}
if (comp != null && comp.visible &&
(ignoreEnabled || comp.enabled))
{
return comp;
}
Component lightweight = null;
// Optimized version of two passes:
// see comment in sun.awt.SunGraphicsCallback
for (final Component comp : component) {
final int x1 = x - comp.x;
final int y1 = y - comp.y;
if (!comp.contains(x1, y1)) {
continue; // fast path
}
}
for (int i = 0; i < component.size(); i++) {
Component comp = component.get(i);
if (comp != null &&
comp.peer instanceof LightweightPeer) {
if (comp instanceof Container) {
comp = ((Container)comp).findComponentAtImpl(x - comp.x,
y - comp.y,
ignoreEnabled);
} else {
comp = comp.getComponentAt(x - comp.x, y - comp.y);
if (!comp.isLightweight()) {
final Component child = getChildAt(comp, x1, y1, ignoreEnabled);
if (child != null) {
// return heavyweight component as soon as possible
return child;
}
if (comp != null && comp.visible &&
(ignoreEnabled || comp.enabled))
{
return comp;
} else {
if (lightweight == null) {
// save and return later the first lightweight component
lightweight = getChildAt(comp, x1, y1, ignoreEnabled);
}
}
}
return lightweight != null ? lightweight : this;
}
return this;
/**
* Helper method for findComponentAtImpl. Finds a child component using
* findComponentAtImpl for Container and getComponentAt for Component.
*/
private static Component getChildAt(Component comp, int x, int y,
boolean ignoreEnabled) {
if (comp instanceof Container) {
comp = ((Container) comp).findComponentAtImpl(x, y,
ignoreEnabled);
} else {
comp = comp.getComponentAt(x, y);
}
if (comp != null && comp.visible &&
(ignoreEnabled || comp.enabled)) {
return comp;
}
return null;
}
/**
......@@ -4402,6 +4401,18 @@ class LightweightDispatcher implements java.io.Serializable, AWTEventListener {
private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.LightweightDispatcher");
private static final int BUTTONS_DOWN_MASK;
static {
int[] buttonsDownMask = AWTAccessor.getInputEventAccessor().
getButtonDownMasks();
int mask = 0;
for (int buttonDownMask : buttonsDownMask) {
mask |= buttonDownMask;
}
BUTTONS_DOWN_MASK = mask;
}
LightweightDispatcher(Container nativeContainer) {
this.nativeContainer = nativeContainer;
mouseEventTarget = new WeakReference<>(null);
......@@ -4470,25 +4481,12 @@ class LightweightDispatcher implements java.io.Serializable, AWTEventListener {
private boolean isMouseGrab(MouseEvent e) {
int modifiers = e.getModifiersEx();
if(e.getID() == MouseEvent.MOUSE_PRESSED
|| e.getID() == MouseEvent.MOUSE_RELEASED)
{
switch (e.getButton()) {
case MouseEvent.BUTTON1:
modifiers ^= InputEvent.BUTTON1_DOWN_MASK;
break;
case MouseEvent.BUTTON2:
modifiers ^= InputEvent.BUTTON2_DOWN_MASK;
break;
case MouseEvent.BUTTON3:
modifiers ^= InputEvent.BUTTON3_DOWN_MASK;
break;
}
if (e.getID() == MouseEvent.MOUSE_PRESSED
|| e.getID() == MouseEvent.MOUSE_RELEASED) {
modifiers ^= InputEvent.getMaskForButton(e.getButton());
}
/* modifiers now as just before event */
return ((modifiers & (InputEvent.BUTTON1_DOWN_MASK
| InputEvent.BUTTON2_DOWN_MASK
| InputEvent.BUTTON3_DOWN_MASK)) != 0);
return ((modifiers & BUTTONS_DOWN_MASK) != 0);
}
/**
......
......@@ -496,9 +496,8 @@ public class ScrollPane extends Container implements Accessible {
Point p = getScrollPosition();
Dimension cs = calculateChildSize();
Dimension vs = getViewportSize();
Insets i = getInsets();
c.reshape(i.left - p.x, i.top - p.y, cs.width, cs.height);
c.reshape(- p.x, - p.y, cs.width, cs.height);
ScrollPanePeer peer = (ScrollPanePeer)this.peer;
if (peer != null) {
peer.childResized(cs.width, cs.height);
......
/*
* 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
......@@ -25,7 +25,6 @@
package java.security;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
......@@ -457,37 +456,24 @@ public class ProtectionDomain {
/**
* Used for storing ProtectionDomains as keys in a Map.
*/
final static class Key {}
// A cache of ProtectionDomains and their Permissions
private static class PDCache implements ProtectionDomainCache {
// We must wrap the PermissionCollection in a WeakReference as there
// are some PermissionCollections which contain strong references
// back to a ProtectionDomain and otherwise would never be removed
// from the WeakHashMap
private final Map<Key, WeakReference<PermissionCollection>>
map = new WeakHashMap<>();
@Override
public synchronized void put(ProtectionDomain pd,
PermissionCollection pc) {
map.put(pd == null ? null : pd.key, new WeakReference<>(pc));
}
@Override
public synchronized PermissionCollection get(ProtectionDomain pd) {
WeakReference<PermissionCollection> ref =
map.get(pd == null ? null : pd.key);
return ref == null ? null : ref.get();
}
}
final class Key {}
static {
SharedSecrets.setJavaSecurityProtectionDomainAccess(
new JavaSecurityProtectionDomainAccess() {
@Override
public ProtectionDomainCache getProtectionDomainCache() {
return new PDCache();
return new ProtectionDomainCache() {
private final Map<Key, PermissionCollection> map =
Collections.synchronizedMap
(new WeakHashMap<Key, PermissionCollection>());
public void put(ProtectionDomain pd,
PermissionCollection pc) {
map.put((pd == null ? null : pd.key), pc);
}
public PermissionCollection get(ProtectionDomain pd) {
return pd == null ? map.get(null) : map.get(pd.key);
}
};
}
});
}
......
......@@ -461,7 +461,7 @@ public abstract class BaseRowSet implements Serializable, Cloneable {
* <code>false</code> that it is not. The default is <code>true</code>.
* @serial
*/
private boolean escapeProcessing;
private boolean escapeProcessing = true;
/**
* A constant indicating the isolation level of the connection
......
/*
* 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
......@@ -48,6 +48,8 @@ import java.lang.reflect.*;
* Therefore, any <code>RowSetMetaDataImpl</code> method that retrieves information
* is defined as having unspecified behavior when it is called
* before the <code>RowSet</code> object contains data.
*
* @since 1.5
*/
public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
......@@ -579,7 +581,7 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
*
* @param columnIndex the first column is 1, the second is 2, and so on;
* must be between <code>1</code> and the number of columns, inclusive
* @return <code>true</code> if if a value in the designated column is a signed
* @return <code>true</code> if a value in the designated column is a signed
* number; <code>false</code> otherwise
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
......@@ -605,7 +607,7 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
}
/**
* Retrieves the the suggested column title for the designated
* Retrieves the suggested column title for the designated
* column for use in printouts and displays.
*
* @param columnIndex the first column is 1, the second is 2, and so on;
......@@ -801,8 +803,10 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
* @throws SQLException if a database access error occurs
* or the given column number is out of bounds
*/
public boolean isDefinitelyWritable(int columnIndex)
throws SQLException { return true;}
public boolean isDefinitelyWritable(int columnIndex) throws SQLException {
checkColRange(columnIndex);
return true;
}
/**
* Retrieves the fully-qualified name of the class in the Java
......@@ -1071,7 +1075,7 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
public int colType;
/**
* The field that holds the the type name used by this particular data source
* The field that holds the type name used by this particular data source
* for the value stored in this column.
*
* @serial
......@@ -1079,7 +1083,7 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
public String colTypeName;
/**
* The field that holds the updatablity boolean per column of a RowSet
* The field that holds the updatability boolean per column of a RowSet
*
* @serial
*/
......
/*
* 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
......@@ -50,14 +50,11 @@ import java.sql.SQLException;
* The inherited methods <code>getMessage</code>, <code>getSQLState</code>,
* and <code>getErrorCode</code> retrieve information contained in a
* <code>RowSetWarning</code> object.
*
* @since 1.5
*/
public class RowSetWarning extends SQLException {
/**
* RowSetWarning object handle.
*/
private RowSetWarning rwarning;
/**
* Constructs a <code>RowSetWarning</code> object
* with the given value for the reason; SQLState defaults to null,
......@@ -109,7 +106,7 @@ public class RowSetWarning extends SQLException {
* @param reason a <code>String</code> giving a description of the
* warning;
* @param SQLState an XOPEN code identifying the warning; if a non standard
* XPOEN <i>SQLState</i> is supplied, no exception is thrown.
* XOPEN <i>SQLState</i> is supplied, no exception is thrown.
* @param vendorCode a database vendor-specific warning code
*/
public RowSetWarning(java.lang.String reason, java.lang.String SQLState, int vendorCode) {
......@@ -126,7 +123,15 @@ public class RowSetWarning extends SQLException {
* @see #setNextWarning
*/
public RowSetWarning getNextWarning() {
return rwarning;
SQLException warning = getNextException();
if ( warning == null || warning instanceof RowSetWarning) {
return (RowSetWarning)warning;
} else {
// The chained value isn't a RowSetWarning.
// This is a programming error by whoever added it to
// the RowSetWarning chain. We throw a Java "Error".
throw new Error("RowSetWarning chain holds value that is not a RowSetWarning: ");
}
}
/**
......@@ -139,7 +144,7 @@ public class RowSetWarning extends SQLException {
* @see #getNextWarning
*/
public void setNextWarning(RowSetWarning warning) {
rwarning = warning;
setNextException(warning);
}
static final long serialVersionUID = 6678332766434564774L;
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2015, 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
......@@ -38,7 +38,6 @@ import javax.accessibility.*;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.lang.StringBuilder;
import java.beans.PropertyChangeListener;
import sun.awt.AppContext;
import sun.swing.SwingUtilities2;
......@@ -1650,7 +1649,7 @@ public class JInternalFrame extends JComponent implements
* <dt><code>DO_NOTHING_ON_CLOSE</code>
* <dd> Do nothing.
* This requires the program to handle the operation
* in the <code>windowClosing</code> method
* in the <code>internalFrameClosing</code> method
* of a registered <code>InternalFrameListener</code> object.
* <dt><code>HIDE_ON_CLOSE</code>
* <dd> Automatically make the internal frame invisible.
......
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2015, 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
......@@ -42,8 +42,6 @@ import java.text.spi.NumberFormatProvider;
import javax.accessibility.*;
import sun.util.locale.provider.LocaleProviderAdapter;
import sun.util.locale.provider.LocaleResources;
import sun.util.locale.provider.LocaleServiceProviderPool;
/**
* A single line input field that lets the user select a
......@@ -77,12 +75,12 @@ import sun.util.locale.provider.LocaleServiceProviderPool;
* try {
* spinner.commitEdit();
* }
* catch (ParseException pe) {{
* catch (ParseException pe) {
* // Edited value is invalid, spinner.getValue() will return
* // the last valid value, you could revert the spinner to show that:
* JComponent editor = spinner.getEditor()
* JComponent editor = spinner.getEditor();
* if (editor instanceof DefaultEditor) {
* ((DefaultEditor)editor).getTextField().setValue(spinner.getValue();
* ((DefaultEditor)editor).getTextField().setValue(spinner.getValue());
* }
* // reset the value to some known value:
* spinner.setValue(fallbackValue);
......
......@@ -181,9 +181,16 @@ public class RepaintManager
*/
private final ProcessingRunnable processingRunnable;
private final static JavaSecurityAccess javaSecurityAccess =
SharedSecrets.getJavaSecurityAccess();
private static final JavaSecurityAccess javaSecurityAccess =
SharedSecrets.getJavaSecurityAccess();
/**
* Listener installed to detect display changes. When display changes,
* schedules a callback to notify all RepaintManagers of the display
* changes.
*/
private static final DisplayChangedListener displayChangedHandler =
new DisplayChangedHandler();
static {
SwingAccessor.setRepaintManagerAccessor(new SwingAccessor.RepaintManagerAccessor() {
......@@ -225,8 +232,8 @@ public class RepaintManager
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
if (ge instanceof SunGraphicsEnvironment) {
((SunGraphicsEnvironment)ge).addDisplayChangedListener(
new DisplayChangedHandler());
((SunGraphicsEnvironment) ge).addDisplayChangedListener(
displayChangedHandler);
}
Toolkit tk = Toolkit.getDefaultToolkit();
if ((tk instanceof SunToolkit)
......@@ -1649,6 +1656,12 @@ public class RepaintManager
*/
private static final class DisplayChangedHandler implements
DisplayChangedListener {
// Empty non private constructor was added because access to this
// class shouldn't be generated by the compiler using synthetic
// accessor method
DisplayChangedHandler() {
}
public void displayChanged() {
scheduleDisplayChanges();
}
......@@ -1656,11 +1669,10 @@ public class RepaintManager
public void paletteChanged() {
}
private void scheduleDisplayChanges() {
private static void scheduleDisplayChanges() {
// To avoid threading problems, we notify each RepaintManager
// on the thread it was created on.
for (Object c : AppContext.getAppContexts()) {
AppContext context = (AppContext) c;
for (AppContext context : AppContext.getAppContexts()) {
synchronized(context) {
if (!context.isDisposed()) {
EventQueue eventQueue = (EventQueue)context.get(
......
......@@ -2905,13 +2905,13 @@ search:
return comp;
}
if (flavor1.isFlavorTextType()) {
return 1;
}
if (flavor2.isFlavorTextType()) {
return -1;
}
// if (flavor1.isFlavorTextType()) {
// return 1;
// }
//
// if (flavor2.isFlavorTextType()) {
// return -1;
// }
// Next, look for application/x-java-* types. Prefer unknown
// MIME types because if the user provides his own data flavor,
......
......@@ -157,6 +157,21 @@ public abstract class Font2D {
}
}
public static final int FWIDTH_NORMAL = 5; // OS/2 usWidthClass
public static final int FWEIGHT_NORMAL = 400; // OS/2 usWeightClass
public static final int FWEIGHT_BOLD = 700; // OS/2 usWeightClass
public int getWidth() {
return FWIDTH_NORMAL;
}
public int getWeight() {
if ((style & Font.BOLD) !=0) {
return FWEIGHT_BOLD;
} else {
return FWEIGHT_NORMAL;
}
}
int getRank() {
return fontRank;
......
......@@ -27,6 +27,7 @@ package sun.font;
import java.io.File;
import java.awt.Font;
import java.util.Collection;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Locale;
......@@ -134,7 +135,104 @@ public class FontFamily {
return java.util.Objects.equals(newDir, existDir);
}
/*
* We want a family to be of the same width and prefer medium/normal width.
* Once we find a particular width we accept more of the same width
* until we find one closer to normal when we 'evict' all existing fonts.
* So once we see a 'normal' width font we evict all members that are not
* normal width and then accept only new ones that are normal width.
*
* Once a font passes the width test we subject it to the weight test.
* For Plain we target the weight the closest that is <= NORMAL (400)
* For Bold we target the weight that is closest to BOLD (700).
*
* In the future, rather than discarding these fonts, we should
* extend the family to include these so lookups on these properties
* can locate them, as presently they will only be located by full name
* based lookup.
*/
private int familyWidth = 0;
private boolean preferredWidth(Font2D font) {
int newWidth = font.getWidth();
if (familyWidth == 0) {
familyWidth = newWidth;
return true;
}
if (newWidth == familyWidth) {
return true;
}
if (Math.abs(Font2D.FWIDTH_NORMAL - newWidth) <
Math.abs(Font2D.FWIDTH_NORMAL - familyWidth))
{
if (FontUtilities.debugFonts()) {
FontUtilities.getLogger().info(
"Found more preferred width. New width = " + newWidth +
" Old width = " + familyWidth + " in font " + font +
" nulling out fonts plain: " + plain + " bold: " + bold +
" italic: " + italic + " bolditalic: " + bolditalic);
}
familyWidth = newWidth;
plain = bold = italic = bolditalic = null;
return true;
} else if (FontUtilities.debugFonts()) {
FontUtilities.getLogger().info(
"Family rejecting font " + font +
" of less preferred width " + newWidth);
}
return false;
}
private boolean closerWeight(Font2D currFont, Font2D font, int style) {
if (familyWidth != font.getWidth()) {
return false;
}
if (currFont == null) {
return true;
}
if (FontUtilities.debugFonts()) {
FontUtilities.getLogger().info(
"New weight for style " + style + ". Curr.font=" + currFont +
" New font="+font+" Curr.weight="+ + currFont.getWeight()+
" New weight="+font.getWeight());
}
int newWeight = font.getWeight();
switch (style) {
case Font.PLAIN:
case Font.ITALIC:
return (newWeight <= Font2D.FWEIGHT_NORMAL &&
newWeight > currFont.getWeight());
case Font.BOLD:
case Font.BOLD|Font.ITALIC:
return (Math.abs(newWeight - Font2D.FWEIGHT_BOLD) <
Math.abs(currFont.getWeight() - Font2D.FWEIGHT_BOLD));
default:
return false;
}
}
public void setFont(Font2D font, int style) {
if (FontUtilities.isLogging()) {
String msg;
if (font instanceof CompositeFont) {
msg = "Request to add " + font.getFamilyName(null) +
" with style " + style + " to family " + familyName;
} else {
msg = "Request to add " + font +
" with style " + style + " to family " + this;
}
FontUtilities.getLogger().info(msg);
}
/* Allow a lower-rank font only if its a file font
* from the exact same source as any previous font.
*/
......@@ -152,19 +250,27 @@ public class FontFamily {
switch (style) {
case Font.PLAIN:
plain = font;
if (preferredWidth(font) && closerWeight(plain, font, style)) {
plain = font;
}
break;
case Font.BOLD:
bold = font;
if (preferredWidth(font) && closerWeight(bold, font, style)) {
bold = font;
}
break;
case Font.ITALIC:
italic = font;
if (preferredWidth(font) && closerWeight(italic, font, style)) {
italic = font;
}
break;
case Font.BOLD|Font.ITALIC:
bolditalic = font;
if (preferredWidth(font) && closerWeight(bolditalic, font, style)) {
bolditalic = font;
}
break;
default:
......@@ -316,6 +422,11 @@ public class FontFamily {
return allLocaleNames.get(name.toLowerCase());
}
public static FontFamily[] getAllFontFamilies() {
Collection<FontFamily> families = familyNameMap.values();
return families.toArray(new FontFamily[0]);
}
public String toString() {
return
"Font family: " + familyName +
......
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2015, 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
......@@ -33,42 +33,43 @@ import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
public class StandardTextSource extends TextSource {
char[] chars;
int start;
int len;
int cstart;
int clen;
int level; // assumed all uniform
int flags; // see GlyphVector.java
Font font;
FontRenderContext frc;
CoreMetrics cm;
/**
* Create a simple implementation of a TextSource.
*
* Chars is an array containing clen chars in the context, in
* logical order, contiguously starting at cstart. Start and len
* represent that portion of the context representing the true
* source; start, like cstart, is relative to the start of the
* character array.
*
* Level is the bidi level (0-63 for the entire context. Flags is
* the layout flags. Font is the font, frc is the render context,
* and lm is the line metrics for the entire source text, but not
* necessarily the context.
*/
public StandardTextSource(char[] chars,
int start,
int len,
int cstart,
int clen,
int level,
int flags,
Font font,
FontRenderContext frc,
CoreMetrics cm) {
final class StandardTextSource extends TextSource {
private final char[] chars;
private final int start;
private final int len;
private final int cstart;
private final int clen;
private final int level; // assumed all uniform
private final int flags; // see GlyphVector.java
private final Font font;
private final FontRenderContext frc;
private final CoreMetrics cm;
/**
* Create a simple implementation of a TextSource.
*
* Chars is an array containing clen chars in the context, in
* logical order, contiguously starting at cstart. Start and len
* represent that portion of the context representing the true
* source; start, like cstart, is relative to the start of the
* character array.
*
* Level is the bidi level (0-63 for the entire context. Flags is
* the layout flags. Font is the font, frc is the render context,
* and lm is the line metrics for the entire source text, but not
* necessarily the context.
*/
StandardTextSource(char[] chars,
int start,
int len,
int cstart,
int clen,
int level,
int flags,
Font font,
FontRenderContext frc,
CoreMetrics cm) {
if (chars == null) {
throw new IllegalArgumentException("bad chars: null");
}
......@@ -97,7 +98,7 @@ public class StandardTextSource extends TextSource {
throw new IllegalArgumentException("bad frc: null");
}
this.chars = chars.clone();
this.chars = chars;
this.start = start;
this.len = len;
this.cstart = cstart;
......@@ -115,40 +116,10 @@ public class StandardTextSource extends TextSource {
}
}
/** Create a StandardTextSource whose context is coextensive with the source. */
public StandardTextSource(char[] chars,
int start,
int len,
int level,
int flags,
Font font,
FontRenderContext frc,
CoreMetrics cm) {
this(chars, start, len, start, len, level, flags, font, frc, cm);
}
/** Create a StandardTextSource whose context and source are coextensive with the entire char array. */
public StandardTextSource(char[] chars,
int level,
int flags,
Font font,
FontRenderContext frc) {
this(chars, 0, chars.length, 0, chars.length, level, flags, font, frc, null);
}
/** Create a StandardTextSource whose context and source are all the text in the String. */
public StandardTextSource(String str,
int level,
int flags,
Font font,
FontRenderContext frc) {
this(str.toCharArray(), 0, str.length(), 0, str.length(), level, flags, font, frc, null);
}
// TextSource API
public char[] getChars() {
return chars.clone();
return chars;
}
public int getStart() {
......
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2015, 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
......@@ -48,12 +48,12 @@ import java.text.Bidi;
* @see TextLayout
*/
public class TextLabelFactory {
private FontRenderContext frc;
private char[] text;
private Bidi bidi;
public final class TextLabelFactory {
private final FontRenderContext frc;
private final char[] text;
private final Bidi bidi;
private Bidi lineBidi;
private int flags;
private final int flags;
private int lineStart;
private int lineLimit;
......
......@@ -959,6 +959,18 @@ public class TrueTypeFont extends FileFont {
setStyle(getTableBuffer(os_2Tag));
}
private int fontWidth = 0;
@Override
public int getWidth() {
return (fontWidth > 0) ? fontWidth : super.getWidth();
}
private int fontWeight = 0;
@Override
public int getWeight() {
return (fontWeight > 0) ? fontWeight : super.getWeight();
}
/* TrueTypeFont can use the fsSelection fields of OS/2 table
* to determine the style. In the unlikely case that doesn't exist,
* can use macStyle in the 'head' table but simpler to
......@@ -974,8 +986,15 @@ public class TrueTypeFont extends FileFont {
private static final int fsSelectionBoldBit = 0x00020;
private static final int fsSelectionRegularBit = 0x00040;
private void setStyle(ByteBuffer os_2Table) {
if (os_2Table == null) {
return;
}
if (os_2Table.capacity() >= 8) {
fontWeight = os_2Table.getChar(4) & 0xffff;
fontWidth = os_2Table.getChar(6) & 0xffff;
}
/* fsSelection is unsigned short at buffer offset 62 */
if (os_2Table == null || os_2Table.capacity() < 64) {
if (os_2Table.capacity() < 64) {
super.setStyle();
return;
}
......
/*
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -59,6 +59,10 @@ final class OGLBlitLoops {
TransformBlit transformBlitIntArgbPreToSurface =
new OGLSwToSurfaceTransform(SurfaceType.IntArgbPre,
OGLSurfaceData.PF_INT_ARGB_PRE);
OGLSurfaceToSwBlit blitSurfaceToIntArgbPre =
new OGLSurfaceToSwBlit(SurfaceType.IntArgbPre,
OGLSurfaceData.PF_INT_ARGB_PRE);
GraphicsPrimitive[] primitives = {
// surface->surface ops
new OGLSurfaceToSurfaceBlit(),
......@@ -73,8 +77,7 @@ final class OGLBlitLoops {
// surface->sw ops
new OGLSurfaceToSwBlit(SurfaceType.IntArgb,
OGLSurfaceData.PF_INT_ARGB),
new OGLSurfaceToSwBlit(SurfaceType.IntArgbPre,
OGLSurfaceData.PF_INT_ARGB_PRE),
blitSurfaceToIntArgbPre,
// sw->surface ops
blitIntArgbPreToSurface,
......@@ -102,7 +105,14 @@ final class OGLBlitLoops {
CompositeType.AnyAlpha,
blitIntArgbPreToSurface),
new OGLAnyCompositeBlit(),
new OGLAnyCompositeBlit(OGLSurfaceData.OpenGLSurface,
blitSurfaceToIntArgbPre,
blitSurfaceToIntArgbPre,
blitIntArgbPreToSurface),
new OGLAnyCompositeBlit(SurfaceType.Any,
null,
blitSurfaceToIntArgbPre,
blitIntArgbPreToSurface),
new OGLSwToSurfaceScale(SurfaceType.IntRgb,
OGLSurfaceData.PF_INT_RGB),
......@@ -869,11 +879,26 @@ final class OGLGeneralTransformedBlit extends TransformBlit {
}
}
/**
* This general OGLAnyCompositeBlit implementation can convert any source/target
* surface to an intermediate surface using convertsrc/convertdst loops, applies
* necessary composite operation, and then uses convertresult loop to get the
* intermediate surface down to OpenGL.
*/
final class OGLAnyCompositeBlit extends Blit {
private WeakReference<SurfaceData> dstTmp;
private WeakReference<SurfaceData> srcTmp;
private final Blit convertsrc;
private final Blit convertdst;
private final Blit convertresult;
OGLAnyCompositeBlit() {
super(SurfaceType.Any, CompositeType.Any, OGLSurfaceData.OpenGLSurface);
OGLAnyCompositeBlit(SurfaceType srctype, Blit convertsrc, Blit convertdst,
Blit convertresult) {
super(srctype, CompositeType.Any, OGLSurfaceData.OpenGLSurface);
this.convertsrc = convertsrc;
this.convertdst = convertdst;
this.convertresult = convertresult;
}
public synchronized void Blit(SurfaceData src, SurfaceData dst,
......@@ -881,9 +906,20 @@ final class OGLAnyCompositeBlit extends Blit {
int sx, int sy, int dx, int dy,
int w, int h)
{
Blit convertdst = Blit.getFromCache(dst.getSurfaceType(),
CompositeType.SrcNoEa,
SurfaceType.IntArgbPre);
if (convertsrc != null) {
SurfaceData cachedSrc = null;
if (srcTmp != null) {
// use cached intermediate surface, if available
cachedSrc = srcTmp.get();
}
// convert source to IntArgbPre
src = convertFrom(convertsrc, src, sx, sy, w, h, cachedSrc,
BufferedImage.TYPE_INT_ARGB_PRE);
if (src != cachedSrc) {
// cache the intermediate surface
srcTmp = new WeakReference<>(src);
}
}
SurfaceData cachedDst = null;
......@@ -906,12 +942,8 @@ final class OGLAnyCompositeBlit extends Blit {
// cache the intermediate surface
dstTmp = new WeakReference(dstBuffer);
}
// now blit the buffer back to the destination
convertdst = Blit.getFromCache(dstBuffer.getSurfaceType(),
CompositeType.SrcNoEa,
dst.getSurfaceType());
convertdst.Blit(dstBuffer, dst, AlphaComposite.Src,
clip, 0, 0, dx, dy, w, h);
convertresult.Blit(dstBuffer, dst, AlphaComposite.Src, clip, 0, 0, dx,
dy, w, h);
}
}
......@@ -26,6 +26,7 @@
package sun.java2d.opengl;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Transparency;
......@@ -400,8 +401,8 @@ public abstract class OGLSurfaceData extends SurfaceData
/**
* For now, we can only render LCD text if:
* - the fragment shader extension is available, and
* - blending is disabled, and
* - the source color is opaque
* - the source color is opaque, and
* - blending is SrcOverNoEa or disabled
* - and the destination is opaque
*
* Eventually, we could enhance the native OGL text rendering code
......@@ -411,9 +412,19 @@ public abstract class OGLSurfaceData extends SurfaceData
public boolean canRenderLCDText(SunGraphics2D sg2d) {
return
graphicsConfig.isCapPresent(CAPS_EXT_LCD_SHADER) &&
sg2d.compositeState <= SunGraphics2D.COMP_ISCOPY &&
sg2d.surfaceData.getTransparency() == Transparency.OPAQUE &&
sg2d.paintState <= SunGraphics2D.PAINT_OPAQUECOLOR &&
sg2d.surfaceData.getTransparency() == Transparency.OPAQUE;
(sg2d.compositeState <= SunGraphics2D.COMP_ISCOPY ||
(sg2d.compositeState <= SunGraphics2D.COMP_ALPHA && canHandleComposite(sg2d.composite)));
}
private boolean canHandleComposite(Composite c) {
if (c instanceof AlphaComposite) {
AlphaComposite ac = (AlphaComposite)c;
return ac.getRule() == AlphaComposite.SRC_OVER && ac.getAlpha() >= 1f;
}
return false;
}
public void validatePipe(SunGraphics2D sg2d) {
......
......@@ -515,6 +515,7 @@ public final class FontPanel extends JPanel implements AdjustmentListener {
/// Sets the font, hints, according to the set parameters
private void setParams( Graphics2D g2 ) {
System.out.println("USING FONT " + testFont + " "+testFont.getPSName());
g2.setFont( testFont );
g2.setRenderingHint(KEY_TEXT_ANTIALIASING, antiAliasType);
g2.setRenderingHint(KEY_FRACTIONALMETRICS, fractionalMetricsType);
......
......@@ -411,7 +411,6 @@ Java_sun_font_FreetypeFontScaler_getFontMetricsNative(
jobject metrics;
jfloat ax, ay, dx, dy, bx, by, lx, ly, mx, my;
jfloat f0 = 0.0;
FT_Pos bmodifier = 0;
FTScalerContext *context =
(FTScalerContext*) jlong_to_ptr(pScalerContext);
FTScalerInfo *scalerInfo =
......@@ -444,43 +443,38 @@ Java_sun_font_FreetypeFontScaler_getFontMetricsNative(
So, we have to do adust them explicitly and stay consistent with what
freetype does to outlines. */
/* For bolding glyphs are not just widened. Height is also changed
(see ftsynth.c).
TODO: In vertical direction we could do better job and adjust metrics
proportionally to glyoh shape. */
if (context->doBold) {
bmodifier = FT_MulFix(
scalerInfo->face->units_per_EM,
scalerInfo->face->size->metrics.y_scale)/24;
}
/**** Note: only some metrics are affected by styling ***/
/* See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=657854 */
#define FT_MulFixFloatShift6(a, b) (((float) (a)) * ((float) (b)) / 65536.0 / 64.0)
/*
* See FreeType source code: src/base/ftobjs.c ft_recompute_scaled_metrics()
* http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=1659
*/
/* ascent */
ax = 0;
ay = -(jfloat) FT26Dot6ToFloat(FT_MulFix(
((jlong) scalerInfo->face->ascender + bmodifier/2),
ay = -(jfloat) (FT_MulFixFloatShift6(
((jlong) scalerInfo->face->ascender),
(jlong) scalerInfo->face->size->metrics.y_scale));
/* descent */
dx = 0;
dy = -(jfloat) FT26Dot6ToFloat(FT_MulFix(
((jlong) scalerInfo->face->descender + bmodifier/2),
dy = -(jfloat) (FT_MulFixFloatShift6(
((jlong) scalerInfo->face->descender),
(jlong) scalerInfo->face->size->metrics.y_scale));
/* baseline */
bx = by = 0;
/* leading */
lx = 0;
ly = (jfloat) FT26Dot6ToFloat(FT_MulFix(
(jlong) scalerInfo->face->height + bmodifier,
ly = (jfloat) (FT_MulFixFloatShift6(
(jlong) scalerInfo->face->height,
(jlong) scalerInfo->face->size->metrics.y_scale))
+ ay - dy;
/* max advance */
mx = (jfloat) FT26Dot6ToFloat(
scalerInfo->face->size->metrics.max_advance +
2*bmodifier +
OBLIQUE_MODIFIER(scalerInfo->face->size->metrics.height));
my = 0;
......
......@@ -748,7 +748,7 @@ OGLContext_IsLCDShaderSupportAvailable(JNIEnv *env,
// finally, check to see if the hardware supports the required number
// of texture units
j2d_glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &maxTexUnits);
if (maxTexUnits < 4) {
if (maxTexUnits < 2) {
J2dRlsTraceLn1(J2D_TRACE_INFO,
"OGLContext_IsLCDShaderSupportAvailable: not enough tex units (%d)",
maxTexUnits);
......
......@@ -94,23 +94,10 @@ static GlyphCacheInfo *glyphCache = NULL;
*/
static GLhandleARB lcdTextProgram = 0;
/**
* The size of one of the gamma LUT textures in any one dimension along
* the edge, in texels.
*/
#define LUT_EDGE 16
/**
* These are the texture object handles for the gamma and inverse gamma
* lookup tables.
*/
static GLuint gammaLutTextureID = 0;
static GLuint invGammaLutTextureID = 0;
/**
* This value tracks the previous LCD contrast setting, so if the contrast
* value hasn't changed since the last time the lookup tables were
* generated (not very common), then we can skip updating the tables.
* value hasn't changed since the last time the gamma uniforms were
* updated (not very common), then we can skip updating the unforms.
*/
static jint lastLCDContrast = -1;
......@@ -275,12 +262,9 @@ OGLTR_AddToGlyphCache(GlyphInfo *glyph, jboolean rgbOrder)
* changes, we will modify the "src_adj" value in OGLTR_UpdateLCDTextColor()).
*
* The "main" function is executed for each "fragment" (or pixel) in the
* glyph image. We have determined that the pow() function can be quite
* slow and it only operates on scalar values, not vectors as we require.
* So instead we build two 3D textures containing gamma (and inverse gamma)
* lookup tables that allow us to approximate a component-wise pow() function
* with a single 3D texture lookup. This approach is at least 2x faster
* than the equivalent pow() calls.
* glyph image. The pow() routine operates on vectors, gives precise results,
* and provides acceptable level of performance, so we use it to perform
* the gamma adjustment.
*
* The variables involved in the equation can be expressed as follows:
*
......@@ -299,8 +283,8 @@ static const char *lcdTextShaderSource =
"uniform vec3 src_adj;"
"uniform sampler2D glyph_tex;"
"uniform sampler2D dst_tex;"
"uniform sampler3D invgamma_tex;"
"uniform sampler3D gamma_tex;"
"uniform vec3 gamma;"
"uniform vec3 invgamma;"
""
"void main(void)"
"{"
......@@ -312,12 +296,12 @@ static const char *lcdTextShaderSource =
" }"
// load the RGB value from the corresponding destination pixel
" vec3 dst_clr = vec3(texture2D(dst_tex, gl_TexCoord[1].st));"
// gamma adjust the dest color using the invgamma LUT
" vec3 dst_adj = vec3(texture3D(invgamma_tex, dst_clr.stp));"
// gamma adjust the dest color
" vec3 dst_adj = pow(dst_clr.rgb, gamma);"
// linearly interpolate the three color values
" vec3 result = mix(dst_adj, src_adj, glyph_clr);"
// gamma re-adjust the resulting color (alpha is always set to 1.0)
" gl_FragColor = vec4(vec3(texture3D(gamma_tex, result.stp)), 1.0);"
" gl_FragColor = vec4(pow(result.rgb, invgamma), 1.0);"
"}";
/**
......@@ -348,10 +332,6 @@ OGLTR_CreateLCDTextProgram()
j2d_glUniform1iARB(loc, 0); // texture unit 0
loc = j2d_glGetUniformLocationARB(lcdTextProgram, "dst_tex");
j2d_glUniform1iARB(loc, 1); // texture unit 1
loc = j2d_glGetUniformLocationARB(lcdTextProgram, "invgamma_tex");
j2d_glUniform1iARB(loc, 2); // texture unit 2
loc = j2d_glGetUniformLocationARB(lcdTextProgram, "gamma_tex");
j2d_glUniform1iARB(loc, 3); // texture unit 3
// "unuse" the program object; it will be re-bound later as needed
j2d_glUseProgramObjectARB(0);
......@@ -360,108 +340,26 @@ OGLTR_CreateLCDTextProgram()
}
/**
* Initializes a 3D texture object for use as a three-dimensional gamma
* lookup table. Note that the wrap mode is initialized to GL_LINEAR so
* that the table will interpolate adjacent values when the index falls
* somewhere in between.
*/
static GLuint
OGLTR_InitGammaLutTexture()
{
GLuint lutTextureID;
j2d_glGenTextures(1, &lutTextureID);
j2d_glBindTexture(GL_TEXTURE_3D, lutTextureID);
j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return lutTextureID;
}
/**
* Updates the lookup table in the given texture object with the float
* values in the given system memory buffer. Note that we could use
* glTexSubImage3D() when updating the texture after its first
* initialization, but since we're updating the entire table (with
* power-of-two dimensions) and this is a relatively rare event, we'll
* just stick with glTexImage3D().
*/
static void
OGLTR_UpdateGammaLutTexture(GLuint texID, GLfloat *lut, jint size)
{
j2d_glBindTexture(GL_TEXTURE_3D, texID);
j2d_glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB8,
size, size, size, 0, GL_RGB, GL_FLOAT, lut);
}
/**
* (Re)Initializes the gamma lookup table textures.
* (Re)Initializes the gamma related uniforms.
*
* The given contrast value is an int in the range [100, 250] which we will
* then scale to fit in the range [1.0, 2.5]. We create two LUTs, one
* that essentially calculates pow(x, gamma) and the other calculates
* pow(x, 1/gamma). These values are replicated in all three dimensions, so
* given a single 3D texture coordinate (typically this will be a triplet
* in the form (r,g,b)), the 3D texture lookup will return an RGB triplet:
*
* (pow(r,g), pow(y,g), pow(z,g)
*
* where g is either gamma or 1/gamma, depending on the table.
* then scale to fit in the range [1.0, 2.5].
*/
static jboolean
OGLTR_UpdateLCDTextContrast(jint contrast)
{
double gamma = ((double)contrast) / 100.0;
double ig = gamma;
double g = 1.0 / ig;
GLfloat lut[LUT_EDGE][LUT_EDGE][LUT_EDGE][3];
GLfloat invlut[LUT_EDGE][LUT_EDGE][LUT_EDGE][3];
int min = 0;
int max = LUT_EDGE - 1;
int x, y, z;
double g = ((double)contrast) / 100.0;
double ig = 1.0 / g;
GLint loc;
J2dTraceLn1(J2D_TRACE_INFO,
"OGLTR_UpdateLCDTextContrast: contrast=%d", contrast);
for (z = min; z <= max; z++) {
double zval = ((double)z) / max;
GLfloat gz = (GLfloat)pow(zval, g);
GLfloat igz = (GLfloat)pow(zval, ig);
for (y = min; y <= max; y++) {
double yval = ((double)y) / max;
GLfloat gy = (GLfloat)pow(yval, g);
GLfloat igy = (GLfloat)pow(yval, ig);
loc = j2d_glGetUniformLocationARB(lcdTextProgram, "gamma");
j2d_glUniform3fARB(loc, g, g, g);
for (x = min; x <= max; x++) {
double xval = ((double)x) / max;
GLfloat gx = (GLfloat)pow(xval, g);
GLfloat igx = (GLfloat)pow(xval, ig);
lut[z][y][x][0] = gx;
lut[z][y][x][1] = gy;
lut[z][y][x][2] = gz;
invlut[z][y][x][0] = igx;
invlut[z][y][x][1] = igy;
invlut[z][y][x][2] = igz;
}
}
}
if (gammaLutTextureID == 0) {
gammaLutTextureID = OGLTR_InitGammaLutTexture();
}
OGLTR_UpdateGammaLutTexture(gammaLutTextureID, (GLfloat *)lut, LUT_EDGE);
if (invGammaLutTextureID == 0) {
invGammaLutTextureID = OGLTR_InitGammaLutTexture();
}
OGLTR_UpdateGammaLutTexture(invGammaLutTextureID,
(GLfloat *)invlut, LUT_EDGE);
loc = j2d_glGetUniformLocationARB(lcdTextProgram, "invgamma");
j2d_glUniform3fARB(loc, ig, ig, ig);
return JNI_TRUE;
}
......@@ -562,14 +460,6 @@ OGLTR_EnableLCDGlyphModeState(GLuint glyphTextureID, jint contrast)
return JNI_FALSE;
}
// bind the gamma LUT textures
j2d_glActiveTextureARB(GL_TEXTURE2_ARB);
j2d_glBindTexture(GL_TEXTURE_3D, invGammaLutTextureID);
j2d_glEnable(GL_TEXTURE_3D);
j2d_glActiveTextureARB(GL_TEXTURE3_ARB);
j2d_glBindTexture(GL_TEXTURE_3D, gammaLutTextureID);
j2d_glEnable(GL_TEXTURE_3D);
return JNI_TRUE;
}
......@@ -629,10 +519,6 @@ OGLTR_DisableGlyphModeState()
j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
j2d_glUseProgramObjectARB(0);
j2d_glActiveTextureARB(GL_TEXTURE3_ARB);
j2d_glDisable(GL_TEXTURE_3D);
j2d_glActiveTextureARB(GL_TEXTURE2_ARB);
j2d_glDisable(GL_TEXTURE_3D);
j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
j2d_glDisable(GL_TEXTURE_2D);
j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
......
......@@ -156,19 +156,29 @@ public final class XClipboard extends SunClipboard implements OwnershipListener
isSelectionNotifyProcessed = true;
boolean mustSchedule = false;
synchronized (XClipboard.classLock) {
if (targetsAtom2Clipboard == null) {
targetsAtom2Clipboard = new HashMap<Long, XClipboard>(2);
XToolkit.awtLock();
try {
synchronized (XClipboard.classLock) {
try {
Thread.sleep(70);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (targetsAtom2Clipboard == null) {
targetsAtom2Clipboard = new HashMap<Long, XClipboard>(2);
}
mustSchedule = targetsAtom2Clipboard.isEmpty();
targetsAtom2Clipboard.put(getTargetsPropertyAtom().getAtom(), this);
if (mustSchedule) {
XToolkit.addEventDispatcher(XWindow.getXAWTRootWindow().getWindow(),
new SelectionNotifyHandler());
}
}
mustSchedule = targetsAtom2Clipboard.isEmpty();
targetsAtom2Clipboard.put(getTargetsPropertyAtom().getAtom(), this);
if (mustSchedule) {
XToolkit.addEventDispatcher(XWindow.getXAWTRootWindow().getWindow(),
new SelectionNotifyHandler());
XToolkit.schedule(new CheckChangeTimerTask(), XClipboard.getPollInterval());
}
}
if (mustSchedule) {
XToolkit.schedule(new CheckChangeTimerTask(), XClipboard.getPollInterval());
} finally {
XToolkit.awtUnlock();
}
}
......
......@@ -31,18 +31,22 @@ package sun.awt.X11;
* common logical ancestor
*/
class XRootWindow extends XBaseWindow {
private static XRootWindow xawtRootWindow = null;
static XRootWindow getInstance() {
XToolkit.awtLock();
try {
if (xawtRootWindow == null) {
private static class LazyHolder {
private static final XRootWindow xawtRootWindow;
static {
XToolkit.awtLock();
try {
xawtRootWindow = new XRootWindow();
xawtRootWindow.init(xawtRootWindow.getDelayedParams().delete(DELAYED));
} finally {
XToolkit.awtUnlock();
}
return xawtRootWindow;
} finally {
XToolkit.awtUnlock();
}
}
static XRootWindow getInstance() {
return LazyHolder.xawtRootWindow;
}
private XRootWindow() {
......
......@@ -598,14 +598,19 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
}
}
}
if( keyEventLog.isLoggable(PlatformLogger.Level.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) {
keyEventLog.fine("before XFilterEvent:"+ev);
if (keyEventLog.isLoggable(PlatformLogger.Level.FINE) && (
ev.get_type() == XConstants.KeyPress
|| ev.get_type() == XConstants.KeyRelease)) {
keyEventLog.fine("before XFilterEvent:" + ev);
}
if (XlibWrapper.XFilterEvent(ev.getPData(), w)) {
continue;
}
if( keyEventLog.isLoggable(PlatformLogger.Level.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) {
keyEventLog.fine("after XFilterEvent:"+ev); // IS THIS CORRECT?
if (keyEventLog.isLoggable(PlatformLogger.Level.FINE) && (
ev.get_type() == XConstants.KeyPress
|| ev.get_type() == XConstants.KeyRelease)) {
keyEventLog.fine(
"after XFilterEvent:" + ev); // IS THIS CORRECT?
}
dispatchEvent(ev);
......@@ -621,21 +626,28 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
}
}
/**
* Listener installed to detect display changes.
*/
private static final DisplayChangedListener displayChangedHandler =
new DisplayChangedListener() {
@Override
public void displayChanged() {
// 7045370: Reset the cached values
XToolkit.screenWidth = -1;
XToolkit.screenHeight = -1;
}
@Override
public void paletteChanged() {
}
};
static {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
if (ge instanceof SunGraphicsEnvironment) {
((SunGraphicsEnvironment)ge).addDisplayChangedListener(
new DisplayChangedListener() {
@Override
public void displayChanged() {
// 7045370: Reset the cached values
XToolkit.screenWidth = -1;
XToolkit.screenHeight = -1;
}
@Override
public void paletteChanged() {}
});
((SunGraphicsEnvironment) ge).addDisplayChangedListener(
displayChangedHandler);
}
}
......@@ -645,7 +657,9 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
try {
XWindowAttributes pattr = new XWindowAttributes();
try {
XlibWrapper.XGetWindowAttributes(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), pattr.pData);
XlibWrapper.XGetWindowAttributes(XToolkit.getDisplay(),
XToolkit.getDefaultRootWindow(),
pattr.pData);
screenWidth = (int) pattr.get_width();
screenHeight = (int) pattr.get_height();
} finally {
......
......@@ -1864,6 +1864,7 @@ Java_sun_awt_windows_WEmbeddedFrame_initIDs(JNIEnv *env, jclass cls)
AwtFrame::activateEmbeddingTopLevelMID = env->GetMethodID(cls, "activateEmbeddingTopLevel", "()V");
DASSERT(AwtFrame::activateEmbeddingTopLevelMID != NULL);
CHECK_NULL(AwtFrame::activateEmbeddingTopLevelMID);
AwtFrame::isEmbeddedInIEID = env->GetFieldID(cls, "isEmbeddedInIE", "Z");
DASSERT(AwtFrame::isEmbeddedInIEID != NULL);
......
......@@ -484,6 +484,10 @@ needs_compact3 = \
sun/security/jgss \
sun/security/krb5 \
java/lang/annotation/AnnotationType/AnnotationTypeDeadlockTest.java \
java/lang/invoke/lambda/LambdaStackTrace.java \
java/lang/invoke/LFCaching/LFGarbageCollectedTest.java \
java/lang/invoke/LFCaching/LFMultiThreadCachingTest.java \
java/lang/invoke/LFCaching/LFSingleThreadCachingTest.java \
java/lang/System/MacEncoding/TestFileEncoding.java \
java/nio/channels/AsynchronousSocketChannel/Leaky.java \
java/security/PermissionCollection/Concurrent.java \
......
/*
* Copyright (c) 2015, 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.Component;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Robot;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
/**
* @test
* @bug 8071306
* @author Sergey Bylokhov
*/
public final class SetEnabledPerformance {
private static Frame frame;
private static void createAndShowGUI() {
frame = new Frame();
frame.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 0));
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
for (int i = 1; i < 10001; ++i) {
frame.add(new JButton("Button " + i));
}
frame.setVisible(true);
}
public static void main(final String[] args) throws Exception {
SwingUtilities.invokeAndWait(() -> createAndShowGUI());
final Robot robot = new Robot();
robot.waitForIdle();
robot.mouseMove(frame.getX() + 15, frame.getY() + 300);
robot.waitForIdle();
SwingUtilities.invokeAndWait(() -> {
long m = System.currentTimeMillis();
for (final Component comp : frame.getComponents()) {
comp.setEnabled(false);
}
m = System.currentTimeMillis() - m;
System.err.println("Disabled in " + m + " ms");
frame.dispose();
// we should be much faster, but leaves 1000 for the slow systems
if (m > 1000) {
throw new RuntimeException("Too slow");
}
});
}
}
\ No newline at end of file
/*
* Copyright (c) 2007, 2008, 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 6255653
@summary REGRESSION: Override isLightweight() causes access violation in awt.dll
@author Andrei Dmitriev: area=awt-component
@run main StubPeerCrash
*/
/*
* The test may not crash for several times so iteratively continue up to some limit.
*/
import java.awt.*;
import java.awt.peer.*;
import java.awt.event.PaintEvent;
import java.awt.image.ImageProducer;
import java.awt.image.ImageObserver;
import java.awt.image.ColorModel;
import java.awt.image.VolatileImage;
import java.awt.GraphicsConfiguration;
import sun.awt.CausedFocusEvent;
import sun.java2d.pipe.Region;
public class StubPeerCrash {
public static int ITERATIONS = 20;
public static void main(String []s)
{
for (int i = 0; i < ITERATIONS; i++){
showFrame(i);
}
}
private static void showFrame(int i){
System.out.println("iteration = "+i);
Frame f = new Frame();
f.add(new AHeavyweightComponent());
f.setVisible(true);
f.setVisible(false);
}
}
class AHeavyweightComponent extends Component {
private ComponentPeer peer = new StubComponentPeer();
public AHeavyweightComponent(){
}
public boolean isLightweight() {
return false;
}
public ComponentPeer getPeer(){
return peer;
}
}
class StubComponentPeer implements ComponentPeer {
public boolean isObscured(){return true;};
public boolean canDetermineObscurity(){return true;};
public void setVisible(boolean b){};
public void setEnabled(boolean b){};
public void paint(Graphics g){};
public void repaint(long tm, int x, int y, int width, int height){};
public void print(Graphics g){};
public void setBounds(int x, int y, int width, int height, int op){};
public void handleEvent(AWTEvent e){};
public void coalescePaintEvent(PaintEvent e){};
public Point getLocationOnScreen(){return null;};
public Dimension getPreferredSize(){return null;};
public Dimension getMinimumSize(){return null;};
public ColorModel getColorModel(){return null;};
public Toolkit getToolkit(){return null;};
public Graphics getGraphics(){return null;};
public FontMetrics getFontMetrics(Font font){return null;};
public void dispose(){};
public void setForeground(Color c){};
public void setBackground(Color c){};
public void setFont(Font f){};
public void updateCursorImmediately(){};
public boolean requestFocus(Component lightweightChild,
boolean temporary,
boolean focusedWindowChangeAllowed,
long time, CausedFocusEvent.Cause cause){
return true;
};
public boolean isFocusable(){return true;};
public Image createImage(ImageProducer producer){return null;};
public Image createImage(int width, int height){return null;};
public VolatileImage createVolatileImage(int width, int height){return null;};
public boolean prepareImage(Image img, int w, int h, ImageObserver o){return true;};
public int checkImage(Image img, int w, int h, ImageObserver o){return 0;};
public GraphicsConfiguration getGraphicsConfiguration(){return null;};
public boolean handlesWheelScrolling(){return true;};
public void createBuffers(int numBuffers, BufferCapabilities caps) throws AWTException{};
public Image getBackBuffer(){return null;};
public void flip(int x1, int y1, int x2, int y2, BufferCapabilities.FlipContents flipAction){};
public void destroyBuffers(){};
/**
* Reparents this peer to the new parent referenced by <code>newContainer</code> peer
* Implementation depends on toolkit and container.
* @param newContainer peer of the new parent container
* @since 1.5
*/
public void reparent(ContainerPeer newContainer){};
/**
* Returns whether this peer supports reparenting to another parent withour destroying the peer
* @return true if appropriate reparent is supported, false otherwise
* @since 1.5
*/
public boolean isReparentSupported(){return true;};
/**
* Used by lightweight implementations to tell a ComponentPeer to layout
* its sub-elements. For instance, a lightweight Checkbox needs to layout
* the box, as well as the text label.
*/
public void layout(){};
public Rectangle getBounds(){return null;};
/**
* Applies the shape to the native component window.
* @since 1.7
*/
public void applyShape(Region shape){};
/**
* DEPRECATED: Replaced by getPreferredSize().
*/
public Dimension preferredSize(){return null;};
/**
* DEPRECATED: Replaced by getMinimumSize().
*/
public Dimension minimumSize(){return null;};
/**
* DEPRECATED: Replaced by setVisible(boolean).
*/
public void show(){};
/**
* DEPRECATED: Replaced by setVisible(boolean).
*/
public void hide(){};
/**
* DEPRECATED: Replaced by setEnabled(boolean).
*/
public void enable(){};
/**
* DEPRECATED: Replaced by setEnabled(boolean).
*/
public void disable(){};
/**
* DEPRECATED: Replaced by setBounds(int, int, int, int).
*/
public void reshape(int x, int y, int width, int height){};
}
/*
* Copyright (c) 2003, 2015, 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 4956241 80769790
* @summary NPE debugging fonts
* @run main/othervm DebugFonts
*/
import java.awt.Font;
public class DebugFonts {
public static void main(String [] args) {
System.setProperty("sun.java2d.debugfonts", "true");
Font font = new Font("dialog", Font.PLAIN, 14);
System.out.println(font);
String s1 = font.getFamily();
String s2 = font.getFontName();
}
}
/*
* Copyright (c) 2015, 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 8064833
* @summary Test correct font is obtained via family+style
* @run main HelvLtOblTest
*/
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
public class HelvLtOblTest extends JComponent {
static Font helvFont = null;
static int[] codes = { 0x23, 0x4a, 0x48, 0x3, 0x4a, 0x55, 0x42, 0x4d,
0x4a, 0x44, 0x3,
0x53, 0x46, 0x45, 0x3, 0x55, 0x46, 0x59, 0x55, };
static String str = "Big italic red text";
public static void main(String[] args) throws Exception {
String os = System.getProperty("os.name");
if (!os.startsWith("Mac")) {
return;
}
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = ge.getAllFonts();
for (int i=0; i<fonts.length; i++) {
if (fonts[i].getPSName().equals("Helvetica-LightOblique")) {
helvFont = fonts[i];
break;
}
}
if (helvFont == null) {
return;
}
final HelvLtOblTest test = new HelvLtOblTest();
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add("Center", test);
f.pack();
f.setVisible(true);
});
test.compareImages();
}
public Dimension getPreferredSize() {
return new Dimension(400,400);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
FontRenderContext frc = new FontRenderContext(null, true, true);
Font f = helvFont.deriveFont(Font.PLAIN, 40);
System.out.println("font = " +f.getFontName());
GlyphVector gv = f.createGlyphVector(frc, codes);
g.setFont(f);
g.setColor(Color.white);
g.fillRect(0,0,400,400);
g.setColor(Color.black);
g2.drawGlyphVector(gv, 5,200);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2.drawString(str, 5, 250);
}
void compareImages() {
BufferedImage bi0 = drawText(false);
BufferedImage bi1 = drawText(true);
compare(bi0, bi1);
}
BufferedImage drawText(boolean doGV) {
int w = 400;
int h = 50;
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setColor(Color.white);
g.fillRect(0,0,w,h);
g.setColor(Color.black);
Font f = helvFont.deriveFont(Font.PLAIN, 40);
g.setFont(f);
int x = 5;
int y = h - 10;
if (doGV) {
FontRenderContext frc = new FontRenderContext(null, true, true);
GlyphVector gv = f.createGlyphVector(frc, codes);
g.drawGlyphVector(gv, 5, y);
} else {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g.drawString(str, x, y);
}
return bi;
}
// Need to allow for minimal rounding error, so allow each component
// to differ by 1.
void compare(BufferedImage bi0, BufferedImage bi1) {
int wid = bi0.getWidth();
int hgt = bi0.getHeight();
for (int x=0; x<wid; x++) {
for (int y=0; y<hgt; y++) {
int rgb0 = bi0.getRGB(x, y);
int rgb1 = bi1.getRGB(x, y);
if (rgb0 == rgb1) continue;
int r0 = (rgb0 & 0xff0000) >> 16;
int r1 = (rgb1 & 0xff0000) >> 16;
int rdiff = r0-r1; if (rdiff<0) rdiff = -rdiff;
int g0 = (rgb0 & 0x00ff00) >> 8;
int g1 = (rgb1 & 0x00ff00) >> 8;
int gdiff = g0-g1; if (gdiff<0) gdiff = -gdiff;
int b0 = (rgb0 & 0x0000ff);
int b1 = (rgb1 & 0x0000ff);
int bdiff = b0-b1; if (bdiff<0) bdiff = -bdiff;
if (rdiff > 1 || gdiff > 1 || bdiff > 1) {
throw new RuntimeException(
"Images differ at x=" + x + " y="+ y + " " +
Integer.toHexString(rgb0) + " vs " +
Integer.toHexString(rgb1));
}
}
}
}
}
/*
* Copyright (c) 2015, 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 javax.swing.*;
/*
* @test
* @bug 8080137
* @summary Dragged events for extra mouse buttons (4,5,6) are not generated
* on JSplitPane
* @author alexandr.scherbatiy area=awt.event
* @run main MouseDraggedTest
*/
public class MouseDraggedTest {
private static JFrame frame;
private static Rectangle frameBounds;
private static volatile boolean mouseDragged;
public static void main(String[] args) throws Exception {
try {
Robot robot = new Robot();
robot.setAutoDelay(50);
SwingUtilities.invokeAndWait(MouseDraggedTest::createAndShowGUI);
robot.waitForIdle();
SwingUtilities.invokeAndWait(() -> frameBounds = frame.getBounds());
robot.waitForIdle();
for (int i = 1; i <= MouseInfo.getNumberOfButtons(); i++) {
testMouseDrag(i, robot);
}
} finally {
SwingUtilities.invokeLater(() -> {
if (frame != null) {
frame.dispose();
}
});
}
}
private static void testMouseDrag(int button, Robot robot) {
mouseDragged = false;
int x1 = frameBounds.x + frameBounds.width / 4;
int y1 = frameBounds.y + frameBounds.height / 4;
int x2 = frameBounds.x + frameBounds.width / 2;
int y2 = frameBounds.y + frameBounds.height / 2;
robot.mouseMove(x1, y1);
robot.waitForIdle();
int buttonMask = InputEvent.getMaskForButton(button);
robot.mousePress(buttonMask);
robot.mouseMove(x2, y2);
robot.mouseRelease(buttonMask);
robot.waitForIdle();
if (!mouseDragged) {
throw new RuntimeException("Mouse button " + button
+ " is not dragged");
}
}
static void createAndShowGUI() {
frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
panel.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
mouseDragged = true;
}
});
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, 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 8077409
@summary Drawing deviates when validate() is invoked on java.awt.ScrollPane
@author mikhail.cherkasov@oracle.com
@run main bug8077409Test
*/
import java.awt.*;
import java.awt.event.*;
public class bug8077409Test extends Frame {
ScrollPane pane;
MyCanvas myCanvas;
class MyCanvas extends Canvas {
public Dimension getPreferredSize() {
return new Dimension(400, 800);
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.drawLine(0, 0, 399, 0);
g.setColor(Color.RED);
g.drawLine(0, 1, 399, 1);
g.setColor(Color.BLUE);
g.drawLine(0, 2, 399, 2);
g.setColor(Color.GREEN);
g.drawLine(0, 3, 399, 3);
}
}
public bug8077409Test() {
super();
setLayout(new BorderLayout());
pane = new ScrollPane();
myCanvas = new MyCanvas();
pane.add(myCanvas);
add(pane, BorderLayout.CENTER);
setSize(320, 480);
}
@Override
protected void processKeyEvent(KeyEvent e) {
super.processKeyEvent(e);
}
public static void main(String[] args) throws AWTException, InterruptedException {
final bug8077409Test obj = new bug8077409Test();
obj.setVisible(true);
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
@Override
public void eventDispatched(AWTEvent e) {
KeyEvent keyEvent = (KeyEvent) e;
if(keyEvent.getID() == KeyEvent.KEY_RELEASED) {
if (keyEvent.getKeyCode() == KeyEvent.VK_1) {
System.out.println(obj.pane.toString());
System.out.println("obj.myCanvas.pos: " + obj.myCanvas.getBounds());
System.out.println(obj.myCanvas.toString());
} else if (keyEvent.getKeyCode() == KeyEvent.VK_2) {
obj.repaint();
} else if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) {
Point scrollPosition = obj.pane.getScrollPosition();
scrollPosition.translate(0, 1);
obj.pane.setScrollPosition(scrollPosition);
} else if (keyEvent.getKeyCode() == KeyEvent.VK_UP) {
Point scrollPosition = obj.pane.getScrollPosition();
scrollPosition.translate(0, -1);
obj.pane.setScrollPosition(scrollPosition);
} else if (keyEvent.getKeyCode() == KeyEvent.VK_SPACE) {
obj.pane.validate();
}
}
}
}, AWTEvent.KEY_EVENT_MASK);
Point scrollPosition = obj.pane.getScrollPosition();
scrollPosition.translate(0, 1);
obj.pane.setScrollPosition(scrollPosition);
int y = obj.pane.getComponent(0).getLocation().y;
obj.pane.validate();
if(y != obj.pane.getComponent(0).getLocation().y){
throw new RuntimeException("Wrong position of component in ScrollPane");
}
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, 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.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.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 8061831
* @summary Tests drawing volatile image to volatile image using different
* clips + xor mode. Results of the blit compatibleImage to
* compatibleImage is used for comparison.
*/
public final class IncorrectClipXorModeSurface2Surface {
private static int[] SIZES = {2, 10, 100};
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 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 (int size : SIZES) {
at = AffineTransform.getScaleInstance(size, size);
for (Shape clip : SHAPES) {
clip = at.createTransformedShape(clip);
for (Shape to : SHAPES) {
to = at.createTransformedShape(to);
// Prepare test images
BufferedImage snapshot;
VolatileImage source = getVolatileImage(gc, size);
VolatileImage target = getVolatileImage(gc, size);
int attempt = 0;
while (true) {
if (++attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
// Prepare source images
source.validate(gc);
Graphics2D g2d = source.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, size, size);
g2d.dispose();
if (source.validate(gc) != VolatileImage.IMAGE_OK) {
continue;
}
// Prepare target images
target.validate(gc);
g2d = target.createGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, size, size);
g2d.dispose();
if (target.validate(gc) != VolatileImage.IMAGE_OK) {
continue;
}
draw(clip, to, source, target);
snapshot = target.getSnapshot();
if (source.contentsLost() || target.contentsLost()) {
continue;
}
break;
}
// Prepare gold images
BufferedImage goldS = getSourceGold(gc, size);
BufferedImage goldT = getTargetGold(gc, size);
draw(clip, to, goldS, goldT);
validate(snapshot, goldT);
source.flush();
target.flush();
}
}
}
}
private static void draw(Shape clip, Shape shape, Image from, Image to) {
Graphics2D g2d = (Graphics2D) to.getGraphics();
g2d.setXORMode(Color.BLACK);
g2d.setClip(clip);
Rectangle toBounds = shape.getBounds();
g2d.drawImage(from, toBounds.x, toBounds.y, toBounds.width,
toBounds.height, null);
g2d.dispose();
}
private static BufferedImage getSourceGold(GraphicsConfiguration gc,
int size) {
final BufferedImage bi = gc.createCompatibleImage(size, size);
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, size, size);
g2d.dispose();
return bi;
}
private static BufferedImage getTargetGold(GraphicsConfiguration gc,
int size) {
BufferedImage image = gc.createCompatibleImage(size, size);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, size, size);
g2d.dispose();
return image;
}
private static VolatileImage getVolatileImage(GraphicsConfiguration gc,
int size) {
return gc.createCompatibleVolatileImage(size, size);
}
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.");
}
}
}
}
}
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2015, 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
......@@ -24,6 +24,7 @@
/*
* @test LFGarbageCollectedTest
* @bug 8046703
* @ignore 8078602
* @summary Test verifies that lambda forms are garbage collected
* @author kshefov
* @library /lib/testlibrary/jsr292 /lib/testlibrary
......
# JDBC unit tests uses TestNG
TestNG.dirs = .
/*
* 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 test.sql;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.ObjectInputStream;
import java.sql.BatchUpdateException;
import java.sql.SQLException;
import java.util.Arrays;
import static org.testng.Assert.*;
import org.testng.annotations.Test;
import util.SerializedBatchUpdateException;
import util.BaseTest;
public class BatchUpdateExceptionTests extends BaseTest {
private final int[] uc = {1, 2, 3};
private final long[] luc = {1, 2, 3};
private final String testSrcDir = System.getProperty("test.src", ".")
+ File.separatorChar;
/**
* Create BatchUpdateException and setting all objects to null
*/
@Test
public void test() {
BatchUpdateException be = new BatchUpdateException(null,
null, errorCode, (int[]) null, null);
assertTrue(be.getMessage() == null && be.getSQLState() == null
&& be.getUpdateCounts() == null && be.getCause() == null
&& be.getLargeUpdateCounts() == null
&& be.getErrorCode() == errorCode);
}
/**
* Create BatchUpdateException with no-arg constructor
*/
@Test
public void test1() {
BatchUpdateException ex = new BatchUpdateException();
assertTrue(ex.getMessage() == null
&& ex.getSQLState() == null
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& ex.getUpdateCounts() == null
&& ex.getLargeUpdateCounts() == null);
}
/**
* Create BatchUpdateException with null Throwable
*/
@Test
public void test2() {
BatchUpdateException ex = new BatchUpdateException((Throwable) null);
assertTrue(ex.getMessage() == null
&& ex.getSQLState() == null
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& ex.getUpdateCounts() == null
&& ex.getLargeUpdateCounts() == null);
}
/**
* Create BatchUpdateException with message and update counts
*/
@Test
public void test3() {
BatchUpdateException ex = new BatchUpdateException(reason, uc);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState() == null
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& Arrays.equals(ex.getUpdateCounts(), uc)
&& Arrays.equals(ex.getLargeUpdateCounts(), luc)
);
}
/**
* Create BatchUpdateException with update counts
*/
@Test
public void test4() {
BatchUpdateException ex = new BatchUpdateException(uc);
assertTrue(ex.getMessage() == null
&& ex.getSQLState() == null
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& Arrays.equals(ex.getUpdateCounts(), uc)
&& Arrays.equals(ex.getLargeUpdateCounts(), luc)
);
}
/**
* Create BatchUpdateException with Throwable and update counts
*/
@Test
public void test5() {
BatchUpdateException ex = new BatchUpdateException(uc, t);
assertTrue(ex.getMessage().equals(cause)
&& ex.getSQLState() == null
&& cause.equals(ex.getCause().toString())
&& ex.getErrorCode() == 0
&& Arrays.equals(ex.getUpdateCounts(), uc)
&& Arrays.equals(ex.getLargeUpdateCounts(), luc)
);
}
/**
* Create BatchUpdateException with message, Throwable, and update counts
*/
@Test
public void test6() {
BatchUpdateException ex = new BatchUpdateException(reason, uc, t);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState() == null
&& cause.equals(ex.getCause().toString())
&& ex.getErrorCode() == 0
&& Arrays.equals(ex.getUpdateCounts(), uc)
&& Arrays.equals(ex.getLargeUpdateCounts(), luc)
);
}
/**
* Create BatchUpdateException with message, SQLState, Throwable, and update
* counts
*/
@Test
public void test7() {
BatchUpdateException ex = new BatchUpdateException(reason, state, uc, t);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState().equals(state)
&& cause.equals(ex.getCause().toString())
&& ex.getErrorCode() == 0
&& Arrays.equals(ex.getUpdateCounts(), uc)
&& Arrays.equals(ex.getLargeUpdateCounts(), luc)
);
}
/**
* Create BatchUpdateException with message, SQLState, errorCode code
* Throwable, and update counts
*/
@Test
public void test8() {
BatchUpdateException ex = new BatchUpdateException(reason, state, errorCode,
uc, t);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState().equals(state)
&& cause.equals(ex.getCause().toString())
&& ex.getErrorCode() == errorCode
&& Arrays.equals(ex.getUpdateCounts(), uc)
&& Arrays.equals(ex.getLargeUpdateCounts(), luc)
);
}
/**
* Create BatchUpdateException with message, SQLState, errorCode code
* Throwable, and long [] update counts
*/
@Test
public void test9() {
BatchUpdateException ex = new BatchUpdateException(reason, state, errorCode,
luc, t);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState().equals(state)
&& cause.equals(ex.getCause().toString())
&& ex.getErrorCode() == errorCode
&& Arrays.equals(ex.getUpdateCounts(), uc)
&& Arrays.equals(ex.getLargeUpdateCounts(), luc)
);
}
/**
* Validate that a copy of the update counts array is made
*/
@Test
public void test10() {
int[] uc1 = {1, 2};
BatchUpdateException ex = new BatchUpdateException(uc1);
assertTrue(Arrays.equals(ex.getUpdateCounts(), uc1));
uc1[0] = 6689;
assertFalse(Arrays.equals(ex.getUpdateCounts(), uc1));
}
/**
* Validate that if null is specified for the update count, it is returned
* as null
*/
@Test
public void test11() {
BatchUpdateException ex = new BatchUpdateException((int[]) null);
assertTrue(ex.getMessage() == null && ex.getSQLState() == null
&& ex.getErrorCode() == 0 && ex.getUpdateCounts() == null
&& ex.getLargeUpdateCounts() == null);
}
/**
* Serialize a BatchUpdateException and make sure you can read it back
* properly
*/
@Test
public void test12() throws Exception {
BatchUpdateException be = new BatchUpdateException(reason, state, errorCode,
uc, t);
BatchUpdateException bue
= createSerializedException(be);
assertTrue(reason.equals(bue.getMessage())
&& bue.getSQLState().equals(state)
&& cause.equals(bue.getCause().toString())
&& bue.getErrorCode() == errorCode
&& Arrays.equals(bue.getLargeUpdateCounts(), luc)
&& Arrays.equals(bue.getUpdateCounts(), uc));
}
/**
* De-Serialize a BatchUpdateException from JDBC 4.0 and make sure you can
* read it back properly
*/
@Test
public void test13() throws Exception {
String reason1 = "This was the error msg";
String state1 = "user defined sqlState";
String cause1 = "java.lang.Throwable: throw 1";
int errorCode1 = 99999;
Throwable t = new Throwable("throw 1");
int[] uc1 = {1, 2, 21};
long[] luc1 = {1, 2, 21};
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(SerializedBatchUpdateException.DATA));
BatchUpdateException bue = (BatchUpdateException) ois.readObject();
assertTrue(reason1.equals(bue.getMessage())
&& bue.getSQLState().equals(state1)
&& bue.getErrorCode() == errorCode1
&& cause1.equals(bue.getCause().toString())
&& Arrays.equals(bue.getLargeUpdateCounts(), luc1)
&& Arrays.equals(bue.getUpdateCounts(), uc1));
}
/**
* Serialize a BatchUpdateException with an Integer.MAX_VALUE + 1 and
* validate you can read it back properly
*/
@Test
public void test14() throws Exception {
int[] uc1 = {Integer.MAX_VALUE, Integer.MAX_VALUE + 1};
long[] luc1 = {Integer.MAX_VALUE, Integer.MAX_VALUE + 1};
BatchUpdateException be = new BatchUpdateException(reason, state, errorCode,
luc1, t);
BatchUpdateException bue
= createSerializedException(be);
assertTrue(reason.equals(bue.getMessage())
&& bue.getSQLState().equals(state)
&& cause.equals(bue.getCause().toString())
&& bue.getErrorCode() == errorCode
&& Arrays.equals(bue.getLargeUpdateCounts(), luc1)
&& Arrays.equals(bue.getUpdateCounts(), uc1));
}
/**
* Validate that the ordering of the returned Exceptions is correct
* using for-each loop
*/
@Test
public void test15() {
BatchUpdateException ex = new BatchUpdateException("Exception 1", uc, t1);
BatchUpdateException ex1 = new BatchUpdateException("Exception 2", uc);
BatchUpdateException ex2 = new BatchUpdateException("Exception 3", uc, t2);
ex.setNextException(ex1);
ex.setNextException(ex2);
int num = 0;
for (Throwable e : ex) {
assertTrue(msgs[num++].equals(e.getMessage()));
}
}
/**
* Validate that the ordering of the returned Exceptions is correct
* using traditional while loop
*/
@Test
public void test16() {
BatchUpdateException ex = new BatchUpdateException("Exception 1", uc, t1);
BatchUpdateException ex1 = new BatchUpdateException("Exception 2", uc);
BatchUpdateException ex2 = new BatchUpdateException("Exception 3", uc, t2);
ex.setNextException(ex1);
ex.setNextException(ex2);
SQLException sqe = ex;
int num = 0;
while (sqe != null) {
assertTrue(msgs[num++].equals(sqe.getMessage()));
Throwable c = sqe.getCause();
while (c != null) {
assertTrue(msgs[num++].equals(c.getMessage()));
c = c.getCause();
}
sqe = sqe.getNextException();
}
}
}
/*
* 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 test.sql;
import java.sql.DataTruncation;
import java.sql.SQLException;
import static org.testng.Assert.*;
import org.testng.annotations.Test;
import util.BaseTest;
public class DataTruncationTests extends BaseTest {
private final String READ_TRUNCATION = "01004";
private final String WRITE_TRUNCATION = "22001";
private final String dtReason = "Data truncation";
private final int dterrorCode = 0;
private final String[] dtmsgs = {dtReason, "cause 1", dtReason,
dtReason, "cause 2"};
private boolean onRead = false;
private final boolean parameter = false;
private final int index = 21;
private final int dataSize = 25;
private final int transferSize = 10;
/**
* Create DataTruncation object indicating a truncation on read
*/
@Test
public void test() {
onRead = true;
DataTruncation e = new DataTruncation(index, parameter, onRead,
dataSize, transferSize);
assertTrue(e.getMessage().equals(dtReason)
&& e.getSQLState().equals(READ_TRUNCATION)
&& e.getCause() == null
&& e.getErrorCode() == dterrorCode
&& e.getParameter() == parameter
&& e.getRead() == onRead
&& e.getDataSize() == dataSize
&& e.getTransferSize() == transferSize
&& e.getIndex() == index);
}
/**
* Create DataTruncation object indicating a truncation on write
*/
@Test
public void test1() {
onRead = false;
DataTruncation e = new DataTruncation(index, parameter, onRead,
dataSize, transferSize);
assertTrue(e.getMessage().equals(dtReason)
&& e.getSQLState().equals(WRITE_TRUNCATION)
&& e.getCause() == null
&& e.getErrorCode() == dterrorCode
&& e.getParameter() == parameter
&& e.getRead() == onRead
&& e.getDataSize() == dataSize
&& e.getTransferSize() == transferSize
&& e.getIndex() == index);
}
/**
* Create DataTruncation object indicating a truncation on read with a
* Throwable
*/
@Test
public void test2() {
onRead = true;
DataTruncation e = new DataTruncation(index, parameter, onRead,
dataSize, transferSize, t);
assertTrue(e.getMessage().equals(dtReason)
&& e.getSQLState().equals(READ_TRUNCATION)
&& cause.equals(e.getCause().toString())
&& e.getErrorCode() == dterrorCode
&& e.getParameter() == parameter
&& e.getRead() == onRead
&& e.getDataSize() == dataSize
&& e.getTransferSize() == transferSize
&& e.getIndex() == index);
}
/**
* Create DataTruncation object indicating a truncation on read with null
* specified for the Throwable
*/
@Test
public void test3() {
onRead = true;;
DataTruncation e = new DataTruncation(index, parameter, onRead,
dataSize, transferSize, null);
assertTrue(e.getMessage().equals(dtReason)
&& e.getSQLState().equals(READ_TRUNCATION)
&& e.getCause() == null
&& e.getErrorCode() == dterrorCode
&& e.getParameter() == parameter
&& e.getRead() == onRead
&& e.getDataSize() == dataSize
&& e.getTransferSize() == transferSize
&& e.getIndex() == index);
}
/**
* Create DataTruncation object indicating a truncation on read and you can
* pass a -1 for the index
*/
@Test
public void test4() {
onRead = true;
int negIndex = -1;
DataTruncation e = new DataTruncation(negIndex, parameter, onRead,
dataSize, transferSize);
assertTrue(e.getMessage().equals(dtReason)
&& e.getSQLState().equals(READ_TRUNCATION)
&& e.getCause() == null
&& e.getErrorCode() == dterrorCode
&& e.getParameter() == parameter
&& e.getRead() == onRead
&& e.getDataSize() == dataSize
&& e.getTransferSize() == transferSize
&& e.getIndex() == negIndex);
}
/**
* Serialize a DataTruncation and make sure you can read it back properly
*/
@Test
public void test5() throws Exception {
DataTruncation e = new DataTruncation(index, parameter, onRead,
dataSize, transferSize);
DataTruncation ex1 = createSerializedException(e);
assertTrue(e.getMessage().equals(dtReason)
&& e.getSQLState().equals(READ_TRUNCATION)
&& e.getCause() == null
&& e.getErrorCode() == dterrorCode
&& e.getParameter() == parameter
&& e.getRead() == onRead
&& e.getDataSize() == dataSize
&& e.getTransferSize() == transferSize
&& e.getIndex() == index);
}
/**
* Validate that the ordering of the returned Exceptions is correct using
* for-each loop
*/
@Test
public void test11() {
DataTruncation ex = new DataTruncation(index, parameter, onRead,
dataSize, transferSize, t1);
DataTruncation ex1 = new DataTruncation(index, parameter, onRead,
dataSize, transferSize);
DataTruncation ex2 = new DataTruncation(index, parameter, onRead,
dataSize, transferSize, t2);
ex.setNextException(ex1);
ex.setNextException(ex2);
int num = 0;
for (Throwable e : ex) {
assertTrue(dtmsgs[num++].equals(e.getMessage()));
}
}
/**
* Validate that the ordering of the returned Exceptions is correct using
* traditional while loop
*/
@Test
public void test12() {
DataTruncation ex = new DataTruncation(index, parameter, onRead,
dataSize, transferSize, t1);
DataTruncation ex1 = new DataTruncation(index, parameter, onRead,
dataSize, transferSize);
DataTruncation ex2 = new DataTruncation(index, parameter, onRead,
dataSize, transferSize, t2);
ex.setNextException(ex1);
ex.setNextException(ex2);
int num = 0;
SQLException sqe = ex;
while (sqe != null) {
assertTrue(dtmsgs[num++].equals(sqe.getMessage()));
Throwable c = sqe.getCause();
while (c != null) {
assertTrue(dtmsgs[num++].equals(c.getMessage()));
c = c.getCause();
}
sqe = sqe.getNextException();
}
}
}
/*
* 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 test.sql;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import static org.testng.Assert.*;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import util.BaseTest;
public class DateTests extends BaseTest {
/*
* Validate an IllegalArgumentException is thrown for an invalid Date string
*/
@Test(dataProvider = "invalidDateValues",
expectedExceptions = IllegalArgumentException.class)
public void test(String d) throws Exception {
Date.valueOf(d);
}
/*
* Test that a date created from a date string is equal to the value
* returned from toString()
*/
@Test(dataProvider = "validDateValues")
public void test00(String d, String expectedD) {
Date d1 = Date.valueOf(d);
Date d2 = Date.valueOf(expectedD);
assertTrue(d1.equals(d2) && d2.equals(d1)
&& d1.toString().equals(expectedD), "Error d1 != d2");
}
/*
* Validate that a Date.after() returns false when same date is compared
*/
@Test
public void test01() {
Date d = Date.valueOf("1961-08-30");
assertFalse(d.after(d), "Error d.after(d) = true");
}
/*
* Validate that a Date.after() returns true when later date is compared to
* earlier date
*/
@Test
public void test2() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(System.currentTimeMillis());
assertTrue(d2.after(d), "Error d2.after(d) = false");
}
/*
* Validate that a Date.after() returns false when earlier date is compared
* to later date
*/
@Test
public void test3() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertFalse(d.after(d2), "Error d.after(d2) = true");
}
/*
* Validate that a Date.after() returns false when date compared to another
* date created from the original date
*/
@Test
public void test4() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertFalse(d.after(d2), "Error d.after(d2) = true");
assertFalse(d2.after(d), "Error d2.after(d) = true");
}
/*
* Validate that a Date.before() returns false when same date is compared
*/
@Test
public void test5() {
Date d = Date.valueOf("1961-08-30");
assertFalse(d.before(d), "Error d.before(d) = true");
}
/*
* Validate that a Date.before() returns true when earlier date is compared
* to later date
*/
@Test
public void test6() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(System.currentTimeMillis());
assertTrue(d.before(d2), "Error d.before(d2) = false");
}
/*
* Validate that a Date.before() returns false when later date is compared
* to earlier date
*/
@Test
public void test7() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertFalse(d2.before(d), "Error d2.before(d) = true");
}
/*
* Validate that a Date.before() returns false when date compared to another
* date created from the original date
*/
@Test
public void test8() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertFalse(d.before(d2), "Error d.before(d2) = true");
assertFalse(d2.before(d), "Error d2.before(d) = true");
}
/*
* Validate that a Date.compareTo returns 0 when both Date objects are the
* same
*/
@Test
public void test9() {
Date d = Date.valueOf("1961-08-30");
assertTrue(d.compareTo(d) == 0, "Error d.compareTo(d) !=0");
}
/*
* Validate that a Date.compareTo returns 0 when both Date objects represent
* the same date
*/
@Test
public void test10() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertTrue(d.compareTo(d2) == 0, "Error d.compareTo(d2) !=0");
}
/*
* Validate that a Date.compareTo returns -1 when comparing a date to a
* later date
*/
@Test
public void test11() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(System.currentTimeMillis());
assertTrue(d.compareTo(d2) == -1, "Error d.compareTo(d2) != -1");
}
/*
* Validate that a Date.compareTo returns 1 when comparing a date to an
* earlier date
*/
@Test
public void test12() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(System.currentTimeMillis());
assertTrue(d2.compareTo(d) == 1, "Error d.compareTo(d2) != 1");
}
/*
* Validate that a Date made from a LocalDate are equal
*/
@Test
public void test13() {
Date d = Date.valueOf("1961-08-30");
LocalDate ldt = d.toLocalDate();
Date d2 = Date.valueOf(ldt);
assertTrue(d.equals(d2), "Error d != d2");
}
/*
* Validate that a Date LocalDate value, made from a LocalDate are equal
*/
@Test
public void test14() {
LocalDate ldt = LocalDate.now();
Date d = Date.valueOf(ldt);
assertTrue(ldt.equals(d.toLocalDate()),
"Error LocalDate values are not equal");
}
/*
* Validate an NPE occurs when a null LocalDate is passed to valueOf
*/
@Test(expectedExceptions = NullPointerException.class)
public void test15() throws Exception {
LocalDate ld = null;
Date.valueOf(ld);
}
/*
* Validate an UnsupportedOperationException occurs when toInstant() is
* called
*/
@Test(expectedExceptions = UnsupportedOperationException.class)
public void test16() throws Exception {
Date d = Date.valueOf("1961-08-30");
Instant instant = d.toInstant();
}
/*
* Validate that two Date objects are equal when one is created from the
* toString() of the other
*/
@Test
public void test17() {
Date d = Date.valueOf("1961-08-30");
Date d2 = Date.valueOf(d.toString());
assertTrue(d.equals(d2) && d2.equals(d), "Error d != d2");
}
/*
* Validate that two Date values one created using valueOf and another via a
* constructor are equal
*/
@Test
public void test18() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(61, 7, 30);
assertTrue(d.equals(d2), "Error d != d2");
}
/*
* Validate that two Date values one created using getTime() of the other
* are equal
*/
@Test
public void test19() {
Date d = Date.valueOf("1961-08-30");
Date d2 = new Date(d.getTime());
assertTrue(d.equals(d2), "Error d != d2");
}
/*
* Validate that a Date value is equal to itself
*/
@Test
public void test20() {
Date d = Date.valueOf("1961-08-30");
assertTrue(d.equals(d), "Error d != d");
}
/*
* Validate an IllegalArgumentException is thrown for calling getHours
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test21() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.getHours();
}
/*
* Validate an IllegalArgumentException is thrown for calling getMinutes
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test22() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.getMinutes();
}
/*
* Validate an IllegalArgumentException is thrown for calling getSeconds
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test23() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.getSeconds();
}
/*
* Validate an IllegalArgumentException is thrown for calling setHours
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test24() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.setHours(8);
}
/*
* Validate an IllegalArgumentException is thrown for calling setMinutes
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test25() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.setMinutes(0);
}
/*
* Validate an IllegalArgumentException is thrown for calling setSeconds
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void test26() throws Exception {
Date d = Date.valueOf("1961-08-30");
d.setSeconds(0);
}
/*
* DataProvider used to provide Date which are not valid and are used
* to validate that an IllegalArgumentException will be thrown from the
* valueOf method
*/
@DataProvider(name = "invalidDateValues")
private Object[][] invalidDateValues() {
return new Object[][]{
{"20009-11-01"},
{"09-11-01"},
{"-11-01"},
{"2009-111-01"},
{"2009--01"},
{"2009-13-01"},
{"2009-11-011"},
{"2009-11-"},
{"2009-11-00"},
{"2009-11-33"},
{"--"},
{""},
{null},
{"-"},
{"2009"},
{"2009-01"},
{"---"},
{"2009-13--1"},
{"1900-1-0"},
{"2009-01-01 10:50:01"},
{"1996-12-10 12:26:19.1"},
{"10:50:01"}
};
}
/*
* DataProvider used to provide Dates which are valid and are used
* to validate that an IllegalArgumentException will not be thrown from the
* valueOf method and the corect value from toString() is returned
*/
@DataProvider(name = "validDateValues")
private Object[][] validDateValues() {
return new Object[][]{
{"2009-08-30", "2009-08-30"},
{"2009-01-8", "2009-01-08"},
{"2009-1-01", "2009-01-01"},
{"2009-1-1", "2009-01-01"}
};
}
}
/*
* 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 test.sql;
import java.security.AccessControlException;
import java.security.Policy;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import util.BaseTest;
import util.StubDriver;
import util.TestPolicy;
public class DriverManagerPermissionsTests extends BaseTest {
private static Policy policy;
private static SecurityManager sm;
/*
* Install a SecurityManager along with a base Policy to allow testNG to run
*/
@BeforeClass
public static void setUpClass() throws Exception {
setPolicy(new TestPolicy());
System.setSecurityManager(new SecurityManager());
}
/*
* Install the original Policy and SecurityManager
*/
@AfterClass
public static void tearDownClass() throws Exception {
System.setSecurityManager(sm);
setPolicy(policy);
}
/*
* Save off the original Policy and SecurityManager
*/
public DriverManagerPermissionsTests() {
policy = Policy.getPolicy();
sm = System.getSecurityManager();
}
/*
* Validate that AccessControlException is thrown if SQLPermission("setLog")
* has not been granted
*/
@Test(expectedExceptions = AccessControlException.class)
public void test() {
setPolicy(new TestPolicy());
DriverManager.setLogStream(null);
}
/*
* Validate that setLogStream succeeds if SQLPermission("setLog") has been
* granted
*/
@Test
public void test1() {
Policy.setPolicy(new TestPolicy("setLog"));
DriverManager.setLogStream(null);
}
/*
* Validate that setLogStream succeeds if AllPermissions has been granted
*/
@Test
public void test2() {
setPolicy(new TestPolicy("all"));
DriverManager.setLogStream(null);
}
/*
* Validate that AccessControlException is thrown if SQLPermission("setLog")
* has not been granted
*/
@Test(expectedExceptions = AccessControlException.class)
public void test4() {
setPolicy(new TestPolicy());
DriverManager.setLogWriter(null);
}
/*
* Validate that setLogWriter succeeds if SQLPermission("setLog") has been
* granted
*/
@Test
public void test5() {
setPolicy(new TestPolicy("setLog"));
DriverManager.setLogWriter(null);
}
/*
* Validate that setLogWriter succeeds if AllPermissions has been granted
*/
@Test
public void test6() {
setPolicy(new TestPolicy("all"));
DriverManager.setLogWriter(null);
}
/*
* Validate that AccessControlException is thrown if
* SQLPermission("deregisterDriver") has not been granted
*/
@Test(expectedExceptions = AccessControlException.class)
public void test7() throws SQLException {
setPolicy(new TestPolicy());
DriverManager.deregisterDriver(new StubDriver());
}
/*
* Validate that deregisterDriver succeeds if
* SQLPermission("deregisterDriver") has been granted
*/
@Test
public void test8() throws SQLException {
setPolicy(new TestPolicy("deregisterDriver"));
DriverManager.deregisterDriver(new StubDriver());
}
/*
* Validate that deregisterDriver succeeds if AllPermissions has been
* granted
*/
@Test
public void test9() throws SQLException {
setPolicy(new TestPolicy("all"));
DriverManager.deregisterDriver(new StubDriver());
}
}
/*
* 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 test.sql;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import static org.testng.Assert.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import util.StubDriver;
public class DriverManagerTests {
private final String StubDriverURL = "jdbc:tennis:boy";
private final String StubDriverDAURL = "jdbc:luckydog:tennis";
private final String InvalidURL = "jdbc:cardio:tennis";
private String[] results = {"output", "more output", "and more", "the end"};
private String noOutput = "should not find this";
public DriverManagerTests() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@BeforeMethod
public void setUpMethod() throws Exception {
removeAllDrivers();
}
@AfterMethod
public void tearDownMethod() throws Exception {
}
/**
* Utility method to remove all registered drivers
*/
private static void removeAllDrivers() {
java.util.Enumeration e = DriverManager.getDrivers();
while (e.hasMoreElements()) {
try {
DriverManager.deregisterDriver((Driver) (e.nextElement()));
} catch (SQLException ex) {
System.out.print(ex.getMessage());
}
}
}
/**
* Utility method to see if a driver is registered
*/
private boolean isDriverRegistered(Driver d) {
boolean foundDriver = false;
java.util.Enumeration e = DriverManager.getDrivers();
while (e.hasMoreElements()) {
if (d == (Driver) e.nextElement()) {
foundDriver = true;
break;
}
}
return foundDriver;
}
/**
* Validate that values set using setLoginTimeout will be returned by
* getLoginTimeout
*/
@Test
public void test() {
int[] vals = {-1, 0, 5};
for (int val : vals) {
DriverManager.setLoginTimeout(val);
assertEquals(val, DriverManager.getLoginTimeout());
}
}
/**
* Validate that NullPointerException is thrown when null is passed to
* registerDriver
*/
@Test(expectedExceptions = NullPointerException.class)
public void test1() throws Exception {
Driver d = null;
DriverManager.registerDriver(d);
}
/**
* Validate that NullPointerException is thrown when null is passed to
* registerDriver
*/
@Test(expectedExceptions = NullPointerException.class)
public void test2() throws Exception {
Driver d = null;
DriverManager.registerDriver(d, null);
}
/**
* Validate that a null value allows for deRegisterDriver to return
*/
@Test
public void test3() throws Exception {
DriverManager.deregisterDriver(null);
}
/**
* Validate that SQLException is thrown when there is no Driver to service
* the URL
*/
@Test(expectedExceptions = SQLException.class)
public void test4() throws Exception {
DriverManager.getConnection(InvalidURL);
}
/**
* Validate that SQLException is thrown when there is no Driver to service
* the URL
*/
@Test(expectedExceptions = SQLException.class)
public void test5() throws Exception {
DriverManager.getConnection(InvalidURL, new Properties());
}
/**
* Validate that SQLException is thrown when there is no Driver to service
* the URL
*/
@Test(expectedExceptions = SQLException.class)
public void test6() throws Exception {
DriverManager.getConnection(InvalidURL, "LuckyDog", "tennisanyone");
}
/**
* Validate that SQLException is thrown when null is passed for the URL
*/
@Test(expectedExceptions = SQLException.class)
public void test7() throws Exception {
DriverManager.getConnection(null);
}
/**
* Validate that SQLException is thrown when null is passed for the URL
*/
@Test(expectedExceptions = SQLException.class)
public void test8() throws Exception {
DriverManager.getConnection(null, new Properties());
}
/**
* Validate that SQLException is thrown when null is passed for the URL
*/
@Test(expectedExceptions = SQLException.class)
public void test9() throws Exception {
DriverManager.getConnection(null, "LuckyDog", "tennisanyone");
}
/**
* Validate that SQLException is thrown when there is no Driver to service
* the URL
*/
@Test(expectedExceptions = SQLException.class)
public void test10() throws Exception {
DriverManager.getDriver(InvalidURL);
}
/**
* Validate that SQLException is thrown when null is passed for the URL
*/
@Test(expectedExceptions = SQLException.class)
public void test11() throws Exception {
DriverManager.getDriver(null);
}
/**
* Validate that a non-null Driver is returned by getDriver when a valid URL
* is specified
*/
@Test
public void test12() throws Exception {
DriverManager.registerDriver(new StubDriver());
assertTrue(DriverManager.getDriver(StubDriverURL) != null);
}
/**
* Validate that SQLException is thrown when the URL is not valid for any of
* the registered drivers
*/
@Test(expectedExceptions = SQLException.class)
public void test13() throws Exception {
DriverManager.registerDriver(new StubDriver());
DriverManager.getDriver(InvalidURL);
}
/**
* Validate that a Connection object is returned when a valid URL is
* specified to getConnection
*
*/
@Test
public void test14() throws Exception {
DriverManager.registerDriver(new StubDriver());
assertTrue(
DriverManager.getConnection(StubDriverURL) != null);
assertTrue(DriverManager.getConnection(StubDriverURL,
"LuckyDog", "tennisanyone") != null);
Properties props = new Properties();
props.put("user", "LuckyDog");
props.put("password", "tennisanyone");
assertTrue(
DriverManager.getConnection(StubDriverURL,
props) != null);
}
/**
* Register a driver and make sure you find it via its URL. Deregister the
* driver and validate it is not longer registered
*
* @throws Exception
*/
@Test()
public void test15() throws Exception {
DriverManager.registerDriver(new StubDriver());
Driver d = DriverManager.getDriver(StubDriverURL);
assertTrue(d != null);
assertTrue(isDriverRegistered(d));
DriverManager.deregisterDriver(d);
assertFalse(isDriverRegistered(d));
}
/**
* Validate that DriverAction.release is called when a driver is registered
* via registerDriver(Driver, DriverAction)
*
* @throws Exception
*/
@Test
public void test16() throws Exception {
File file = new File(util.StubDriverDA.DriverActionCalled);
file.delete();
assertFalse(file.exists());
Driver d = null;
Class.forName("util.StubDriverDA");
d = DriverManager.getDriver(StubDriverDAURL);
DriverManager.deregisterDriver(d);
assertFalse(isDriverRegistered(d), "Driver is registered");
assertTrue(file.exists());
}
/**
* Create a PrintStream and use to send output via DriverManager.println
* Validate that if you disable the stream, the output sent is not present
*/
@Test
public void tests17() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
DriverManager.setLogStream(ps);
assertTrue(DriverManager.getLogStream() == ps);
DriverManager.println(results[0]);
DriverManager.setLogStream((PrintStream) null);
assertTrue(DriverManager.getLogStream() == null);
DriverManager.println(noOutput);
DriverManager.setLogStream(ps);
DriverManager.println(results[1]);
DriverManager.println(results[2]);
DriverManager.println(results[3]);
DriverManager.setLogStream((PrintStream) null);
DriverManager.println(noOutput);
/*
* Check we do not get the output when the stream is disabled
*/
InputStreamReader is
= new InputStreamReader(new ByteArrayInputStream(os.toByteArray()));
BufferedReader reader = new BufferedReader(is);
for (String result : results) {
assertTrue(result.equals(reader.readLine()));
}
}
/**
* Create a PrintWriter and use to to send output via DriverManager.println
* Validate that if you disable the writer, the output sent is not present
*/
@Test
public void tests18() throws Exception {
CharArrayWriter cw = new CharArrayWriter();
PrintWriter pw = new PrintWriter(cw);
DriverManager.setLogWriter(pw);
assertTrue(DriverManager.getLogWriter() == pw);
DriverManager.println(results[0]);
DriverManager.setLogWriter(null);
assertTrue(DriverManager.getLogWriter() == null);
DriverManager.println(noOutput);
DriverManager.setLogWriter(pw);
DriverManager.println(results[1]);
DriverManager.println(results[2]);
DriverManager.println(results[3]);
DriverManager.setLogWriter(null);
DriverManager.println(noOutput);
/*
* Check we do not get the output when the stream is disabled
*/
BufferedReader reader
= new BufferedReader(new CharArrayReader(cw.toCharArray()));
for (String result : results) {
assertTrue(result.equals(reader.readLine()));
}
}
}
/*
* 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 test.sql;
import java.sql.ClientInfoStatus;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.util.HashMap;
import static org.testng.Assert.*;
import org.testng.annotations.Test;
import util.BaseTest;
public class SQLClientInfoExceptionTests extends BaseTest {
private final HashMap<String, ClientInfoStatus> map = new HashMap<>();
public SQLClientInfoExceptionTests() {
map.put("1", ClientInfoStatus.REASON_UNKNOWN_PROPERTY);
map.put("21", ClientInfoStatus.REASON_UNKNOWN_PROPERTY);
}
/**
* Create SQLClientInfoException and setting all objects to null
*/
@Test
public void test() {
SQLClientInfoException e = new SQLClientInfoException(null);
assertTrue(e.getMessage() == null && e.getSQLState() == null
&& e.getCause() == null && e.getErrorCode() == 0
&& e.getFailedProperties() == null);
}
/**
* Create SQLClientInfoException with no-arg constructor
*/
@Test
public void test1() {
SQLClientInfoException ex = new SQLClientInfoException();
assertTrue(ex.getMessage() == null
&& ex.getSQLState() == null
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& ex.getFailedProperties() == null);
}
/**
* Create SQLClientInfoException with null Throwable
*/
@Test
public void test2() {
SQLClientInfoException ex = new SQLClientInfoException(map, null);
assertTrue(ex.getMessage() == null
&& ex.getSQLState() == null
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& ex.getFailedProperties().equals(map));
}
/**
* Create SQLClientInfoException with message
*/
@Test
public void test3() {
SQLClientInfoException ex = new SQLClientInfoException(reason, map);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState() == null
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& ex.getFailedProperties().equals(map));
}
/**
* Create SQLClientInfoException with null Throwable
*/
@Test
public void test4() {
SQLClientInfoException ex = new SQLClientInfoException(reason, map, null);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState() == null
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& ex.getFailedProperties().equals(map));
}
/**
* Create SQLClientInfoException with message, and SQLState
*/
@Test
public void test5() {
SQLClientInfoException ex = new SQLClientInfoException(reason, state,
map);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState().equals(state)
&& ex.getCause() == null
&& ex.getErrorCode() == 0
&& ex.getFailedProperties().equals(map));
}
/**
* Create SQLClientInfoException with message, and SQLState
*/
@Test
public void test6() {
SQLClientInfoException ex = new SQLClientInfoException(reason, state,
map, t);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState().equals(state)
&& cause.equals(ex.getCause().toString())
&& ex.getErrorCode() == 0
&& ex.getFailedProperties().equals(map));
}
/**
* Create SQLClientInfoException with message, SQLState, errorCode, and
* Throwable
*/
@Test
public void test7() {
SQLClientInfoException ex = new SQLClientInfoException(reason, state,
errorCode, map);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState().equals(state)
&& ex.getCause() == null
&& ex.getErrorCode() == errorCode
&& ex.getFailedProperties().equals(map));
}
/**
* Create SQLClientInfoException with message, SQLState, and error code
*/
@Test
public void test8() {
SQLClientInfoException ex = new SQLClientInfoException(reason, state,
errorCode, map, t);
assertTrue(ex.getMessage().equals(reason)
&& ex.getSQLState().equals(state)
&& cause.equals(ex.getCause().toString())
&& ex.getErrorCode() == errorCode
&& ex.getFailedProperties().equals(map));
}
/**
* Serialize a SQLClientInfoException and make sure you can read it back
* properly
*/
@Test
public void test10() throws Exception {
SQLClientInfoException e = new SQLClientInfoException(reason, state,
errorCode, map, t);
SQLClientInfoException ex1 =
createSerializedException(e);
assertTrue(reason.equals(ex1.getMessage())
&& ex1.getSQLState().equals(state)
&& cause.equals(ex1.getCause().toString())
&& ex1.getErrorCode() == errorCode
&& ex1.getFailedProperties().equals(map));
}
/**
* Validate that the ordering of the returned Exceptions is correct using
* for-each loop
*/
@Test
public void test11() {
SQLClientInfoException ex = new SQLClientInfoException("Exception 1",
map, t1);
SQLClientInfoException ex1 = new SQLClientInfoException("Exception 2",
map);
SQLClientInfoException ex2 = new SQLClientInfoException("Exception 3",
map, t2);
ex.setNextException(ex1);
ex.setNextException(ex2);
int num = 0;
for (Throwable e : ex) {
assertTrue(msgs[num++].equals(e.getMessage()));
}
}
/**
* Validate that the ordering of the returned Exceptions is correct using
* traditional while loop
*/
@Test
public void test12() {
SQLClientInfoException ex = new SQLClientInfoException("Exception 1",
map, t1);
SQLClientInfoException ex1 = new SQLClientInfoException("Exception 2",
map);
SQLClientInfoException ex2 = new SQLClientInfoException("Exception 3",
map, t2);
ex.setNextException(ex1);
ex.setNextException(ex2);
int num = 0;
SQLException sqe = ex;
while (sqe != null) {
assertTrue(msgs[num++].equals(sqe.getMessage()));
Throwable c = sqe.getCause();
while (c != null) {
assertTrue(msgs[num++].equals(c.getMessage()));
c = c.getCause();
}
sqe = sqe.getNextException();
}
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
/*
* 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 util;
import java.sql.DriverAction;
/**
* Simple implementation of DriverAction which calls back into the Driver when
* release is called.
*/
class DriverActionImpl implements DriverAction {
public DriverActionImpl(StubDriverDA d) {
driver = d;
}
private final StubDriverDA driver;
@Override
public void deregister() {
driver.release();
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
# JDBC unit tests uses TestNG
TestNG.dirs= .
othervm.dirs= .
lib.dirs = /java/sql/testng
modules = java.sql.rowset/com.sun.rowset \
java.sql.rowset/com.sun.rowset.internal \
java.sql.rowset/com.sun.rowset.providers
此差异已折叠。
/*
* Copyright (c) 2015, 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 test.rowset.cachedrowset;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
public class CachedRowSetTests extends CommonCachedRowSetTests {
@Override
protected CachedRowSet newInstance() throws SQLException {
return rsf.createCachedRowSet();
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册