This commit is contained in:
J. Duke 2017-07-05 18:51:33 +02:00
commit 345a01c826
948 changed files with 56498 additions and 19116 deletions

View File

@ -207,3 +207,4 @@ fd1a5574cf68af24bfd52decc37ac6361afb278a jdk8-b78
466685ba01bfb7bc1e1ac61490fd8c0f3cc18763 jdk8-b83
01f631f89fa392b4e484d0812c40ea8f9d2353aa jdk8-b84
7fc358f5943676b82f1dccd3152b1ac07d92e38b jdk8-b85
df9b5240f0a76c91cfe1a5b39da4d08df56e05be jdk8-b86

View File

@ -333,3 +333,4 @@ a947f40fb536e5b9e0aa210cf26abb430f80887a hs25-b26
42fe530cd478744a4d12a0cbf803f0fc804bab1a jdk8-b85
09b0d3e9ba6cdf7da07d4010d2d1df14596f6864 hs25-b27
6d88a566d369f6a1f86912cad7d0912686b2fda1 hs25-b28
86db4847f195c0ecceea646431f1ff22d56282e8 jdk8-b86

View File

@ -207,3 +207,4 @@ c0f8022eba536dcdc8aae659005b33f3982b9368 jdk8-b81
ac519af51769e92c51b597a730974e8607357709 jdk8-b83
7b4721e4edb4e1c65e9c839a70d7cc67f81c7632 jdk8-b84
296676d534c52888c36e305a2bf7f345c4ca70f8 jdk8-b85
7989cd0cc3a9149864589438ee2c949015d8aa9a jdk8-b86

View File

@ -48,7 +48,6 @@ FILES_c = \
Proxy.c \
RandomAccessFile.c \
RandomAccessFile_md.c \
ResourceBundle.c \
Runtime.c \
SecurityManager.c \
Shutdown.c \

View File

@ -312,6 +312,12 @@ PROPS = content-types.properties
#
CAL_PROPS = calendars.properties
#
# Rule to copy Hijrah-umalqura calendar properties file.
#
HIJRAH_UMALQURA_PROPS = hijrah-config-umalqura.properties
#
# Rule to copy tzmappings file on Windows
#
@ -324,7 +330,7 @@ $(TZMAP): $(TZMAPFILE)
$(call chmod-file, 444)
endif
build: $(LIBDIR)/$(PROPS) $(LIBDIR)/$(CAL_PROPS) $(TZMAP)
build: $(LIBDIR)/$(PROPS) $(LIBDIR)/$(CAL_PROPS) $(LIBDIR)/$(HIJRAH_UMALQURA_PROPS) $(TZMAP)
$(LIBDIR)/$(PROPS): $(PLATFORM_SRC)/lib/$(PROPS)
$(install-file)
@ -332,6 +338,9 @@ $(LIBDIR)/$(PROPS): $(PLATFORM_SRC)/lib/$(PROPS)
$(LIBDIR)/$(CAL_PROPS): $(SHARE_SRC)/lib/$(CAL_PROPS)
$(install-file)
$(LIBDIR)/$(HIJRAH_UMALQURA_PROPS): $(SHARE_SRC)/lib/$(HIJRAH_UMALQURA_PROPS)
$(install-file)
clean::
$(RM) -r $(LIBDIR)/$(PROPS) $(TZMAP)

View File

@ -134,7 +134,6 @@ SUNWprivate_1.1 {
Java_java_lang_ClassLoader_00024NativeLibrary_load;
Java_java_lang_ClassLoader_00024NativeLibrary_unload;
Java_java_lang_ClassLoader_00024NativeLibrary_findBuiltinLib;
Java_java_lang_ClassLoader_getCaller;
Java_java_lang_ClassLoader_registerNatives;
Java_java_lang_Compiler_registerNatives;
Java_java_lang_Double_longBitsToDouble;
@ -217,7 +216,7 @@ SUNWprivate_1.1 {
Java_java_lang_Throwable_fillInStackTrace;
Java_java_lang_Throwable_getStackTraceDepth;
Java_java_lang_Throwable_getStackTraceElement;
Java_java_lang_UNIXProcess_initIDs;
Java_java_lang_UNIXProcess_init;
Java_java_lang_UNIXProcess_waitForProcessExit;
Java_java_lang_UNIXProcess_forkAndExec;
Java_java_lang_UNIXProcess_destroyProcess;
@ -233,7 +232,6 @@ SUNWprivate_1.1 {
Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2Ljava_security_AccessControlContext_2;
Java_java_security_AccessController_getStackAccessControlContext;
Java_java_security_AccessController_getInheritedAccessControlContext;
Java_java_util_ResourceBundle_getClassContext;
Java_java_util_TimeZone_getSystemTimeZoneID;
Java_java_util_TimeZone_getSystemGMTOffsetID;
Java_java_util_concurrent_atomic_AtomicLong_VMSupportsCS8;

View File

@ -73,7 +73,6 @@ text: .text%writeBytes;
# Test Sleep
# Test IntToString
# Test LoadToolkit
text: .text%Java_java_util_ResourceBundle_getClassContext;
text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedAction_2Ljava_security_AccessControlContext_2;
text: .text%JNU_GetEnv;
text: .text%Java_java_io_UnixFileSystem_checkAccess;

View File

@ -78,7 +78,6 @@ text: .text%writeBytes;
# Test Sleep
# Test IntToString
# Test LoadToolkit
text: .text%Java_java_util_ResourceBundle_getClassContext;
text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedAction_2Ljava_security_AccessControlContext_2;
text: .text%JNU_GetEnv;
text: .text%Java_java_io_UnixFileSystem_checkAccess;

View File

@ -74,7 +74,6 @@ text: .text%writeBytes;
# Test Sleep
# Test IntToString
# Test LoadToolkit
text: .text%Java_java_util_ResourceBundle_getClassContext;
text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedAction_2Ljava_security_AccessControlContext_2;
text: .text%JNU_GetEnv;
text: .text%Java_java_io_UnixFileSystem_checkAccess;

View File

@ -1,5 +1,5 @@
#
# Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 1996, 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
@ -105,5 +105,7 @@ FILES_java = \
sun/text/resources/CollationData.java \
\
sun/text/resources/FormatData.java \
sun/text/resources/JavaTimeSupplementary.java \
sun/text/resources/en/FormatData_en.java \
sun/text/resources/en/FormatData_en_US.java
sun/text/resources/en/FormatData_en_US.java \
sun/text/resources/en/JavaTimeSupplementary_en.java \

View File

@ -1,5 +1,5 @@
#
# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2005, 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
@ -26,6 +26,7 @@
FILES_java = \
sun/util/resources/LocaleData.java \
sun/util/resources/OpenListResourceBundle.java \
sun/util/resources/ParallelListResourceBundle.java \
sun/util/resources/LocaleNamesBundle.java \
sun/util/resources/TimeZoneNamesBundle.java \
sun/util/resources/TimeZoneNames.java \

View File

@ -27,8 +27,9 @@ BUILDDIR = ../..
PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk
SUBDIRS += lcms
ifdef OPENJDK
SUBDIRS += lcms
ICCPROFILE_SRC_DIR = $(SHARE_SRC)/lib/cmm/lcms
else # !OPENJDK
SUBDIRS += kcms

View File

@ -57,7 +57,7 @@ include $(BUILDDIR)/common/Library.gmk
SERVICEDIR = $(CLASSBINDIR)/META-INF/services
FILES_copy = \
$(SERVICEDIR)/sun.java2d.cmm.PCMM
$(SERVICEDIR)/sun.java2d.cmm.CMMServiceProvider
build: copy-files

View File

@ -58,7 +58,7 @@ include $(BUILDDIR)/common/Library.gmk
SERVICEDIR = $(CLASSBINDIR)/META-INF/services
FILES_copy = \
$(SERVICEDIR)/sun.java2d.cmm.PCMM
$(SERVICEDIR)/sun.java2d.cmm.CMMServiceProvider
build: copy-files

View File

@ -106,7 +106,21 @@ FILES_cpp_shared = \
OpenTypeLayoutEngine.cpp \
ThaiLayoutEngine.cpp \
ScriptAndLanguageTags.cpp \
FontInstanceAdapter.cpp
FontInstanceAdapter.cpp \
ContextualGlyphInsertionProc2.cpp \
ContextualGlyphSubstProc2.cpp \
GXLayoutEngine2.cpp \
IndicRearrangementProcessor2.cpp \
LigatureSubstProc2.cpp \
MorphTables2.cpp \
NonContextualGlyphSubstProc2.cpp \
SegmentArrayProcessor2.cpp \
SegmentSingleProcessor2.cpp \
SimpleArrayProcessor2.cpp \
SingleTableProcessor2.cpp \
StateTableProcessor2.cpp \
SubtableProcessor2.cpp \
TrimmedArrayProcessor2.cpp
ifeq ($(PLATFORM),windows)

View File

@ -1,5 +1,5 @@
#
# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2005, 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
@ -83,21 +83,17 @@ ifeq ($(PLATFORM), macosx)
-framework JavaNativeFoundation
else ifneq ($(PLATFORM), windows)
CFLAGS += -DWITH_X11
ifeq ($(PLATFORM), macosx))
OTHER_LDLIBS += -liconv
CPPFLAGS += -I$(OPENWIN_HOME)/include \
-I$(OPENWIN_HOME)/include/X11/extensions
OTHER_LDLIBS += -L$(OPENWIN_LIB) -lX11 -lXext $(LIBM) -pthread
else
CPPFLAGS += -I$(OPENWIN_HOME)/include -I$(OPENWIN_HOME)/include/X11/extensions
OTHER_LDLIBS += -L$(OPENWIN_LIB) -lX11 -lXext $(LIBM) -lpthread
endif
CPPFLAGS += -I$(OPENWIN_HOME)/include -I$(OPENWIN_HOME)/include/X11/extensions
OTHER_LDLIBS += -L$(OPENWIN_LIB) -lX11 -lXext $(LIBM) -lpthread
else # PLATFORM
CFLAGS += -DWITH_WIN32
OTHER_LDLIBS += kernel32.lib user32.lib gdi32.lib delayimp.lib /DELAYLOAD:user32.dll
#$(JVMLIB) $(OBJDIR)/../../jpeg/$(OBJDIRNAME)/jpeg$(SUFFIX).lib
endif # PLATFORM
# Add giflib include path for all platforms
CPPFLAGS += -I$(SHARE_SRC)/native/sun/awt/giflib
#
# Add to ambient vpath to get files in a subdirectory
#

View File

@ -1,5 +1,5 @@
#
# Copyright (c) 1997, 2012, 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
@ -227,5 +227,54 @@ FILES_java = \
sun/util/resources/sv/TimeZoneNames_sv.java \
sun/util/resources/zh/TimeZoneNames_zh_CN.java \
sun/util/resources/zh/TimeZoneNames_zh_TW.java \
sun/util/resources/zh/TimeZoneNames_zh_HK.java
sun/util/resources/zh/TimeZoneNames_zh_HK.java \
\
sun/text/resources/ar/JavaTimeSupplementary_ar.java \
sun/text/resources/be/JavaTimeSupplementary_be.java \
sun/text/resources/bg/JavaTimeSupplementary_bg.java \
sun/text/resources/ca/JavaTimeSupplementary_ca.java \
sun/text/resources/cs/JavaTimeSupplementary_cs.java \
sun/text/resources/da/JavaTimeSupplementary_da.java \
sun/text/resources/de/JavaTimeSupplementary_de.java \
sun/text/resources/el/JavaTimeSupplementary_el.java \
sun/text/resources/en/JavaTimeSupplementary_en_GB.java \
sun/text/resources/en/JavaTimeSupplementary_en_SG.java \
sun/text/resources/es/JavaTimeSupplementary_es.java \
sun/text/resources/et/JavaTimeSupplementary_et.java \
sun/text/resources/fi/JavaTimeSupplementary_fi.java \
sun/text/resources/fr/JavaTimeSupplementary_fr.java \
sun/text/resources/ga/JavaTimeSupplementary_ga.java \
sun/text/resources/hi/JavaTimeSupplementary_hi_IN.java \
sun/text/resources/hr/JavaTimeSupplementary_hr.java \
sun/text/resources/hu/JavaTimeSupplementary_hu.java \
sun/text/resources/is/JavaTimeSupplementary_is.java \
sun/text/resources/it/JavaTimeSupplementary_it.java \
sun/text/resources/iw/JavaTimeSupplementary_iw.java \
sun/text/resources/iw/JavaTimeSupplementary_iw_IL.java \
sun/text/resources/ja/JavaTimeSupplementary_ja.java \
sun/text/resources/ko/JavaTimeSupplementary_ko.java \
sun/text/resources/lt/JavaTimeSupplementary_lt.java \
sun/text/resources/lv/JavaTimeSupplementary_lv.java \
sun/text/resources/mk/JavaTimeSupplementary_mk.java \
sun/text/resources/ms/JavaTimeSupplementary_ms.java \
sun/text/resources/mt/JavaTimeSupplementary_mt.java \
sun/text/resources/nl/JavaTimeSupplementary_nl.java \
sun/text/resources/no/JavaTimeSupplementary_no.java \
sun/text/resources/pl/JavaTimeSupplementary_pl.java \
sun/text/resources/pt/JavaTimeSupplementary_pt.java \
sun/text/resources/pt/JavaTimeSupplementary_pt_PT.java \
sun/text/resources/ro/JavaTimeSupplementary_ro.java \
sun/text/resources/ru/JavaTimeSupplementary_ru.java \
sun/text/resources/sk/JavaTimeSupplementary_sk.java \
sun/text/resources/sl/JavaTimeSupplementary_sl.java \
sun/text/resources/sq/JavaTimeSupplementary_sq.java \
sun/text/resources/sr/JavaTimeSupplementary_sr.java \
sun/text/resources/sr/JavaTimeSupplementary_sr_Latn.java \
sun/text/resources/sv/JavaTimeSupplementary_sv.java \
sun/text/resources/th/JavaTimeSupplementary_th.java \
sun/text/resources/tr/JavaTimeSupplementary_tr.java \
sun/text/resources/uk/JavaTimeSupplementary_uk.java \
sun/text/resources/vi/JavaTimeSupplementary_vi.java \
sun/text/resources/zh/JavaTimeSupplementary_zh.java \
sun/text/resources/zh/JavaTimeSupplementary_zh_TW.java

View File

@ -42,7 +42,6 @@ BUILD_MANIFEST=true
# Time zone data file creation
#
TZDATA_DIR := ../javazic/tzdata
TZDATA_VER := $(subst tzdata,,$(shell $(GREP) '^tzdata' $(TZDATA_DIR)/VERSION))
TZFILE := \
africa antarctica asia australasia europe northamerica \
pacificnew southamerica backward etcetera \
@ -50,9 +49,7 @@ TZFILE := \
TZFILES := $(addprefix $(TZDATA_DIR)/,$(TZFILE))
TZDB_JAR = tzdb.jar
TZDB_DAT = $(LIBDIR)/tzdb.dat
#
# Rules
@ -62,13 +59,12 @@ include $(BUILDDIR)/common/Classes.gmk
#
# Add to the build rule
#
build: $(LIBDIR)/$(TZDB_JAR)
build: $(TZDB_DAT)
$(LIBDIR)/$(TZDB_JAR): $(TZFILES)
$(TZDB_DAT): $(TZFILES)
$(prep-target)
echo build tzdb from version $(TZDATA_VER)
$(BOOT_JAVA_CMD) -jar $(BUILDTOOLJARDIR)/tzdb.jar \
-version $(TZDATA_VER) -srcdir $(TZDATA_DIR) -dstdir $(LIBDIR) $(TZFILE)
-srcdir $(TZDATA_DIR) -dstfile $(TZDB_DAT) $(TZFILE)
clean clobber::
$(RM) $(LIBDIR)/$(TZDB_JAR)
$(RM) $(TZDB_DAT)

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 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,6 +25,7 @@
package build.tools.cldrconverter;
import build.tools.cldrconverter.CLDRConverter.DraftType;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@ -88,7 +89,7 @@ abstract class AbstractLDMLHandler<V> extends DefaultHandler {
}
String draftValue = attributes.getValue("draft");
if (draftValue != null) {
return CLDRConverter.draftType > CLDRConverter.DRAFT_MAP.get(draftValue);
return DraftType.getDefault().ordinal() > DraftType.forKeyword(draftValue).ordinal();
}
return false;
}

View File

@ -266,6 +266,9 @@ class Bundle {
handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "DayNarrows");
handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "AmPmMarkers");
handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "narrow.AmPmMarkers");
handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "QuarterNames");
handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "QuarterAbbreviations");
handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "QuarterNarrows");
adjustEraNames(myMap, calendarType);
@ -484,25 +487,33 @@ class Bundle {
for (String k : patternKeys) {
if (myMap.containsKey(calendarPrefix + k)) {
int len = patternKeys.length;
List<String> rawPatterns = new ArrayList<>();
List<String> patterns = new ArrayList<>();
List<String> rawPatterns = new ArrayList<>(len);
List<String> patterns = new ArrayList<>(len);
for (int i = 0; i < len; i++) {
String key = calendarPrefix + patternKeys[i];
String pattern = (String) myMap.remove(key);
if (pattern == null) {
pattern = (String) parentsMap.remove(key);
}
rawPatterns.add(i, pattern);
if (pattern != null) {
rawPatterns.add(i, pattern);
patterns.add(i, translateDateFormatLetters(calendarType, pattern));
} else {
patterns.add(i, null);
}
}
// If patterns is empty or has any nulls, discard patterns.
if (patterns.isEmpty()) {
return;
}
for (String p : patterns) {
if (p == null) {
return;
}
}
String key = calendarPrefix + name;
if (!rawPatterns.equals(patterns)) {
myMap.put("cldr." + key, rawPatterns.toArray(new String[len]));
myMap.put("java.time." + key, rawPatterns.toArray(new String[len]));
}
myMap.put(key, patterns.toArray(new String[len]));
break;

View File

@ -68,25 +68,43 @@ public class CLDRConverter {
static MetaZonesParseHandler handlerMetaZones;
private static BundleGenerator bundleGenerator;
static int draftType;
private static final String DRAFT_UNCONFIRMED = "unconfirmed";
private static final String DRAFT_PROVISIONAL = "provisional";
private static final String DRAFT_CONTRIBUTED = "contributed";
private static final String DRAFT_APPROVED = "approved";
private static final String DRAFT_TRUE = "true";
private static final String DRAFT_FALSE = "false";
private static final String DRAFT_DEFAULT = DRAFT_APPROVED;
static final Map<String, Integer> DRAFT_MAP = new HashMap<>();
static enum DraftType {
UNCONFIRMED,
PROVISIONAL,
CONTRIBUTED,
APPROVED;
static {
DRAFT_MAP.put(DRAFT_UNCONFIRMED, 0);
DRAFT_MAP.put(DRAFT_PROVISIONAL, 1);
DRAFT_MAP.put(DRAFT_CONTRIBUTED, 2);
DRAFT_MAP.put(DRAFT_APPROVED, 3);
DRAFT_MAP.put(DRAFT_TRUE, 0);
DRAFT_MAP.put(DRAFT_FALSE, 2);
draftType = DRAFT_MAP.get(DRAFT_DEFAULT);
};
private static final Map<String, DraftType> map = new HashMap<>();
static {
for (DraftType dt : values()) {
map.put(dt.getKeyword(), dt);
}
}
static private DraftType defaultType = CONTRIBUTED;
private final String keyword;
private DraftType() {
keyword = this.name().toLowerCase(Locale.ROOT);
}
static DraftType forKeyword(String keyword) {
return map.get(keyword);
}
static DraftType getDefault() {
return defaultType;
}
static void setDefault(String keyword) {
defaultType = Objects.requireNonNull(forKeyword(keyword));
}
String getKeyword() {
return keyword;
}
}
static boolean USE_UTF8 = false;
private static boolean verbose;
@ -106,7 +124,7 @@ public class CLDRConverter {
case "-draft":
String draftDataType = args[++i];
try {
draftType = DRAFT_MAP.get(draftDataType);
DraftType.setDefault(draftDataType);
} catch (NullPointerException e) {
severe("Error: incorrect draft value: %s%n", draftDataType);
System.exit(1);
@ -525,7 +543,7 @@ public class CLDRConverter {
"standalone.MonthNames",
"MonthAbbreviations",
"standalone.MonthAbbreviations",
"MonthNarrow",
"MonthNarrows",
"standalone.MonthNarrows",
"DayNames",
"standalone.DayNames",
@ -533,6 +551,12 @@ public class CLDRConverter {
"standalone.DayAbbreviations",
"DayNarrows",
"standalone.DayNarrows",
"QuarterNames",
"standalone.QuarterNames",
"QuarterAbbreviations",
"standalone.QuarterAbbreviations",
"QuarterNarrows",
"standalone.QuarterNarrows",
"AmPmMarkers",
"narrow.AmPmMarkers",
"long.Eras",
@ -560,7 +584,7 @@ public class CLDRConverter {
String prefix = calendarType.keyElementName();
for (String element : FORMAT_DATA_ELEMENTS) {
String key = prefix + element;
copyIfPresent(map, "cldr." + key, formatData);
copyIfPresent(map, "java.time." + key, formatData);
copyIfPresent(map, key, formatData);
}
}

View File

@ -356,6 +356,44 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
}
}
break;
case "quarterContext":
{
// for FormatData
// need to keep stand-alone and format, to allow for inheritance in CLDR
String type = attributes.getValue("type");
if ("stand-alone".equals(type) || "format".equals(type)) {
pushKeyContainer(qName, attributes, type);
} else {
pushIgnoredContainer(qName);
}
}
break;
case "quarterWidth":
{
// for FormatData
// keep info about the context type so we can sort out inheritance later
String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName();
switch (attributes.getValue("type")) {
case "wide":
pushStringArrayEntry(qName, attributes, prefix + "QuarterNames/" + getContainerKey(), 4);
break;
case "abbreviated":
pushStringArrayEntry(qName, attributes, prefix + "QuarterAbbreviations/" + getContainerKey(), 4);
break;
case "narrow":
pushStringArrayEntry(qName, attributes, prefix + "QuarterNarrows/" + getContainerKey(), 4);
break;
default:
pushIgnoredContainer(qName);
break;
}
}
break;
case "quarter":
// for FormatData
// add to string array entry of quarterWidth element
pushStringArrayElement(qName, attributes, Integer.parseInt(attributes.getValue("type")) - 1);
break;
//
// Time zone names

View File

@ -58,12 +58,12 @@ package build.tools.tzdb;
import static build.tools.tzdb.Utils.*;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Arrays;
@ -71,132 +71,131 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.regex.Matcher;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
/**
* A builder that can read the TZDB time-zone files and build {@code ZoneRules} instances.
* A compiler that reads a set of TZDB time-zone files and builds a single
* combined TZDB data file.
*
* @since 1.8
*/
public final class TzdbZoneRulesCompiler {
private static final Matcher YEAR = Pattern.compile("(?i)(?<min>min)|(?<max>max)|(?<only>only)|(?<year>[0-9]+)").matcher("");
private static final Matcher MONTH = Pattern.compile("(?i)(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec)").matcher("");
private static final Matcher DOW = Pattern.compile("(?i)(mon)|(tue)|(wed)|(thu)|(fri)|(sat)|(sun)").matcher("");
private static final Matcher TIME = Pattern.compile("(?<neg>-)?+(?<hour>[0-9]{1,2})(:(?<minute>[0-5][0-9]))?+(:(?<second>[0-5][0-9]))?+").matcher("");
/**
* Constant for MJD 1972-01-01.
*/
private static final long MJD_1972_01_01 = 41317L;
/**
* Reads a set of TZDB files and builds a single combined data file.
*
* @param args the arguments
*/
public static void main(String[] args) {
new TzdbZoneRulesCompiler().compile(args);
}
private void compile(String[] args) {
if (args.length < 2) {
outputHelp();
return;
}
// parse args
Path srcDir = null;
Path dstFile = null;
String version = null;
File baseSrcDir = null;
File dstDir = null;
boolean verbose = false;
// parse options
// parse args/options
int i;
for (i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("-") == false) {
if (!arg.startsWith("-")) {
break;
}
if ("-srcdir".equals(arg)) {
if (baseSrcDir == null && ++i < args.length) {
baseSrcDir = new File(args[i]);
if (srcDir == null && ++i < args.length) {
srcDir = Paths.get(args[i]);
continue;
}
} else if ("-dstdir".equals(arg)) {
if (dstDir == null && ++i < args.length) {
dstDir = new File(args[i]);
continue;
}
} else if ("-version".equals(arg)) {
if (version == null && ++i < args.length) {
version = args[i];
} else if ("-dstfile".equals(arg)) {
if (dstFile == null && ++i < args.length) {
dstFile = Paths.get(args[i]);
continue;
}
} else if ("-verbose".equals(arg)) {
if (verbose == false) {
if (!verbose) {
verbose = true;
continue;
}
} else if ("-help".equals(arg) == false) {
} else if (!"-help".equals(arg)) {
System.out.println("Unrecognised option: " + arg);
}
outputHelp();
return;
}
// check source directory
if (baseSrcDir == null) {
System.out.println("Source directory must be specified using -srcdir: " + baseSrcDir);
return;
if (srcDir == null) {
System.err.println("Source directory must be specified using -srcdir");
System.exit(1);
}
if (baseSrcDir.isDirectory() == false) {
System.out.println("Source does not exist or is not a directory: " + baseSrcDir);
return;
if (!Files.isDirectory(srcDir)) {
System.err.println("Source does not exist or is not a directory: " + srcDir);
System.exit(1);
}
dstDir = (dstDir != null ? dstDir : baseSrcDir);
// parse source file names
List<String> srcFileNames = Arrays.asList(Arrays.copyOfRange(args, i, args.length));
if (srcFileNames.isEmpty()) {
System.out.println("Source filenames not specified, using default set");
System.out.println("(africa antarctica asia australasia backward etcetera europe northamerica southamerica)");
srcFileNames = Arrays.asList("africa", "antarctica", "asia", "australasia", "backward",
"etcetera", "europe", "northamerica", "southamerica");
if (i == args.length) {
i = 0;
args = new String[] {"africa", "antarctica", "asia", "australasia", "europe",
"northamerica","southamerica", "backward", "etcetera" };
System.out.println("Source filenames not specified, using default set ( ");
for (String name : args) {
System.out.printf(name + " ");
}
System.out.println(")");
}
// find source directories to process
List<File> srcDirs = new ArrayList<>();
if (version != null) {
// if the "version" specified, as in jdk repo, the "baseSrcDir" is
// the "srcDir" that contains the tzdb data.
srcDirs.add(baseSrcDir);
} else {
File[] dirs = baseSrcDir.listFiles();
for (File dir : dirs) {
if (dir.isDirectory() && dir.getName().matches("[12][0-9]{3}[A-Za-z0-9._-]+")) {
srcDirs.add(dir);
}
// source files in this directory
List<Path> srcFiles = new ArrayList<>();
for (; i < args.length; i++) {
Path file = srcDir.resolve(args[i]);
if (Files.exists(file)) {
srcFiles.add(file);
} else {
System.err.println("Source directory does not contain source file: " + args[i]);
System.exit(1);
}
}
if (srcDirs.isEmpty()) {
System.out.println("Source directory contains no valid source folders: " + baseSrcDir);
return;
// check destination file
if (dstFile == null) {
dstFile = srcDir.resolve("tzdb.dat");
} else {
Path parent = dstFile.getParent();
if (parent != null && !Files.exists(parent)) {
System.err.println("Destination directory does not exist: " + parent);
System.exit(1);
}
}
// check destination directory
if (dstDir.exists() == false && dstDir.mkdirs() == false) {
System.out.println("Destination directory could not be created: " + dstDir);
return;
try {
// get tzdb source version
Matcher m = Pattern.compile("tzdata(?<ver>[0-9]{4}[A-z])")
.matcher(new String(Files.readAllBytes(srcDir.resolve("VERSION")),
"ISO-8859-1"));
if (m.find()) {
version = m.group("ver");
} else {
System.exit(1);
System.err.println("Source directory does not contain file: VERSION");
}
printVerbose("Compiling TZDB version " + version);
// parse source files
for (Path file : srcFiles) {
printVerbose("Parsing file: " + file);
parseFile(file);
}
// build zone rules
printVerbose("Building rules");
buildZoneRules();
// output to file
printVerbose("Outputting tzdb file: " + dstFile);
outputFile(dstFile, version, builtZones, links);
} catch (Exception ex) {
System.out.println("Failed: " + ex.toString());
ex.printStackTrace();
System.exit(1);
}
if (dstDir.isDirectory() == false) {
System.out.println("Destination is not a directory: " + dstDir);
return;
}
process(srcDirs, srcFileNames, dstDir, version, verbose);
System.exit(0);
}
@ -206,145 +205,35 @@ public final class TzdbZoneRulesCompiler {
private static void outputHelp() {
System.out.println("Usage: TzdbZoneRulesCompiler <options> <tzdb source filenames>");
System.out.println("where options include:");
System.out.println(" -srcdir <directory> Where to find source directories (required)");
System.out.println(" -dstdir <directory> Where to output generated files (default srcdir)");
System.out.println(" -version <version> Specify the version, such as 2009a (optional)");
System.out.println(" -srcdir <directory> Where to find tzdb source directory (required)");
System.out.println(" -dstfile <file> Where to output generated file (default srcdir/tzdb.dat)");
System.out.println(" -help Print this usage message");
System.out.println(" -verbose Output verbose information during compilation");
System.out.println(" There must be one directory for each version in srcdir");
System.out.println(" Each directory must have the name of the version, such as 2009a");
System.out.println(" Each directory must contain the unpacked tzdb files, such as asia or europe");
System.out.println(" Directories must match the regex [12][0-9][0-9][0-9][A-Za-z0-9._-]+");
System.out.println(" There will be one jar file for each version and one combined jar in dstdir");
System.out.println(" If the version is specified, only that version is processed");
}
/**
* Process to create the jar files.
*/
private static void process(List<File> srcDirs, List<String> srcFileNames, File dstDir, String version, boolean verbose) {
// build actual jar files
Map<String, SortedMap<String, ZoneRules>> allBuiltZones = new TreeMap<>();
Set<String> allRegionIds = new TreeSet<String>();
Set<ZoneRules> allRules = new HashSet<ZoneRules>();
Map<String, Map<String, String>> allLinks = new TreeMap<>();
for (File srcDir : srcDirs) {
// source files in this directory
List<File> srcFiles = new ArrayList<>();
for (String srcFileName : srcFileNames) {
File file = new File(srcDir, srcFileName);
if (file.exists()) {
srcFiles.add(file);
}
}
if (srcFiles.isEmpty()) {
continue; // nothing to process
}
// compile
String loopVersion = (srcDirs.size() == 1 && version != null)
? version : srcDir.getName();
TzdbZoneRulesCompiler compiler = new TzdbZoneRulesCompiler(loopVersion, srcFiles, verbose);
try {
// compile
compiler.compile();
SortedMap<String, ZoneRules> builtZones = compiler.getZones();
// output version-specific file
File dstFile = version == null ? new File(dstDir, "tzdb" + loopVersion + ".jar")
: new File(dstDir, "tzdb.jar");
if (verbose) {
System.out.println("Outputting file: " + dstFile);
}
outputFile(dstFile, loopVersion, builtZones, compiler.links);
// create totals
allBuiltZones.put(loopVersion, builtZones);
allRegionIds.addAll(builtZones.keySet());
allRules.addAll(builtZones.values());
allLinks.put(loopVersion, compiler.links);
} catch (Exception ex) {
System.out.println("Failed: " + ex.toString());
ex.printStackTrace();
System.exit(1);
}
}
// output merged file
if (version == null) {
File dstFile = new File(dstDir, "tzdb-all.jar");
if (verbose) {
System.out.println("Outputting combined file: " + dstFile);
}
outputFile(dstFile, allBuiltZones, allRegionIds, allRules, allLinks);
}
System.out.println(" The source directory must contain the unpacked tzdb files, such as asia or europe");
}
/**
* Outputs the file.
*/
private static void outputFile(File dstFile,
String version,
SortedMap<String, ZoneRules> builtZones,
Map<String, String> links) {
Map<String, SortedMap<String, ZoneRules>> loopAllBuiltZones = new TreeMap<>();
loopAllBuiltZones.put(version, builtZones);
Set<String> loopAllRegionIds = new TreeSet<String>(builtZones.keySet());
Set<ZoneRules> loopAllRules = new HashSet<ZoneRules>(builtZones.values());
Map<String, Map<String, String>> loopAllLinks = new TreeMap<>();
loopAllLinks.put(version, links);
outputFile(dstFile, loopAllBuiltZones, loopAllRegionIds, loopAllRules, loopAllLinks);
}
/**
* Outputs the file.
*/
private static void outputFile(File dstFile,
Map<String, SortedMap<String, ZoneRules>> allBuiltZones,
Set<String> allRegionIds,
Set<ZoneRules> allRules,
Map<String, Map<String, String>> allLinks) {
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(dstFile))) {
outputTZEntry(jos, allBuiltZones, allRegionIds, allRules, allLinks);
} catch (Exception ex) {
System.out.println("Failed: " + ex.toString());
ex.printStackTrace();
System.exit(1);
}
}
/**
* Outputs the timezone entry in the JAR file.
*/
private static void outputTZEntry(JarOutputStream jos,
Map<String, SortedMap<String, ZoneRules>> allBuiltZones,
Set<String> allRegionIds,
Set<ZoneRules> allRules,
Map<String, Map<String, String>> allLinks) {
// this format is not publicly specified
try {
jos.putNextEntry(new ZipEntry("TZDB.dat"));
DataOutputStream out = new DataOutputStream(jos);
private void outputFile(Path dstFile, String version,
SortedMap<String, ZoneRules> builtZones,
Map<String, String> links) {
try (DataOutputStream out = new DataOutputStream(Files.newOutputStream(dstFile))) {
// file version
out.writeByte(1);
// group
out.writeUTF("TZDB");
// versions
String[] versionArray = allBuiltZones.keySet().toArray(new String[allBuiltZones.size()]);
out.writeShort(versionArray.length);
for (String version : versionArray) {
out.writeUTF(version);
}
out.writeShort(1);
out.writeUTF(version);
// regions
String[] regionArray = allRegionIds.toArray(new String[allRegionIds.size()]);
String[] regionArray = builtZones.keySet().toArray(new String[builtZones.size()]);
out.writeShort(regionArray.length);
for (String regionId : regionArray) {
out.writeUTF(regionId);
}
// rules
List<ZoneRules> rulesList = new ArrayList<>(allRules);
// rules -- hashset -> remove the dup
List<ZoneRules> rulesList = new ArrayList<>(new HashSet<>(builtZones.values()));
out.writeShort(rulesList.size());
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
for (ZoneRules rules : rulesList) {
@ -357,27 +246,22 @@ public final class TzdbZoneRulesCompiler {
out.write(bytes);
}
// link version-region-rules
for (String version : allBuiltZones.keySet()) {
out.writeShort(allBuiltZones.get(version).size());
for (Map.Entry<String, ZoneRules> entry : allBuiltZones.get(version).entrySet()) {
int regionIndex = Arrays.binarySearch(regionArray, entry.getKey());
int rulesIndex = rulesList.indexOf(entry.getValue());
out.writeShort(regionIndex);
out.writeShort(rulesIndex);
}
out.writeShort(builtZones.size());
for (Map.Entry<String, ZoneRules> entry : builtZones.entrySet()) {
int regionIndex = Arrays.binarySearch(regionArray, entry.getKey());
int rulesIndex = rulesList.indexOf(entry.getValue());
out.writeShort(regionIndex);
out.writeShort(rulesIndex);
}
// alias-region
for (String version : allLinks.keySet()) {
out.writeShort(allLinks.get(version).size());
for (Map.Entry<String, String> entry : allLinks.get(version).entrySet()) {
int aliasIndex = Arrays.binarySearch(regionArray, entry.getKey());
int regionIndex = Arrays.binarySearch(regionArray, entry.getValue());
out.writeShort(aliasIndex);
out.writeShort(regionIndex);
}
out.writeShort(links.size());
for (Map.Entry<String, String> entry : links.entrySet()) {
int aliasIndex = Arrays.binarySearch(regionArray, entry.getKey());
int regionIndex = Arrays.binarySearch(regionArray, entry.getValue());
out.writeShort(aliasIndex);
out.writeShort(regionIndex);
}
out.flush();
jos.closeEntry();
} catch (Exception ex) {
System.out.println("Failed: " + ex.toString());
ex.printStackTrace();
@ -385,76 +269,30 @@ public final class TzdbZoneRulesCompiler {
}
}
//-----------------------------------------------------------------------
private static final Pattern YEAR = Pattern.compile("(?i)(?<min>min)|(?<max>max)|(?<only>only)|(?<year>[0-9]+)");
private static final Pattern MONTH = Pattern.compile("(?i)(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec)");
private static final Matcher DOW = Pattern.compile("(?i)(mon)|(tue)|(wed)|(thu)|(fri)|(sat)|(sun)").matcher("");
private static final Matcher TIME = Pattern.compile("(?<neg>-)?+(?<hour>[0-9]{1,2})(:(?<minute>[0-5][0-9]))?+(:(?<second>[0-5][0-9]))?+").matcher("");
/** The TZDB rules. */
private final Map<String, List<TZDBRule>> rules = new HashMap<>();
/** The TZDB zones. */
private final Map<String, List<TZDBZone>> zones = new HashMap<>();
/** The TZDB links. */
/** The TZDB links. */
private final Map<String, String> links = new HashMap<>();
/** The built zones. */
private final SortedMap<String, ZoneRules> builtZones = new TreeMap<>();
/** The version to produce. */
private final String version;
/** The source files. */
private final List<File> sourceFiles;
/** The version to produce. */
private final boolean verbose;
/** Whether to output verbose messages. */
private boolean verbose;
/**
* Creates an instance if you want to invoke the compiler manually.
*
* @param version the version, such as 2009a, not null
* @param sourceFiles the list of source files, not empty, not null
* @param verbose whether to output verbose messages
* private contructor
*/
public TzdbZoneRulesCompiler(String version, List<File> sourceFiles, boolean verbose) {
this.version = version;
this.sourceFiles = sourceFiles;
this.verbose = verbose;
}
/**
* Compile the rules file.
* <p>
* Use {@link #getZones()} to retrieve the parsed data.
*
* @throws Exception if an error occurs
*/
public void compile() throws Exception {
printVerbose("Compiling TZDB version " + version);
parseFiles();
buildZoneRules();
printVerbose("Compiled TZDB version " + version);
}
/**
* Gets the parsed zone rules.
*
* @return the parsed zone rules, not null
*/
public SortedMap<String, ZoneRules> getZones() {
return builtZones;
}
/**
* Parses the source files.
*
* @throws Exception if an error occurs
*/
private void parseFiles() throws Exception {
for (File file : sourceFiles) {
printVerbose("Parsing file: " + file);
parseFile(file);
}
private TzdbZoneRulesCompiler() {
}
/**
@ -463,14 +301,14 @@ public final class TzdbZoneRulesCompiler {
* @param file the file being read, not null
* @throws Exception if an error occurs
*/
private void parseFile(File file) throws Exception {
private void parseFile(Path file) throws Exception {
int lineNumber = 1;
String line = null;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
List<String> lines = Files.readAllLines(file, StandardCharsets.ISO_8859_1);
List<TZDBZone> openZone = null;
for ( ; (line = in.readLine()) != null; lineNumber++) {
for (; lineNumber < lines.size(); lineNumber++) {
line = lines.get(lineNumber);
int index = line.indexOf('#'); // remove comments (doesn't handle # in quotes)
if (index >= 0) {
line = line.substring(0, index);
@ -478,41 +316,43 @@ public final class TzdbZoneRulesCompiler {
if (line.trim().length() == 0) { // ignore blank lines
continue;
}
StringTokenizer st = new StringTokenizer(line, " \t");
if (openZone != null && Character.isWhitespace(line.charAt(0)) && st.hasMoreTokens()) {
if (parseZoneLine(st, openZone)) {
Scanner s = new Scanner(line);
if (openZone != null && Character.isWhitespace(line.charAt(0)) && s.hasNext()) {
if (parseZoneLine(s, openZone)) {
openZone = null;
}
} else {
if (st.hasMoreTokens()) {
String first = st.nextToken();
if (s.hasNext()) {
String first = s.next();
if (first.equals("Zone")) {
if (st.countTokens() < 3) {
openZone = new ArrayList<>();
try {
zones.put(s.next(), openZone);
if (parseZoneLine(s, openZone)) {
openZone = null;
}
} catch (NoSuchElementException x) {
printVerbose("Invalid Zone line in file: " + file + ", line: " + line);
throw new IllegalArgumentException("Invalid Zone line");
}
openZone = new ArrayList<>();
zones.put(st.nextToken(), openZone);
if (parseZoneLine(st, openZone)) {
openZone = null;
}
} else {
openZone = null;
if (first.equals("Rule")) {
if (st.countTokens() < 9) {
try {
parseRuleLine(s);
} catch (NoSuchElementException x) {
printVerbose("Invalid Rule line in file: " + file + ", line: " + line);
throw new IllegalArgumentException("Invalid Rule line");
}
parseRuleLine(st);
} else if (first.equals("Link")) {
if (st.countTokens() < 2) {
try {
String realId = s.next();
String aliasId = s.next();
links.put(aliasId, realId);
} catch (NoSuchElementException x) {
printVerbose("Invalid Link line in file: " + file + ", line: " + line);
throw new IllegalArgumentException("Invalid Link line");
}
String realId = st.nextToken();
String aliasId = st.nextToken();
links.put(aliasId, realId);
} else {
throw new IllegalArgumentException("Unknown line");
@ -522,52 +362,44 @@ public final class TzdbZoneRulesCompiler {
}
}
} catch (Exception ex) {
throw new Exception("Failed while processing file '" + file + "' on line " + lineNumber + " '" + line + "'", ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
// ignore NPE and IOE
}
throw new Exception("Failed while parsing file '" + file + "' on line " + lineNumber + " '" + line + "'", ex);
}
}
/**
* Parses a Rule line.
*
* @param st the tokenizer, not null
* @param s the line scanner, not null
*/
private void parseRuleLine(StringTokenizer st) {
private void parseRuleLine(Scanner s) {
TZDBRule rule = new TZDBRule();
String name = st.nextToken();
String name = s.next();
if (rules.containsKey(name) == false) {
rules.put(name, new ArrayList<TZDBRule>());
}
rules.get(name).add(rule);
rule.startYear = parseYear(st.nextToken(), 0);
rule.endYear = parseYear(st.nextToken(), rule.startYear);
rule.startYear = parseYear(s, 0);
rule.endYear = parseYear(s, rule.startYear);
if (rule.startYear > rule.endYear) {
throw new IllegalArgumentException("Year order invalid: " + rule.startYear + " > " + rule.endYear);
}
parseOptional(st.nextToken()); // type is unused
parseMonthDayTime(st, rule);
rule.savingsAmount = parsePeriod(st.nextToken());
rule.text = parseOptional(st.nextToken());
parseOptional(s.next()); // type is unused
parseMonthDayTime(s, rule);
rule.savingsAmount = parsePeriod(s.next());
rule.text = parseOptional(s.next());
}
/**
* Parses a Zone line.
*
* @param st the tokenizer, not null
* @param s the line scanner, not null
* @return true if the zone is complete
*/
private boolean parseZoneLine(StringTokenizer st, List<TZDBZone> zoneList) {
private boolean parseZoneLine(Scanner s, List<TZDBZone> zoneList) {
TZDBZone zone = new TZDBZone();
zoneList.add(zone);
zone.standardOffset = parseOffset(st.nextToken());
String savingsRule = parseOptional(st.nextToken());
zone.standardOffset = parseOffset(s.next());
String savingsRule = parseOptional(s.next());
if (savingsRule == null) {
zone.fixedSavingsSecs = 0;
zone.savingsRule = null;
@ -580,11 +412,11 @@ public final class TzdbZoneRulesCompiler {
zone.savingsRule = savingsRule;
}
}
zone.text = st.nextToken();
if (st.hasMoreTokens()) {
zone.year = Integer.parseInt(st.nextToken());
if (st.hasMoreTokens()) {
parseMonthDayTime(st, zone);
zone.text = s.next();
if (s.hasNext()) {
zone.year = Integer.parseInt(s.next());
if (s.hasNext()) {
parseMonthDayTime(s, zone);
}
return false;
} else {
@ -595,13 +427,13 @@ public final class TzdbZoneRulesCompiler {
/**
* Parses a Rule line.
*
* @param st the tokenizer, not null
* @param s the line scanner, not null
* @param mdt the object to parse into, not null
*/
private void parseMonthDayTime(StringTokenizer st, TZDBMonthDayTime mdt) {
mdt.month = parseMonth(st.nextToken());
if (st.hasMoreTokens()) {
String dayRule = st.nextToken();
private void parseMonthDayTime(Scanner s, TZDBMonthDayTime mdt) {
mdt.month = parseMonth(s);
if (s.hasNext()) {
String dayRule = s.next();
if (dayRule.startsWith("last")) {
mdt.dayOfMonth = -1;
mdt.dayOfWeek = parseDayOfWeek(dayRule.substring(4));
@ -621,8 +453,8 @@ public final class TzdbZoneRulesCompiler {
}
mdt.dayOfMonth = Integer.parseInt(dayRule);
}
if (st.hasMoreTokens()) {
String timeStr = st.nextToken();
if (s.hasNext()) {
String timeStr = s.next();
int secsOfDay = parseSecs(timeStr);
if (secsOfDay == 86400) {
mdt.endOfDay = true;
@ -635,30 +467,43 @@ public final class TzdbZoneRulesCompiler {
}
}
private int parseYear(String str, int defaultYear) {
if (YEAR.reset(str).matches()) {
if (YEAR.group("min") != null) {
//return YEAR_MIN_VALUE;
private int parseYear(Scanner s, int defaultYear) {
if (s.hasNext(YEAR)) {
s.next(YEAR);
MatchResult mr = s.match();
if (mr.group(1) != null) {
return 1900; // systemv has min
} else if (YEAR.group("max") != null) {
} else if (mr.group(2) != null) {
return YEAR_MAX_VALUE;
} else if (YEAR.group("only") != null) {
} else if (mr.group(3) != null) {
return defaultYear;
}
return Integer.parseInt(YEAR.group("year"));
return Integer.parseInt(mr.group(4));
/*
if (mr.group("min") != null) {
//return YEAR_MIN_VALUE;
return 1900; // systemv has min
} else if (mr.group("max") != null) {
return YEAR_MAX_VALUE;
} else if (mr.group("only") != null) {
return defaultYear;
}
return Integer.parseInt(mr.group("year"));
*/
}
throw new IllegalArgumentException("Unknown year: " + str);
throw new IllegalArgumentException("Unknown year: " + s.next());
}
private int parseMonth(String str) {
if (MONTH.reset(str).matches()) {
private int parseMonth(Scanner s) {
if (s.hasNext(MONTH)) {
s.next(MONTH);
for (int moy = 1; moy < 13; moy++) {
if (MONTH.group(moy) != null) {
if (s.match().group(moy) != null) {
return moy;
}
}
}
throw new IllegalArgumentException("Unknown month: " + str);
throw new IllegalArgumentException("Unknown month: " + s.next());
}
private int parseDayOfWeek(String str) {
@ -729,7 +574,6 @@ public final class TzdbZoneRulesCompiler {
}
}
//-----------------------------------------------------------------------
/**
* Build the rules, zones and links into real zones.
*
@ -744,8 +588,7 @@ public final class TzdbZoneRulesCompiler {
for (TZDBZone tzdbZone : tzdbZones) {
bld = tzdbZone.addToBuilder(bld, rules);
}
ZoneRules buildRules = bld.toRules(zoneId);
builtZones.put(zoneId, buildRules);
builtZones.put(zoneId, bld.toRules(zoneId));
}
// build aliases
@ -758,25 +601,25 @@ public final class TzdbZoneRulesCompiler {
printVerbose("Relinking alias " + aliasId + " to " + realId);
realRules = builtZones.get(realId);
if (realRules == null) {
throw new IllegalArgumentException("Alias '" + aliasId + "' links to invalid zone '" + realId + "' for '" + version + "'");
throw new IllegalArgumentException("Alias '" + aliasId + "' links to invalid zone '" + realId);
}
links.put(aliasId, realId);
}
builtZones.put(aliasId, realRules);
}
// remove UTC and GMT
//builtZones.remove("UTC");
//builtZones.remove("GMT");
//builtZones.remove("GMT0");
// builtZones.remove("UTC");
// builtZones.remove("GMT");
// builtZones.remove("GMT0");
builtZones.remove("GMT+0");
builtZones.remove("GMT-0");
links.remove("GMT+0");
links.remove("GMT-0");
// remove ROC, which is not supported in j.u.tz
builtZones.remove("ROC");
links.remove("ROC");
}
//-----------------------------------------------------------------------
/**
* Prints a verbose message.
*
@ -788,7 +631,6 @@ public final class TzdbZoneRulesCompiler {
}
}
//-----------------------------------------------------------------------
/**
* Class representing a month-day-time in the TZDB file.
*/
@ -893,5 +735,4 @@ public final class TzdbZoneRulesCompiler {
return ldt;
}
}
}

View File

@ -1213,7 +1213,6 @@ BUILD_LIBRARIES += $(BUILD_LIBJSDT)
##########################################################################################
ifdef OPENJDK
# TODO: Update awt lib path when awt is converted
$(eval $(call SetupNativeCompilation,BUILD_LIBLCMS,\
LIBRARY:=lcms,\
@ -1246,7 +1245,6 @@ ifdef OPENJDK
BUILD_LIBRARIES += $(BUILD_LIBLCMS)
$(BUILD_LIBLCMS) : $(BUILD_LIBAWT)
endif
##########################################################################################

View File

@ -174,6 +174,13 @@ $(LIBDIR)/calendars.properties: $(CALENDARS_SRC)/calendars.properties
COPY_FILES += $(LIBDIR)/calendars.properties
$(LIBDIR)/hijrah-config-umalqura.properties: $(CALENDARS_SRC)/hijrah-config-umalqura.properties
$(MKDIR) -p $(@D)
$(RM) $@
$(CP) $< $@
COPY_FILES += $(LIBDIR)/hijrah-config-umalqura.properties
##########################################################################################
ifeq ($(OPENJDK_TARGET_OS),windows)

View File

@ -185,10 +185,10 @@ SRC_SERVICES_FILES:=$(wildcard $(addsuffix /services/*,$(ALL_META-INF_DIRS)))
ifdef OPENJDK
SRC_SERVICES_FILES:=$(filter-out %sun/dc/META-INF/services/sun.java2d.pipe.RenderingEngine,$(SRC_SERVICES_FILES))
SRC_SERVICES_FILES:=$(filter-out %sun/java2d/cmm/kcms/META-INF/services/sun.java2d.cmm.PCMM,$(SRC_SERVICES_FILES))
SRC_SERVICES_FILES:=$(filter-out %sun/java2d/cmm/kcms/META-INF/services/sun.java2d.cmm.CMMServiceProvider,$(SRC_SERVICES_FILES))
else
SRC_SERVICES_FILES:=$(filter-out %sun/java2d/pisces/META-INF/services/sun.java2d.pipe.RenderingEngine,$(SRC_SERVICES_FILES))
SRC_SERVICES_FILES:=$(filter-out %sun/java2d/cmm/lcms/META-INF/services/sun.java2d.cmm.PCMM,$(SRC_SERVICES_FILES))
SRC_SERVICES_FILES:=$(filter-out %sun/java2d/cmm/lcms/META-INF/services/sun.java2d.cmm.CMMServiceProvider,$(SRC_SERVICES_FILES))
endif
# The number of services files are relatively few. If the increase in numbers, then

View File

@ -73,11 +73,6 @@ $(eval $(call SetupArchive,BUILD_DNS_JAR,,\
##########################################################################################
$(IMAGES_OUTPUTDIR)/lib/tzdb.jar: $(JDK_OUTPUTDIR)/lib/tzdb.jar
$(install-file)
##########################################################################################
LOCALEDATA_INCLUDE_LOCALES := ar be bg ca cs da de el es et fi fr ga hi hr hu in is it \
iw ja ko lt lv mk ms mt nl no pl pt ro ru sk sl sq sr sv \
th tr uk vi zh

View File

@ -29,16 +29,13 @@ GENDATA_TZDB :=
# Time zone data file creation
#
TZDATA_DIR := $(JDK_TOPDIR)/make/sun/javazic/tzdata
TZDATA_VER := $(subst tzdata,,$(shell $(GREP) '^tzdata' $(TZDATA_DIR)/VERSION))
TZDATA_TZFILE := africa antarctica asia australasia europe northamerica pacificnew southamerica backward etcetera gmt jdk11_backward
TZDATA_TZFILES := $(addprefix $(TZDATA_DIR)/,$(TZDATA_TZFILE))
GENDATA_TZDB_DST := $(JDK_OUTPUTDIR)/lib
GENDATA_TZDB_JAR := tzdb.jar
GENDATA_TZDB_DAT := $(JDK_OUTPUTDIR)/lib/tzdb.dat
$(GENDATA_TZDB_DST)/$(GENDATA_TZDB_JAR) : $(TZDATA_TZFILES)
$(RM) $(GENDATA_TZDB_DST)/$(GENDATA_TZDB_JAR)
echo building tzdb from version $(TZDATA_VER)
$(TOOL_TZDB) -version $(TZDATA_VER) -srcdir $(TZDATA_DIR) -dstdir $(GENDATA_TZDB_DST) $(TZDATA_TZFILE)
$(GENDATA_TZDB_DAT) : $(TZDATA_TZFILES)
$(RM) $(GENDATA_TZDB_DAT)
$(TOOL_TZDB) -srcdir $(TZDATA_DIR) -dstfile $(GENDATA_TZDB_DAT) $(TZDATA_TZFILE)
GENDATA_TZDB += $(GENDATA_TZDB_DST)/$(GENDATA_TZDB_JAR)
GENDATA_TZDB += $(GENDATA_TZDB_DAT)

View File

@ -134,7 +134,6 @@ SUNWprivate_1.1 {
Java_java_lang_ClassLoader_00024NativeLibrary_load;
Java_java_lang_ClassLoader_00024NativeLibrary_unload;
Java_java_lang_ClassLoader_00024NativeLibrary_findBuiltinLib;
Java_java_lang_ClassLoader_getCaller;
Java_java_lang_ClassLoader_registerNatives;
Java_java_lang_Compiler_registerNatives;
Java_java_lang_Double_longBitsToDouble;
@ -217,7 +216,7 @@ SUNWprivate_1.1 {
Java_java_lang_Throwable_fillInStackTrace;
Java_java_lang_Throwable_getStackTraceDepth;
Java_java_lang_Throwable_getStackTraceElement;
Java_java_lang_UNIXProcess_initIDs;
Java_java_lang_UNIXProcess_init;
Java_java_lang_UNIXProcess_waitForProcessExit;
Java_java_lang_UNIXProcess_forkAndExec;
Java_java_lang_UNIXProcess_destroyProcess;
@ -233,7 +232,6 @@ SUNWprivate_1.1 {
Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2Ljava_security_AccessControlContext_2;
Java_java_security_AccessController_getStackAccessControlContext;
Java_java_security_AccessController_getInheritedAccessControlContext;
Java_java_util_ResourceBundle_getClassContext;
Java_java_util_TimeZone_getSystemTimeZoneID;
Java_java_util_TimeZone_getSystemGMTOffsetID;
Java_java_util_concurrent_atomic_AtomicLong_VMSupportsCS8;

View File

@ -78,7 +78,6 @@ text: .text%writeBytes;
# Test Sleep
# Test IntToString
# Test LoadToolkit
text: .text%Java_java_util_ResourceBundle_getClassContext;
text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedAction_2Ljava_security_AccessControlContext_2;
text: .text%JNU_GetEnv;
text: .text%Java_java_io_UnixFileSystem_checkAccess;

View File

@ -74,7 +74,6 @@ text: .text%writeBytes;
# Test Sleep
# Test IntToString
# Test LoadToolkit
text: .text%Java_java_util_ResourceBundle_getClassContext;
text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedAction_2Ljava_security_AccessControlContext_2;
text: .text%JNU_GetEnv;
text: .text%Java_java_io_UnixFileSystem_checkAccess;

View File

@ -73,7 +73,6 @@ text: .text%writeBytes;
# Test Sleep
# Test IntToString
# Test LoadToolkit
text: .text%Java_java_util_ResourceBundle_getClassContext;
text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedAction_2Ljava_security_AccessControlContext_2;
text: .text%JNU_GetEnv;
text: .text%Java_java_io_UnixFileSystem_checkAccess;

View File

@ -66,6 +66,7 @@ PROFILE_1_JRE_LIB_FILES := \
ext/sunec.jar \
ext/sunjce_provider.jar \
ext/sunpkcs11.jar \
hijrah-config-umalqura.properties \
jce.jar \
jsse.jar \
logging.properties \
@ -80,7 +81,7 @@ PROFILE_1_JRE_LIB_FILES := \
security/java.security \
security/local_policy.jar \
security/trusted.libraries \
tzdb.jar
tzdb.dat
PROFILE_1_JRE_OTHER_FILES := \
COPYRIGHT \
@ -100,9 +101,7 @@ PROFILE_1_JRE_JAR_FILES := \
resources.jar \
rt.jar \
security/US_export_policy.jar \
security/local_policy.jar \
tzdb.jar
security/local_policy.jar
PROFILE_2_JRE_BIN_FILES := \
rmid$(EXE_SUFFIX) \

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 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
@ -41,15 +41,15 @@ import apple.laf.JRSUIUtils.NineSliceMetricsProvider;
abstract class AquaPainter <T extends JRSUIState> {
static <T extends JRSUIState> AquaPainter<T> create(final T state) {
return new AquaSingleImagePainter<T>(state);
return new AquaSingleImagePainter<>(state);
}
static <T extends JRSUIState> AquaPainter<T> create(final T state, final int minWidth, final int minHeight, final int westCut, final int eastCut, final int northCut, final int southCut) {
return AquaPainter.create(state, minWidth, minHeight, westCut, eastCut, northCut, southCut, true);
return create(state, minWidth, minHeight, westCut, eastCut, northCut, southCut, true);
}
static <T extends JRSUIState> AquaPainter<T> create(final T state, final int minWidth, final int minHeight, final int westCut, final int eastCut, final int northCut, final int southCut, final boolean useMiddle) {
return AquaPainter.create(state, minWidth, minHeight, westCut, eastCut, northCut, southCut, useMiddle, true, true);
return create(state, minWidth, minHeight, westCut, eastCut, northCut, southCut, useMiddle, true, true);
}
static <T extends JRSUIState> AquaPainter<T> create(final T state, final int minWidth, final int minHeight, final int westCut, final int eastCut, final int northCut, final int southCut, final boolean useMiddle, final boolean stretchHorizontally, final boolean stretchVertically) {
@ -65,7 +65,7 @@ abstract class AquaPainter <T extends JRSUIState> {
return new AquaNineSlicingImagePainter<>(state, metricsProvider);
}
abstract void paint(final Graphics2D g, final T stateToPaint, final Component c);
abstract void paint(Graphics2D g, T stateToPaint);
final Rectangle boundsRect = new Rectangle();
final JRSUIControl control;
@ -75,23 +75,26 @@ abstract class AquaPainter <T extends JRSUIState> {
this.state = state;
}
JRSUIControl getControl() {
control.set(state = (T)state.derive());
final JRSUIControl getControl() {
control.set(state = state.derive());
return control;
}
void paint(final Graphics g, final Component c, final int x, final int y, final int w, final int h) {
final void paint(final Graphics g, final Component c, final int x,
final int y, final int w, final int h) {
boundsRect.setBounds(x, y, w, h);
final T nextState = (T)state.derive();
final T nextState = state.derive();
final Graphics2D g2d = getGraphics2D(g);
if (g2d != null) paint(g2d, nextState, c);
if (g2d != null) paint(g2d, nextState);
state = nextState;
}
static class AquaNineSlicingImagePainter<T extends JRSUIState> extends AquaPainter<T> {
protected final HashMap<T, RecyclableJRSUISlicedImageControl> slicedControlImages;
protected final NineSliceMetricsProvider metricsProvider;
private static class AquaNineSlicingImagePainter<T extends JRSUIState>
extends AquaPainter<T> {
private final HashMap<T, RecyclableJRSUISlicedImageControl> slicedControlImages;
private final NineSliceMetricsProvider metricsProvider;
AquaNineSlicingImagePainter(final T state) {
this(state, null);
@ -104,9 +107,9 @@ abstract class AquaPainter <T extends JRSUIState> {
}
@Override
void paint(final Graphics2D g, final T stateToPaint, final Component c) {
void paint(final Graphics2D g, final T stateToPaint) {
if (metricsProvider == null) {
AquaSingleImagePainter.paintFromSingleCachedImage(g, control, stateToPaint, c, boundsRect);
AquaSingleImagePainter.paintFromSingleCachedImage(g, control, stateToPaint, boundsRect);
return;
}
@ -114,7 +117,7 @@ abstract class AquaPainter <T extends JRSUIState> {
if (slicesRef == null) {
final NineSliceMetrics metrics = metricsProvider.getNineSliceMetricsForState(stateToPaint);
if (metrics == null) {
AquaSingleImagePainter.paintFromSingleCachedImage(g, control, stateToPaint, c, boundsRect);
AquaSingleImagePainter.paintFromSingleCachedImage(g, control, stateToPaint, boundsRect);
return;
}
slicesRef = new RecyclableJRSUISlicedImageControl(control, stateToPaint, metrics);
@ -125,47 +128,55 @@ abstract class AquaPainter <T extends JRSUIState> {
}
}
static class AquaSingleImagePainter<T extends JRSUIState> extends AquaPainter<T> {
private static final class AquaSingleImagePainter<T extends JRSUIState>
extends AquaPainter<T> {
AquaSingleImagePainter(final T state) {
super(new JRSUIControl(false), state);
}
@Override
void paint(Graphics2D g, T stateToPaint, Component c) {
paintFromSingleCachedImage(g, control, stateToPaint, c, boundsRect);
void paint(final Graphics2D g, final T stateToPaint) {
paintFromSingleCachedImage(g, control, stateToPaint, boundsRect);
}
static void paintFromSingleCachedImage(final Graphics2D g, final JRSUIControl control, final JRSUIState controlState, final Component c, final Rectangle boundsRect) {
final Rectangle clipRect = g.getClipBounds();
final Rectangle intersection = boundsRect.intersection(clipRect);
if (intersection.width <= 0 || intersection.height <= 0) return;
final int imgX1 = intersection.x - boundsRect.x;
final int imgY1 = intersection.y - boundsRect.y;
static void paintFromSingleCachedImage(final Graphics2D g,
final JRSUIControl control, final JRSUIState controlState,
final Rectangle bounds) {
if (bounds.width <= 0 || bounds.height <= 0) {
return;
}
int scale = 1;
if (g instanceof SunGraphics2D) {
scale = ((SunGraphics2D) g).surfaceData.getDefaultScale();
}
final GraphicsConfiguration config = g.getDeviceConfiguration();
final ImageCache cache = ImageCache.getInstance();
BufferedImage image = (BufferedImage)cache.getImage(config, boundsRect.width, boundsRect.height, controlState);
if (image == null) {
image = new BufferedImage(boundsRect.width, boundsRect.height, BufferedImage.TYPE_INT_ARGB_PRE);
cache.setImage(image, config, boundsRect.width, boundsRect.height, controlState);
final WritableRaster raster = image.getRaster();
final DataBufferInt buffer = (DataBufferInt)raster.getDataBuffer();
final int imgW = bounds.width * scale;
final int imgH = bounds.height * scale;
BufferedImage img = (BufferedImage) cache.getImage(config, imgW, imgH, scale, controlState);
if (img == null) {
img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB_PRE);
cache.setImage(img, config, imgW, imgH, scale, controlState);
final WritableRaster raster = img.getRaster();
final DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
control.set(controlState);
control.paint(SunWritableRaster.stealData(buffer, 0),
image.getWidth(), image.getHeight(), 0, 0, boundsRect.width, boundsRect.height);
imgW, imgH, 0, 0, bounds.width, bounds.height);
SunWritableRaster.markDirty(buffer);
}
g.drawImage(image, intersection.x, intersection.y, intersection.x + intersection.width, intersection.y + intersection.height,
imgX1, imgY1, imgX1 + intersection.width, imgY1 + intersection.height, null);
g.drawImage(img, bounds.x, bounds.y, bounds.width, bounds.height, null);
}
}
static class RecyclableJRSUISlicedImageControl extends RecyclableSlicedImageControl {
final JRSUIControl control;
final JRSUIState state;
private static class RecyclableJRSUISlicedImageControl
extends RecyclableSlicedImageControl {
private final JRSUIControl control;
private final JRSUIState state;
RecyclableJRSUISlicedImageControl(final JRSUIControl control, final JRSUIState state, final NineSliceMetrics metrics) {
super(metrics);
@ -189,17 +200,19 @@ abstract class AquaPainter <T extends JRSUIState> {
}
}
protected Graphics2D getGraphics2D(final Graphics g) {
private Graphics2D getGraphics2D(final Graphics g) {
try {
return (SunGraphics2D)g; // doing a blind try is faster than checking instanceof
} catch (Exception e) {
} catch (Exception ignored) {
if (g instanceof PeekGraphics) {
// if it is a peek just dirty the region
g.fillRect(boundsRect.x, boundsRect.y, boundsRect.width, boundsRect.height);
} else if (g instanceof ProxyGraphics2D) {
final ProxyGraphics2D pg = (ProxyGraphics2D)g;
final Graphics2D g2d = pg.getDelegate();
if (g2d instanceof SunGraphics2D) { return (SunGraphics2D)g2d; }
if (g2d instanceof SunGraphics2D) {
return g2d;
}
} else if (g instanceof Graphics2D) {
return (Graphics2D) g;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 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
@ -81,16 +81,23 @@ final class ImageCache {
}
}
public Image getImage(final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
public Image getImage(final GraphicsConfiguration config, final int w,
final int h, final int scale,
final JRSUIState state) {
final int hash = hash(config, w, h, scale, state);
final PixelCountSoftReference ref;
lock.readLock().lock();
try {
final PixelCountSoftReference ref = map.get(hash(config, w, h, state));
// check reference has not been lost and the key truly matches, in case of false positive hash match
if (ref != null && ref.equals(config, w, h, state)) return ref.get();
return null;
ref = map.get(hash);
} finally {
lock.readLock().unlock();
}
// check reference has not been lost and the key truly matches,
// in case of false positive hash match
if (ref != null && ref.equals(config, w, h, scale, state)) {
return ref.get();
}
return null;
}
/**
@ -100,14 +107,17 @@ final class ImageCache {
* @param config The graphics configuration, needed if cached image is a Volatile Image. Used as part of cache key
* @param w The image width, used as part of cache key
* @param h The image height, used as part of cache key
* @param scale The image scale factor, used as part of cache key
* @return true if the image could be cached, false otherwise.
*/
public boolean setImage(final Image image, final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
public boolean setImage(final Image image,
final GraphicsConfiguration config, final int w, final int h,
final int scale, final JRSUIState state) {
if (state.is(JRSUIConstants.Animating.YES)) {
return false;
}
final int hash = hash(config, w, h, state);
final int hash = hash(config, w, h, scale, state);
lock.writeLock().lock();
try {
@ -145,44 +155,60 @@ final class ImageCache {
}
}
// finally put new in map
map.put(hash, new PixelCountSoftReference(image, referenceQueue, newPixelCount, hash, config, w, h, state));
map.put(hash, new PixelCountSoftReference(image, referenceQueue, newPixelCount, hash, config, w, h, scale, state));
return true;
} finally {
lock.writeLock().unlock();
}
}
private int hash(final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
int hash = (config != null ? config.hashCode() : 0);
private static int hash(final GraphicsConfiguration config, final int w,
final int h, final int scale,
final JRSUIState state) {
int hash = config != null ? config.hashCode() : 0;
hash = 31 * hash + w;
hash = 31 * hash + h;
hash = 31 * hash + scale;
hash = 31 * hash + state.hashCode();
return hash;
}
/** Extended SoftReference that stores the pixel count even after the image is lost */
/**
* Extended SoftReference that stores the pixel count even after the image
* is lost.
*/
private static class PixelCountSoftReference extends SoftReference<Image> {
private final int pixelCount;
private final int hash;
// default access, because access to these fields shouldn't be emulated
// by a synthetic accessor.
final int pixelCount;
final int hash;
// key parts
private final GraphicsConfiguration config;
private final int w;
private final int h;
private final int scale;
private final JRSUIState state;
PixelCountSoftReference(final Image referent, final ReferenceQueue<? super Image> q, final int pixelCount, final int hash, final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
PixelCountSoftReference(final Image referent,
final ReferenceQueue<? super Image> q, final int pixelCount,
final int hash, final GraphicsConfiguration config, final int w,
final int h, final int scale, final JRSUIState state) {
super(referent, q);
this.pixelCount = pixelCount;
this.hash = hash;
this.config = config;
this.w = w;
this.h = h;
this.scale = scale;
this.state = state;
}
public boolean equals(final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
return config == this.config && w == this.w && h == this.h && state.equals(this.state);
boolean equals(final GraphicsConfiguration config, final int w,
final int h, final int scale, final JRSUIState state) {
return config == this.config && w == this.w && h == this.h
&& scale == this.scale && state.equals(this.state);
}
}

View File

@ -219,6 +219,12 @@ public final class CGraphicsDevice extends GraphicsDevice {
return nativeGetDisplayModes(displayID);
}
public int getScaleFactor() {
return (int) nativeGetScaleFactor(displayID);
}
private static native double nativeGetScaleFactor(int displayID);
private static native void nativeSetDisplayMode(int displayID, int w, int h, int bpp, int refrate);
private static native DisplayMode nativeGetDisplayMode(int displayID);

View File

@ -441,29 +441,37 @@ public final class CGLGraphicsConfig extends CGraphicsConfig
@Override
public int getMaxTextureWidth() {
int width;
//Temporary disable this logic and use some magic constrain.
/*
int width;
synchronized (totalDisplayBounds) {
if (totalDisplayBounds.width == 0) {
updateTotalDisplayBounds();
}
width = totalDisplayBounds.width;
}
synchronized (totalDisplayBounds) {
if (totalDisplayBounds.width == 0) {
updateTotalDisplayBounds();
}
width = totalDisplayBounds.width;
}
return Math.min(width, getMaxTextureSize());
return Math.min(width, getMaxTextureSize());
*/
return getMaxTextureSize() / (getDevice().getScaleFactor() * 2);
}
@Override
public int getMaxTextureHeight() {
int height;
//Temporary disable this logic and use some magic constrain.
/*
int height;
synchronized (totalDisplayBounds) {
if (totalDisplayBounds.height == 0) {
updateTotalDisplayBounds();
}
height = totalDisplayBounds.height;
}
synchronized (totalDisplayBounds) {
if (totalDisplayBounds.height == 0) {
updateTotalDisplayBounds();
}
height = totalDisplayBounds.height;
}
return Math.min(height, getMaxTextureSize());
return Math.min(height, getMaxTextureSize());
*/
return getMaxTextureSize() / (getDevice().getScaleFactor() * 2);
}
}

View File

@ -40,11 +40,12 @@ import java.awt.Transparency;
public class CGLLayer extends CFRetainedResource {
private native long nativeCreateLayer();
private static native void nativeSetScale(long layerPtr, double scale);
private static native void validate(long layerPtr, CGLSurfaceData cglsd);
private static native void blitTexture(long layerPtr);
private LWWindowPeer peer;
private int scale = 1;
private SurfaceData surfaceData; // represents intermediate buffer (texture)
@ -90,7 +91,7 @@ public class CGLLayer extends CFRetainedResource {
// and blits the buffer to the layer surface (in drawInCGLContext callback)
CGraphicsConfig gc = (CGraphicsConfig)peer.getGraphicsConfiguration();
surfaceData = gc.createSurfaceData(this);
setScale(gc.getDevice().getScaleFactor());
// the layer holds a reference to the buffer, which in
// turn has a reference back to this layer
if (surfaceData instanceof CGLSurfaceData) {
@ -121,6 +122,13 @@ public class CGLLayer extends CFRetainedResource {
super.dispose();
}
private void setScale(final int _scale) {
if (scale != _scale) {
scale = _scale;
nativeSetScale(getPointer(), scale);
}
}
// ----------------------------------------------------------------------
// NATIVE CALLBACKS
// ----------------------------------------------------------------------

View File

@ -30,7 +30,6 @@ import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.image.ColorModel;
@ -41,6 +40,9 @@ import sun.lwawt.macosx.CPlatformView;
public abstract class CGLSurfaceData extends OGLSurfaceData {
protected final int scale;
protected final int width;
protected final int height;
protected CPlatformView pView;
private CGLGraphicsConfig graphicsConfig;
@ -52,10 +54,19 @@ public abstract class CGLSurfaceData extends OGLSurfaceData {
protected native boolean initPbuffer(long pData, long pConfigInfo,
boolean isOpaque, int width, int height);
protected CGLSurfaceData(CPlatformView pView, CGLGraphicsConfig gc,
ColorModel cm, int type)
{
protected CGLSurfaceData(CGLGraphicsConfig gc, ColorModel cm, int type,
int width, int height) {
super(gc, cm, type);
// TEXTURE shouldn't be scaled, it is used for managed BufferedImages.
scale = type == TEXTURE ? 1 : gc.getDevice().getScaleFactor();
this.width = width * scale;
this.height = height * scale;
}
protected CGLSurfaceData(CPlatformView pView, CGLGraphicsConfig gc,
ColorModel cm, int type,int width, int height)
{
this(gc, cm, type, width, height);
this.pView = pView;
this.graphicsConfig = gc;
@ -70,9 +81,9 @@ public abstract class CGLSurfaceData extends OGLSurfaceData {
}
protected CGLSurfaceData(CGLLayer layer, CGLGraphicsConfig gc,
ColorModel cm, int type)
ColorModel cm, int type,int width, int height)
{
super(gc, cm, type);
this(gc, cm, type, width, height);
this.graphicsConfig = gc;
long pConfigInfo = gc.getNativeConfigInfo();
@ -157,13 +168,43 @@ public abstract class CGLSurfaceData extends OGLSurfaceData {
// Overridden in CGLWindowSurfaceData below
}
@Override
public int getDefaultScale() {
return scale;
}
@Override
public boolean copyArea(SunGraphics2D sg2d, int x, int y, int w, int h,
int dx, int dy) {
final int state = sg2d.transformState;
if (state > SunGraphics2D.TRANSFORM_TRANSLATESCALE
|| sg2d.compositeState >= SunGraphics2D.COMP_XOR) {
return false;
}
if (state <= SunGraphics2D.TRANSFORM_ANY_TRANSLATE) {
x += sg2d.transX;
y += sg2d.transY;
} else if (state == SunGraphics2D.TRANSFORM_TRANSLATESCALE) {
final double[] coords = {x, y, x + w, y + h, x + dx, y + dy};
sg2d.transform.transform(coords, 0, coords, 0, 3);
x = (int) Math.ceil(coords[0] - 0.5);
y = (int) Math.ceil(coords[1] - 0.5);
w = ((int) Math.ceil(coords[2] - 0.5)) - x;
h = ((int) Math.ceil(coords[3] - 0.5)) - y;
dx = ((int) Math.ceil(coords[4] - 0.5)) - x;
dy = ((int) Math.ceil(coords[5] - 0.5)) - y;
}
oglRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy);
return true;
}
protected native void clearWindow();
public static class CGLWindowSurfaceData extends CGLSurfaceData {
public CGLWindowSurfaceData(CPlatformView pView,
CGLGraphicsConfig gc) {
super(pView, gc, gc.getColorModel(), WINDOW);
super(pView, gc, gc.getColorModel(), WINDOW, 0, 0);
}
@Override
@ -217,17 +258,12 @@ public abstract class CGLSurfaceData extends OGLSurfaceData {
public static class CGLLayerSurfaceData extends CGLSurfaceData {
private CGLLayer layer;
private int width, height;
public CGLLayerSurfaceData(CGLLayer layer, CGLGraphicsConfig gc,
int width, int height) {
super(layer, gc, gc.getColorModel(), FBOBJECT);
this.width = width;
this.height = height;
super(layer, gc, gc.getColorModel(), FBOBJECT, width, height);
this.layer = layer;
initSurface(width, height);
initSurface(this.width, this.height);
}
@Override
@ -296,18 +332,13 @@ public abstract class CGLSurfaceData extends OGLSurfaceData {
public static class CGLOffScreenSurfaceData extends CGLSurfaceData {
private Image offscreenImage;
private int width, height;
public CGLOffScreenSurfaceData(CPlatformView pView,
CGLGraphicsConfig gc, int width, int height, Image image,
ColorModel cm, int type) {
super(pView, gc, cm, type);
this.width = width;
this.height = height;
super(pView, gc, cm, type, width, height);
offscreenImage = image;
initSurface(width, height);
initSurface(this.width, this.height);
}
@Override

View File

@ -463,35 +463,8 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
private void applyConstrain(final Graphics g) {
final SunGraphics2D sg2d = (SunGraphics2D) g;
final Rectangle constr = localToWindow(getSize());
// translate and set rectangle constrain.
sg2d.constrain(constr.x, constr.y, constr.width, constr.height);
// set region constrain.
//sg2d.constrain(getVisibleRegion());
SG2DConstraint(sg2d, getVisibleRegion());
}
//TODO Move this method to SG2D?
void SG2DConstraint(final SunGraphics2D sg2d, Region r) {
sg2d.constrainX = sg2d.transX;
sg2d.constrainY = sg2d.transY;
Region c = sg2d.constrainClip;
if ((sg2d.constrainX | sg2d.constrainY) != 0) {
r = r.getTranslatedRegion(sg2d.constrainX, sg2d.constrainY);
}
if (c == null) {
c = r;
} else {
c = c.getIntersection(r);
if (c == sg2d.constrainClip) {
// Common case to ignore
return;
}
}
sg2d.constrainClip = c;
//validateCompClip() forced call.
sg2d.setDevClip(r.getLoX(), r.getLoY(), r.getWidth(), r.getHeight());
final Rectangle size = localToWindow(getSize());
sg2d.constrain(size.x, size.y, size.width, size.height, getVisibleRegion());
}
public Region getVisibleRegion() {

View File

@ -170,7 +170,7 @@ public class LWWindowPeer
setTitle(((Dialog) getTarget()).getTitle());
}
setAlwaysOnTop(getTarget().isAlwaysOnTop());
updateAlwaysOnTopState();
updateMinimumSize();
final Shape shape = getTarget().getShape();
@ -357,8 +357,8 @@ public class LWWindowPeer
}
@Override
public void setAlwaysOnTop(boolean value) {
platformWindow.setAlwaysOnTop(value);
public void updateAlwaysOnTopState() {
platformWindow.setAlwaysOnTop(getTarget().isAlwaysOnTop());
}
@Override
@ -580,17 +580,16 @@ public class LWWindowPeer
setBounds(x, y, w, h, SET_BOUNDS, false, false);
// Second, update the graphics config and surface data
checkIfOnNewScreen();
if (resized) {
final boolean isNewDevice = updateGraphicsDevice();
if (resized || isNewDevice) {
replaceSurfaceData();
flushOnscreenGraphics();
}
// Third, COMPONENT_MOVED/COMPONENT_RESIZED/PAINT events
if (moved || invalid) {
handleMove(x, y, true);
}
if (resized || invalid) {
if (resized || invalid || isNewDevice) {
handleResize(w, h, true);
repaintPeer();
}
@ -610,7 +609,7 @@ public class LWWindowPeer
}
if (!isTextured()) {
if (g instanceof SunGraphics2D) {
SG2DConstraint((SunGraphics2D) g, getRegion());
((SunGraphics2D) g).constrain(0, 0, w, h, getRegion());
}
g.setColor(getBackground());
g.fillRect(0, 0, w, h);
@ -922,7 +921,7 @@ public class LWWindowPeer
}
// If window's graphics config is changed from the app code, the
// config correspond to the same device as before; when the window
// is moved by user, graphicsDevice is updated in checkIfOnNewScreen().
// is moved by user, graphicsDevice is updated in notifyReshape().
// In either case, there's nothing to do with screenOn here
graphicsConfig = gc;
}
@ -930,11 +929,14 @@ public class LWWindowPeer
return true;
}
private void checkIfOnNewScreen() {
/**
* Returns true if the GraphicsDevice has been changed, false otherwise.
*/
public boolean updateGraphicsDevice() {
GraphicsDevice newGraphicsDevice = platformWindow.getGraphicsDevice();
synchronized (getStateLock()) {
if (graphicsDevice == newGraphicsDevice) {
return;
return false;
}
graphicsDevice = newGraphicsDevice;
}
@ -942,13 +944,14 @@ public class LWWindowPeer
// TODO: DisplayChangedListener stuff
final GraphicsConfiguration newGC = newGraphicsDevice.getDefaultConfiguration();
if (!setGraphicsConfig(newGC)) return;
if (!setGraphicsConfig(newGC)) return false;
SunToolkit.executeOnEventHandlerThread(getTarget(), new Runnable() {
public void run() {
AWTAccessor.getComponentAccessor().setGraphicsConfiguration(getTarget(), newGC);
}
});
return true;
}
/*
@ -983,6 +986,7 @@ public class LWWindowPeer
oldData.flush();
}
}
flushOnscreenGraphics();
}
private void blitSurfaceData(final SurfaceData src, final SurfaceData dst) {
@ -990,14 +994,15 @@ public class LWWindowPeer
if (src != dst && src != null && dst != null
&& !(dst instanceof NullSurfaceData)
&& !(src instanceof NullSurfaceData)
&& src.getSurfaceType().equals(dst.getSurfaceType())) {
final Rectangle size = getSize();
&& src.getSurfaceType().equals(dst.getSurfaceType())
&& src.getDefaultScale() == dst.getDefaultScale()) {
final Rectangle size = src.getBounds();
final Blit blit = Blit.locate(src.getSurfaceType(),
CompositeType.Src,
dst.getSurfaceType());
if (blit != null) {
blit.Blit(src, dst, AlphaComposite.Src,
getRegion(), 0, 0, 0, 0, size.width, size.height);
blit.Blit(src, dst, AlphaComposite.Src, null, 0, 0, 0, 0,
size.width, size.height);
}
}
}
@ -1152,7 +1157,9 @@ public class LWWindowPeer
if (!becomesFocused &&
(isGrabbing() || getOwnerFrameDialog(grabbingWindow) == this))
{
focusLog.fine("ungrabbing on " + grabbingWindow);
if (focusLog.isLoggable(PlatformLogger.FINE)) {
focusLog.fine("ungrabbing on " + grabbingWindow);
}
// ungrab a simple window if its owner looses activation.
grabbingWindow.ungrab();
}

View File

@ -97,13 +97,7 @@ public class CEmbeddedFrame extends EmbeddedFrame {
public void handleKeyEvent(int eventType, int modifierFlags, String characters,
String charsIgnoringMods, boolean isRepeat, short keyCode,
boolean needsKeyTyped) {
responder.handleKeyEvent(eventType, modifierFlags, charsIgnoringMods, keyCode, needsKeyTyped);
}
// REMIND: delete this method once 'deploy' changes for 7156194 is pushed
public void handleKeyEvent(int eventType, int modifierFlags, String characters,
String charsIgnoringMods, boolean isRepeat, short keyCode) {
handleKeyEvent(eventType, modifierFlags, characters, charsIgnoringMods, isRepeat, keyCode, true);
responder.handleKeyEvent(eventType, modifierFlags, charsIgnoringMods, keyCode, needsKeyTyped, isRepeat);
}
public void handleInputEvent(String text) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 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
@ -180,7 +180,7 @@ class CFileDialog implements FileDialogPeer {
}
@Override
public void setAlwaysOnTop(boolean alwaysOnTop) {
public void updateAlwaysOnTopState() {
}
@Override

View File

@ -41,6 +41,7 @@ final class CPlatformResponder {
private final LWWindowPeer peer;
private final boolean isNpapiCallback;
private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
CPlatformResponder(final LWWindowPeer peer, final boolean isNpapiCallback) {
this.peer = peer;
@ -123,7 +124,7 @@ final class CPlatformResponder {
* Handles key events.
*/
void handleKeyEvent(int eventType, int modifierFlags, String chars,
short keyCode, boolean needsKeyTyped) {
short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) {
boolean isFlagsChangedEvent =
isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) :
(eventType == CocoaConstants.NSFlagsChanged);
@ -183,6 +184,9 @@ final class CPlatformResponder {
int jmodifiers = NSEvent.nsToJavaKeyModifiers(modifierFlags);
long when = System.currentTimeMillis();
if (jeventType == KeyEvent.KEY_PRESSED) {
lastKeyPressCode = jkeyCode;
}
peer.dispatchKeyEvent(jeventType, when, jmodifiers,
jkeyCode, javaChar, jkeyLocation);
@ -195,26 +199,41 @@ final class CPlatformResponder {
// Modifier keys (shift, etc) don't want to send TYPED events.
// On the other hand we don't want to generate keyTyped events
// for clipboard related shortcuts like Meta + [CVX]
boolean isMetaDown = (jmodifiers & KeyEvent.META_DOWN_MASK) != 0;
if (jeventType == KeyEvent.KEY_PRESSED && postsTyped && !isMetaDown) {
if (jeventType == KeyEvent.KEY_PRESSED && postsTyped &&
(jmodifiers & KeyEvent.META_DOWN_MASK) == 0) {
// Enter and Space keys finish the input method processing,
// KEY_TYPED and KEY_RELEASED events for them are synthesized in handleInputEvent.
if (needsKeyReleased && (jkeyCode == KeyEvent.VK_ENTER || jkeyCode == KeyEvent.VK_SPACE)) {
return;
}
peer.dispatchKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
KeyEvent.VK_UNDEFINED, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN);
//If events come from Firefox, released events should also be generated.
if (needsKeyReleased) {
peer.dispatchKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
jkeyCode, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN);
}
}
}
void handleInputEvent(String text) {
if (text != null) {
int index = 0, length = text.length();
char c;
char c = 0;
while (index < length) {
c = text.charAt(index);
peer.dispatchKeyEvent(KeyEvent.KEY_TYPED,
System.currentTimeMillis(),
0, KeyEvent.VK_UNDEFINED, c,
KeyEvent.KEY_LOCATION_UNKNOWN);
System.currentTimeMillis(),
0, KeyEvent.VK_UNDEFINED, c,
KeyEvent.KEY_LOCATION_UNKNOWN);
index++;
}
peer.dispatchKeyEvent(KeyEvent.KEY_RELEASED,
System.currentTimeMillis(),
0, lastKeyPressCode, c,
KeyEvent.KEY_LOCATION_UNKNOWN);
}
}

View File

@ -202,7 +202,7 @@ public class CPlatformView extends CFRetainedResource {
private void deliverKeyEvent(NSEvent event) {
responder.handleKeyEvent(event.getType(), event.getModifierFlags(),
event.getCharactersIgnoringModifiers(), event.getKeyCode(), true);
event.getCharactersIgnoringModifiers(), event.getKeyCode(), true, false);
}
/**

View File

@ -860,8 +860,8 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
}
}
private void flushBuffers() {
if (isVisible() && !nativeBounds.isEmpty()) {
void flushBuffers() {
if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
try {
LWCToolkit.invokeAndWait(new Runnable() {
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 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
@ -87,7 +87,7 @@ public class CPrinterDialogPeer extends LWWindowPeer {
}
// 1.6 peer method
public void setAlwaysOnTop(boolean value) {
public void updateAlwaysOnTopState() {
// no-op, since we just show the native print dialog
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 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
@ -199,6 +199,7 @@ static inline jint doPaintImage
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef cgRef = CGBitmapContextCreate(rawPixelData, imgW, imgH, 8, imgW * 4, colorspace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host);
CGColorSpaceRelease(colorspace);
CGContextScaleCTM(cgRef, imgW/w , imgH/h);
jint status = doPaintCGContext(cgRef, controlPtr, oldProperties, newProperties, x, y, w, h);
CGContextRelease(cgRef);

View File

@ -315,3 +315,34 @@ Java_sun_awt_CGraphicsDevice_nativeGetDisplayModes
return jreturnArray;
}
/*
* Class: sun_awt_CGraphicsDevice
* Method: nativeGetScaleFactor
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_sun_awt_CGraphicsDevice_nativeGetScaleFactor
(JNIEnv *env, jclass class, jint displayID)
{
__block jdouble ret = 1.0f;
JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
NSArray *screens = [NSScreen screens];
for (NSScreen *screen in screens) {
NSDictionary *screenInfo = [screen deviceDescription];
NSNumber *screenID = [screenInfo objectForKey:@"NSScreenNumber"];
if ([screenID pointerValue] == displayID){
if ([screen respondsToSelector:@selector(backingScaleFactor)]) {
ret = [screen backingScaleFactor];
}
break;
}
}
}];
JNF_COCOA_EXIT(env);
return ret;
}

View File

@ -61,6 +61,19 @@ AWT_ASSERT_APPKIT_THREAD;
//Layer backed view
//self.needsDisplayOnBoundsChange = YES;
//self.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
//Disable CALayer's default animation
NSMutableDictionary * actions = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
[NSNull null], @"bounds",
[NSNull null], @"contents",
[NSNull null], @"contentsScale",
[NSNull null], @"onOrderIn",
[NSNull null], @"onOrderOut",
[NSNull null], @"sublayers",
nil];
self.actions = actions;
[actions release];
textureID = 0; // texture will be created by rendering pipe
target = 0;
@ -121,8 +134,12 @@ AWT_ASSERT_APPKIT_THREAD;
// Set the current context to the one given to us.
CGLSetCurrentContext(glContext);
glViewport(0, 0, textureWidth, textureHeight);
// Should clear the whole CALayer, because it can be larger than our texture.
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, textureWidth, textureHeight);
JNIEnv *env = [ThreadUtilities getJNIEnv];
static JNF_CLASS_CACHE(jc_JavaLayer, "sun/java2d/opengl/CGLLayer");
static JNF_MEMBER_CACHE(jm_drawInCGLContext, jc_JavaLayer, "drawInCGLContext", "()V");
@ -168,7 +185,7 @@ JNF_COCOA_EXIT(env);
// Must be called under the RQ lock.
JNIEXPORT void JNICALL
Java_sun_java2d_opengl_CGLLayer_validate
(JNIEnv *env, jobject obj, jlong layerPtr, jobject surfaceData)
(JNIEnv *env, jclass cls, jlong layerPtr, jobject surfaceData)
{
CGLLayer *layer = OBJC(layerPtr);
@ -186,9 +203,21 @@ Java_sun_java2d_opengl_CGLLayer_validate
// Must be called on the AppKit thread and under the RQ lock.
JNIEXPORT void JNICALL
Java_sun_java2d_opengl_CGLLayer_blitTexture
(JNIEnv *env, jobject obj, jlong layerPtr)
(JNIEnv *env, jclass cls, jlong layerPtr)
{
CGLLayer *layer = jlong_to_ptr(layerPtr);
[layer blitTexture];
}
JNIEXPORT void JNICALL
Java_sun_java2d_opengl_CGLLayer_nativeSetScale
(JNIEnv *env, jclass cls, jlong layerPtr, jdouble scale)
{
JNF_COCOA_ENTER(env);
CGLLayer *layer = jlong_to_ptr(layerPtr);
[ThreadUtilities performOnMainThreadWaiting:NO block:^(){
layer.contentsScale = scale;
}];
JNF_COCOA_EXIT(env);
}

View File

@ -426,17 +426,13 @@ final class CipherCore {
}
}
try {
params = AlgorithmParameters.getInstance(algName, "SunJCE");
params = AlgorithmParameters.getInstance(algName,
SunJCE.getInstance());
params.init(spec);
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("Cannot find " + algName +
" AlgorithmParameters implementation in SunJCE provider");
} catch (NoSuchProviderException nspe) {
// should never happen
throw new RuntimeException("Cannot find SunJCE provider");
}
try {
params.init(spec);
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException(spec.getClass() + " not supported");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 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
@ -169,7 +169,8 @@ public abstract class CipherWithWrappingSpi extends CipherSpi {
try {
KeyFactory keyFactory =
KeyFactory.getInstance(encodedKeyAlgorithm, "SunJCE");
KeyFactory.getInstance(encodedKeyAlgorithm,
SunJCE.getInstance());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
key = keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException nsae) {
@ -191,8 +192,6 @@ public abstract class CipherWithWrappingSpi extends CipherSpi {
}
} catch (InvalidKeySpecException ikse) {
// Should never happen.
} catch (NoSuchProviderException nspe) {
// Should never happen.
}
return key;
@ -215,7 +214,8 @@ public abstract class CipherWithWrappingSpi extends CipherSpi {
try {
KeyFactory keyFactory =
KeyFactory.getInstance(encodedKeyAlgorithm, "SunJCE");
KeyFactory.getInstance(encodedKeyAlgorithm,
SunJCE.getInstance());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException nsae) {
@ -237,8 +237,6 @@ public abstract class CipherWithWrappingSpi extends CipherSpi {
}
} catch (InvalidKeySpecException ikse) {
// Should never happen.
} catch (NoSuchProviderException nspe) {
// Should never happen.
}
return key;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 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
@ -30,7 +30,6 @@ import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.KeyFactory;
import java.security.InvalidKeyException;
import java.security.NoSuchProviderException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
@ -66,7 +65,8 @@ final class ConstructKeys {
try {
KeyFactory keyFactory =
KeyFactory.getInstance(encodedKeyAlgorithm, "SunJCE");
KeyFactory.getInstance(encodedKeyAlgorithm,
SunJCE.getInstance());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
key = keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException nsae) {
@ -94,8 +94,6 @@ final class ConstructKeys {
new InvalidKeyException("Cannot construct public key");
ike.initCause(ikse);
throw ike;
} catch (NoSuchProviderException nspe) {
// Should never happen.
}
return key;
@ -118,7 +116,8 @@ final class ConstructKeys {
try {
KeyFactory keyFactory =
KeyFactory.getInstance(encodedKeyAlgorithm, "SunJCE");
KeyFactory.getInstance(encodedKeyAlgorithm,
SunJCE.getInstance());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException nsae) {
@ -146,8 +145,6 @@ final class ConstructKeys {
new InvalidKeyException("Cannot construct private key");
ike.initCause(ikse);
throw ike;
} catch (NoSuchProviderException nspe) {
// Should never happen.
}
return key;

View File

@ -389,17 +389,13 @@ public final class DESedeWrapCipher extends CipherSpi {
if (iv != null) {
String algo = cipherKey.getAlgorithm();
try {
params = AlgorithmParameters.getInstance(algo, "SunJCE");
params = AlgorithmParameters.getInstance(algo,
SunJCE.getInstance());
params.init(new IvParameterSpec(iv));
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("Cannot find " + algo +
" AlgorithmParameters implementation in SunJCE provider");
} catch (NoSuchProviderException nspe) {
// should never happen
throw new RuntimeException("Cannot find SunJCE provider");
}
try {
params.init(new IvParameterSpec(iv));
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("IvParameterSpec not supported");

View File

@ -151,7 +151,8 @@ extends AlgorithmParameterGeneratorSpi {
dhParamSpec = new DHParameterSpec(dsaParamSpec.getP(),
dsaParamSpec.getG());
}
algParams = AlgorithmParameters.getInstance("DH", "SunJCE");
algParams = AlgorithmParameters.getInstance("DH",
SunJCE.getInstance());
algParams.init(dhParamSpec);
} catch (InvalidParameterSpecException e) {
// this should never happen
@ -159,11 +160,7 @@ extends AlgorithmParameterGeneratorSpi {
} catch (NoSuchAlgorithmException e) {
// this should never happen, because we provide it
throw new RuntimeException(e.getMessage());
} catch (NoSuchProviderException e) {
// this should never happen, because we provide it
throw new RuntimeException(e.getMessage());
}
return algParams;
}
}

View File

@ -81,8 +81,6 @@ final class KeyProtector {
// key protector
private char[] password;
private static final Provider PROV = Security.getProvider("SunJCE");
KeyProtector(char[] password) {
if (password == null) {
throw new IllegalArgumentException("password can't be null");
@ -119,7 +117,7 @@ final class KeyProtector {
// wrap encrypted private key in EncryptedPrivateKeyInfo
// (as defined in PKCS#8)
AlgorithmParameters pbeParams =
AlgorithmParameters.getInstance("PBE", PROV);
AlgorithmParameters.getInstance("PBE", SunJCE.getInstance());
pbeParams.init(pbeSpec);
AlgorithmId encrAlg = new AlgorithmId
@ -299,7 +297,7 @@ final class KeyProtector {
PBEWithMD5AndTripleDESCipher cipherSpi;
cipherSpi = new PBEWithMD5AndTripleDESCipher();
cipher = new CipherForKeyProtector(cipherSpi, PROV,
cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
"PBEWithMD5AndTripleDES");
cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
return new SealedObjectForKeyProtector(key, cipher);
@ -330,8 +328,9 @@ final class KeyProtector {
}
PBEWithMD5AndTripleDESCipher cipherSpi;
cipherSpi = new PBEWithMD5AndTripleDESCipher();
Cipher cipher = new CipherForKeyProtector(cipherSpi, PROV,
"PBEWithMD5AndTripleDES");
Cipher cipher = new CipherForKeyProtector(cipherSpi,
SunJCE.getInstance(),
"PBEWithMD5AndTripleDES");
cipher.init(Cipher.DECRYPT_MODE, skey, params);
return (Key)soForKeyProtector.getObject(cipher);
} catch (NoSuchAlgorithmException ex) {

View File

@ -169,16 +169,12 @@ final class PBECipherCore {
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount);
try {
params = AlgorithmParameters.getInstance("PBEWithMD5And" +
(algo.equalsIgnoreCase("DES")? "DES":"TripleDES"), "SunJCE");
(algo.equalsIgnoreCase("DES")? "DES":"TripleDES"),
SunJCE.getInstance());
params.init(pbeSpec);
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("SunJCE called, but not configured");
} catch (NoSuchProviderException nspe) {
// should never happen
throw new RuntimeException("SunJCE called, but not configured");
}
try {
params.init(pbeSpec);
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("PBEParameterSpec not supported");

View File

@ -169,16 +169,12 @@ final class PBES1Core {
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount);
try {
params = AlgorithmParameters.getInstance("PBEWithMD5And" +
(algo.equalsIgnoreCase("DES")? "DES":"TripleDES"), "SunJCE");
(algo.equalsIgnoreCase("DES")? "DES":"TripleDES"),
SunJCE.getInstance());
params.init(pbeSpec);
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("SunJCE called, but not configured");
} catch (NoSuchProviderException nspe) {
// should never happen
throw new RuntimeException("SunJCE called, but not configured");
}
try {
params.init(pbeSpec);
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("PBEParameterSpec not supported");

View File

@ -25,11 +25,9 @@
package com.sun.crypto.provider;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.interfaces.*;
import javax.crypto.spec.*;
/**
@ -145,16 +143,12 @@ abstract class PBES2Core extends CipherSpi {
}
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount, ivSpec);
try {
params = AlgorithmParameters.getInstance(pbeAlgo, "SunJCE");
params = AlgorithmParameters.getInstance(pbeAlgo,
SunJCE.getInstance());
params.init(pbeSpec);
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("SunJCE called, but not configured");
} catch (NoSuchProviderException nspe) {
// should never happen
throw new RuntimeException("SunJCE called, but not configured");
}
try {
params.init(pbeSpec);
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("PBEParameterSpec not supported");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
@ -33,7 +33,6 @@ import java.util.Arrays;
import java.security.KeyRep;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
@ -102,21 +101,16 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey {
int keyLength = keySpec.getKeyLength();
if (keyLength == 0) {
throw new InvalidKeySpecException("Key length not found");
} else if (keyLength == 0) {
} else if (keyLength < 0) {
throw new InvalidKeySpecException("Key length is negative");
}
try {
this.prf = Mac.getInstance(prfAlgo, "SunJCE");
this.prf = Mac.getInstance(prfAlgo, SunJCE.getInstance());
} catch (NoSuchAlgorithmException nsae) {
// not gonna happen; re-throw just in case
InvalidKeySpecException ike = new InvalidKeySpecException();
ike.initCause(nsae);
throw ike;
} catch (NoSuchProviderException nspe) {
// Again, not gonna happen; re-throw just in case
InvalidKeySpecException ike = new InvalidKeySpecException();
ike.initCause(nspe);
throw ike;
}
this.key = deriveKey(prf, passwdBytes, salt, iterCount, keyLength);
}

View File

@ -25,7 +25,6 @@
package com.sun.crypto.provider;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
@ -232,14 +231,13 @@ final class PKCS12PBECipherCore {
}
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount);
try {
params = AlgorithmParameters.getInstance(pbeAlgo, "SunJCE");
} catch (GeneralSecurityException gse) {
params = AlgorithmParameters.getInstance(pbeAlgo,
SunJCE.getInstance());
params.init(pbeSpec);
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException(
"SunJCE provider is not configured properly");
}
try {
params.init(pbeSpec);
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("PBEParameterSpec not supported");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
@ -178,16 +178,14 @@ public final class RSACipher extends CipherSpi {
if (spec != null) {
try {
AlgorithmParameters params =
AlgorithmParameters.getInstance("OAEP", "SunJCE");
AlgorithmParameters.getInstance("OAEP",
SunJCE.getInstance());
params.init(spec);
return params;
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("Cannot find OAEP " +
" AlgorithmParameters implementation in SunJCE provider");
} catch (NoSuchProviderException nspe) {
// should never happen
throw new RuntimeException("Cannot find SunJCE provider");
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("OAEPParameterSpec not supported");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 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
@ -46,14 +46,15 @@ final class SealedObjectForKeyProtector extends SealedObject {
AlgorithmParameters params = null;
if (super.encodedParams != null) {
try {
params = AlgorithmParameters.getInstance("PBE", "SunJCE");
params = AlgorithmParameters.getInstance("PBE",
SunJCE.getInstance());
params.init(super.encodedParams);
} catch (NoSuchProviderException nspe) {
// eat.
} catch (NoSuchAlgorithmException nsae) {
//eat.
} catch (IOException ioe) {
//eat.
throw new RuntimeException(
"SunJCE provider is not configured properly");
} catch (IOException io) {
throw new RuntimeException("Parameter failure: "+
io.getMessage());
}
}
return params;

View File

@ -91,6 +91,10 @@ public final class SunJCE extends Provider {
/* Are we debugging? -- for developers */
static final boolean debug = false;
// Instance of this provider, so we don't have to call the provider list
// to find ourselves or run the risk of not being in the list.
private static volatile SunJCE instance = null;
// lazy initialize SecureRandom to avoid potential recursion if Sun
// provider has not been installed yet
private static class SecureRandomHolder {
@ -770,5 +774,17 @@ public final class SunJCE extends Provider {
return null;
}
});
if (instance == null) {
instance = this;
}
}
// Return the instance of this class or create one if needed.
static SunJCE getInstance() {
if (instance == null) {
return new SunJCE();
}
return instance;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
@ -165,16 +165,18 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
// partition keyblock into individual secrets
int ofs = 0;
byte[] tmp = new byte[macLength];
if (macLength != 0) {
byte[] tmp = new byte[macLength];
// mac keys
System.arraycopy(keyBlock, ofs, tmp, 0, macLength);
ofs += macLength;
clientMacKey = new SecretKeySpec(tmp, "Mac");
// mac keys
System.arraycopy(keyBlock, ofs, tmp, 0, macLength);
ofs += macLength;
clientMacKey = new SecretKeySpec(tmp, "Mac");
System.arraycopy(keyBlock, ofs, tmp, 0, macLength);
ofs += macLength;
serverMacKey = new SecretKeySpec(tmp, "Mac");
System.arraycopy(keyBlock, ofs, tmp, 0, macLength);
ofs += macLength;
serverMacKey = new SecretKeySpec(tmp, "Mac");
}
if (keyLength == 0) { // SSL_RSA_WITH_NULL_* ciphersuites
return new TlsKeyMaterialSpec(clientMacKey, serverMacKey);
@ -198,7 +200,7 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
// IV keys if needed.
if (ivLength != 0) {
tmp = new byte[ivLength];
byte[] tmp = new byte[ivLength];
System.arraycopy(keyBlock, ofs, tmp, 0, ivLength);
ofs += ivLength;
@ -220,8 +222,8 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
// TLS 1.0
byte[] seed = concat(clientRandom, serverRandom);
tmp = doTLS10PRF(clientKeyBytes, LABEL_CLIENT_WRITE_KEY, seed,
expandedKeyLength, md5, sha);
byte[] tmp = doTLS10PRF(clientKeyBytes,
LABEL_CLIENT_WRITE_KEY, seed, expandedKeyLength, md5, sha);
clientCipherKey = new SecretKeySpec(tmp, alg);
tmp = doTLS10PRF(serverKeyBytes, LABEL_SERVER_WRITE_KEY, seed,
@ -239,7 +241,7 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
}
} else {
// SSLv3
tmp = new byte[expandedKeyLength];
byte[] tmp = new byte[expandedKeyLength];
md5.update(clientKeyBytes);
md5.update(clientRandom);

View File

@ -243,12 +243,17 @@ public class JPEGImageReader extends ImageReader {
* sending warnings to listeners.
*/
protected void warningOccurred(int code) {
if ((code < 0) || (code > MAX_WARNING)){
throw new InternalError("Invalid warning index");
cbLock.lock();
try {
if ((code < 0) || (code > MAX_WARNING)){
throw new InternalError("Invalid warning index");
}
processWarningOccurred
("com.sun.imageio.plugins.jpeg.JPEGImageReaderResources",
Integer.toString(code));
} finally {
cbLock.unlock();
}
processWarningOccurred
("com.sun.imageio.plugins.jpeg.JPEGImageReaderResources",
Integer.toString(code));
}
/**
@ -265,7 +270,12 @@ public class JPEGImageReader extends ImageReader {
* library warnings from being printed to stderr.
*/
protected void warningWithMessage(String msg) {
processWarningOccurred(msg);
cbLock.lock();
try {
processWarningOccurred(msg);
} finally {
cbLock.unlock();
}
}
public void setInput(Object input,
@ -274,18 +284,55 @@ public class JPEGImageReader extends ImageReader {
{
setThreadLock();
try {
cbLock.check();
super.setInput(input, seekForwardOnly, ignoreMetadata);
this.ignoreMetadata = ignoreMetadata;
resetInternalState();
iis = (ImageInputStream) input; // Always works
setSource(structPointer, iis);
setSource(structPointer);
} finally {
clearThreadLock();
}
}
private native void setSource(long structPointer,
ImageInputStream source);
/**
* This method is called from native code in order to fill
* native input buffer.
*
* We block any attempt to change the reading state during this
* method, in order to prevent a corruption of the native decoder
* state.
*
* @return number of bytes read from the stream.
*/
private int readInputData(byte[] buf, int off, int len) throws IOException {
cbLock.lock();
try {
return iis.read(buf, off, len);
} finally {
cbLock.unlock();
}
}
/**
* This method is called from the native code in order to
* skip requested number of bytes in the input stream.
*
* @param n
* @return
* @throws IOException
*/
private long skipInputBytes(long n) throws IOException {
cbLock.lock();
try {
return iis.skipBytes(n);
} finally {
cbLock.unlock();
}
}
private native void setSource(long structPointer);
private void checkTablesOnly() throws IOException {
if (debug) {
@ -337,6 +384,8 @@ public class JPEGImageReader extends ImageReader {
public int getNumImages(boolean allowSearch) throws IOException {
setThreadLock();
try { // locked thread
cbLock.check();
return getNumImagesOnThread(allowSearch);
} finally {
clearThreadLock();
@ -536,8 +585,13 @@ public class JPEGImageReader extends ImageReader {
if (debug) {
System.out.println("pushing back " + num + " bytes");
}
iis.seek(iis.getStreamPosition()-num);
// The buffer is clear after this, so no need to set haveSeeked.
cbLock.lock();
try {
iis.seek(iis.getStreamPosition()-num);
// The buffer is clear after this, so no need to set haveSeeked.
} finally {
cbLock.unlock();
}
}
/**
@ -644,7 +698,12 @@ public class JPEGImageReader extends ImageReader {
* Ignore this profile.
*/
iccCS = null;
warningOccurred(WARNING_IGNORE_INVALID_ICC);
cbLock.lock();
try {
warningOccurred(WARNING_IGNORE_INVALID_ICC);
} finally {
cbLock.unlock();
}
}
}
}
@ -653,6 +712,7 @@ public class JPEGImageReader extends ImageReader {
setThreadLock();
try {
if (currentImage != imageIndex) {
cbLock.check();
readHeader(imageIndex, true);
}
return width;
@ -665,6 +725,7 @@ public class JPEGImageReader extends ImageReader {
setThreadLock();
try {
if (currentImage != imageIndex) {
cbLock.check();
readHeader(imageIndex, true);
}
return height;
@ -693,6 +754,8 @@ public class JPEGImageReader extends ImageReader {
setThreadLock();
try {
if (currentImage != imageIndex) {
cbLock.check();
readHeader(imageIndex, true);
}
@ -716,6 +779,7 @@ public class JPEGImageReader extends ImageReader {
private Iterator getImageTypesOnThread(int imageIndex)
throws IOException {
if (currentImage != imageIndex) {
cbLock.check();
readHeader(imageIndex, true);
}
@ -931,6 +995,7 @@ public class JPEGImageReader extends ImageReader {
setThreadLock();
try {
if (!tablesOnlyChecked) {
cbLock.check();
checkTablesOnly();
}
return streamMetadata;
@ -951,6 +1016,8 @@ public class JPEGImageReader extends ImageReader {
return imageMetadata;
}
cbLock.check();
gotoImage(imageIndex);
imageMetadata = new JPEGMetadata(false, false, iis, this);
@ -967,6 +1034,7 @@ public class JPEGImageReader extends ImageReader {
throws IOException {
setThreadLock();
try {
cbLock.check();
try {
readInternal(imageIndex, param, false);
} catch (RuntimeException e) {
@ -1196,58 +1264,63 @@ public class JPEGImageReader extends ImageReader {
}
target.setRect(destROI.x, destROI.y + y, raster);
processImageUpdate(image,
destROI.x, destROI.y+y,
raster.getWidth(), 1,
1, 1,
destinationBands);
if ((y > 0) && (y%progInterval == 0)) {
int height = target.getHeight()-1;
float percentOfPass = ((float)y)/height;
if (progressive) {
if (knownPassCount != UNKNOWN) {
processImageProgress((pass + percentOfPass)*100.0F
/ knownPassCount);
} else if (maxProgressivePass != Integer.MAX_VALUE) {
// Use the range of allowed progressive passes
processImageProgress((pass + percentOfPass)*100.0F
/ (maxProgressivePass - minProgressivePass + 1));
} else {
// Assume there are a minimum of MIN_ESTIMATED_PASSES
// and that there is always one more pass
// Compute the percentage as the percentage at the end
// of the previous pass, plus the percentage of this
// pass scaled to be the percentage of the total remaining,
// assuming a minimum of MIN_ESTIMATED_PASSES passes and
// that there is always one more pass. This is monotonic
// and asymptotic to 1.0, which is what we need.
int remainingPasses = // including this one
Math.max(2, MIN_ESTIMATED_PASSES-pass);
int totalPasses = pass + remainingPasses-1;
progInterval = Math.max(height/20*totalPasses,
totalPasses);
if (y%progInterval == 0) {
percentToDate = previousPassPercentage +
(1.0F - previousPassPercentage)
* (percentOfPass)/remainingPasses;
if (debug) {
System.out.print("pass= " + pass);
System.out.print(", y= " + y);
System.out.print(", progInt= " + progInterval);
System.out.print(", % of pass: " + percentOfPass);
System.out.print(", rem. passes: "
+ remainingPasses);
System.out.print(", prev%: "
+ previousPassPercentage);
System.out.print(", %ToDate: " + percentToDate);
System.out.print(" ");
cbLock.lock();
try {
processImageUpdate(image,
destROI.x, destROI.y+y,
raster.getWidth(), 1,
1, 1,
destinationBands);
if ((y > 0) && (y%progInterval == 0)) {
int height = target.getHeight()-1;
float percentOfPass = ((float)y)/height;
if (progressive) {
if (knownPassCount != UNKNOWN) {
processImageProgress((pass + percentOfPass)*100.0F
/ knownPassCount);
} else if (maxProgressivePass != Integer.MAX_VALUE) {
// Use the range of allowed progressive passes
processImageProgress((pass + percentOfPass)*100.0F
/ (maxProgressivePass - minProgressivePass + 1));
} else {
// Assume there are a minimum of MIN_ESTIMATED_PASSES
// and that there is always one more pass
// Compute the percentage as the percentage at the end
// of the previous pass, plus the percentage of this
// pass scaled to be the percentage of the total remaining,
// assuming a minimum of MIN_ESTIMATED_PASSES passes and
// that there is always one more pass. This is monotonic
// and asymptotic to 1.0, which is what we need.
int remainingPasses = // including this one
Math.max(2, MIN_ESTIMATED_PASSES-pass);
int totalPasses = pass + remainingPasses-1;
progInterval = Math.max(height/20*totalPasses,
totalPasses);
if (y%progInterval == 0) {
percentToDate = previousPassPercentage +
(1.0F - previousPassPercentage)
* (percentOfPass)/remainingPasses;
if (debug) {
System.out.print("pass= " + pass);
System.out.print(", y= " + y);
System.out.print(", progInt= " + progInterval);
System.out.print(", % of pass: " + percentOfPass);
System.out.print(", rem. passes: "
+ remainingPasses);
System.out.print(", prev%: "
+ previousPassPercentage);
System.out.print(", %ToDate: " + percentToDate);
System.out.print(" ");
}
processImageProgress(percentToDate*100.0F);
}
processImageProgress(percentToDate*100.0F);
}
} else {
processImageProgress(percentOfPass * 100.0F);
}
} else {
processImageProgress(percentOfPass * 100.0F);
}
} finally {
cbLock.unlock();
}
}
@ -1260,33 +1333,58 @@ public class JPEGImageReader extends ImageReader {
}
private void passStarted (int pass) {
this.pass = pass;
previousPassPercentage = percentToDate;
processPassStarted(image,
pass,
minProgressivePass,
maxProgressivePass,
0, 0,
1,1,
destinationBands);
cbLock.lock();
try {
this.pass = pass;
previousPassPercentage = percentToDate;
processPassStarted(image,
pass,
minProgressivePass,
maxProgressivePass,
0, 0,
1,1,
destinationBands);
} finally {
cbLock.unlock();
}
}
private void passComplete () {
processPassComplete(image);
cbLock.lock();
try {
processPassComplete(image);
} finally {
cbLock.unlock();
}
}
void thumbnailStarted(int thumbnailIndex) {
processThumbnailStarted(currentImage, thumbnailIndex);
cbLock.lock();
try {
processThumbnailStarted(currentImage, thumbnailIndex);
} finally {
cbLock.unlock();
}
}
// Provide access to protected superclass method
void thumbnailProgress(float percentageDone) {
processThumbnailProgress(percentageDone);
cbLock.lock();
try {
processThumbnailProgress(percentageDone);
} finally {
cbLock.unlock();
}
}
// Provide access to protected superclass method
void thumbnailComplete() {
processThumbnailComplete();
cbLock.lock();
try {
processThumbnailComplete();
} finally {
cbLock.unlock();
}
}
/**
@ -1310,6 +1408,11 @@ public class JPEGImageReader extends ImageReader {
public void abort() {
setThreadLock();
try {
/**
* NB: we do not check the call back lock here,
* we allow to abort the reader any time.
*/
super.abort();
abortRead(structPointer);
} finally {
@ -1332,6 +1435,7 @@ public class JPEGImageReader extends ImageReader {
setThreadLock();
Raster retval = null;
try {
cbLock.check();
/*
* This could be further optimized by not resetting the dest.
* offset and creating a translated raster in readInternal()
@ -1371,6 +1475,8 @@ public class JPEGImageReader extends ImageReader {
public int getNumThumbnails(int imageIndex) throws IOException {
setThreadLock();
try {
cbLock.check();
getImageMetadata(imageIndex); // checks iis state for us
// Now check the jfif segments
JFIFMarkerSegment jfif =
@ -1391,6 +1497,8 @@ public class JPEGImageReader extends ImageReader {
throws IOException {
setThreadLock();
try {
cbLock.check();
if ((thumbnailIndex < 0)
|| (thumbnailIndex >= getNumThumbnails(imageIndex))) {
throw new IndexOutOfBoundsException("No such thumbnail");
@ -1409,6 +1517,8 @@ public class JPEGImageReader extends ImageReader {
throws IOException {
setThreadLock();
try {
cbLock.check();
if ((thumbnailIndex < 0)
|| (thumbnailIndex >= getNumThumbnails(imageIndex))) {
throw new IndexOutOfBoundsException("No such thumbnail");
@ -1428,6 +1538,8 @@ public class JPEGImageReader extends ImageReader {
throws IOException {
setThreadLock();
try {
cbLock.check();
if ((thumbnailIndex < 0)
|| (thumbnailIndex >= getNumThumbnails(imageIndex))) {
throw new IndexOutOfBoundsException("No such thumbnail");
@ -1468,6 +1580,7 @@ public class JPEGImageReader extends ImageReader {
public void reset() {
setThreadLock();
try {
cbLock.check();
super.reset();
} finally {
clearThreadLock();
@ -1479,6 +1592,8 @@ public class JPEGImageReader extends ImageReader {
public void dispose() {
setThreadLock();
try {
cbLock.check();
if (structPointer != 0) {
disposerRecord.dispose();
structPointer = 0;
@ -1540,6 +1655,36 @@ public class JPEGImageReader extends ImageReader {
theThread = null;
}
}
private CallBackLock cbLock = new CallBackLock();
private static class CallBackLock {
private State lockState;
CallBackLock() {
lockState = State.Unlocked;
}
void check() {
if (lockState != State.Unlocked) {
throw new IllegalStateException("Access to the reader is not allowed");
}
}
private void lock() {
lockState = State.Locked;
}
private void unlock() {
lockState = State.Unlocked;
}
private static enum State {
Unlocked,
Locked
}
}
}
/**

View File

@ -183,8 +183,7 @@ public class JPEGImageWriter extends ImageWriter {
return null;
}
});
initWriterIDs(ImageOutputStream.class,
JPEGQTable.class,
initWriterIDs(JPEGQTable.class,
JPEGHuffmanTable.class);
}
@ -200,11 +199,13 @@ public class JPEGImageWriter extends ImageWriter {
public void setOutput(Object output) {
setThreadLock();
try {
cbLock.check();
super.setOutput(output); // validates output
resetInternalState();
ios = (ImageOutputStream) output; // so this will always work
// Set the native destination
setDest(structPointer, ios);
setDest(structPointer);
} finally {
clearThreadLock();
}
@ -359,6 +360,8 @@ public class JPEGImageWriter extends ImageWriter {
ImageWriteParam param) throws IOException {
setThreadLock();
try {
cbLock.check();
writeOnThread(streamMetadata, image, param);
} finally {
clearThreadLock();
@ -1082,13 +1085,18 @@ public class JPEGImageWriter extends ImageWriter {
haveMetadata,
restartInterval);
if (aborted) {
processWriteAborted();
} else {
processImageComplete();
}
cbLock.lock();
try {
if (aborted) {
processWriteAborted();
} else {
processImageComplete();
}
ios.flush();
ios.flush();
} finally {
cbLock.unlock();
}
currentImage++; // After a successful write
}
@ -1096,6 +1104,8 @@ public class JPEGImageWriter extends ImageWriter {
throws IOException {
setThreadLock();
try {
cbLock.check();
prepareWriteSequenceOnThread(streamMetadata);
} finally {
clearThreadLock();
@ -1175,6 +1185,8 @@ public class JPEGImageWriter extends ImageWriter {
throws IOException {
setThreadLock();
try {
cbLock.check();
if (sequencePrepared == false) {
throw new IllegalStateException("sequencePrepared not called!");
}
@ -1188,6 +1200,8 @@ public class JPEGImageWriter extends ImageWriter {
public void endWriteSequence() throws IOException {
setThreadLock();
try {
cbLock.check();
if (sequencePrepared == false) {
throw new IllegalStateException("sequencePrepared not called!");
}
@ -1200,6 +1214,10 @@ public class JPEGImageWriter extends ImageWriter {
public synchronized void abort() {
setThreadLock();
try {
/**
* NB: we do not check the call back lock here, we allow to abort
* the reader any time.
*/
super.abort();
abortWrite(structPointer);
} finally {
@ -1223,6 +1241,8 @@ public class JPEGImageWriter extends ImageWriter {
public void reset() {
setThreadLock();
try {
cbLock.check();
super.reset();
} finally {
clearThreadLock();
@ -1232,6 +1252,8 @@ public class JPEGImageWriter extends ImageWriter {
public void dispose() {
setThreadLock();
try {
cbLock.check();
if (structPointer != 0) {
disposerRecord.dispose();
structPointer = 0;
@ -1251,13 +1273,18 @@ public class JPEGImageWriter extends ImageWriter {
* sending warnings to listeners.
*/
void warningOccurred(int code) {
if ((code < 0) || (code > MAX_WARNING)){
throw new InternalError("Invalid warning index");
cbLock.lock();
try {
if ((code < 0) || (code > MAX_WARNING)){
throw new InternalError("Invalid warning index");
}
processWarningOccurred
(currentImage,
"com.sun.imageio.plugins.jpeg.JPEGImageWriterResources",
Integer.toString(code));
} finally {
cbLock.unlock();
}
processWarningOccurred
(currentImage,
"com.sun.imageio.plugins.jpeg.JPEGImageWriterResources",
Integer.toString(code));
}
/**
@ -1274,21 +1301,41 @@ public class JPEGImageWriter extends ImageWriter {
* library warnings from being printed to stderr.
*/
void warningWithMessage(String msg) {
processWarningOccurred(currentImage, msg);
cbLock.lock();
try {
processWarningOccurred(currentImage, msg);
} finally {
cbLock.unlock();
}
}
void thumbnailStarted(int thumbnailIndex) {
processThumbnailStarted(currentImage, thumbnailIndex);
cbLock.lock();
try {
processThumbnailStarted(currentImage, thumbnailIndex);
} finally {
cbLock.unlock();
}
}
// Provide access to protected superclass method
void thumbnailProgress(float percentageDone) {
processThumbnailProgress(percentageDone);
cbLock.lock();
try {
processThumbnailProgress(percentageDone);
} finally {
cbLock.unlock();
}
}
// Provide access to protected superclass method
void thumbnailComplete() {
processThumbnailComplete();
cbLock.lock();
try {
processThumbnailComplete();
} finally {
cbLock.unlock();
}
}
///////// End of Package-access API
@ -1615,16 +1662,14 @@ public class JPEGImageWriter extends ImageWriter {
////////////// Native methods and callbacks
/** Sets up static native structures. */
private static native void initWriterIDs(Class iosClass,
Class qTableClass,
private static native void initWriterIDs(Class qTableClass,
Class huffClass);
/** Sets up per-writer native structure and returns a pointer to it. */
private native long initJPEGImageWriter();
/** Sets up native structures for output stream */
private native void setDest(long structPointer,
ImageOutputStream ios);
private native void setDest(long structPointer);
/**
* Returns <code>true</code> if the write was aborted.
@ -1749,7 +1794,12 @@ public class JPEGImageWriter extends ImageWriter {
}
raster.setRect(sourceLine);
if ((y > 7) && (y%8 == 0)) { // Every 8 scanlines
processImageProgress((float) y / (float) sourceHeight * 100.0F);
cbLock.lock();
try {
processImageProgress((float) y / (float) sourceHeight * 100.0F);
} finally {
cbLock.unlock();
}
}
}
@ -1777,6 +1827,25 @@ public class JPEGImageWriter extends ImageWriter {
}
}
/**
* This method is called from native code in order to write encoder
* output to the destination.
*
* We block any attempt to change the writer state during this
* method, in order to prevent a corruption of the native encoder
* state.
*/
private void writeOutputData(byte[] data, int offset, int len)
throws IOException
{
cbLock.lock();
try {
ios.write(data, offset, len);
} finally {
cbLock.unlock();
}
}
private Thread theThread = null;
private int theLockCount = 0;
@ -1811,4 +1880,34 @@ public class JPEGImageWriter extends ImageWriter {
theThread = null;
}
}
private CallBackLock cbLock = new CallBackLock();
private static class CallBackLock {
private State lockState;
CallBackLock() {
lockState = State.Unlocked;
}
void check() {
if (lockState != State.Unlocked) {
throw new IllegalStateException("Access to the writer is not allowed");
}
}
private void lock() {
lockState = State.Locked;
}
private void unlock() {
lockState = State.Unlocked;
}
private static enum State {
Unlocked,
Locked
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -32,6 +32,7 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.security.Permission;
import java.util.Map;
import java.util.logging.Level;
@ -213,7 +214,6 @@ public class MBeanInstantiator {
Object moi;
// ------------------------------
// ------------------------------
Constructor<?> cons = findConstructor(theClass, null);
@ -224,6 +224,7 @@ public class MBeanInstantiator {
// Instantiate the new object
try {
ReflectUtil.checkPackageAccess(theClass);
ensureClassAccess(theClass);
moi= cons.newInstance();
} catch (InvocationTargetException e) {
// Wrap the exception.
@ -270,7 +271,6 @@ public class MBeanInstantiator {
checkMBeanPermission(theClass, null, null, "instantiate");
// Instantiate the new object
// ------------------------------
// ------------------------------
final Class<?>[] tab;
@ -300,6 +300,7 @@ public class MBeanInstantiator {
}
try {
ReflectUtil.checkPackageAccess(theClass);
ensureClassAccess(theClass);
moi = cons.newInstance(params);
}
catch (NoSuchMethodError error) {
@ -741,4 +742,13 @@ public class MBeanInstantiator {
sm.checkPermission(perm);
}
}
private static void ensureClassAccess(Class clazz)
throws IllegalAccessException
{
int mod = clazz.getModifiers();
if (!Modifier.isPublic(mod)) {
throw new IllegalAccessException("Class is not public and can't be instantiated");
}
}
}

View File

@ -56,7 +56,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice
// from simultaneous creation and destruction
// reduces possibility of deadlock, compared to
// synchronizing to the class instance
private Object traRecLock = new Object();
private final Object traRecLock = new Object();
// DEVICE ATTRIBUTES
@ -474,7 +474,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice
This is necessary for Receivers retrieved via MidiSystem.getReceiver()
(which opens the device implicitely).
*/
protected abstract class AbstractReceiver implements MidiDeviceReceiver {
abstract class AbstractReceiver implements MidiDeviceReceiver {
private boolean open = true;
@ -483,24 +483,24 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice
Receiver. Therefore, subclasses should not override this method.
Instead, they should implement implSend().
*/
public synchronized void send(MidiMessage message, long timeStamp) {
if (open) {
implSend(message, timeStamp);
} else {
@Override
public final synchronized void send(final MidiMessage message,
final long timeStamp) {
if (!open) {
throw new IllegalStateException("Receiver is not open");
}
implSend(message, timeStamp);
}
protected abstract void implSend(MidiMessage message, long timeStamp);
abstract void implSend(MidiMessage message, long timeStamp);
/** Close the Receiver.
* Here, the call to the magic method closeInternal() takes place.
* Therefore, subclasses that override this method must call
* 'super.close()'.
*/
public void close() {
@Override
public final void close() {
open = false;
synchronized (AbstractMidiDevice.this.traRecLock) {
AbstractMidiDevice.this.getReceiverList().remove(this);
@ -508,11 +508,12 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice
AbstractMidiDevice.this.closeInternal(this);
}
public MidiDevice getMidiDevice() {
@Override
public final MidiDevice getMidiDevice() {
return AbstractMidiDevice.this;
}
protected boolean isOpen() {
final boolean isOpen() {
return open;
}

View File

@ -32,7 +32,7 @@ import javax.sound.midi.*;
*
* @author Florian Bomers
*/
class FastShortMessage extends ShortMessage {
final class FastShortMessage extends ShortMessage {
private int packedMsg;
public FastShortMessage(int packedMsg) throws InvalidMidiDataException {

View File

@ -32,7 +32,7 @@ import javax.sound.midi.*;
*
* @author Florian Bomers
*/
class FastSysexMessage extends SysexMessage {
final class FastSysexMessage extends SysexMessage {
FastSysexMessage(byte[] data) throws InvalidMidiDataException {
super(data);

View File

@ -103,9 +103,9 @@ class MidiOutDevice extends AbstractMidiDevice {
class MidiOutReceiver extends AbstractReceiver {
protected void implSend(MidiMessage message, long timeStamp) {
int length = message.getLength();
int status = message.getStatus();
void implSend(final MidiMessage message, final long timeStamp) {
final int length = message.getLength();
final int status = message.getStatus();
if (length <= 3 && status != 0xF0 && status != 0xF7) {
int packedMsg;
if (message instanceof ShortMessage) {
@ -140,11 +140,15 @@ class MidiOutDevice extends AbstractMidiDevice {
}
nSendShortMessage(id, packedMsg, timeStamp);
} else {
final byte[] data;
if (message instanceof FastSysexMessage) {
nSendLongMessage(id, ((FastSysexMessage) message).getReadOnlyMessage(),
length, timeStamp);
data = ((FastSysexMessage) message).getReadOnlyMessage();
} else {
nSendLongMessage(id, message.getMessage(), length, timeStamp);
data = message.getMessage();
}
final int dataLength = Math.min(length, data.length);
if (dataLength > 0) {
nSendLongMessage(id, data, dataLength, timeStamp);
}
}
}

View File

@ -1026,7 +1026,7 @@ class RealTimeSequencer extends AbstractMidiDevice implements Sequencer, AutoCon
class SequencerReceiver extends AbstractReceiver {
protected void implSend(MidiMessage message, long timeStamp) {
void implSend(MidiMessage message, long timeStamp) {
if (recording) {
long tickPos = 0;

View File

@ -851,6 +851,11 @@ public class EventSetImpl extends ArrayList<Event> implements EventSet {
}
}
@Override
public Spliterator<Event> spliterator() {
return Spliterators.spliterator(this, Spliterator.DISTINCT);
}
/* below make this unmodifiable */
public boolean add(Event o){

View File

@ -208,7 +208,9 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
* aComponent is null
*/
public Component getComponentAfter(Container aContainer, Component aComponent) {
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Searching in " + aContainer + " for component after " + aComponent);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Searching in " + aContainer + " for component after " + aComponent);
}
if (aContainer == null || aComponent == null) {
throw new IllegalArgumentException("aContainer and aComponent cannot be null");
@ -247,7 +249,9 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
// Null result means that we overstepped the limit of the FTP's cycle.
// In that case we must quit the cycle, otherwise return the component found.
if (afterComp != null) {
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### FTP returned " + afterComp);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### FTP returned " + afterComp);
}
return afterComp;
}
aComponent = provider;
@ -255,7 +259,9 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
List<Component> cycle = getFocusTraversalCycle(aContainer);
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is " + cycle + ", component is " + aComponent);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Cycle is " + cycle + ", component is " + aComponent);
}
int index = getComponentIndex(cycle, aComponent);
@ -336,7 +342,9 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
// Null result means that we overstepped the limit of the FTP's cycle.
// In that case we must quit the cycle, otherwise return the component found.
if (beforeComp != null) {
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### FTP returned " + beforeComp);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### FTP returned " + beforeComp);
}
return beforeComp;
}
aComponent = provider;
@ -349,7 +357,9 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
List<Component> cycle = getFocusTraversalCycle(aContainer);
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is " + cycle + ", component is " + aComponent);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Cycle is " + cycle + ", component is " + aComponent);
}
int index = getComponentIndex(cycle, aComponent);
@ -401,7 +411,9 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
public Component getFirstComponent(Container aContainer) {
List<Component> cycle;
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Getting first component in " + aContainer);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Getting first component in " + aContainer);
}
if (aContainer == null) {
throw new IllegalArgumentException("aContainer cannot be null");
@ -420,10 +432,14 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
}
if (cycle.size() == 0) {
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is empty");
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Cycle is empty");
}
return null;
}
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is " + cycle);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Cycle is " + cycle);
}
for (Component comp : cycle) {
if (accept(comp)) {
@ -451,7 +467,9 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
*/
public Component getLastComponent(Container aContainer) {
List<Component> cycle;
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Getting last component in " + aContainer);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Getting last component in " + aContainer);
}
if (aContainer == null) {
throw new IllegalArgumentException("aContainer cannot be null");
@ -470,10 +488,14 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
}
if (cycle.size() == 0) {
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is empty");
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Cycle is empty");
}
return null;
}
if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is " + cycle);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("### Cycle is " + cycle);
}
for (int i= cycle.size() - 1; i >= 0; i--) {
Component comp = cycle.get(i);

View File

@ -310,7 +310,9 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
* <code>false</code> otherwise
*/
public boolean dispatchEvent(AWTEvent e) {
if (focusLog.isLoggable(PlatformLogger.FINE) && (e instanceof WindowEvent || e instanceof FocusEvent)) focusLog.fine("" + e);
if (focusLog.isLoggable(PlatformLogger.FINE) && (e instanceof WindowEvent || e instanceof FocusEvent)) {
focusLog.fine("" + e);
}
switch (e.getID()) {
case WindowEvent.WINDOW_GAINED_FOCUS: {
if (repostIfFollowsKeyEvents((WindowEvent)e)) {
@ -871,7 +873,9 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
}
}
if (ke != null) {
focusLog.finer("Pumping approved event {0}", ke);
if (focusLog.isLoggable(PlatformLogger.FINER)) {
focusLog.finer("Pumping approved event {0}", ke);
}
enqueuedKeyEvents.removeFirst();
}
}
@ -920,7 +924,9 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
// The fix is rolled out.
if (ke.getWhen() > marker.after) {
focusLog.finer("Storing event {0} because of marker {1}", ke, marker);
if (focusLog.isLoggable(PlatformLogger.FINER)) {
focusLog.finer("Storing event {0} because of marker {1}", ke, marker);
}
enqueuedKeyEvents.addLast(ke);
return true;
}
@ -932,7 +938,9 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
}
case FocusEvent.FOCUS_GAINED:
focusLog.finest("Markers before FOCUS_GAINED on {0}", target);
if (focusLog.isLoggable(PlatformLogger.FINEST)) {
focusLog.finest("Markers before FOCUS_GAINED on {0}", target);
}
dumpMarkers();
// Search the marker list for the first marker tied to
// the Component which just gained focus. Then remove
@ -959,7 +967,9 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
}
} else {
// Exception condition - event without marker
focusLog.finer("Event without marker {0}", e);
if (focusLog.isLoggable(PlatformLogger.FINER)) {
focusLog.finer("Event without marker {0}", e);
}
}
}
focusLog.finest("Markers after FOCUS_GAINED");
@ -1198,8 +1208,10 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
return;
}
focusLog.finer("Enqueue at {0} for {1}",
if (focusLog.isLoggable(PlatformLogger.FINER)) {
focusLog.finer("Enqueue at {0} for {1}",
after, untilFocused);
}
int insertionIndex = 0,
i = typeAheadMarkers.size();
@ -1238,8 +1250,10 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
return;
}
focusLog.finer("Dequeue at {0} for {1}",
if (focusLog.isLoggable(PlatformLogger.FINER)) {
focusLog.finer("Dequeue at {0} for {1}",
after, untilFocused);
}
TypeAheadMarker marker;
ListIterator<TypeAheadMarker> iter = typeAheadMarkers.listIterator

View File

@ -138,7 +138,9 @@ class EventDispatchThread extends Thread {
}
void addEventFilter(EventFilter filter) {
eventLog.finest("adding the event filter: " + filter);
if (eventLog.isLoggable(PlatformLogger.FINEST)) {
eventLog.finest("adding the event filter: " + filter);
}
synchronized (eventFilters) {
if (!eventFilters.contains(filter)) {
if (filter instanceof ModalEventFilter) {
@ -162,7 +164,9 @@ class EventDispatchThread extends Thread {
}
void removeEventFilter(EventFilter filter) {
eventLog.finest("removing the event filter: " + filter);
if (eventLog.isLoggable(PlatformLogger.FINEST)) {
eventLog.finest("removing the event filter: " + filter);
}
synchronized (eventFilters) {
eventFilters.remove(filter);
}

View File

@ -2410,7 +2410,7 @@ public abstract class KeyboardFocusManager
Window nativeFocusedWindow = thisManager.getNativeFocusedWindow();
if (focusLog.isLoggable(PlatformLogger.FINER)) {
focusLog.finer("SNFH for {0} in {1}",
String.valueOf(descendant), String.valueOf(heavyweight));
String.valueOf(descendant), String.valueOf(heavyweight));
}
if (focusLog.isLoggable(PlatformLogger.FINEST)) {
focusLog.finest("0. Current focus owner {0}",
@ -2478,9 +2478,10 @@ public abstract class KeyboardFocusManager
manager.enqueueKeyEvents(time, descendant);
}
if (focusLog.isLoggable(PlatformLogger.FINEST))
if (focusLog.isLoggable(PlatformLogger.FINEST)) {
focusLog.finest("3. SNFH_HANDLED for lightweight" +
descendant + " in " + heavyweight);
}
return SNFH_SUCCESS_HANDLED;
} else {
if (!focusedWindowChangeAllowed) {
@ -2501,8 +2502,9 @@ public abstract class KeyboardFocusManager
(hwFocusRequest != null)
? hwFocusRequest.heavyweight
: nativeFocusedWindow)) {
if (focusLog.isLoggable(PlatformLogger.FINEST))
if (focusLog.isLoggable(PlatformLogger.FINEST)) {
focusLog.finest("4. SNFH_FAILURE for " + descendant);
}
return SNFH_FAILURE;
}
}
@ -2511,8 +2513,9 @@ public abstract class KeyboardFocusManager
heavyweightRequests.add
(new HeavyweightFocusRequest(heavyweight, descendant,
temporary, cause));
if (focusLog.isLoggable(PlatformLogger.FINEST))
if (focusLog.isLoggable(PlatformLogger.FINEST)) {
focusLog.finest("5. SNFH_PROCEED for " + descendant);
}
return SNFH_SUCCESS_PROCEED;
}
}

View File

@ -165,8 +165,10 @@ class WaitDispatchSupport implements SecondaryLoop {
*/
@Override
public boolean enter() {
log.fine("enter(): blockingEDT=" + keepBlockingEDT.get() +
", blockingCT=" + keepBlockingCT.get());
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("enter(): blockingEDT=" + keepBlockingEDT.get() +
", blockingCT=" + keepBlockingCT.get());
}
if (!keepBlockingEDT.compareAndSet(false, true)) {
log.fine("The secondary loop is already running, aborting");
@ -190,9 +192,13 @@ class WaitDispatchSupport implements SecondaryLoop {
Thread currentThread = Thread.currentThread();
if (currentThread == dispatchThread) {
log.finest("On dispatch thread: " + dispatchThread);
if (log.isLoggable(PlatformLogger.FINEST)) {
log.finest("On dispatch thread: " + dispatchThread);
}
if (interval != 0) {
log.finest("scheduling the timer for " + interval + " ms");
if (log.isLoggable(PlatformLogger.FINEST)) {
log.finest("scheduling the timer for " + interval + " ms");
}
timer.schedule(timerTask = new TimerTask() {
@Override
public void run() {
@ -207,7 +213,9 @@ class WaitDispatchSupport implements SecondaryLoop {
SequencedEvent currentSE = KeyboardFocusManager.
getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
if (currentSE != null) {
log.fine("Dispose current SequencedEvent: " + currentSE);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("Dispose current SequencedEvent: " + currentSE);
}
currentSE.dispose();
}
// In case the exit() method is called before starting
@ -223,7 +231,9 @@ class WaitDispatchSupport implements SecondaryLoop {
}
});
} else {
log.finest("On non-dispatch thread: " + currentThread);
if (log.isLoggable(PlatformLogger.FINEST)) {
log.finest("On non-dispatch thread: " + currentThread);
}
synchronized (getTreeLock()) {
if (filter != null) {
dispatchThread.addEventFilter(filter);
@ -247,9 +257,13 @@ class WaitDispatchSupport implements SecondaryLoop {
getTreeLock().wait();
}
}
log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
}
} catch (InterruptedException e) {
log.fine("Exception caught while waiting: " + e);
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("Exception caught while waiting: " + e);
}
} finally {
if (filter != null) {
dispatchThread.removeEventFilter(filter);
@ -270,8 +284,10 @@ class WaitDispatchSupport implements SecondaryLoop {
* @inheritDoc
*/
public boolean exit() {
log.fine("exit(): blockingEDT=" + keepBlockingEDT.get() +
", blockingCT=" + keepBlockingCT.get());
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine("exit(): blockingEDT=" + keepBlockingEDT.get() +
", blockingCT=" + keepBlockingCT.get());
}
if (keepBlockingEDT.compareAndSet(true, false)) {
wakeupEDT();
return true;
@ -295,7 +311,9 @@ class WaitDispatchSupport implements SecondaryLoop {
};
private void wakeupEDT() {
log.finest("wakeupEDT(): EDT == " + dispatchThread);
if (log.isLoggable(PlatformLogger.FINEST)) {
log.finest("wakeupEDT(): EDT == " + dispatchThread);
}
EventQueue eq = dispatchThread.getEventQueue();
eq.postEvent(new PeerEvent(this, wakingRunnable, PeerEvent.PRIORITY_EVENT));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 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
@ -2234,7 +2234,7 @@ public class Window extends Container implements Accessible {
WindowPeer peer = (WindowPeer)this.peer;
synchronized(getTreeLock()) {
if (peer != null) {
peer.setAlwaysOnTop(alwaysOnTop);
peer.updateAlwaysOnTopState();
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1995, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 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
@ -53,15 +53,14 @@ public interface WindowPeer extends ContainerPeer {
void toBack();
/**
* Sets if the window should always stay on top of all other windows or
* not.
*
* @param alwaysOnTop if the window should always stay on top of all other
* windows or not
* Updates the window's always-on-top state.
* Sets if the window should always stay
* on top of all other windows or not.
*
* @see Window#getAlwaysOnTop()
* @see Window#setAlwaysOnTop(boolean)
*/
void setAlwaysOnTop(boolean alwaysOnTop);
void updateAlwaysOnTopState();
/**
* Updates the window's focusable state.

View File

@ -28,6 +28,7 @@ package java.beans;
import com.sun.beans.TypeResolver;
import com.sun.beans.WeakCache;
import com.sun.beans.finder.ClassFinder;
import com.sun.beans.finder.MethodFinder;
import java.awt.Component;
@ -1281,7 +1282,20 @@ public class Introspector {
for (int i = 0; i < result.length; i++) {
Method method = result[i];
if (!method.getDeclaringClass().equals(clz)) {
result[i] = null;
result[i] = null; // ignore methods declared elsewhere
}
else {
try {
method = MethodFinder.findAccessibleMethod(method);
Class<?> type = method.getDeclaringClass();
result[i] = type.equals(clz) || type.isInterface()
? method
: null; // ignore methods from superclasses
}
catch (NoSuchMethodException exception) {
// commented out because of 6976577
// result[i] = null; // ignore inaccessible methods
}
}
}
declaredMethodCache.put(clz, result);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 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
@ -29,7 +29,6 @@ import com.sun.beans.finder.BeanInfoFinder;
import com.sun.beans.finder.PropertyEditorFinder;
import java.awt.GraphicsEnvironment;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
@ -42,7 +41,7 @@ import java.util.WeakHashMap;
*/
final class ThreadGroupContext {
private static final Map<ThreadGroup, ThreadGroupContext> contexts = new WeakHashMap<>();
private static final WeakIdentityMap<ThreadGroupContext> contexts = new WeakIdentityMap<>();
/**
* Returns the appropriate {@code AppContext} for the caller,
@ -69,6 +68,8 @@ final class ThreadGroupContext {
private BeanInfoFinder beanInfoFinder;
private PropertyEditorFinder propertyEditorFinder;
private ThreadGroupContext() {
}
boolean isDesignTime() {
return this.isDesignTime;

View File

@ -0,0 +1,181 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.beans;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
/**
* Hash table based mapping, which uses weak references to store keys
* and reference-equality in place of object-equality to compare them.
* An entry will automatically be removed when its key is no longer
* in ordinary use. Both null values and the null key are supported.
*
* @see java.util.IdentityHashMap
* @see java.util.WeakHashMap
*/
final class WeakIdentityMap<T> {
private static final int MAXIMUM_CAPACITY = 1 << 30; // it MUST be a power of two
private static final Object NULL = new Object(); // special object for null key
private final ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
private Entry<T>[] table = newTable(1<<3); // table's length MUST be a power of two
private int threshold = 6; // the next size value at which to resize
private int size = 0; // the number of key-value mappings
public T get(Object key) {
removeStaleEntries();
if (key == null) {
key = NULL;
}
int hash = key.hashCode();
int index = getIndex(this.table, hash);
for (Entry<T> entry = this.table[index]; entry != null; entry = entry.next) {
if (entry.isMatched(key, hash)) {
return entry.value;
}
}
return null;
}
public T put(Object key, T value) {
removeStaleEntries();
if (key == null) {
key = NULL;
}
int hash = key.hashCode();
int index = getIndex(this.table, hash);
for (Entry<T> entry = this.table[index]; entry != null; entry = entry.next) {
if (entry.isMatched(key, hash)) {
T oldValue = entry.value;
entry.value = value;
return oldValue;
}
}
this.table[index] = new Entry<T>(key, hash, value, this.queue, this.table[index]);
if (++this.size >= this.threshold) {
if (this.table.length == MAXIMUM_CAPACITY) {
this.threshold = Integer.MAX_VALUE;
}
else {
removeStaleEntries();
Entry<T>[] table = newTable(this.table.length * 2);
transfer(this.table, table);
// If ignoring null elements and processing ref queue caused massive
// shrinkage, then restore old table. This should be rare, but avoids
// unbounded expansion of garbage-filled tables.
if (this.size >= this.threshold / 2) {
this.table = table;
this.threshold *= 2;
}
else {
transfer(table, this.table);
}
}
}
return null;
}
private void removeStaleEntries() {
for (Object ref = this.queue.poll(); ref != null; ref = this.queue.poll()) {
@SuppressWarnings("unchecked")
Entry<T> entry = (Entry<T>) ref;
int index = getIndex(this.table, entry.hash);
Entry<T> prev = this.table[index];
Entry<T> current = prev;
while (current != null) {
Entry<T> next = current.next;
if (current == entry) {
if (prev == entry) {
this.table[index] = next;
}
else {
prev.next = next;
}
entry.value = null; // Help GC
entry.next = null; // Help GC
this.size--;
break;
}
prev = current;
current = next;
}
}
}
private void transfer(Entry<T>[] oldTable, Entry<T>[] newTable) {
for (int i = 0; i < oldTable.length; i++) {
Entry<T> entry = oldTable[i];
oldTable[i] = null;
while (entry != null) {
Entry<T> next = entry.next;
Object key = entry.get();
if (key == null) {
entry.value = null; // Help GC
entry.next = null; // Help GC
this.size--;
}
else {
int index = getIndex(newTable, entry.hash);
entry.next = newTable[index];
newTable[index] = entry;
}
entry = next;
}
}
}
@SuppressWarnings("unchecked")
private Entry<T>[] newTable(int length) {
return (Entry<T>[]) new Entry<?>[length];
}
private static int getIndex(Entry<?>[] table, int hash) {
return hash & (table.length - 1);
}
private static class Entry<T> extends WeakReference<Object> {
private final int hash;
private T value;
private Entry<T> next;
Entry(Object key, int hash, T value, ReferenceQueue<Object> queue, Entry<T> next) {
super(key, queue);
this.hash = hash;
this.value = value;
this.next = next;
}
boolean isMatched(Object key, int hash) {
return (this.hash == hash) && (key == get());
}
}
}

View File

@ -41,6 +41,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.io.ObjectStreamClass.processQueue;
import sun.reflect.misc.ReflectUtil;
/**
* An ObjectInputStream deserializes primitive data and objects previously
@ -1519,6 +1520,12 @@ public class ObjectInputStream
}
}
private boolean isCustomSubclass() {
// Return true if this class is a custom subclass of ObjectInputStream
return getClass().getClassLoader()
!= ObjectInputStream.class.getClassLoader();
}
/**
* Reads in and returns class descriptor for a dynamic proxy class. Sets
* passHandle to proxy class descriptor's assigned handle. If proxy class
@ -1548,6 +1555,15 @@ public class ObjectInputStream
try {
if ((cl = resolveProxyClass(ifaces)) == null) {
resolveEx = new ClassNotFoundException("null class");
} else if (!Proxy.isProxyClass(cl)) {
throw new InvalidClassException("Not a proxy");
} else {
// ReflectUtil.checkProxyPackageAccess makes a test
// equivalent to isCustomSubclass so there's no need
// to condition this call to isCustomSubclass == true here.
ReflectUtil.checkProxyPackageAccess(
getClass().getClassLoader(),
cl.getInterfaces());
}
} catch (ClassNotFoundException ex) {
resolveEx = ex;
@ -1589,9 +1605,12 @@ public class ObjectInputStream
Class<?> cl = null;
ClassNotFoundException resolveEx = null;
bin.setBlockDataMode(true);
final boolean checksRequired = isCustomSubclass();
try {
if ((cl = resolveClass(readDesc)) == null) {
resolveEx = new ClassNotFoundException("null class");
} else if (checksRequired) {
ReflectUtil.checkPackageAccess(cl);
}
} catch (ClassNotFoundException ex) {
resolveEx = ex;

View File

@ -53,6 +53,7 @@ import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
import sun.misc.Unsafe;
import sun.reflect.CallerSensitive;
import sun.reflect.ConstantPool;
import sun.reflect.Reflection;
import sun.reflect.ReflectionFactory;
@ -250,9 +251,11 @@ public final class Class<T> implements java.io.Serializable,
* by this method fails
* @exception ClassNotFoundException if the class cannot be located
*/
@CallerSensitive
public static Class<?> forName(String className)
throws ClassNotFoundException {
return forName0(className, true, ClassLoader.getCallerClassLoader());
return forName0(className, true,
ClassLoader.getClassLoader(Reflection.getCallerClass()));
}
@ -317,6 +320,7 @@ public final class Class<T> implements java.io.Serializable,
* @see java.lang.ClassLoader
* @since 1.2
*/
@CallerSensitive
public static Class<?> forName(String name, boolean initialize,
ClassLoader loader)
throws ClassNotFoundException
@ -324,7 +328,7 @@ public final class Class<T> implements java.io.Serializable,
if (sun.misc.VM.isSystemDomainLoader(loader)) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader ccl = ClassLoader.getCallerClassLoader();
ClassLoader ccl = ClassLoader.getClassLoader(Reflection.getCallerClass());
if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
sm.checkPermission(
SecurityConstants.GET_CLASSLOADER_PERMISSION);
@ -386,18 +390,14 @@ public final class Class<T> implements java.io.Serializable,
* </ul>
*
*/
@CallerSensitive
public T newInstance()
throws InstantiationException, IllegalAccessException
{
if (System.getSecurityManager() != null) {
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), false);
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
}
return newInstance0();
}
private T newInstance0()
throws InstantiationException, IllegalAccessException
{
// NOTE: the following code may not be strictly correct under
// the current Java memory model.
@ -432,7 +432,7 @@ public final class Class<T> implements java.io.Serializable,
// Security check (same as in java.lang.reflect.Constructor)
int modifiers = tmpConstructor.getModifiers();
if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
Class<?> caller = Reflection.getCallerClass(3);
Class<?> caller = Reflection.getCallerClass();
if (newInstanceCallerCache != caller) {
Reflection.ensureMemberAccess(caller, this, null, modifiers);
newInstanceCallerCache = caller;
@ -674,16 +674,14 @@ public final class Class<T> implements java.io.Serializable,
* @see SecurityManager#checkPermission
* @see java.lang.RuntimePermission
*/
@CallerSensitive
public ClassLoader getClassLoader() {
ClassLoader cl = getClassLoader0();
if (cl == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader ccl = ClassLoader.getCallerClassLoader();
if (ClassLoader.needsClassLoaderPermissionCheck(ccl, cl)) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
}
return cl;
}
@ -1392,11 +1390,9 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Class<?>[] getClasses() {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), false);
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
// Privileged so this implementation can look at DECLARED classes,
// something the caller might not have privilege to do. The code here
@ -1467,11 +1463,9 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Field[] getFields() throws SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyFields(privateGetPublicFields(null));
}
@ -1518,11 +1512,9 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Method[] getMethods() throws SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyMethods(privateGetPublicMethods());
}
@ -1567,11 +1559,9 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Constructor<?>[] getConstructors() throws SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyConstructors(privateGetDeclaredConstructors(true));
}
@ -1625,12 +1615,10 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Field getField(String name)
throws NoSuchFieldException, SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
Field field = getField0(name);
if (field == null) {
throw new NoSuchFieldException(name);
@ -1710,12 +1698,10 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
Method method = getMethod0(name, parameterTypes);
if (method == null) {
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
@ -1764,12 +1750,10 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Constructor<T> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return getConstructor0(parameterTypes, Member.PUBLIC);
}
@ -1807,11 +1791,9 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Class<?>[] getDeclaredClasses() throws SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), false);
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
return getDeclaredClasses0();
}
@ -1851,11 +1833,9 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
return copyFields(privateGetDeclaredFields(false));
}
@ -1899,11 +1879,9 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
return copyMethods(privateGetDeclaredMethods(false));
}
@ -1944,11 +1922,9 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
return copyConstructors(privateGetDeclaredConstructors(false));
}
@ -1987,12 +1963,10 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Field getDeclaredField(String name)
throws NoSuchFieldException, SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
Field field = searchFields(privateGetDeclaredFields(false), name);
if (field == null) {
throw new NoSuchFieldException(name);
@ -2042,12 +2016,10 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
if (method == null) {
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
@ -2092,12 +2064,10 @@ public final class Class<T> implements java.io.Serializable,
*
* @since JDK1.1
*/
@CallerSensitive
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
// be very careful not to change the stack depth of this
// checkMemberAccess call for security reasons
// see java.lang.SecurityManager.checkMemberAccess
checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
return getConstructor0(parameterTypes, Member.DECLARED);
}
@ -2255,23 +2225,40 @@ public final class Class<T> implements java.io.Serializable,
*/
static native Class<?> getPrimitiveClass(String name);
private static boolean isCheckMemberAccessOverridden(SecurityManager smgr) {
if (smgr.getClass() == SecurityManager.class) return false;
Class<?>[] paramTypes = new Class<?>[] {Class.class, int.class};
return smgr.getClass().getMethod0("checkMemberAccess", paramTypes).
getDeclaringClass() != SecurityManager.class;
}
/*
* Check if client is allowed to access members. If access is denied,
* throw a SecurityException.
*
* Be very careful not to change the stack depth of this checkMemberAccess
* call for security reasons.
* See java.lang.SecurityManager.checkMemberAccess.
*
* <p> Default policy: allow all clients access with normal Java access
* control.
*/
private void checkMemberAccess(int which, ClassLoader ccl, boolean checkProxyInterfaces) {
SecurityManager s = System.getSecurityManager();
private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
final SecurityManager s = System.getSecurityManager();
if (s != null) {
s.checkMemberAccess(this, which);
ClassLoader cl = getClassLoader0();
final ClassLoader ccl = ClassLoader.getClassLoader(caller);
final ClassLoader cl = getClassLoader0();
if (!isCheckMemberAccessOverridden(s)) {
// Inlined SecurityManager.checkMemberAccess
if (which != Member.PUBLIC) {
if (ccl != cl) {
s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
}
}
} else {
// Don't refactor; otherwise break the stack depth for
// checkMemberAccess of subclasses of SecurityManager as specified.
s.checkMemberAccess(this, which);
}
if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
String name = this.getName();
int i = name.lastIndexOf('.');

View File

@ -55,6 +55,7 @@ import sun.misc.CompoundEnumeration;
import sun.misc.Resource;
import sun.misc.URLClassPath;
import sun.misc.VM;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import sun.security.util.SecurityConstants;
@ -1159,11 +1160,6 @@ public abstract class ClassLoader {
return java.util.Collections.emptyEnumeration();
}
// index 0: java.lang.ClassLoader.class
// index 1: the immediate caller of index 0.
// index 2: the immediate caller of index 1.
private static native Class<? extends ClassLoader> getCaller(int index);
/**
* Registers the caller as parallel capable.</p>
* The registration succeeds if and only if all of the following
@ -1179,8 +1175,11 @@ public abstract class ClassLoader {
*
* @since 1.7
*/
@CallerSensitive
protected static boolean registerAsParallelCapable() {
return ParallelLoaders.register(getCaller(1));
Class<? extends ClassLoader> callerClass =
Reflection.getCallerClass().asSubclass(ClassLoader.class);
return ParallelLoaders.register(callerClass);
}
/**
@ -1340,15 +1339,13 @@ public abstract class ClassLoader {
*
* @since 1.2
*/
@CallerSensitive
public final ClassLoader getParent() {
if (parent == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader ccl = getCallerClassLoader();
if (needsClassLoaderPermissionCheck(ccl, this)) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
checkClassLoaderPermission(this, Reflection.getCallerClass());
}
return parent;
}
@ -1408,6 +1405,7 @@ public abstract class ClassLoader {
*
* @revised 1.4
*/
@CallerSensitive
public static ClassLoader getSystemClassLoader() {
initSystemClassLoader();
if (scl == null) {
@ -1415,10 +1413,7 @@ public abstract class ClassLoader {
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader ccl = getCallerClassLoader();
if (needsClassLoaderPermissionCheck(ccl, scl)) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
checkClassLoaderPermission(scl, Reflection.getCallerClass());
}
return scl;
}
@ -1471,8 +1466,8 @@ public abstract class ClassLoader {
// class loader 'from' is same as class loader 'to' or an ancestor
// of 'to'. The class loader in a system domain can access
// any class loader.
static boolean needsClassLoaderPermissionCheck(ClassLoader from,
ClassLoader to)
private static boolean needsClassLoaderPermissionCheck(ClassLoader from,
ClassLoader to)
{
if (from == to)
return false;
@ -1483,13 +1478,8 @@ public abstract class ClassLoader {
return !to.isAncestor(from);
}
// Returns the invoker's class loader, or null if none.
// NOTE: This must always be invoked when there is exactly one intervening
// frame from the core libraries on the stack between this method's
// invocation and the desired invoker.
static ClassLoader getCallerClassLoader() {
// NOTE use of more generic Reflection.getCallerClass()
Class<?> caller = Reflection.getCallerClass(3);
// Returns the class's class loader, or null if none.
static ClassLoader getClassLoader(Class<?> caller) {
// This can be null if the VM is requesting it
if (caller == null) {
return null;
@ -1498,6 +1488,17 @@ public abstract class ClassLoader {
return caller.getClassLoader0();
}
static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// caller can be null if the VM is requesting it
ClassLoader ccl = getClassLoader(caller);
if (needsClassLoaderPermissionCheck(ccl, cl)) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
}
// The class loader for the system
// @GuardedBy("ClassLoader.class")
private static ClassLoader scl;

View File

@ -22,26 +22,55 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Implementing this interface allows an object to be the target of
* the "foreach" statement.
* the "for-each loop" statement. See
* <strong>
* <a href="{@docRoot}/../technotes/guides/language/foreach.html">For-each Loop</a>
* </strong>
*
* @param <T> the type of elements returned by the iterator
*
* @since 1.5
* @jls 14.14.2 The enhanced for statement
*/
@FunctionalInterface
public interface Iterable<T> {
/**
* Returns an iterator over a set of elements of type T.
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
Iterator<T> iterator();
/**
* Performs the given action on the contents of the {@code Iterable}, in the
* order elements occur when iterating, until all elements have been
* processed or the action throws an exception. Errors or runtime
* exceptions thrown by the action are relayed to the caller.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
}

View File

@ -479,7 +479,7 @@ public final class Long extends Number implements Comparable<Long> {
* of the string as a type indicator, as would be permitted in
* Java programming language source code - except that either
* {@code L} or {@code l} may appear as a digit for a
* radix greater than 22.
* radix greater than or equal to 22.
*
* <p>An exception of type {@code NumberFormatException} is
* thrown if any of the following situations occurs:

View File

@ -49,6 +49,8 @@ import java.util.HashMap;
import java.util.Iterator;
import sun.net.www.ParseUtil;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import java.lang.annotation.Annotation;
@ -273,8 +275,9 @@ public class Package implements java.lang.reflect.AnnotatedElement {
* @return the package of the requested name. It may be null if no package
* information is available from the archive or codebase.
*/
@CallerSensitive
public static Package getPackage(String name) {
ClassLoader l = ClassLoader.getCallerClassLoader();
ClassLoader l = ClassLoader.getClassLoader(Reflection.getCallerClass());
if (l != null) {
return l.getPackage(name);
} else {
@ -294,8 +297,9 @@ public class Package implements java.lang.reflect.AnnotatedElement {
* @return a new array of packages known to the callers {@code ClassLoader}
* instance. An zero length array is returned if none are known.
*/
@CallerSensitive
public static Package[] getPackages() {
ClassLoader l = ClassLoader.getCallerClassLoader();
ClassLoader l = ClassLoader.getClassLoader(Reflection.getCallerClass());
if (l != null) {
return l.getPackages();
} else {

View File

@ -30,6 +30,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.security.AccessControlException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
@ -1024,13 +1025,24 @@ public final class ProcessBuilder
redirects,
redirectErrorStream);
} catch (IOException e) {
String exceptionInfo = ": " + e.getMessage();
Throwable cause = e;
if (security != null) {
// Can not disclose the fail reason for read-protected files.
try {
security.checkRead(prog);
} catch (AccessControlException ace) {
exceptionInfo = "";
cause = ace;
}
}
// It's much easier for us to create a high-quality error
// message than the low-level C code which found the problem.
throw new IOException(
"Cannot run program \"" + prog + "\""
+ (dir == null ? "" : " (in directory \"" + dir + "\")")
+ ": " + e.getMessage(),
e);
+ exceptionInfo,
cause);
}
}
}

View File

@ -27,6 +27,8 @@ package java.lang;
import java.io.*;
import java.util.StringTokenizer;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
/**
* Every Java application has a single instance of class
@ -790,8 +792,9 @@ public class Runtime {
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
public void load(String filename) {
load0(System.getCallerClass(), filename);
load0(Reflection.getCallerClass(), filename);
}
synchronized void load0(Class<?> fromClass, String filename) {
@ -850,8 +853,9 @@ public class Runtime {
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
public void loadLibrary(String libname) {
loadLibrary0(System.getCallerClass(), libname);
loadLibrary0(Reflection.getCallerClass(), libname);
}
synchronized void loadLibrary0(Class<?> fromClass, String libname) {

View File

@ -36,10 +36,10 @@ import java.net.SocketPermission;
import java.net.NetPermission;
import java.util.Hashtable;
import java.net.InetAddress;
import java.lang.reflect.Member;
import java.lang.reflect.*;
import java.net.URL;
import sun.reflect.CallerSensitive;
import sun.security.util.SecurityConstants;
/**
@ -1679,6 +1679,7 @@ class SecurityManager {
* @since JDK1.1
* @see #checkPermission(java.security.Permission) checkPermission
*/
@CallerSensitive
public void checkMemberAccess(Class<?> clazz, int which) {
if (clazz == null) {
throw new NullPointerException("class can't be null");

View File

@ -35,6 +35,7 @@ import java.security.AllPermission;
import java.nio.channels.Channel;
import java.nio.channels.spi.SelectorProvider;
import sun.nio.ch.Interruptible;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import sun.security.util.SecurityConstants;
import sun.reflect.annotation.AnnotationType;
@ -1072,8 +1073,9 @@ public final class System {
* @see java.lang.Runtime#load(java.lang.String)
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
public static void load(String filename) {
Runtime.getRuntime().load0(getCallerClass(), filename);
Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);
}
/**
@ -1107,8 +1109,9 @@ public final class System {
* @see java.lang.Runtime#loadLibrary(java.lang.String)
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
public static void loadLibrary(String libname) {
Runtime.getRuntime().loadLibrary0(getCallerClass(), libname);
Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
}
/**
@ -1245,10 +1248,4 @@ public final class System {
}
});
}
/* returns the class of the caller. */
static Class<?> getCallerClass() {
// NOTE use of more generic Reflection.getCallerClass()
return Reflection.getCallerClass(3);
}
}

View File

@ -37,6 +37,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.LockSupport;
import sun.nio.ch.Interruptible;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import sun.security.util.SecurityConstants;
@ -1443,15 +1445,14 @@ class Thread implements Runnable {
*
* @since 1.2
*/
@CallerSensitive
public ClassLoader getContextClassLoader() {
if (contextClassLoader == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader ccl = ClassLoader.getCallerClassLoader();
if (ClassLoader.needsClassLoaderPermissionCheck(ccl, contextClassLoader)) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
ClassLoader.checkClassLoaderPermission(contextClassLoader,
Reflection.getCallerClass());
}
return contextClassLoader;
}

View File

@ -709,7 +709,9 @@ import jdk.internal.org.objectweb.asm.Type;
InvokerBytecodeGenerator.maybeDump(className, classFile);
Class<? extends BoundMethodHandle> bmhClass =
//UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class);
UNSAFE.defineClass(className, classFile, 0, classFile.length).asSubclass(BoundMethodHandle.class);
UNSAFE.defineClass(className, classFile, 0, classFile.length,
BoundMethodHandle.class.getClassLoader(), null)
.asSubclass(BoundMethodHandle.class);
UNSAFE.ensureClassInitialized(bmhClass);
return bmhClass;

View File

@ -184,7 +184,7 @@ import java.security.PrivilegedAction;
for (int i=0; i<markerInterfaces.length; i++) {
interfaces[i+1] = markerInterfaces[i].getName().replace('.', '/');
}
cw.visit(CLASSFILE_VERSION, ACC_SUPER,
cw.visit(CLASSFILE_VERSION, ACC_SUPER + ACC_FINAL + ACC_SYNTHETIC,
lambdaClassName, null,
NAME_MAGIC_ACCESSOR_IMPL, interfaces);

View File

@ -391,10 +391,11 @@ import java.util.Objects;
// private flags, not part of RECOGNIZED_MODIFIERS:
static final int
IS_METHOD = MN_IS_METHOD, // method (not constructor)
IS_CONSTRUCTOR = MN_IS_CONSTRUCTOR, // constructor
IS_FIELD = MN_IS_FIELD, // field
IS_TYPE = MN_IS_TYPE; // nested type
IS_METHOD = MN_IS_METHOD, // method (not constructor)
IS_CONSTRUCTOR = MN_IS_CONSTRUCTOR, // constructor
IS_FIELD = MN_IS_FIELD, // field
IS_TYPE = MN_IS_TYPE, // nested type
CALLER_SENSITIVE = MN_CALLER_SENSITIVE; // @CallerSensitive annotation detected
static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE;
@ -430,6 +431,10 @@ import java.util.Objects;
public boolean isPackage() {
return !testAnyFlags(ALL_ACCESS);
}
/** Query whether this member has a CallerSensitive annotation. */
public boolean isCallerSensitive() {
return testAllFlags(CALLER_SENSITIVE);
}
/** Utility method to query whether this member is accessible from a given lookup class. */
public boolean isAccessibleFrom(Class<?> lookupClass) {

View File

@ -34,6 +34,8 @@ import sun.invoke.empty.Empty;
import sun.invoke.util.ValueConversions;
import sun.invoke.util.VerifyType;
import sun.invoke.util.Wrapper;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import static java.lang.invoke.LambdaForm.*;
import static java.lang.invoke.MethodHandleStatics.*;
import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
@ -891,9 +893,11 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
}
}
@CallerSensitive
private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
final int FRAME_COUNT_ARG = 2; // [0] Reflection [1] BindCaller [2] Expected
Class<?> actual = sun.reflect.Reflection.getCallerClass(FRAME_COUNT_ARG);
// This method is called via MH_checkCallerClass and so it's
// correct to ask for the immediate caller here.
Class<?> actual = Reflection.getCallerClass();
if (actual != expected && actual != expected2)
throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
+(expected == expected2 ? "" : ", or else "+expected2.getName()));

View File

@ -26,7 +26,6 @@
package java.lang.invoke;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import static java.lang.invoke.MethodHandleNatives.Constants.*;
import static java.lang.invoke.MethodHandleStatics.*;
@ -34,7 +33,7 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
/**
* The JVM interface for the method handles package is all here.
* This is an interface internal and private to an implemetantion of JSR 292.
* This is an interface internal and private to an implementation of JSR 292.
* <em>This class is not part of the JSR 292 standard.</em>
* @author jrose
*/
@ -101,6 +100,7 @@ class MethodHandleNatives {
MN_IS_CONSTRUCTOR = 0x00020000, // constructor
MN_IS_FIELD = 0x00040000, // field
MN_IS_TYPE = 0x00080000, // nested type
MN_CALLER_SENSITIVE = 0x00100000, // @CallerSensitive annotation detected
MN_REFERENCE_KIND_SHIFT = 24, // refKind
MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
// The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
@ -391,129 +391,24 @@ class MethodHandleNatives {
* I.e., does it call Reflection.getCallerClass or a similer method
* to ask about the identity of its caller?
*/
// FIXME: Replace this pattern match by an annotation @sun.reflect.CallerSensitive.
static boolean isCallerSensitive(MemberName mem) {
if (!mem.isInvocable()) return false; // fields are not caller sensitive
return mem.isCallerSensitive() || canBeCalledVirtual(mem);
}
static boolean canBeCalledVirtual(MemberName mem) {
assert(mem.isInvocable());
Class<?> defc = mem.getDeclaringClass();
switch (mem.getName()) {
case "doPrivileged":
case "doPrivilegedWithCombiner":
return defc == java.security.AccessController.class;
case "checkMemberAccess":
return canBeCalledVirtual(mem, java.lang.SecurityManager.class);
case "getUnsafe":
return defc == sun.misc.Unsafe.class;
case "lookup":
return defc == java.lang.invoke.MethodHandles.class;
case "findStatic":
case "findVirtual":
case "findConstructor":
case "findSpecial":
case "findGetter":
case "findSetter":
case "findStaticGetter":
case "findStaticSetter":
case "bind":
case "unreflect":
case "unreflectSpecial":
case "unreflectConstructor":
case "unreflectGetter":
case "unreflectSetter":
return defc == java.lang.invoke.MethodHandles.Lookup.class;
case "invoke":
return defc == java.lang.reflect.Method.class;
case "get":
case "getBoolean":
case "getByte":
case "getChar":
case "getShort":
case "getInt":
case "getLong":
case "getFloat":
case "getDouble":
case "set":
case "setBoolean":
case "setByte":
case "setChar":
case "setShort":
case "setInt":
case "setLong":
case "setFloat":
case "setDouble":
return defc == java.lang.reflect.Field.class;
case "newInstance":
if (defc == java.lang.reflect.Constructor.class) return true;
if (defc == java.lang.Class.class) return true;
break;
case "forName":
case "getClassLoader":
case "getClasses":
case "getFields":
case "getMethods":
case "getConstructors":
case "getDeclaredClasses":
case "getDeclaredFields":
case "getDeclaredMethods":
case "getDeclaredConstructors":
case "getField":
case "getMethod":
case "getConstructor":
case "getDeclaredField":
case "getDeclaredMethod":
case "getDeclaredConstructor":
return defc == java.lang.Class.class;
case "getConnection":
case "getDriver":
case "getDrivers":
case "deregisterDriver":
return defc == getClass("java.sql.DriverManager");
case "newUpdater":
if (defc == java.util.concurrent.atomic.AtomicIntegerFieldUpdater.class) return true;
if (defc == java.util.concurrent.atomic.AtomicLongFieldUpdater.class) return true;
if (defc == java.util.concurrent.atomic.AtomicReferenceFieldUpdater.class) return true;
break;
case "getContextClassLoader":
return canBeCalledVirtual(mem, java.lang.Thread.class);
case "getPackage":
case "getPackages":
return defc == java.lang.Package.class;
case "getParent":
case "getSystemClassLoader":
return defc == java.lang.ClassLoader.class;
case "load":
case "loadLibrary":
if (defc == java.lang.Runtime.class) return true;
if (defc == java.lang.System.class) return true;
break;
case "getCallerClass":
if (defc == sun.reflect.Reflection.class) return true;
if (defc == java.lang.System.class) return true;
break;
case "getCallerClassLoader":
return defc == java.lang.ClassLoader.class;
case "registerAsParallelCapable":
return canBeCalledVirtual(mem, java.lang.ClassLoader.class);
case "getProxyClass":
case "newProxyInstance":
return defc == java.lang.reflect.Proxy.class;
case "asInterfaceInstance":
return defc == java.lang.invoke.MethodHandleProxies.class;
case "getBundle":
case "clearCache":
return defc == java.util.ResourceBundle.class;
}
return false;
}
// avoid static dependency to a class in other modules
private static Class<?> getClass(String cn) {
try {
return Class.forName(cn, false,
MethodHandleNatives.class.getClassLoader());
} catch (ClassNotFoundException e) {
throw new InternalError(e);
}
}
static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
if (symbolicRefClass == definingClass) return true;

Some files were not shown because too many files have changed in this diff Show More