This commit is contained in:
Lana Steuck 2014-10-16 14:14:57 -07:00
commit 46fb368afe
175 changed files with 5267 additions and 1097 deletions

View File

@ -25,10 +25,6 @@
include GensrcCommon.gmk
# TODO: maybe split into separate modules?
include GensrcProperties.gmk
GENSRC_JAVA_BASE += $(GENSRC_PROPERTIES)
include GensrcLocaleData.gmk
include GensrcCharacterData.gmk
include GensrcMisc.gmk
@ -37,6 +33,34 @@ include GensrcCharsetCoder.gmk
include GensrcBuffer.gmk
include GensrcExceptions.gmk
################################################################################
include GensrcProperties.gmk
$(eval $(call SetupCompileProperties,LIST_RESOURCE_BUNDLE, \
$(filter %.properties, \
$(call CacheFind, $(JDK_TOPDIR)/src/java.base/share/classes/sun/launcher/resources)), \
ListResourceBundle))
$(eval $(call SetupCompileProperties,SUN_UTIL, \
$(filter %.properties, \
$(call CacheFind, $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/resources)), \
sun.util.resources.LocaleNamesBundle))
GENSRC_JAVA_BASE += $(LIST_RESOURCE_BUNDLE) $(SUN_UTIL)
# Some resources bundles are already present as java files but still need to be
# copied to zh_HK locale.
$(eval $(call SetupCopy-zh_HK,COPY_ZH_HK, \
$(addprefix $(JDK_TOPDIR)/src/java.base/share/classes/, \
sun/misc/resources/Messages_zh_TW.java \
sun/security/util/AuthResources_zh_TW.java \
sun/security/util/Resources_zh_TW.java)))
GENSRC_JAVA_BASE += $(COPY_ZH_HK)
################################################################################
java.base: $(GENSRC_JAVA_BASE)
all: java.base

View File

@ -38,6 +38,48 @@ endif
include GensrcSwing.gmk
################################################################################
include GensrcProperties.gmk
PROP_SRC_DIRS := \
$(JDK_TOPDIR)/src/java.desktop/share/classes/sun/awt/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/accessibility/internal/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/basic/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/metal/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/synth/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/sun/print/resources \
#
ifeq ($(OPENJDK_TARGET_OS), macosx)
PROP_SRC_DIRS += \
$(JDK_TOPDIR)/src/java.desktop/macosx/classes/com/apple/laf/resources \
$(JDK_TOPDIR)/src/java.desktop/macosx/classes/sun/awt/resources \
#
endif
ifeq ($(OPENJDK_TARGET_OS), windows)
PROP_SRC_DIRS += $(JDK_TOPDIR)/src/java.desktop/windows/classes/sun/awt/windows
else
PROP_SRC_DIRS += $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/resources
endif
$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
$(filter %.properties, $(call CacheFind, $(PROP_SRC_DIRS))), ListResourceBundle))
GENSRC_JAVA_DESKTOP += $(COMPILE_PROPERTIES)
# Some resources bundles are already present as java files but still need to be
# copied to zh_HK locale.
$(eval $(call SetupCopy-zh_HK,COPY_ZH_HK, \
$(JDK_TOPDIR)/src/java.desktop/share/classes/sun/applet/resources/MsgAppletViewer_zh_TW.java))
GENSRC_JAVA_DESKTOP += $(COPY_ZH_HK)
################################################################################
java.desktop: $(GENSRC_JAVA_DESKTOP)
all: java.desktop

View File

@ -0,0 +1,43 @@
#
# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. 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.
#
include GensrcCommon.gmk
################################################################################
include GensrcProperties.gmk
$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
$(filter %.properties, \
$(call CacheFind, $(JDK_TOPDIR)/src/java.logging/share/classes/sun/util/logging/resources)), \
ListResourceBundle))
TARGETS += $(COMPILE_PROPERTIES)
################################################################################
all: $(TARGETS)
.PHONY: all

View File

@ -0,0 +1,43 @@
#
# 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
# 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.
#
include GensrcCommon.gmk
################################################################################
include GensrcProperties.gmk
$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
$(filter %.properties, \
$(call CacheFind, $(JDK_TOPDIR)/src/java.management/share/classes/sun/management/resources)), \
ListResourceBundle))
TARGETS += $(COMPILE_PROPERTIES)
################################################################################
all: $(TARGETS)
.PHONY: all

View File

@ -0,0 +1,43 @@
#
# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. 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.
#
include GensrcCommon.gmk
################################################################################
include GensrcProperties.gmk
$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
$(filter %.properties, \
$(call CacheFind, $(JDK_TOPDIR)/src/jdk.dev/share/classes/sun/tools/jar/resources)), \
ListResourceBundle))
TARGETS += $(COMPILE_PROPERTIES)
################################################################################
all: $(TARGETS)
.PHONY: all

View File

@ -69,6 +69,17 @@ GENSRC_JDK_JDI += $(JDK_OUTPUTDIR)/gensrc/jdk.jdi/META-INF/services/com.sun.jdi.
################################################################################
include GensrcProperties.gmk
$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
$(filter %.properties, \
$(call CacheFind, $(JDK_TOPDIR)/src/jdk.jdi/share/classes/com/sun/tools/jdi/resources)), \
ListResourceBundle))
GENSRC_JDK_JDI += $(COMPILE_PROPERTIES)
################################################################################
jdk.jdi: $(GENSRC_JDK_JDI)
all: jdk.jdi

View File

@ -31,6 +31,20 @@ $(eval $(call IncludeCustomExtension, jdk, gensrc/Gensrc-jdk.localedata.gmk))
include GensrcLocaleData.gmk
include GensrcCLDR.gmk
################################################################################
include GensrcProperties.gmk
$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
$(filter %.properties, \
$(call CacheFind, $(JDK_TOPDIR)/src/jdk.localedata/share/classes/sun/util/resources)), \
sun.util.resources.LocaleNamesBundle))
# Skip generating zh_HK from zh_TW for this module.
GENSRC_JDK_LOCALEDATA += $(filter-out %_zh_HK.java, $(COMPILE_PROPERTIES))
################################################################################
jdk.localedata: $(GENSRC_JDK_LOCALEDATA)
all: jdk.localedata

View File

@ -23,132 +23,81 @@
# questions.
#
# All .properties files to be compiled are appended to this variable.
ALL_COMPILED_PROPSOURCES :=
# All generated .java files from compilation are appended to this variable.
ALL_COMPILED_PROPJAVAS :=
# The (very long) command line for compilation, stored in a file, prior to use.
COMPILE_PROPCMDLINE :=
# This file defines macros that sets up rules for generating java classes
# from resource bundle properties files.
define add_properties_to_compile
# $1 is the name of the properties group
# $2 is the files belonging to this group
# $3 is the super class for the generated java file.
################################################################################
# Helper macro for SetupCopy-zh_HK.
define SetupOneCopy-zh_HK
$1_$2_TARGET := $$(patsubst $(JDK_TOPDIR)/src/$(MODULE)/share/classes/%, \
$(JDK_OUTPUTDIR)/gensrc/$(MODULE)/%, \
$$(subst _zh_TW,_zh_HK, $2))
# Convert <root>/jdk/src/<module>/share/classes/sun/util/resources/CurrencyNames_sv.properties
# to <build>/jdk/gensrc/<module/sun/util/resources/CurrencyNames_sv.java
$1_PROPJAVAS := $$(patsubst $(JDK_TOPDIR)/src/%.properties, \
$(JDK_OUTPUTDIR)/gensrc/%.java, \
$$(subst /share/classes,, \
$$(subst /$(OPENJDK_TARGET_OS_API_DIR)/classes,, \
$$(subst /$(OPENJDK_TARGET_OS)/classes,, $2))))
$$($1_$2_TARGET): $2
$(MKDIR) -p $$(@D)
$(CAT) $$< | $(SED) -e '/class/s/_zh_TW/_zh_HK/' > $$@
# Accumulate all found properties files.
ALL_COMPILED_PROPSOURCES += $2
$1 += $$($1_$2_TARGET)
endef
# Generate the list of to be created java files.
ALL_COMPILED_PROPJAVAS += $$($1_PROPJAVAS)
################################################################################
# Creates rules for copying zh_TW resources to zh_HK.
# Param 1 - Variable to add targets to
# Param 2 - Files to copy from
define SetupCopy-zh_HK
$$(foreach f, $2, $$(eval $$(call SetupOneCopy-zh_HK,$1,$$f)))
endef
# Now generate a sequence of
# "-compile ...CurrencyNames_sv.properties ...CurrencyNames_sv.java ListResourceBundle"
################################################################################
# Creates a rule that runs CompileProperties on a set of properties files.
# Param 1 - Variable to add targets to, must not contain space
# Param 2 - Properties files to process
# Param 3 - The super class for the generated classes
define SetupCompileProperties
$1_SRCS := $2
$1_CLASS := $3
# Convert .../src/<module>/share/classes/com/sun/tools/javac/resources/javac_zh_CN.properties
# to .../langtools/gensrc/<module>/com/sun/tools/javac/resources/javac_zh_CN.java
# Strip away prefix and suffix, leaving for example only:
# "<module>/share/classes/com/sun/tools/javac/resources/javac_zh_CN"
$1_JAVAS := $$(patsubst $(JDK_TOPDIR)/src/%, \
$(JDK_OUTPUTDIR)/gensrc/%, \
$$(patsubst %.properties, %.java, \
$$(subst /share/classes,, $$($1_SRCS))))
# Generate the package dirs for the to be generated java files. Sort to remove
# duplicates.
$1_DIRS := $$(sort $$(dir $$($1_JAVAS)))
# Now generate a sequence of:
# "-compile ...javac_zh_CN.properties ...javac_zh_CN.java java.util.ListResourceBundle"
# suitable to be fed into the CompileProperties command.
COMPILE_PROPCMDLINE += $$(subst _SPACE_,$(SPACE),$$(join $$(addprefix -compile_SPACE_, $2), \
$$(addsuffix _SPACE_$(strip $3), \
$$(addprefix _SPACE_, $$($1_PROPJAVAS)))))
$1_CMDLINE := $$(subst _SPACE_, $(SPACE), \
$$(join $$(addprefix -compile_SPACE_, $$($1_SRCS)), \
$$(addsuffix _SPACE_$$($1_CLASS), \
$$(addprefix _SPACE_, $$($1_JAVAS)))))
$1_TARGET := $(JDK_OUTPUTDIR)/gensrc/$(MODULE)/_the.$1.done
$1_CMDLINE_FILE := $(JDK_OUTPUTDIR)/gensrc/$(MODULE)/_the.$1.cmdline
# Now setup the rule for the generation of the resource bundles.
$$($1_TARGET): $$($1_SRCS) $$($1_JAVAS) $(BUILD_TOOLS_JDK)
$(MKDIR) -p $$(@D) $$($1_DIRS)
$(ECHO) Compiling $$(words $$($1_SRCS)) properties into resource bundles for $(MODULE)
$(RM) $$($1_CMDLINE_FILE)
$$(call ListPathsSafely,$1_CMDLINE,\n, >> $$($1_CMDLINE_FILE))
$(TOOL_COMPILEPROPERTIES) -quiet @$$($1_CMDLINE_FILE)
$(TOUCH) $$@
$$($1_JAVAS): $$($1_SRCS)
# Create zh_HK versions of all zh_TW files created above
$$(eval $$(call SetupCopy-zh_HK,$1_HK,$$(filter %_zh_TW.java, $$($1_JAVAS))))
# The zh_HK copy must wait for the compile properties tool to run
$$($1_HK): $$($1_TARGET)
$1 += $$($1_JAVAS) $$($1_TARGET) $$($1_HK)
endef
################################################################################
# Some packages have properties that need to be converted to java source files.
COMPILE_PROP_SRC_FILES := \
$(filter %.properties, $(call CacheFind, \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/accessibility/internal/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/basic/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/metal/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/synth/resources \
$(JDK_TOPDIR)/src/jdk.jdi/share/classes/com/sun/tools/jdi/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/sun/awt/resources \
$(JDK_TOPDIR)/src/java.base/share/classes/sun/launcher/resources \
$(JDK_TOPDIR)/src/java.management/share/classes/sun/management/resources \
$(JDK_TOPDIR)/src/java.desktop/share/classes/sun/print/resources \
$(JDK_TOPDIR)/src/jdk.dev/share/classes/sun/tools/jar/resources \
$(JDK_TOPDIR)/src/java.logging/share/classes/sun/util/logging/resources)) \
#
ifeq ($(OPENJDK_TARGET_OS), macosx)
COMPILE_PROP_SRC_FILES += \
$(filter %.properties, $(call CacheFind, \
$(JDK_TOPDIR)/src/java.desktop/macosx/classes/com/apple/laf/resources \
$(JDK_TOPDIR)/src/java.desktop/macosx/classes/sun/awt/resources)) \
#
endif
ifeq ($(OPENJDK_TARGET_OS), windows)
COMPILE_PROP_SRC_FILES += \
$(filter %.properties, $(call CacheFind, \
$(JDK_TOPDIR)/src/java.desktop/windows/classes/sun/awt/windows)) \
#
else # ! windows
COMPILE_PROP_SRC_FILES += \
$(filter %.properties, $(call CacheFind, \
$(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/resources)) \
#
endif
$(eval $(call add_properties_to_compile,LIST_RESOURCE_BUNDLE, \
$(COMPILE_PROP_SRC_FILES), ListResourceBundle))
# sun/util/resources
$(eval $(call add_properties_to_compile,SUN_UTIL, \
$(filter %.properties, \
$(call CacheFind, $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/resources) \
$(call CacheFind, $(JDK_TOPDIR)/src/jdk.localedata/share/classes/sun/util/resources)), \
sun.util.resources.LocaleNamesBundle))
################################################################################
# Now setup the rule for the generation of the resource bundles.
$(JDK_OUTPUTDIR)/gensrc/_the.compiled_properties: $(ALL_COMPILED_PROPSOURCES) $(BUILD_TOOLS_JDK)
# Generate all output directories in advance since the build tool does not do that...
$(MKDIR) -p $(sort $(dir $(ALL_COMPILED_PROPJAVAS)))
$(ECHO) Compiling $(words $(ALL_COMPILED_PROPSOURCES)) properties into resource bundles
$(call ListPathsSafely,COMPILE_PROPCMDLINE,\n, >> $(JDK_OUTPUTDIR)/gensrc/_the.cmdline)
$(TOOL_COMPILEPROPERTIES) -quiet @$(JDK_OUTPUTDIR)/gensrc/_the.cmdline
$(TOUCH) $@
$(ALL_COMPILED_PROPJAVAS): $(JDK_OUTPUTDIR)/gensrc/_the.compiled_properties
################################################################################
# Some zh_HK resources are just copies of zh_TW
define convert_tw_to_hk
$(MKDIR) -p $(@D)
$(CAT) $< | $(SED) -e '/class/s/_zh_TW/_zh_HK/' > $@
endef
# Some are copies of existing sources
$(JDK_OUTPUTDIR)/gensrc/java.desktop/%_zh_HK.java: \
$(JDK_TOPDIR)/src/java.desktop/share/classes/%_zh_TW.java
$(call convert_tw_to_hk)
$(JDK_OUTPUTDIR)/gensrc/java.base/%_zh_HK.java: \
$(JDK_TOPDIR)/src/java.base/share/classes/%_zh_TW.java
$(call convert_tw_to_hk)
# Others are copies of sources generated by this makefile
$(JDK_OUTPUTDIR)/gensrc/%_zh_HK.java: $(JDK_OUTPUTDIR)/gensrc/%_zh_TW.java
$(call convert_tw_to_hk)
# The existing sources
ZH_HK_JAVA := java.desktop/sun/applet/resources/MsgAppletViewer_zh_HK.java \
java.base/sun/misc/resources/Messages_zh_HK.java \
java.base/sun/security/util/AuthResources_zh_HK.java \
java.base/sun/security/util/Resources_zh_HK.java
ZH_HK_JAVA_FILES := $(addprefix $(JDK_OUTPUTDIR)/gensrc/, $(ZH_HK_JAVA)) \
$(filter-out $(JDK_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/zh/%, \
$(subst _zh_TW,_zh_HK,$(filter %_zh_TW.java, $(ALL_COMPILED_PROPJAVAS))))
################################################################################
GENSRC_PROPERTIES := $(ALL_COMPILED_PROPJAVAS) $(ZH_HK_JAVA_FILES)

View File

@ -224,7 +224,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBZIP, \
$(call SET_SHARED_LIBRARY_ORIGIN) \
$(EXPORT_ZIP_FUNCS), \
LDFLAGS_windows := -export:ZIP_Open -export:ZIP_Close -export:ZIP_FindEntry \
-export:ZIP_ReadEntry -export:ZIP_GetNextEntry jvm.lib \
-export:ZIP_ReadEntry -export:ZIP_GetNextEntry -export:ZIP_CRC32 jvm.lib \
$(WIN_JAVA_LIB), \
LDFLAGS_SUFFIX_linux := -ljvm -ljava $(LIBZ), \
LDFLAGS_SUFFIX_solaris := -ljvm -ljava $(LIBZ) -lc, \

View File

@ -10,8 +10,13 @@ SUNWprivate_1.1 {
Java_oracle_jrockit_jfr_Process_getpid;
Java_oracle_jrockit_jfr_Timing_counterTime;
Java_oracle_jrockit_jfr_Timing_init;
Java_oracle_jrockit_jfr_NativeLogger_output0;
Java_oracle_jrockit_jfr_VMJFR_isEnabled;
Java_oracle_jrockit_jfr_Logger_output0;
Java_oracle_jrockit_jfr_JFR_isCommercialFeaturesUnlocked;
Java_oracle_jrockit_jfr_JFR_isStarted;
Java_oracle_jrockit_jfr_JFR_isSupportedInVM;
Java_oracle_jrockit_jfr_JFR_startFlightRecorder;
Java_oracle_jrockit_jfr_JFR_isDisabledOnCommandLine;
Java_oracle_jrockit_jfr_JFR_isEnabled;
Java_oracle_jrockit_jfr_VMJFR_options;
Java_oracle_jrockit_jfr_VMJFR_init;
Java_oracle_jrockit_jfr_VMJFR_addConstPool;
@ -33,7 +38,6 @@ SUNWprivate_1.1 {
Java_oracle_jrockit_jfr_VMJFR_setPeriod;
Java_oracle_jrockit_jfr_VMJFR_getPeriod;
Java_oracle_jrockit_jfr_VMJFR_descriptors;
Java_oracle_jrockit_jfr_VMJFR_redefineClass0;
Java_oracle_jrockit_jfr_VMJFR_retransformClasses0;
JNI_OnLoad;
local:

View File

@ -28,6 +28,8 @@
SUNWprivate_1.1 {
global:
JNI_OnLoad;
Java_java_net_AbstractPlainDatagramSocketImpl_init;
Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable;
Java_java_net_PlainSocketImpl_socketListen;
Java_java_net_PlainDatagramSocketImpl_getTTL;
Java_java_net_PlainDatagramSocketImpl_init;

View File

@ -112,8 +112,7 @@ public final class GenModulesList {
}
static final List<String> AGGREGATORS = Arrays.asList(new String[] {
"java.se", "java.compact1", "java.compact2",
"java.compact3", "jdk.compact3"});
"java.se", "java.compact1", "java.compact2", "java.compact3"});
class TopoSorter {
final Deque<Module> result = new LinkedList<>();

View File

@ -262,8 +262,8 @@ public final class Class<T> implements java.io.Serializable,
@CallerSensitive
public static Class<?> forName(String className)
throws ClassNotFoundException {
return forName0(className, true,
ClassLoader.getClassLoader(Reflection.getCallerClass()));
Class<?> caller = Reflection.getCallerClass();
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
@ -333,22 +333,27 @@ public final class Class<T> implements java.io.Serializable,
ClassLoader loader)
throws ClassNotFoundException
{
if (sun.misc.VM.isSystemDomainLoader(loader)) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader ccl = ClassLoader.getClassLoader(Reflection.getCallerClass());
Class<?> caller = null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Reflective call to get caller class is only needed if a security manager
// is present. Avoid the overhead of making this call otherwise.
caller = Reflection.getCallerClass();
if (sun.misc.VM.isSystemDomainLoader(loader)) {
ClassLoader ccl = ClassLoader.getClassLoader(caller);
if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
sm.checkPermission(
SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
}
return forName0(name, initialize, loader);
return forName0(name, initialize, loader, caller);
}
/** Called after security checks have been made. */
/** Called after security check for system loader access checks have been made. */
private static native Class<?> forName0(String name, boolean initialize,
ClassLoader loader)
ClassLoader loader,
Class<?> caller)
throws ClassNotFoundException;
/**

View File

@ -1045,8 +1045,9 @@ public final class String
}
}
// Argument is a String
if (cs.equals(this))
return true;
if (cs instanceof String) {
return equals(cs);
}
// Argument is a generic CharSequence
char v1[] = value;
int n = v1.length;

View File

@ -594,6 +594,9 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
static class Lazy {
private static final Class<?> MHI = MethodHandleImpl.class;
private static final MethodHandle[] ARRAYS;
private static final MethodHandle[] FILL_ARRAYS;
static final NamedFunction NF_checkSpreadArgument;
static final NamedFunction NF_guardWithCatch;
static final NamedFunction NF_throwException;
@ -606,6 +609,9 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
static final MethodHandle MH_arrayIdentity;
static {
ARRAYS = makeArrays();
FILL_ARRAYS = makeFillArrays();
try {
NF_checkSpreadArgument = new NamedFunction(MHI.getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
NF_guardWithCatch = new NamedFunction(MHI.getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class,
@ -1268,7 +1274,6 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
assert(mhs.size() == 11); // current number of methods
return mhs.toArray(new MethodHandle[MAX_ARITY+1]);
}
private static final MethodHandle[] ARRAYS = makeArrays();
// filling versions of the above:
// using Integer len instead of int len and no varargs to avoid bootstrapping problems
@ -1315,6 +1320,9 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
Object a4, Object a5, Object a6, Object a7,
Object a8, Object a9)
{ fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return a; }
private static final int FILL_ARRAYS_COUNT = 11; // current number of fillArray methods
private static MethodHandle[] makeFillArrays() {
ArrayList<MethodHandle> mhs = new ArrayList<>();
mhs.add(null); // there is no empty fill; at least a0 is required
@ -1323,10 +1331,9 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
if (mh == null) break;
mhs.add(mh);
}
assert(mhs.size() == 11); // current number of methods
assert(mhs.size() == FILL_ARRAYS_COUNT);
return mhs.toArray(new MethodHandle[0]);
}
private static final MethodHandle[] FILL_ARRAYS = makeFillArrays();
private static Object copyAsPrimitiveArray(Wrapper w, Object... boxes) {
Object a = w.makeArray(boxes.length);
@ -1338,15 +1345,15 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
* arguments and returns an Object array of them, as if for varargs.
*/
static MethodHandle varargsArray(int nargs) {
MethodHandle mh = ARRAYS[nargs];
MethodHandle mh = Lazy.ARRAYS[nargs];
if (mh != null) return mh;
mh = findCollector("array", nargs, Object[].class);
if (mh != null) mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
if (mh != null) return ARRAYS[nargs] = mh;
if (mh != null) return Lazy.ARRAYS[nargs] = mh;
mh = buildVarargsArray(Lazy.MH_fillNewArray, Lazy.MH_arrayIdentity, nargs);
assert(assertCorrectArity(mh, nargs));
mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
return ARRAYS[nargs] = mh;
return Lazy.ARRAYS[nargs] = mh;
}
private static boolean assertCorrectArity(MethodHandle mh, int arity) {
@ -1382,7 +1389,7 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
return mh;
}
private static final int LEFT_ARGS = (FILL_ARRAYS.length - 1);
private static final int LEFT_ARGS = FILL_ARRAYS_COUNT - 1;
private static final MethodHandle[] FILL_ARRAY_TO_RIGHT = new MethodHandle[MAX_ARITY+1];
/** fill_array_to_right(N).invoke(a, argL..arg[N-1])
* fills a[L]..a[N-1] with corresponding arguments,
@ -1413,7 +1420,7 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
if (midLen < LEFT_ARGS) rightLen = nargs - (midLen = LEFT_ARGS);
assert(rightLen > 0);
MethodHandle midFill = fillToRight(midLen); // recursive fill
MethodHandle rightFill = FILL_ARRAYS[rightLen].bindTo(midLen); // [midLen..nargs-1]
MethodHandle rightFill = Lazy.FILL_ARRAYS[rightLen].bindTo(midLen); // [midLen..nargs-1]
assert(midFill.type().parameterCount() == 1 + midLen - LEFT_ARGS);
assert(rightFill.type().parameterCount() == 1 + rightLen);

View File

@ -727,7 +727,7 @@ class MethodType implements java.io.Serializable {
* @return the parameter types (as an immutable list)
*/
public List<Class<?>> parameterList() {
return Collections.unmodifiableList(Arrays.asList(ptypes));
return Collections.unmodifiableList(Arrays.asList(ptypes.clone()));
}
/*non-public*/ Class<?> lastParameterType() {

View File

@ -68,6 +68,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
return null;
}
});
init();
}
/**
@ -362,4 +363,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
protected boolean nativeConnectDisabled() {
return connectDisabled;
}
native int dataAvailable();
private static native void init();
}

View File

@ -85,6 +85,17 @@ class DatagramSocket implements java.io.Closeable {
*/
boolean oldImpl = false;
/**
* Set when a socket is ST_CONNECTED until we are certain
* that any packets which might have been received prior
* to calling connect() but not read by the application
* have been read. During this time we check the source
* address of all packets received to be sure they are from
* the connected destination. Other packets are read but
* silently dropped.
*/
private boolean explicitFilter = false;
private int bytesLeftToFilter;
/*
* Connection state:
* ST_NOT_CONNECTED = socket not connected
@ -144,6 +155,15 @@ class DatagramSocket implements java.io.Closeable {
// socket is now connected by the impl
connectState = ST_CONNECTED;
// Do we need to filter some packets?
int avail = getImpl().dataAvailable();
if (avail == -1) {
throw new SocketException();
}
explicitFilter = avail > 0;
if (explicitFilter) {
bytesLeftToFilter = getReceiveBufferSize();
}
} catch (SocketException se) {
// connection will be emulated by DatagramSocket
@ -492,6 +512,7 @@ class DatagramSocket implements java.io.Closeable {
connectedAddress = null;
connectedPort = -1;
connectState = ST_NOT_CONNECTED;
explicitFilter = false;
}
}
@ -750,10 +771,12 @@ class DatagramSocket implements java.io.Closeable {
} // end of while
}
}
if (connectState == ST_CONNECTED_NO_IMPL) {
if ((connectState == ST_CONNECTED_NO_IMPL) || explicitFilter) {
// We have to do the filtering the old fashioned way since
// the native impl doesn't support connect or the connect
// via the impl failed.
// via the impl failed, or .. "explicitFilter" may be set when
// a socket is connected via the impl, for a period of time
// when packets from other sources might be queued on socket.
boolean stop = false;
while (!stop) {
InetAddress peekAddress = null;
@ -772,8 +795,12 @@ class DatagramSocket implements java.io.Closeable {
if ((!connectedAddress.equals(peekAddress)) ||
(connectedPort != peekPort)) {
// throw the packet away and silently continue
DatagramPacket tmp = new DatagramPacket(new byte[1], 1);
DatagramPacket tmp = new DatagramPacket(
new byte[1024], 1024);
getImpl().receive(tmp);
if (explicitFilter) {
bytesLeftToFilter -= tmp.getLength();
}
} else {
stop = true;
}
@ -782,6 +809,15 @@ class DatagramSocket implements java.io.Closeable {
// If the security check succeeds, or the datagram is
// connected then receive the packet
getImpl().receive(p);
if (explicitFilter) {
bytesLeftToFilter -= p.getLength();
if (bytesLeftToFilter <= 0) {
explicitFilter = false;
} else {
// break out of filter, if there is no more data queued
explicitFilter = getImpl().dataAvailable() > 0;
}
}
}
}

View File

@ -63,6 +63,12 @@ public abstract class DatagramSocketImpl implements SocketOptions {
return socket;
}
int dataAvailable() {
// default impl returns zero, which disables the calling
// functionality
return 0;
}
/**
* Creates a datagram socket.
* @exception SocketException if there is an error in the

View File

@ -604,9 +604,13 @@ public abstract class Signature extends SignatureSpi {
* @return the number of bytes placed into {@code outbuf}.
*
* @exception SignatureException if this signature object is not
* initialized properly, if this signature algorithm is unable to
* process the input data provided, or if {@code len} is less
* than the actual signature length.
* initialized properly, if this signature algorithm is unable to
* process the input data provided, or if {@code len} is less
* than the actual signature length.
* @exception IllegalArgumentException if {@code outbuf} is {@code null},
* or {@code offset} or {@code len} is less than 0, or the sum of
* {@code offset} and {@code len} is greater than the length of
* {@code outbuf}.
*
* @since 1.2
*/
@ -615,6 +619,9 @@ public abstract class Signature extends SignatureSpi {
if (outbuf == null) {
throw new IllegalArgumentException("No output buffer given");
}
if (offset < 0 || len < 0) {
throw new IllegalArgumentException("offset or len is less than 0");
}
if (outbuf.length - offset < len) {
throw new IllegalArgumentException
("Output buffer too small for specified offset and length");
@ -683,9 +690,16 @@ public abstract class Signature extends SignatureSpi {
public final boolean verify(byte[] signature, int offset, int length)
throws SignatureException {
if (state == VERIFY) {
if ((signature == null) || (offset < 0) || (length < 0) ||
(length > signature.length - offset)) {
throw new IllegalArgumentException("Bad arguments");
if (signature == null) {
throw new IllegalArgumentException("signature is null");
}
if (offset < 0 || length < 0) {
throw new IllegalArgumentException
("offset or length is less than 0");
}
if (signature.length - offset < length) {
throw new IllegalArgumentException
("signature too small for specified offset and length");
}
return engineVerify(signature, offset, length);
@ -733,11 +747,25 @@ public abstract class Signature extends SignatureSpi {
* @param len the number of bytes to use, starting at offset.
*
* @exception SignatureException if this signature object is not
* initialized properly.
* initialized properly.
* @exception IllegalArgumentException if {@code data} is {@code null},
* or {@code off} or {@code len} is less than 0, or the sum of
* {@code off} and {@code len} is greater than the length of
* {@code data}.
*/
public final void update(byte[] data, int off, int len)
throws SignatureException {
if (state == SIGN || state == VERIFY) {
if (data == null) {
throw new IllegalArgumentException("data is null");
}
if (off < 0 || len < 0) {
throw new IllegalArgumentException("off or len is less than 0");
}
if (data.length - off < len) {
throw new IllegalArgumentException
("data too small for specified offset and length");
}
engineUpdate(data, off, len);
} else {
throw new SignatureException("object not initialized for "

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -84,6 +84,8 @@ public class CertificateRevokedException extends CertificateException {
* @throws NullPointerException if {@code revocationDate},
* {@code reason}, {@code authority}, or
* {@code extensions} is {@code null}
* @throws ClassCastException if {@code extensions} contains an incorrectly
* typed key or value
*/
public CertificateRevokedException(Date revocationDate, CRLReason reason,
X500Principal authority, Map<String, Extension> extensions) {
@ -94,7 +96,10 @@ public class CertificateRevokedException extends CertificateException {
this.revocationDate = new Date(revocationDate.getTime());
this.reason = reason;
this.authority = authority;
this.extensions = new HashMap<String, Extension>(extensions);
// make sure Map only contains correct types
this.extensions = Collections.checkedMap(new HashMap<>(),
String.class, Extension.class);
this.extensions.putAll(extensions);
}
/**
@ -172,7 +177,8 @@ public class CertificateRevokedException extends CertificateException {
public String getMessage() {
return "Certificate has been revoked, reason: "
+ reason + ", revocation date: " + revocationDate
+ ", authority: " + authority + ", extensions: " + extensions;
+ ", authority: " + authority + ", extension OIDs: "
+ extensions.keySet();
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -290,25 +290,26 @@ final class DigitList implements Cloneable {
FloatingDecimal.BinaryToASCIIConverter fdConverter = FloatingDecimal.getBinaryToASCIIConverter(source);
boolean hasBeenRoundedUp = fdConverter.digitsRoundedUp();
boolean allDecimalDigits = fdConverter.decimalDigitsExact();
boolean valueExactAsDecimal = fdConverter.decimalDigitsExact();
assert !fdConverter.isExceptional();
String digitsString = fdConverter.toJavaFormatString();
set(isNegative, digitsString,
hasBeenRoundedUp, allDecimalDigits,
hasBeenRoundedUp, valueExactAsDecimal,
maximumDigits, fixedPoint);
}
/**
* Generate a representation of the form DDDDD, DDDDD.DDDDD, or
* DDDDDE+/-DDDDD.
* @param roundedUp Boolean value indicating if the s digits were rounded-up.
* @param allDecimalDigits Boolean value indicating if the digits in s are
* an exact decimal representation of the double that was passed.
* @param roundedUp whether or not rounding up has already happened.
* @param valueExactAsDecimal whether or not collected digits provide
* an exact decimal representation of the value.
*/
private void set(boolean isNegative, String s,
boolean roundedUp, boolean allDecimalDigits,
boolean roundedUp, boolean valueExactAsDecimal,
int maximumDigits, boolean fixedPoint) {
this.isNegative = isNegative;
int len = s.length();
char[] source = getDataChars(len);
@ -361,7 +362,7 @@ final class DigitList implements Cloneable {
} else if (-decimalAt == maximumDigits) {
// If we round 0.0009 to 3 fractional digits, then we have to
// create a new one digit in the least significant location.
if (shouldRoundUp(0, roundedUp, allDecimalDigits)) {
if (shouldRoundUp(0, roundedUp, valueExactAsDecimal)) {
count = 1;
++decimalAt;
digits[0] = '1';
@ -381,25 +382,26 @@ final class DigitList implements Cloneable {
// Eliminate digits beyond maximum digits to be displayed.
// Round up if appropriate.
round(fixedPoint ? (maximumDigits + decimalAt) : maximumDigits,
roundedUp, allDecimalDigits);
}
roundedUp, valueExactAsDecimal);
}
/**
* Round the representation to the given number of digits.
* @param maximumDigits The maximum number of digits to be shown.
* @param alreadyRounded Boolean indicating if rounding up already happened.
* @param allDecimalDigits Boolean indicating if the digits provide an exact
* representation of the value.
* @param alreadyRounded whether or not rounding up has already happened.
* @param valueExactAsDecimal whether or not collected digits provide
* an exact decimal representation of the value.
*
* Upon return, count will be less than or equal to maximumDigits.
*/
private final void round(int maximumDigits,
boolean alreadyRounded,
boolean allDecimalDigits) {
boolean valueExactAsDecimal) {
// Eliminate digits beyond maximum digits to be displayed.
// Round up if appropriate.
if (maximumDigits >= 0 && maximumDigits < count) {
if (shouldRoundUp(maximumDigits, alreadyRounded, allDecimalDigits)) {
if (shouldRoundUp(maximumDigits, alreadyRounded, valueExactAsDecimal)) {
// Rounding up involved incrementing digits from LSD to MSD.
// In most cases this is simple, but in a worst case situation
// (9999..99) we have to adjust the decimalAt value.
@ -440,6 +442,9 @@ final class DigitList implements Cloneable {
* <code>count-1</code>. If 0, then all digits are rounded away, and
* this method returns true if a one should be generated (e.g., formatting
* 0.09 with "#.#").
* @param alreadyRounded whether or not rounding up has already happened.
* @param valueExactAsDecimal whether or not collected digits provide
* an exact decimal representation of the value.
* @exception ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @return true if digit <code>maximumDigits-1</code> should be
@ -447,7 +452,7 @@ final class DigitList implements Cloneable {
*/
private boolean shouldRoundUp(int maximumDigits,
boolean alreadyRounded,
boolean allDecimalDigits) {
boolean valueExactAsDecimal) {
if (maximumDigits < count) {
/*
* To avoid erroneous double-rounding or truncation when converting
@ -460,7 +465,7 @@ final class DigitList implements Cloneable {
* account what FloatingDecimal has done in the binary to decimal
* conversion.
*
* Considering the tie cases, FloatingDecimal may round-up the
* Considering the tie cases, FloatingDecimal may round up the
* value (returning decimal digits equal to tie when it is below),
* or "truncate" the value to the tie while value is above it,
* or provide the exact decimal digits when the binary value can be
@ -490,7 +495,7 @@ final class DigitList implements Cloneable {
*
* - For other numbers that are always converted to exact digits
* (like BigInteger, Long, ...), the passed alreadyRounded boolean
* have to be set to false, and allDecimalDigits has to be set to
* have to be set to false, and valueExactAsDecimal has to be set to
* true in the upper DigitList call stack, providing the right state
* for those situations..
*/
@ -520,42 +525,31 @@ final class DigitList implements Cloneable {
}
break;
case HALF_UP:
if (digits[maximumDigits] >= '5') {
// We should not round up if the rounding digits position is
// exactly the last index and if digits were already rounded.
if ((maximumDigits == (count - 1)) &&
(alreadyRounded))
return false;
// Value was exactly at or was above tie. We must round up.
return true;
}
break;
case HALF_DOWN:
if (digits[maximumDigits] > '5') {
// Value is above tie ==> must round up
return true;
} else if (digits[maximumDigits] == '5' ) {
if (maximumDigits == (count - 1)) {
// The rounding position is exactly the last index.
if (allDecimalDigits || alreadyRounded)
/* FloatingDecimal rounded up (value was below tie),
* or provided the exact list of digits (value was
* an exact tie). We should not round up, following
* the HALF_DOWN rounding rule.
*/
return false;
else
// Value was above the tie, we must round up.
return true;
}
// We must round up if it gives a non null digit after '5'.
for (int i=maximumDigits+1; i<count; ++i) {
if (digits[i] != '0') {
return true;
} else if (digits[maximumDigits] == '5') {
// Digit at rounding position is a '5'. Tie cases.
if (maximumDigits != (count - 1)) {
// There are remaining digits. Above tie => must round up
return true;
} else {
// Digit at rounding position is the last one !
if (valueExactAsDecimal) {
// Exact binary representation. On the tie.
// Apply rounding given by roundingMode.
return roundingMode == RoundingMode.HALF_UP;
} else {
// Not an exact binary representation.
// Digit sequence either rounded up or truncated.
// Round up only if it was truncated.
return !alreadyRounded;
}
}
}
// Digit at rounding position is < '5' ==> no round up.
// Just let do the default, which is no round up (thus break).
break;
case HALF_EVEN:
// Implement IEEE half-even rounding
@ -569,7 +563,7 @@ final class DigitList implements Cloneable {
// then we should not round up again.
return false;
if (!allDecimalDigits)
if (!valueExactAsDecimal)
// Otherwise if the digits don't represent exact value,
// value was above tie and FloatingDecimal truncated
// digits to tie. We must round up.

View File

@ -2646,7 +2646,10 @@ public abstract class ResourceBundle {
} catch (ClassNotFoundException e) {
}
} else if (format.equals("java.properties")) {
final String resourceName = toResourceName(bundleName, "properties");
final String resourceName = toResourceName0(bundleName, "properties");
if (resourceName == null) {
return bundle;
}
final ClassLoader classLoader = loader;
final boolean reloadFlag = reload;
InputStream stream = null;
@ -2800,7 +2803,10 @@ public abstract class ResourceBundle {
}
boolean result = false;
try {
String resourceName = toResourceName(toBundleName(baseName, locale), format);
String resourceName = toResourceName0(toBundleName(baseName, locale), format);
if (resourceName == null) {
return result;
}
URL url = loader.getResource(resourceName);
if (url != null) {
long lastModified = 0;
@ -2934,6 +2940,15 @@ public abstract class ResourceBundle {
sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
return sb.toString();
}
private String toResourceName0(String bundleName, String suffix) {
// application protocol check
if (bundleName.contains("://")) {
return null;
} else {
return toResourceName(bundleName, suffix);
}
}
}
private static class SingleFormatControl extends Control {

View File

@ -163,7 +163,7 @@ public class FutureTask<V> implements RunnableFuture<V> {
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
U.compareAndSwapInt(this, STATE, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
@ -173,7 +173,7 @@ public class FutureTask<V> implements RunnableFuture<V> {
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
U.putOrderedInt(this, STATE, INTERRUPTED);
}
}
} finally {
@ -227,9 +227,9 @@ public class FutureTask<V> implements RunnableFuture<V> {
* @param v the value
*/
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
U.putOrderedInt(this, STATE, NORMAL); // final state
finishCompletion();
}
}
@ -245,17 +245,16 @@ public class FutureTask<V> implements RunnableFuture<V> {
* @param t the cause of failure
*/
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
U.putOrderedInt(this, STATE, EXCEPTIONAL); // final state
finishCompletion();
}
}
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
@ -296,8 +295,7 @@ public class FutureTask<V> implements RunnableFuture<V> {
*/
protected boolean runAndReset() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return false;
boolean ran = false;
int s = state;
@ -364,7 +362,7 @@ public class FutureTask<V> implements RunnableFuture<V> {
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
if (U.compareAndSwapObject(this, WAITERS, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
@ -391,11 +389,18 @@ public class FutureTask<V> implements RunnableFuture<V> {
*
* @param timed true if use timed waits
* @param nanos time to wait, if timed
* @return state upon completion
* @return state upon completion or at timeout
*/
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
// The code below is very delicate, to achieve these goals:
// - call nanoTime exactly once for each call to park
// - if nanos <= 0, return promptly without allocation or nanoTime
// - if nanos == Long.MIN_VALUE, don't underflow
// - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic
// and we suffer a spurious wakeup, we will do no worse than
// to park-spin for a while
long startTime = 0L; // Special value 0L means not yet parked
WaitNode q = null;
boolean queued = false;
for (;;) {
@ -412,18 +417,30 @@ public class FutureTask<V> implements RunnableFuture<V> {
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
else if (q == null) {
if (timed && nanos <= 0L)
return s;
q = new WaitNode();
}
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
queued = U.compareAndSwapObject(this, WAITERS,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
final long parkNanos;
if (startTime == 0L) { // first time
startTime = System.nanoTime();
if (startTime == 0L)
startTime = 1L;
parkNanos = nanos;
} else {
long elapsed = System.nanoTime() - startTime;
if (elapsed >= nanos) {
removeWaiter(q);
return state;
}
parkNanos = nanos - elapsed;
}
LockSupport.parkNanos(this, nanos);
LockSupport.parkNanos(this, parkNanos);
}
else
LockSupport.park(this);
@ -454,8 +471,7 @@ public class FutureTask<V> implements RunnableFuture<V> {
if (pred.thread == null) // check for race
continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
else if (!U.compareAndSwapObject(this, WAITERS, q, s))
continue retry;
}
break;
@ -464,20 +480,17 @@ public class FutureTask<V> implements RunnableFuture<V> {
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
private static final long runnerOffset;
private static final long waitersOffset;
private static final sun.misc.Unsafe U;
private static final long STATE;
private static final long RUNNER;
private static final long WAITERS;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
U = sun.misc.Unsafe.getUnsafe();
Class<?> k = FutureTask.class;
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
runnerOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("runner"));
waitersOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("waiters"));
STATE = U.objectFieldOffset(k.getDeclaredField("state"));
RUNNER = U.objectFieldOffset(k.getDeclaredField("runner"));
WAITERS = U.objectFieldOffset(k.getDeclaredField("waiters"));
} catch (Exception e) {
throw new Error(e);
}

View File

@ -107,9 +107,10 @@ public class CipherInputStream extends FilterInputStream {
done = true;
try {
obuffer = cipher.doFinal();
} catch (IllegalBlockSizeException | BadPaddingException e) {
obuffer = null;
throw new IOException(e);
}
catch (IllegalBlockSizeException e) {obuffer = null;}
catch (BadPaddingException e) {obuffer = null;}
if (obuffer == null)
return -1;
else {
@ -120,7 +121,10 @@ public class CipherInputStream extends FilterInputStream {
}
try {
obuffer = cipher.update(ibuffer, 0, readin);
} catch (IllegalStateException e) {obuffer = null;};
} catch (IllegalStateException e) {
obuffer = null;
throw e;
}
ostart = 0;
if (obuffer == null)
ofinish = 0;
@ -302,6 +306,7 @@ public class CipherInputStream extends FilterInputStream {
}
}
catch (BadPaddingException | IllegalBlockSizeException ex) {
throw new IOException(ex);
}
ostart = 0;
ofinish = 0;

View File

@ -102,19 +102,24 @@ public class VerifyAccess {
case PUBLIC:
return true; // already checked above
case PROTECTED:
assert !defc.isInterface(); // protected members aren't allowed in interfaces
if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 &&
isSamePackage(defc, lookupClass))
return true;
if ((allowedModes & PROTECTED) == 0)
return false;
// Protected members are accessible by subclasses, which does not include interfaces.
// Interfaces are types, not classes. They should not have access to
// protected members in j.l.Object, even though it is their superclass.
if ((mods & STATIC) != 0 &&
!isRelatedClass(refc, lookupClass))
return false;
if ((allowedModes & PROTECTED) != 0 &&
isSuperClass(defc, lookupClass))
isSubClass(lookupClass, defc))
return true;
return false;
case PACKAGE_ONLY: // That is, zero. Unmarked member is package-only access.
assert !defc.isInterface(); // package-private members aren't allowed in interfaces
return ((allowedModes & PACKAGE_ALLOWED) != 0 &&
isSamePackage(defc, lookupClass));
case PRIVATE:
@ -129,12 +134,13 @@ public class VerifyAccess {
static boolean isRelatedClass(Class<?> refc, Class<?> lookupClass) {
return (refc == lookupClass ||
refc.isAssignableFrom(lookupClass) ||
lookupClass.isAssignableFrom(refc));
isSubClass(refc, lookupClass) ||
isSubClass(lookupClass, refc));
}
static boolean isSuperClass(Class<?> defc, Class<?> lookupClass) {
return defc.isAssignableFrom(lookupClass);
static boolean isSubClass(Class<?> lookupClass, Class<?> defc) {
return defc.isAssignableFrom(lookupClass) &&
!lookupClass.isInterface(); // interfaces are types, not classes.
}
static int getClassModifiers(Class<?> c) {

View File

@ -740,6 +740,25 @@ class DatagramChannelImpl
// set or refresh local address
localAddress = Net.localAddress(fd);
// flush any packets already received.
boolean blocking = false;
synchronized (blockingLock()) {
try {
blocking = isBlocking();
ByteBuffer tmpBuf = ByteBuffer.allocate(100);
if (blocking) {
configureBlocking(false);
}
do {
tmpBuf.clear();
} while (read(tmpBuf) > 0);
} finally {
if (blocking) {
configureBlocking(true);
}
}
}
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,7 +29,6 @@ import java.lang.annotation.*;
import java.lang.reflect.*;
import java.io.Serializable;
import java.util.*;
import java.lang.annotation.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
@ -45,6 +44,11 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
private final Map<String, Object> memberValues;
AnnotationInvocationHandler(Class<? extends Annotation> type, Map<String, Object> memberValues) {
Class<?>[] superInterfaces = type.getInterfaces();
if (!type.isAnnotation() ||
superInterfaces.length != 1 ||
superInterfaces[0] != java.lang.annotation.Annotation.class)
throw new AnnotationFormatError("Attempt to create proxy for a non-annotation type.");
this.type = type;
this.memberValues = memberValues;
}
@ -57,13 +61,17 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
if (member.equals("equals") && paramTypes.length == 1 &&
paramTypes[0] == Object.class)
return equalsImpl(args[0]);
assert paramTypes.length == 0;
if (member.equals("toString"))
if (paramTypes.length != 0)
throw new AssertionError("Too many parameters for an annotation method");
switch(member) {
case "toString":
return toStringImpl();
if (member.equals("hashCode"))
case "hashCode":
return hashCodeImpl();
if (member.equals("annotationType"))
case "annotationType":
return type;
}
// Handle annotation member accessors
Object result = memberValues.get(member);
@ -129,7 +137,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
* Implementation of dynamicProxy.toString()
*/
private String toStringImpl() {
StringBuffer result = new StringBuffer(128);
StringBuilder result = new StringBuilder(128);
result.append('@');
result.append(type.getName());
result.append('(');
@ -277,6 +285,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
new PrivilegedAction<Method[]>() {
public Method[] run() {
final Method[] mm = type.getDeclaredMethods();
validateAnnotationMethods(mm);
AccessibleObject.setAccessible(mm, true);
return mm;
}
@ -286,6 +295,94 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
}
private transient volatile Method[] memberMethods = null;
/**
* Validates that a method is structurally appropriate for an
* annotation type. As of Java SE 8, annotation types cannot
* contain static methods and the declared methods of an
* annotation type must take zero arguments and there are
* restrictions on the return type.
*/
private void validateAnnotationMethods(Method[] memberMethods) {
/*
* Specification citations below are from JLS
* 9.6.1. Annotation Type Elements
*/
boolean valid = true;
for(Method method : memberMethods) {
/*
* "By virtue of the AnnotationTypeElementDeclaration
* production, a method declaration in an annotation type
* declaration cannot have formal parameters, type
* parameters, or a throws clause.
*
* "By virtue of the AnnotationTypeElementModifier
* production, a method declaration in an annotation type
* declaration cannot be default or static."
*/
if (method.getModifiers() != (Modifier.PUBLIC | Modifier.ABSTRACT) ||
method.isDefault() ||
method.getParameterCount() != 0 ||
method.getExceptionTypes().length != 0) {
valid = false;
break;
}
/*
* "It is a compile-time error if the return type of a
* method declared in an annotation type is not one of the
* following: a primitive type, String, Class, any
* parameterized invocation of Class, an enum type
* (section 8.9), an annotation type, or an array type
* (chapter 10) whose element type is one of the preceding
* types."
*/
Class<?> returnType = method.getReturnType();
if (returnType.isArray()) {
returnType = returnType.getComponentType();
if (returnType.isArray()) { // Only single dimensional arrays
valid = false;
break;
}
}
if (!((returnType.isPrimitive() && returnType != void.class) ||
returnType == java.lang.String.class ||
returnType == java.lang.Class.class ||
returnType.isEnum() ||
returnType.isAnnotation())) {
valid = false;
break;
}
/*
* "It is a compile-time error if any method declared in an
* annotation type has a signature that is
* override-equivalent to that of any public or protected
* method declared in class Object or in the interface
* java.lang.annotation.Annotation."
*
* The methods in Object or Annotation meeting the other
* criteria (no arguments, contrained return type, etc.)
* above are:
*
* String toString()
* int hashCode()
* Class<? extends Annotation> annotationType()
*/
String methodName = method.getName();
if ((methodName.equals("toString") && returnType == java.lang.String.class) ||
(methodName.equals("hashCode") && returnType == int.class) ||
(methodName.equals("annotationType") && returnType == java.lang.Class.class)) {
valid = false;
break;
}
}
if (valid)
return;
else
throw new AnnotationFormatError("Malformed method on an annotation type");
}
/**
* Implementation of dynamicProxy.hashCode()
*/
@ -330,7 +427,6 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// Check to make sure that types have not evolved incompatibly
AnnotationType annotationType = null;
@ -343,7 +439,6 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
Map<String, Class<?>> memberTypes = annotationType.memberTypes();
// If there are annotation members without values, that
// situation is handled by the invoke method.
for (Map.Entry<String, Object> memberValue : memberValues.entrySet()) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -80,6 +80,7 @@ public class X509Factory extends CertificateFactorySpi {
*
* @exception CertificateException on parsing errors.
*/
@Override
public Certificate engineGenerateCertificate(InputStream is)
throws CertificateException
{
@ -103,8 +104,8 @@ public class X509Factory extends CertificateFactorySpi {
throw new IOException("Empty input");
}
} catch (IOException ioe) {
throw (CertificateException)new CertificateException
("Could not parse certificate: " + ioe.toString()).initCause(ioe);
throw new CertificateException("Could not parse certificate: " +
ioe.toString(), ioe);
}
}
@ -140,6 +141,12 @@ public class X509Factory extends CertificateFactorySpi {
* It is useful for certificates that cannot be created via
* generateCertificate() and for converting other X509Certificate
* implementations to an X509CertImpl.
*
* @param c The source X509Certificate
* @return An X509CertImpl object that is either a cached certificate or a
* newly built X509CertImpl from the provided X509Certificate
* @throws CertificateException if failures occur while obtaining the DER
* encoding for certificate data.
*/
public static synchronized X509CertImpl intern(X509Certificate c)
throws CertificateException {
@ -170,6 +177,12 @@ public class X509Factory extends CertificateFactorySpi {
/**
* Return an interned X509CRLImpl for the given certificate.
* For more information, see intern(X509Certificate).
*
* @param c The source X509CRL
* @return An X509CRLImpl object that is either a cached CRL or a
* newly built X509CRLImpl from the provided X509CRL
* @throws CRLException if failures occur while obtaining the DER
* encoding for CRL data.
*/
public static synchronized X509CRLImpl intern(X509CRL c)
throws CRLException {
@ -229,6 +242,7 @@ public class X509Factory extends CertificateFactorySpi {
* @exception CertificateException if an exception occurs while decoding
* @since 1.4
*/
@Override
public CertPath engineGenerateCertPath(InputStream inStream)
throws CertificateException
{
@ -260,6 +274,7 @@ public class X509Factory extends CertificateFactorySpi {
* the encoding requested is not supported
* @since 1.4
*/
@Override
public CertPath engineGenerateCertPath(InputStream inStream,
String encoding) throws CertificateException
{
@ -292,6 +307,7 @@ public class X509Factory extends CertificateFactorySpi {
* @exception CertificateException if an exception occurs
* @since 1.4
*/
@Override
public CertPath
engineGenerateCertPath(List<? extends Certificate> certificates)
throws CertificateException
@ -311,6 +327,7 @@ public class X509Factory extends CertificateFactorySpi {
* <code>CertPath</code> encodings (as <code>String</code>s)
* @since 1.4
*/
@Override
public Iterator<String> engineGetCertPathEncodings() {
return(X509CertPath.getEncodingsStatic());
}
@ -326,6 +343,7 @@ public class X509Factory extends CertificateFactorySpi {
*
* @exception CertificateException on parsing errors.
*/
@Override
public Collection<? extends java.security.cert.Certificate>
engineGenerateCertificates(InputStream is)
throws CertificateException {
@ -351,6 +369,7 @@ public class X509Factory extends CertificateFactorySpi {
*
* @exception CRLException on parsing errors.
*/
@Override
public CRL engineGenerateCRL(InputStream is)
throws CRLException
{
@ -388,6 +407,7 @@ public class X509Factory extends CertificateFactorySpi {
*
* @exception CRLException on parsing errors.
*/
@Override
public Collection<? extends java.security.cert.CRL> engineGenerateCRLs(
InputStream is) throws CRLException
{
@ -410,11 +430,30 @@ public class X509Factory extends CertificateFactorySpi {
parseX509orPKCS7Cert(InputStream is)
throws CertificateException, IOException
{
int peekByte;
byte[] data;
PushbackInputStream pbis = new PushbackInputStream(is);
Collection<X509CertImpl> coll = new ArrayList<>();
byte[] data = readOneBlock(is);
if (data == null) {
// Test the InputStream for end-of-stream. If the stream's
// initial state is already at end-of-stream then return
// an empty collection. Otherwise, push the byte back into the
// stream and let readOneBlock look for the first certificate.
peekByte = pbis.read();
if (peekByte == -1) {
return new ArrayList<>(0);
} else {
pbis.unread(peekByte);
data = readOneBlock(pbis);
}
// If we end up with a null value after reading the first block
// then we know the end-of-stream has been reached and no certificate
// data has been found.
if (data == null) {
throw new CertificateException("No certificate data found");
}
try {
PKCS7 pkcs7 = new PKCS7(data);
X509Certificate[] certs = pkcs7.getCertificates();
@ -422,13 +461,13 @@ public class X509Factory extends CertificateFactorySpi {
if (certs != null) {
return Arrays.asList(certs);
} else {
// no crls provided
// no certificates provided
return new ArrayList<>(0);
}
} catch (ParsingException e) {
while (data != null) {
coll.add(new X509CertImpl(data));
data = readOneBlock(is);
data = readOneBlock(pbis);
}
}
return coll;
@ -443,11 +482,30 @@ public class X509Factory extends CertificateFactorySpi {
parseX509orPKCS7CRL(InputStream is)
throws CRLException, IOException
{
int peekByte;
byte[] data;
PushbackInputStream pbis = new PushbackInputStream(is);
Collection<X509CRLImpl> coll = new ArrayList<>();
byte[] data = readOneBlock(is);
if (data == null) {
// Test the InputStream for end-of-stream. If the stream's
// initial state is already at end-of-stream then return
// an empty collection. Otherwise, push the byte back into the
// stream and let readOneBlock look for the first CRL.
peekByte = pbis.read();
if (peekByte == -1) {
return new ArrayList<>(0);
} else {
pbis.unread(peekByte);
data = readOneBlock(pbis);
}
// If we end up with a null value after reading the first block
// then we know the end-of-stream has been reached and no CRL
// data has been found.
if (data == null) {
throw new CRLException("No CRL data found");
}
try {
PKCS7 pkcs7 = new PKCS7(data);
X509CRL[] crls = pkcs7.getCRLs();
@ -461,7 +519,7 @@ public class X509Factory extends CertificateFactorySpi {
} catch (ParsingException e) {
while (data != null) {
coll.add(new X509CRLImpl(data));
data = readOneBlock(is);
data = readOneBlock(pbis);
}
}
return coll;
@ -623,7 +681,7 @@ public class X509Factory extends CertificateFactorySpi {
int n = is.read();
if (n == -1) {
throw new IOException("BER/DER length info ansent");
throw new IOException("BER/DER length info absent");
}
bout.write(n);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -36,6 +36,8 @@ import java.security.spec.ECParameterSpec;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateParsingException;
import javax.security.auth.x500.X500Principal;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
@ -89,11 +91,65 @@ final class ClientHandshaker extends Handshaker {
private final static boolean enableSNIExtension =
Debug.getBooleanProperty("jsse.enableSNIExtension", true);
/*
* Allow unsafe server certificate change?
*
* Server certificate change during SSL/TLS renegotiation may be considered
* unsafe, as described in the Triple Handshake attacks:
*
* https://secure-resumption.com/tlsauth.pdf
*
* Endpoint identification (See
* SSLParameters.getEndpointIdentificationAlgorithm()) is a pretty nice
* guarantee that the server certificate change in renegotiation is legal.
* However, endpoing identification is only enabled for HTTPS and LDAP
* over SSL/TLS by default. It is not enough to protect SSL/TLS
* connections other than HTTPS and LDAP.
*
* The renegotiation indication extension (See RFC 5764) is a pretty
* strong guarantee that the endpoints on both client and server sides
* are identical on the same connection. However, the Triple Handshake
* attacks can bypass this guarantee if there is a session-resumption
* handshake between the initial full handshake and the renegotiation
* full handshake.
*
* Server certificate change may be unsafe and should be restricted if
* endpoint identification is not enabled and the previous handshake is
* a session-resumption abbreviated initial handshake, unless the
* identities represented by both certificates can be regraded as the
* same (See isIdentityEquivalent()).
*
* Considering the compatibility impact and the actual requirements to
* support server certificate change in practice, the system property,
* jdk.tls.allowUnsafeServerCertChange, is used to define whether unsafe
* server certificate change in renegotiation is allowed or not. The
* default value of the system property is "false". To mitigate the
* compactibility impact, applications may want to set the system
* property to "true" at their own risk.
*
* If the value of the system property is "false", server certificate
* change in renegotiation after a session-resumption abbreviated initial
* handshake is restricted (See isIdentityEquivalent()).
*
* If the system property is set to "true" explicitly, the restriction on
* server certificate change in renegotiation is disabled.
*/
private final static boolean allowUnsafeServerCertChange =
Debug.getBooleanProperty("jdk.tls.allowUnsafeServerCertChange", false);
private List<SNIServerName> requestedServerNames =
Collections.<SNIServerName>emptyList();
private boolean serverNamesAccepted = false;
/*
* the reserved server certificate chain in previous handshaking
*
* The server certificate chain is only reserved if the previous
* handshake is a session-resumption abbreviated initial handshake.
*/
private X509Certificate[] reservedServerCerts = null;
/*
* Constructors
*/
@ -555,14 +611,19 @@ final class ClientHandshaker extends Handshaker {
// we wanted to resume, but the server refused
session = null;
if (!enableNewSession) {
throw new SSLException
("New session creation is disabled");
throw new SSLException("New session creation is disabled");
}
}
}
if (resumingSession && session != null) {
setHandshakeSessionSE(session);
// Reserve the handshake state if this is a session-resumption
// abbreviated initial handshake.
if (isInitialHandshake) {
session.setAsSessionResumption(true);
}
return;
}
@ -1063,6 +1124,13 @@ final class ClientHandshaker extends Handshaker {
serverVerifyData = mesg.getVerifyData();
}
/*
* Reset the handshake state if this is not an initial handshake.
*/
if (!isInitialHandshake) {
session.setAsSessionResumption(false);
}
/*
* OK, it verified. If we're doing the fast handshake, add that
* "Finished" message to the hash of handshake messages, then send
@ -1161,8 +1229,23 @@ final class ClientHandshaker extends Handshaker {
System.out.println("%% No cached client session");
}
}
if ((session != null) && (session.isRejoinable() == false)) {
session = null;
if (session != null) {
// If unsafe server certificate change is not allowed, reserve
// current server certificates if the previous handshake is a
// session-resumption abbreviated initial handshake.
if (!allowUnsafeServerCertChange && session.isSessionResumption()) {
try {
// If existing, peer certificate chain cannot be null.
reservedServerCerts =
(X509Certificate[])session.getPeerCertificates();
} catch (SSLPeerUnverifiedException puve) {
// Maybe not certificate-based, ignore the exception.
}
}
if (!session.isRejoinable()) {
session = null;
}
}
if (session != null) {
@ -1331,9 +1414,28 @@ final class ClientHandshaker extends Handshaker {
}
X509Certificate[] peerCerts = mesg.getCertificateChain();
if (peerCerts.length == 0) {
fatalSE(Alerts.alert_bad_certificate,
"empty certificate chain");
fatalSE(Alerts.alert_bad_certificate, "empty certificate chain");
}
// Allow server certificate change in client side during renegotiation
// after a session-resumption abbreviated initial handshake?
//
// DO NOT need to check allowUnsafeServerCertChange here. We only
// reserve server certificates when allowUnsafeServerCertChange is
// flase.
if (reservedServerCerts != null) {
// It is not necessary to check the certificate update if endpoint
// identification is enabled.
String identityAlg = getEndpointIdentificationAlgorithmSE();
if ((identityAlg == null || identityAlg.length() == 0) &&
!isIdentityEquivalent(peerCerts[0], reservedServerCerts[0])) {
fatalSE(Alerts.alert_bad_certificate,
"server certificate change is restricted " +
"during renegotiation");
}
}
// ask the trust manager to verify the chain
X509TrustManager tm = sslContext.getX509TrustManager();
try {
@ -1370,4 +1472,81 @@ final class ClientHandshaker extends Handshaker {
}
session.setPeerCertificates(peerCerts);
}
/*
* Whether the certificates can represent the same identity?
*
* The certificates can be used to represent the same identity:
* 1. If the subject alternative names of IP address are present in
* both certificates, they should be identical; otherwise,
* 2. if the subject alternative names of DNS name are present in
* both certificates, they should be identical; otherwise,
* 3. if the subject fields are present in both certificates, the
* certificate subjects and issuers should be identical.
*/
private static boolean isIdentityEquivalent(X509Certificate thisCert,
X509Certificate prevCert) {
if (thisCert.equals(prevCert)) {
return true;
}
// check the iPAddress field in subjectAltName extension
Object thisIPAddress = getSubjectAltName(thisCert, 7); // 7: iPAddress
Object prevIPAddress = getSubjectAltName(prevCert, 7);
if (thisIPAddress != null && prevIPAddress!= null) {
// only allow the exactly match
return Objects.equals(thisIPAddress, prevIPAddress);
}
// check the dNSName field in subjectAltName extension
Object thisDNSName = getSubjectAltName(thisCert, 2); // 2: dNSName
Object prevDNSName = getSubjectAltName(prevCert, 2);
if (thisDNSName != null && prevDNSName!= null) {
// only allow the exactly match
return Objects.equals(thisDNSName, prevDNSName);
}
// check the certificate subject and issuer
X500Principal thisSubject = thisCert.getSubjectX500Principal();
X500Principal prevSubject = prevCert.getSubjectX500Principal();
X500Principal thisIssuer = thisCert.getIssuerX500Principal();
X500Principal prevIssuer = prevCert.getIssuerX500Principal();
if (!thisSubject.getName().isEmpty() &&
!prevSubject.getName().isEmpty() &&
thisSubject.equals(prevSubject) &&
thisIssuer.equals(prevIssuer)) {
return true;
}
return false;
}
/*
* Returns the subject alternative name of the specified type in the
* subjectAltNames extension of a certificate.
*/
private static Object getSubjectAltName(X509Certificate cert, int type) {
Collection<List<?>> subjectAltNames;
try {
subjectAltNames = cert.getSubjectAlternativeNames();
} catch (CertificateParsingException cpe) {
if (debug != null && Debug.isOn("handshake")) {
System.out.println(
"Attempt to obtain subjectAltNames extension failed!");
}
return null;
}
if (subjectAltNames != null) {
for (List<?> subjectAltName : subjectAltNames) {
int subjectAltNameType = (Integer)subjectAltName.get(0);
if (subjectAltNameType == type) {
return subjectAltName.get(1);
}
}
}
return null;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -359,6 +359,17 @@ abstract class Handshaker {
}
}
String getEndpointIdentificationAlgorithmSE() {
SSLParameters paras;
if (conn != null) {
paras = conn.getSSLParameters();
} else {
paras = engine.getSSLParameters();
}
return paras.getEndpointIdentificationAlgorithm();
}
private void setVersionSE(ProtocolVersion protocolVersion) {
if (conn != null) {
conn.setVersion(protocolVersion);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -114,6 +114,14 @@ final class SSLSessionImpl extends ExtendedSSLSession {
private Principal peerPrincipal;
private Principal localPrincipal;
/*
* Is the session currently re-established with a session-resumption
* abbreviated initial handshake?
*
* Note that currently we only set this variable in client side.
*/
private boolean isSessionResumption = false;
/*
* We count session creations, eventually for statistical data but
* also since counters make shorter debugging IDs than the big ones
@ -324,6 +332,22 @@ final class SSLSessionImpl extends ExtendedSSLSession {
}
}
/**
* Return true if the session is currently re-established with a
* session-resumption abbreviated initial handshake.
*/
boolean isSessionResumption() {
return isSessionResumption;
}
/**
* Resets whether the session is re-established with a session-resumption
* abbreviated initial handshake.
*/
void setAsSessionResumption(boolean flag) {
isSessionResumption = flag;
}
/**
* Returns the name of the cipher suite in use on this session
*/

View File

@ -64,6 +64,7 @@ import java.security.cert.X509CRLSelector;
import javax.security.auth.x500.X500Principal;
import java.util.Base64;
import sun.security.util.KeyUtil;
import sun.security.util.ObjectIdentifier;
import sun.security.pkcs10.PKCS10;
import sun.security.pkcs10.PKCS10Attribute;
@ -1103,8 +1104,13 @@ public final class Main {
doChangeKeyPasswd(alias);
kssave = true;
} else if (command == LIST) {
if (storePass == null
&& !KeyStoreUtil.isWindowsKeyStore(storetype)) {
printWarning();
}
if (alias != null) {
doPrintEntry(alias, out, true);
doPrintEntry(alias, out);
} else {
doPrintEntries(out);
}
@ -1765,15 +1771,9 @@ public final class Main {
/**
* Prints a single keystore entry.
*/
private void doPrintEntry(String alias, PrintStream out,
boolean printWarning)
private void doPrintEntry(String alias, PrintStream out)
throws Exception
{
if (storePass == null && printWarning
&& !KeyStoreUtil.isWindowsKeyStore(storetype)) {
printWarning();
}
if (keyStore.containsAlias(alias) == false) {
MessageFormat form = new MessageFormat
(rb.getString("Alias.alias.does.not.exist"));
@ -2090,13 +2090,6 @@ public final class Main {
private void doPrintEntries(PrintStream out)
throws Exception
{
if (storePass == null
&& !KeyStoreUtil.isWindowsKeyStore(storetype)) {
printWarning();
} else {
out.println();
}
out.println(rb.getString("Keystore.type.") + keyStore.getType());
out.println(rb.getString("Keystore.provider.") +
keyStore.getProvider().getName());
@ -2115,7 +2108,7 @@ public final class Main {
for (Enumeration<String> e = keyStore.aliases();
e.hasMoreElements(); ) {
String alias = e.nextElement();
doPrintEntry(alias, out, false);
doPrintEntry(alias, out);
if (verbose || rfc) {
out.println(rb.getString("NEWLINE"));
out.println(rb.getString
@ -2922,6 +2915,7 @@ public final class Main {
MessageFormat form = new MessageFormat
(rb.getString(".PATTERN.printX509Cert"));
PublicKey pkey = cert.getPublicKey();
Object[] source = {cert.getSubjectDN().toString(),
cert.getIssuerDN().toString(),
cert.getSerialNumber().toString(16),
@ -2931,7 +2925,9 @@ public final class Main {
getCertFingerPrint("SHA1", cert),
getCertFingerPrint("SHA-256", cert),
cert.getSigAlgName(),
cert.getVersion()
pkey.getAlgorithm(),
KeyUtil.getKeySize(pkey),
cert.getVersion(),
};
out.println(form.format(source));

View File

@ -347,7 +347,7 @@ public class Resources extends java.util.ListResourceBundle {
{".RETURN.if.same.as.for.otherAlias.",
"\t(RETURN if same as for <{0}>)"},
{".PATTERN.printX509Cert",
"Owner: {0}\nIssuer: {1}\nSerial number: {2}\nValid from: {3} until: {4}\nCertificate fingerprints:\n\t MD5: {5}\n\t SHA1: {6}\n\t SHA256: {7}\n\t Signature algorithm name: {8}\n\t Version: {9}"},
"Owner: {0}\nIssuer: {1}\nSerial number: {2}\nValid from: {3} until: {4}\nCertificate fingerprints:\n\t MD5: {5}\n\t SHA1: {6}\n\t SHA256: {7}\nSignature algorithm name: {8}\nSubject Public Key Algorithm: {9} ({10,number,#})\nVersion: {11}"},
{"What.is.your.first.and.last.name.",
"What is your first and last name?"},
{"What.is.the.name.of.your.organizational.unit.",

View File

@ -31,6 +31,7 @@
*/
package sun.util.locale;
import java.lang.ref.SoftReference;
import java.util.StringJoiner;
@ -151,11 +152,11 @@ public final class BaseLocale {
return h;
}
private static final class Key implements Comparable<Key> {
private final String lang;
private final String scrt;
private final String regn;
private final String vart;
private static final class Key {
private final SoftReference<String> lang;
private final SoftReference<String> scrt;
private final SoftReference<String> regn;
private final SoftReference<String> vart;
private final boolean normalized;
private final int hash;
@ -167,10 +168,10 @@ public final class BaseLocale {
assert language.intern() == language
&& region.intern() == region;
lang = language;
scrt = "";
regn = region;
vart = "";
lang = new SoftReference<>(language);
scrt = new SoftReference<>("");
regn = new SoftReference<>(region);
vart = new SoftReference<>("");
this.normalized = true;
int h = language.hashCode();
@ -191,40 +192,40 @@ public final class BaseLocale {
String variant, boolean normalized) {
int h = 0;
if (language != null) {
lang = language;
lang = new SoftReference<>(language);
int len = language.length();
for (int i = 0; i < len; i++) {
h = 31*h + LocaleUtils.toLower(language.charAt(i));
}
} else {
lang = "";
lang = new SoftReference<>("");
}
if (script != null) {
scrt = script;
scrt = new SoftReference<>(script);
int len = script.length();
for (int i = 0; i < len; i++) {
h = 31*h + LocaleUtils.toLower(script.charAt(i));
}
} else {
scrt = "";
scrt = new SoftReference<>("");
}
if (region != null) {
regn = region;
regn = new SoftReference<>(region);
int len = region.length();
for (int i = 0; i < len; i++) {
h = 31*h + LocaleUtils.toLower(region.charAt(i));
}
} else {
regn = "";
regn = new SoftReference<>("");
}
if (variant != null) {
vart = variant;
vart = new SoftReference<>(variant);
int len = variant.length();
for (int i = 0; i < len; i++) {
h = 31*h + variant.charAt(i);
}
} else {
vart = "";
vart = new SoftReference<>("");
}
hash = h;
this.normalized = normalized;
@ -232,28 +233,31 @@ public final class BaseLocale {
@Override
public boolean equals(Object obj) {
return (this == obj) ||
(obj instanceof Key)
&& this.hash == ((Key)obj).hash
&& LocaleUtils.caseIgnoreMatch(((Key)obj).lang, this.lang)
&& LocaleUtils.caseIgnoreMatch(((Key)obj).scrt, this.scrt)
&& LocaleUtils.caseIgnoreMatch(((Key)obj).regn, this.regn)
&& ((Key)obj).vart.equals(vart); // variant is case sensitive in JDK!
}
if (this == obj) {
return true;
}
@Override
public int compareTo(Key other) {
int res = LocaleUtils.caseIgnoreCompare(this.lang, other.lang);
if (res == 0) {
res = LocaleUtils.caseIgnoreCompare(this.scrt, other.scrt);
if (res == 0) {
res = LocaleUtils.caseIgnoreCompare(this.regn, other.regn);
if (res == 0) {
res = this.vart.compareTo(other.vart);
if (obj instanceof Key && this.hash == ((Key)obj).hash) {
String tl = this.lang.get();
String ol = ((Key)obj).lang.get();
if (tl != null && ol != null &&
LocaleUtils.caseIgnoreMatch(ol, tl)) {
String ts = this.scrt.get();
String os = ((Key)obj).scrt.get();
if (ts != null && os != null &&
LocaleUtils.caseIgnoreMatch(os, ts)) {
String tr = this.regn.get();
String or = ((Key)obj).regn.get();
if (tr != null && or != null &&
LocaleUtils.caseIgnoreMatch(or, tr)) {
String tv = this.vart.get();
String ov = ((Key)obj).vart.get();
return (ov != null && ov.equals(tv));
}
}
}
}
return res;
return false;
}
@Override
@ -266,10 +270,10 @@ public final class BaseLocale {
return key;
}
String lang = LocaleUtils.toLowerString(key.lang).intern();
String scrt = LocaleUtils.toTitleString(key.scrt).intern();
String regn = LocaleUtils.toUpperString(key.regn).intern();
String vart = key.vart.intern(); // preserve upper/lower cases
String lang = LocaleUtils.toLowerString(key.lang.get()).intern();
String scrt = LocaleUtils.toTitleString(key.scrt.get()).intern();
String regn = LocaleUtils.toUpperString(key.regn.get()).intern();
String vart = key.vart.get().intern(); // preserve upper/lower cases
return new Key(lang, scrt, regn, vart, true);
}
@ -282,12 +286,18 @@ public final class BaseLocale {
@Override
protected Key normalizeKey(Key key) {
assert key.lang.get() != null &&
key.scrt.get() != null &&
key.regn.get() != null &&
key.vart.get() != null;
return Key.normalize(key);
}
@Override
protected BaseLocale createObject(Key key) {
return new BaseLocale(key.lang, key.scrt, key.regn, key.vart);
return new BaseLocale(key.lang.get(), key.scrt.get(),
key.regn.get(), key.vart.get());
}
}
}

View File

@ -57,8 +57,10 @@ public abstract class LocaleObjectCache<K, V> {
value = entry.get();
}
if (value == null) {
key = normalizeKey(key);
V newVal = createObject(key);
// make sure key is normalized *after* the object creation
// so that newVal is assured to be created from a valid key.
key = normalizeKey(key);
if (key == null || newVal == null) {
// subclass must return non-null key/value object
return null;

View File

@ -385,6 +385,19 @@ JVM_ResolveClass(JNIEnv *env, jclass cls);
JNIEXPORT jclass JNICALL
JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
/*
* Find a class from a given class loader. Throws ClassNotFoundException.
* name: name of class
* init: whether initialization is done
* loader: class loader to look up the class. This may not be the same as the caller's
* class loader.
* caller: initiating class. The initiating class may be null when a security
* manager is not installed.
*/
JNIEXPORT jclass JNICALL
JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
jobject loader, jclass caller);
/*
* Find a class from a given class loader. Throw ClassNotFoundException
* or NoClassDefFoundError depending on the value of the last

View File

@ -93,7 +93,7 @@ Java_java_lang_Class_registerNatives(JNIEnv *env, jclass cls)
JNIEXPORT jclass JNICALL
Java_java_lang_Class_forName0(JNIEnv *env, jclass this, jstring classname,
jboolean initialize, jobject loader)
jboolean initialize, jobject loader, jclass caller)
{
char *clname;
jclass cls = 0;
@ -131,8 +131,7 @@ Java_java_lang_Class_forName0(JNIEnv *env, jclass this, jstring classname,
goto done;
}
cls = JVM_FindClassFromClassLoader(env, clname, initialize,
loader, JNI_FALSE);
cls = JVM_FindClassFromCaller(env, clname, initialize, loader, caller);
done:
if (clname != buf) {

View File

@ -54,7 +54,8 @@ Java_java_util_zip_CRC32_updateBytes(JNIEnv *env, jclass cls, jint crc,
return crc;
}
JNIEXPORT jint ZIP_CRC32(jint crc, const jbyte *buf, jint len)
JNIEXPORT jint JNICALL
ZIP_CRC32(jint crc, const jbyte *buf, jint len)
{
return crc32(crc, (Bytef*)buf, len);
}

View File

@ -174,11 +174,7 @@ Java_java_util_zip_ZipFile_getEntry(JNIEnv *env, jclass cls, jlong zfile,
}
(*env)->GetByteArrayRegion(env, name, 0, ulen, (jbyte *)path);
path[ulen] = '\0';
if (addSlash == JNI_FALSE) {
ze = ZIP_GetEntry(zip, path, 0);
} else {
ze = ZIP_GetEntry(zip, path, (jint)ulen);
}
ze = ZIP_GetEntry2(zip, path, (jint)ulen, addSlash);
if (path != buf) {
free(path);
}
@ -271,7 +267,7 @@ Java_java_util_zip_ZipFile_getEntryBytes(JNIEnv *env,
switch (type) {
case java_util_zip_ZipFile_JZENTRY_NAME:
if (ze->name != 0) {
len = (int)strlen(ze->name);
len = (int)ze->nlen;
// Unlike for extra and comment, we never return null for
// an (extremely rarely seen) empty name
if ((jba = (*env)->NewByteArray(env, len)) == NULL)

View File

@ -1021,6 +1021,7 @@ newEntry(jzfile *zip, jzcell *zc, AccessHint accessHint)
if ((ze->name = malloc(nlen + 1)) == NULL) goto Catch;
memcpy(ze->name, cen + CENHDR, nlen);
ze->name[nlen] = '\0';
ze->nlen = nlen;
if (elen > 0) {
char *extra = cen + CENHDR + nlen;
@ -1118,7 +1119,34 @@ ZIP_FreeEntry(jzfile *jz, jzentry *ze)
jzentry *
ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
{
unsigned int hsh = hash(name);
if (ulen == 0) {
return ZIP_GetEntry2(zip, name, strlen(name), JNI_FALSE);
}
return ZIP_GetEntry2(zip, name, ulen, JNI_TRUE);
}
jboolean equals(char* name1, int len1, char* name2, int len2) {
if (len1 != len2) {
return JNI_FALSE;
}
while (len1-- > 0) {
if (*name1++ != *name2++) {
return JNI_FALSE;
}
}
return JNI_TRUE;
}
/*
* Returns the zip entry corresponding to the specified name, or
* NULL if not found.
* This method supports embedded null character in "name", use ulen
* for the length of "name".
*/
jzentry *
ZIP_GetEntry2(jzfile *zip, char *name, jint ulen, jboolean addSlash)
{
unsigned int hsh = hashN(name, ulen);
jint idx;
jzentry *ze = 0;
@ -1139,7 +1167,7 @@ ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
/* Check the cached entry first */
ze = zip->cache;
if (ze && strcmp(ze->name,name) == 0) {
if (ze && equals(ze->name, ze->nlen, name, ulen)) {
/* Cache hit! Remove and return the cached entry. */
zip->cache = 0;
ZIP_Unlock(zip);
@ -1165,7 +1193,7 @@ ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
* we keep searching.
*/
ze = newEntry(zip, zc, ACCESS_RANDOM);
if (ze && strcmp(ze->name, name)==0) {
if (ze && equals(ze->name, ze->nlen, name, ulen)) {
break;
}
if (ze != 0) {
@ -1184,8 +1212,8 @@ ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
break;
}
/* If no real length was passed in, we are done */
if (ulen == 0) {
/* If no need to try appending slash, we are done */
if (!addSlash) {
break;
}
@ -1195,11 +1223,11 @@ ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
}
/* Add slash and try once more */
name[ulen] = '/';
name[ulen+1] = '\0';
name[ulen++] = '/';
name[ulen] = '\0';
hsh = hash_append(hsh, '/');
idx = zip->table[hsh % zip->tablelen];
ulen = 0;
addSlash = JNI_FALSE;
}
Finally:

View File

@ -154,6 +154,7 @@
* - If pos <= 0 then it is the position of entry LOC header.
* If pos > 0 then it is the position of entry data.
* pos should not be accessed directly, but only by ZIP_GetEntryDataOffset.
* - entry name may include embedded null character, use nlen for length
*/
typedef struct jzentry { /* Zip file entry */
@ -166,6 +167,7 @@ typedef struct jzentry { /* Zip file entry */
jbyte *extra; /* optional extra data */
jlong pos; /* position of LOC header or entry data */
jint flag; /* general purpose flag */
jint nlen; /* length of the entry name */
} jzentry;
/*
@ -269,5 +271,5 @@ void ZIP_Unlock(jzfile *zip);
jint ZIP_Read(jzfile *zip, jzentry *entry, jlong pos, void *buf, jint len);
void ZIP_FreeEntry(jzfile *zip, jzentry *ze);
jlong ZIP_GetEntryDataOffset(jzfile *zip, jzentry *entry);
jzentry * ZIP_GetEntry2(jzfile *zip, char *name, jint ulen, jboolean addSlash);
#endif /* !_ZIP_H_ */

View File

@ -0,0 +1,89 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. 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.
*/
#include <sys/types.h>
#include <sys/socket.h>
#ifdef __solaris__
#include <unistd.h>
#include <stropts.h>
#ifndef BSD_COMP
#define BSD_COMP
#endif
#endif
#include <sys/ioctl.h>
#include "jvm.h"
#include "jni_util.h"
#include "net_util.h"
#include "java_net_AbstractPlainDatagramSocketImpl.h"
static jfieldID IO_fd_fdID;
static jfieldID apdsi_fdID;
/*
* Class: java_net_AbstractPlainDatagramSocketImpl
* Method: init
* Signature: ()V
*/
JNIEXPORT void JNICALL
Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) {
apdsi_fdID = (*env)->GetFieldID(env, cls, "fd",
"Ljava/io/FileDescriptor;");
CHECK_NULL(apdsi_fdID);
IO_fd_fdID = NET_GetFileDescriptorID(env);
}
/*
* Class: java_net_AbstractPlainDatagramSocketImpl
* Method: dataAvailable
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable
(JNIEnv *env, jobject this) {
int fd, retval;
jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID);
if (IS_NULL(fdObj)) {
JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
"Socket closed");
return -1;
}
fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
if (ioctl(fd, FIONREAD, &retval) < 0) {
return -1;
}
return retval;
}

View File

@ -193,5 +193,10 @@ Kaliningrad Standard Time:925,925:RU:Europe/Kaliningrad:
Turkey Standard Time:926,926::Asia/Istanbul:
Bahia Standard Time:927,927::America/Bahia:
Libya Standard Time:928,928:LY:Africa/Tripoli:
Western Brazilian Standard Time:929,929:BR:America/Rio_Branco:
Armenian Standard Time:930,930:AM:Asia/Yerevan:
Belarus Standard Time:929,929:BY:Europe/Minsk:
Line Islands Standard Time:930,930::Pacific/Kiritimati:
Russia Time Zone 10:931,931::Asia/Srednekolymsk:
Russia Time Zone 11:932,932::Asia/Anadyr:
Russia Time Zone 3:933,933::Europe/Samara:
Western Brazilian Standard Time:934,934:BR:America/Rio_Branco:
Armenian Standard Time:935,935:AM:Asia/Yerevan:

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. 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.
*/
#include <windows.h>
#include <winsock2.h>
#include "jvm.h"
#include "jni_util.h"
#include "net_util.h"
#include "java_net_AbstractPlainDatagramSocketImpl.h"
static jfieldID IO_fd_fdID;
static jfieldID apdsi_fdID;
/*
* Class: java_net_AbstractPlainDatagramSocketImpl
* Method: init
* Signature: ()V
*/
JNIEXPORT void JNICALL
Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) {
apdsi_fdID = (*env)->GetFieldID(env, cls, "fd",
"Ljava/io/FileDescriptor;");
CHECK_NULL(apdsi_fdID);
IO_fd_fdID = NET_GetFileDescriptorID(env);
CHECK_NULL(IO_fd_fdID);
JNU_CHECK_EXCEPTION(env);
}
/*
* Class: java_net_AbstractPlainDatagramSocketImpl
* Method: dataAvailable
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable
(JNIEnv *env, jobject this) {
SOCKET fd;
int retval;
jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID);
if (IS_NULL(fdObj)) {
JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
"Socket closed");
return -1;
}
fd = (SOCKET)(*env)->GetIntField(env, fdObj, IO_fd_fdID);
if (ioctlsocket(fd, FIONREAD, &retval) < 0) {
return -1;
}
return retval;
}

View File

@ -567,7 +567,10 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
}
} else {
// immediately hide the window
CWrapper.NSWindow.orderOut(nsWindowPtr);
// process the close
CWrapper.NSWindow.close(nsWindowPtr);
}
} else {
// otherwise, put it in a proper z-order

View File

@ -54,8 +54,26 @@ final class CWrapper {
static native void orderFront(long window);
static native void orderFrontRegardless(long window);
static native void orderWindow(long window, int ordered, long relativeTo);
/**
* Removes the window from the screen.
*
* @param window the pointer of the NSWindow
*/
static native void orderOut(long window);
/**
* Removes the window from the screen and releases it. According to
* documentation this method should be similar to {@link #orderOut},
* because we use ReleasedWhenClosed:NO, so the window shouldn't be
* released. But the close method works differently, for example it
* close the space if the window was in the full screen via
* {@link CPlatformWindow#toggleFullScreen()}.
*
* @param window the pointer of the NSWindow
*/
static native void close(long window);
static native void addChildWindow(long parent, long child, int ordered);
static native void removeChildWindow(long parent, long child);

View File

@ -173,6 +173,23 @@ JNF_COCOA_ENTER(env);
JNF_COCOA_EXIT(env);
}
/*
* Class: sun_lwawt_macosx_CWrapper$NSWindow
* Method: close
* Signature: (J)V
*/
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CWrapper_00024NSWindow_close
(JNIEnv *env, jclass cls, jlong windowPtr)
{
JNF_COCOA_ENTER(env);
NSWindow *window = (NSWindow *)jlong_to_ptr(windowPtr);
[ThreadUtilities performOnMainThreadWaiting:NO block:^(){
[window close];
}];
JNF_COCOA_EXIT(env);
}
/*
* Class: sun_lwawt_macosx_CWrapper$NSWindow
* Method: orderFrontRegardless

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -117,7 +117,7 @@ public abstract class AbstractMidiDeviceProvider extends MidiDeviceProvider {
}
}
@Override
public final MidiDevice.Info[] getDeviceInfo() {
readDeviceInfos();
Info[] infos = getInfoCache();
@ -126,7 +126,7 @@ public abstract class AbstractMidiDeviceProvider extends MidiDeviceProvider {
return localArray;
}
@Override
public final MidiDevice getDevice(MidiDevice.Info info) {
if (info instanceof Info) {
readDeviceInfos();
@ -143,9 +143,7 @@ public abstract class AbstractMidiDeviceProvider extends MidiDeviceProvider {
}
}
}
throw new IllegalArgumentException("MidiDevice " + info.toString()
+ " not supported by this provider.");
throw MidiUtils.unsupportedDevice(info);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,9 +25,15 @@
package com.sun.media.sound;
import javax.sound.midi.*;
import java.util.ArrayList;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.Sequence;
import javax.sound.midi.Track;
// TODO:
// - define and use a global symbolic constant for 60000000 (see convertTempo)
@ -48,6 +54,17 @@ public final class MidiUtils {
private MidiUtils() {
}
/**
* Returns an exception which should be thrown if MidiDevice is unsupported.
*
* @param info an info object that describes the desired device
* @return an exception instance
*/
static RuntimeException unsupportedDevice(final MidiDevice.Info info) {
return new IllegalArgumentException(String.format(
"MidiDevice %s not supported by this provider", info));
}
/** return true if the passed message is Meta End Of Track */
public static boolean isMetaEndOfTrack(MidiMessage midiMsg) {
// first check if it is a META message at all

View File

@ -64,7 +64,7 @@ final class RealTimeSequencer extends AbstractMidiDevice
/**
* All RealTimeSequencers share this info object.
*/
static final RealTimeSequencerInfo info = new RealTimeSequencerInfo();
static final MidiDevice.Info info = new RealTimeSequencerInfo();
private static final Sequencer.SyncMode[] masterSyncModes = { Sequencer.SyncMode.INTERNAL_CLOCK };
@ -154,7 +154,7 @@ final class RealTimeSequencer extends AbstractMidiDevice
/* ****************************** CONSTRUCTOR ****************************** */
RealTimeSequencer() throws MidiUnavailableException {
RealTimeSequencer(){
super(info);
if (Printer.trace) Printer.trace(">> RealTimeSequencer CONSTRUCTOR");
@ -1088,7 +1088,7 @@ final class RealTimeSequencer extends AbstractMidiDevice
private static final String description = "Software sequencer";
private static final String version = "Version 1.0";
private RealTimeSequencerInfo() {
RealTimeSequencerInfo() {
super(name, vendor, description, version);
}
} // class Info

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -26,7 +26,6 @@
package com.sun.media.sound;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.spi.MidiDeviceProvider;
/**
@ -36,23 +35,16 @@ import javax.sound.midi.spi.MidiDeviceProvider;
*/
public final class RealTimeSequencerProvider extends MidiDeviceProvider {
@Override
public MidiDevice.Info[] getDeviceInfo() {
MidiDevice.Info[] localArray = { RealTimeSequencer.info };
return localArray;
return new MidiDevice.Info[]{RealTimeSequencer.info};
}
public MidiDevice getDevice(MidiDevice.Info info) {
if ((info != null) && (!info.equals(RealTimeSequencer.info))) {
return null;
}
try {
@Override
public MidiDevice getDevice(final MidiDevice.Info info) {
if (RealTimeSequencer.info.equals(info)) {
return new RealTimeSequencer();
} catch (MidiUnavailableException e) {
return null;
}
throw MidiUtils.unsupportedDevice(info);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -22,11 +22,10 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.media.sound;
import java.util.Arrays;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiDevice.Info;
import javax.sound.midi.spi.MidiDeviceProvider;
/**
@ -36,17 +35,16 @@ import javax.sound.midi.spi.MidiDeviceProvider;
*/
public final class SoftProvider extends MidiDeviceProvider {
static final Info softinfo = SoftSynthesizer.info;
private static final Info[] softinfos = {softinfo};
@Override
public MidiDevice.Info[] getDeviceInfo() {
return Arrays.copyOf(softinfos, softinfos.length);
return new MidiDevice.Info[]{SoftSynthesizer.info};
}
public MidiDevice getDevice(MidiDevice.Info info) {
if (info == softinfo) {
@Override
public MidiDevice getDevice(final MidiDevice.Info info) {
if (SoftSynthesizer.info.equals(info)) {
return new SoftSynthesizer();
}
return null;
throw MidiUtils.unsupportedDevice(info);
}
}

View File

@ -182,7 +182,8 @@ public abstract class GraphicsEnvironment {
"SunOS".equals(osName) ||
"FreeBSD".equals(osName) ||
"NetBSD".equals(osName) ||
"OpenBSD".equals(osName)) &&
"OpenBSD".equals(osName) ||
"AIX".equals(osName)) &&
(System.getenv("DISPLAY") == null));
}
}

View File

@ -245,7 +245,7 @@ public abstract class PrintServiceLookup {
public static boolean registerService(PrintService service) {
synchronized (PrintServiceLookup.class) {
if (service instanceof StreamPrintService) {
if (service == null || service instanceof StreamPrintService) {
return false;
}
ArrayList<PrintService> registeredServices = getRegisteredServices();

View File

@ -31,6 +31,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@ -162,18 +163,11 @@ public class MidiSystem {
* of length 0 is returned.
*/
public static MidiDevice.Info[] getMidiDeviceInfo() {
List<MidiDevice.Info> allInfos = new ArrayList<>();
List<MidiDeviceProvider> providers = getMidiDeviceProviders();
for(int i = 0; i < providers.size(); i++) {
MidiDeviceProvider provider = providers.get(i);
MidiDevice.Info[] tmpinfo = provider.getDeviceInfo();
for (int j = 0; j < tmpinfo.length; j++) {
allInfos.add( tmpinfo[j] );
}
final List<MidiDevice.Info> allInfos = new ArrayList<>();
for (final MidiDeviceProvider provider : getMidiDeviceProviders()) {
Collections.addAll(allInfos, provider.getDeviceInfo());
}
MidiDevice.Info[] infosArray = allInfos.toArray(new MidiDevice.Info[0]);
return infosArray;
return allInfos.toArray(new MidiDevice.Info[allInfos.size()]);
}
/**
@ -187,17 +181,15 @@ public class MidiSystem {
* MIDI device installed on the system
* @see #getMidiDeviceInfo
*/
public static MidiDevice getMidiDevice(MidiDevice.Info info) throws MidiUnavailableException {
List<MidiDeviceProvider> providers = getMidiDeviceProviders();
for(int i = 0; i < providers.size(); i++) {
MidiDeviceProvider provider = providers.get(i);
public static MidiDevice getMidiDevice(final MidiDevice.Info info)
throws MidiUnavailableException {
for (final MidiDeviceProvider provider : getMidiDeviceProviders()) {
if (provider.isDeviceSupported(info)) {
MidiDevice device = provider.getDevice(info);
return device;
return provider.getDevice(info);
}
}
throw new IllegalArgumentException("Requested device not installed: " + info);
throw new IllegalArgumentException(String.format(
"Requested device not installed: %s", info));
}
/**

View File

@ -25,6 +25,8 @@
package javax.sound.midi.spi;
import java.util.Arrays;
import javax.sound.midi.MidiDevice;
/**
@ -45,16 +47,8 @@ public abstract class MidiDeviceProvider {
* @return {@code true} if the specified device is supported, otherwise
* {@code false}
*/
public boolean isDeviceSupported(MidiDevice.Info info) {
MidiDevice.Info infos[] = getDeviceInfo();
for(int i=0; i<infos.length; i++) {
if( info.equals( infos[i] ) ) {
return true;
}
}
return false;
public boolean isDeviceSupported(final MidiDevice.Info info) {
return Arrays.asList(getDeviceInfo()).contains(info);
}
/**

View File

@ -56,6 +56,7 @@ import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ObjectInputValidation;
import java.io.InvalidObjectException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.border.*;
import javax.swing.event.*;
@ -354,7 +355,8 @@ public abstract class JComponent extends Container implements Serializable,
private static final int AUTOSCROLLS_SET = 25;
private static final int FOCUS_TRAVERSAL_KEYS_FORWARD_SET = 26;
private static final int FOCUS_TRAVERSAL_KEYS_BACKWARD_SET = 27;
private static final int REVALIDATE_RUNNABLE_SCHEDULED = 28;
private transient AtomicBoolean revalidateRunnableScheduled = new AtomicBoolean(false);
/**
* Temporary rectangles.
@ -4901,16 +4903,11 @@ public abstract class JComponent extends Container implements Serializable,
// To avoid a flood of Runnables when constructing GUIs off
// the EDT, a flag is maintained as to whether or not
// a Runnable has been scheduled.
synchronized(this) {
if (getFlag(REVALIDATE_RUNNABLE_SCHEDULED)) {
return;
}
setFlag(REVALIDATE_RUNNABLE_SCHEDULED, true);
if (revalidateRunnableScheduled.getAndSet(true)) {
return;
}
SunToolkit.executeOnEventHandlerThread(this, () -> {
synchronized(JComponent.this) {
setFlag(REVALIDATE_RUNNABLE_SCHEDULED, false);
}
revalidateRunnableScheduled.set(false);
revalidate();
});
}
@ -5567,6 +5564,7 @@ public abstract class JComponent extends Container implements Serializable,
ToolTipManager.sharedInstance().registerComponent(this);
}
setWriteObjCounter(this, (byte)0);
revalidateRunnableScheduled = new AtomicBoolean(false);
}

View File

@ -3688,17 +3688,17 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
//
/**
* Sets the data model for this table to <code>newModel</code> and registers
* Sets the data model for this table to {@code dataModel} and registers
* with it for listener notifications from the new data model.
*
* @param dataModel the new data source for this table
* @exception IllegalArgumentException if <code>newModel</code> is <code>null</code>
* @see #getModel
* @param dataModel the new data source for this table
* @throws IllegalArgumentException if {@code dataModel} is {@code null}
* @see #getModel
* @beaninfo
* bound: true
* description: The model that is the source of the data for this view.
*/
public void setModel(TableModel dataModel) {
public void setModel(final TableModel dataModel) {
if (dataModel == null) {
throw new IllegalArgumentException("Cannot set a null TableModel");
}
@ -3721,29 +3721,30 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
}
/**
* Returns the <code>TableModel</code> that provides the data displayed by this
* <code>JTable</code>.
* Returns the {@code TableModel} that provides the data displayed by this
* {@code JTable}.
*
* @return the <code>TableModel</code> that provides the data displayed by this <code>JTable</code>
* @see #setModel
* @return the {@code TableModel} that provides the data displayed by this
* {@code JTable}
* @see #setModel
*/
public TableModel getModel() {
return dataModel;
}
/**
* Sets the column model for this table to <code>newModel</code> and registers
* for listener notifications from the new column model. Also sets
* the column model of the <code>JTableHeader</code> to <code>columnModel</code>.
* Sets the column model for this table to {@code columnModel} and registers
* for listener notifications from the new column model. Also sets the
* column model of the {@code JTableHeader} to {@code columnModel}.
*
* @param columnModel the new data source for this table
* @exception IllegalArgumentException if <code>columnModel</code> is <code>null</code>
* @see #getColumnModel
* @param columnModel the new data source for this table
* @throws IllegalArgumentException if {@code columnModel} is {@code null}
* @see #getColumnModel
* @beaninfo
* bound: true
* description: The object governing the way columns appear in the view.
*/
public void setColumnModel(TableColumnModel columnModel) {
public void setColumnModel(final TableColumnModel columnModel) {
if (columnModel == null) {
throw new IllegalArgumentException("Cannot set a null ColumnModel");
}
@ -3766,54 +3767,55 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
}
/**
* Returns the <code>TableColumnModel</code> that contains all column information
* Returns the {@code TableColumnModel} that contains all column information
* of this table.
*
* @return the object that provides the column state of the table
* @see #setColumnModel
* @return the object that provides the column state of the table
* @see #setColumnModel
*/
public TableColumnModel getColumnModel() {
return columnModel;
}
/**
* Sets the row selection model for this table to <code>newModel</code>
* Sets the row selection model for this table to {@code selectionModel}
* and registers for listener notifications from the new selection model.
*
* @param newModel the new selection model
* @exception IllegalArgumentException if <code>newModel</code> is <code>null</code>
* @see #getSelectionModel
* @param selectionModel the new selection model
* @throws IllegalArgumentException if {@code selectionModel} is
* {@code null}
* @see #getSelectionModel
* @beaninfo
* bound: true
* description: The selection model for rows.
*/
public void setSelectionModel(ListSelectionModel newModel) {
if (newModel == null) {
public void setSelectionModel(final ListSelectionModel selectionModel) {
if (selectionModel == null) {
throw new IllegalArgumentException("Cannot set a null SelectionModel");
}
ListSelectionModel oldModel = selectionModel;
ListSelectionModel oldModel = this.selectionModel;
if (newModel != oldModel) {
if (selectionModel != oldModel) {
if (oldModel != null) {
oldModel.removeListSelectionListener(this);
}
selectionModel = newModel;
newModel.addListSelectionListener(this);
this.selectionModel = selectionModel;
selectionModel.addListSelectionListener(this);
firePropertyChange("selectionModel", oldModel, newModel);
firePropertyChange("selectionModel", oldModel, selectionModel);
repaint();
}
}
/**
* Returns the <code>ListSelectionModel</code> that is used to maintain row
* Returns the {@code ListSelectionModel} that is used to maintain row
* selection state.
*
* @return the object that provides row selection state, <code>null</code>
* if row selection is not allowed
* @see #setSelectionModel
* @return the object that provides row selection state, {@code null} if row
* selection is not allowed
* @see #setSelectionModel
*/
public ListSelectionModel getSelectionModel() {
return selectionModel;

View File

@ -1122,6 +1122,11 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory {
Position.Bias b, int direction, Position.Bias[] biasRet)
throws BadLocationException{
Document doc = editor.getDocument();
if (pos < -1 || pos > doc.getLength()) {
throw new BadLocationException("Invalid position", pos);
}
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).readLock();
}
@ -1594,7 +1599,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory {
int direction,
Position.Bias[] biasRet)
throws BadLocationException {
if (pos < -1) {
if (pos < -1 || pos > getDocument().getLength()) {
throw new BadLocationException("invalid position", pos);
}
if( view != null ) {

View File

@ -854,7 +854,7 @@ public class AsyncBoxView extends View {
int direction,
Position.Bias[] biasRet)
throws BadLocationException {
if (pos < -1) {
if (pos < -1 || pos > getDocument().getLength()) {
throw new BadLocationException("invalid position", pos);
}
return Utilities.getNextVisualPositionFrom(

View File

@ -463,7 +463,7 @@ public abstract class CompositeView extends View {
public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a,
int direction, Position.Bias[] biasRet)
throws BadLocationException {
if (pos < -1) {
if (pos < -1 || pos > getDocument().getLength()) {
throw new BadLocationException("invalid position", pos);
}
Rectangle alloc = getInsideAllocation(a);
@ -723,6 +723,9 @@ public abstract class CompositeView extends View {
Shape a, int direction,
Position.Bias[] biasRet)
throws BadLocationException {
if (pos < -1 || pos > getDocument().getLength()) {
throw new BadLocationException("invalid position", pos);
}
return Utilities.getNextVisualPositionFrom(
this, pos, b, a, direction, biasRet);
}
@ -754,6 +757,9 @@ public abstract class CompositeView extends View {
int direction,
Position.Bias[] biasRet)
throws BadLocationException {
if (pos < -1 || pos > getDocument().getLength()) {
throw new BadLocationException("invalid position", pos);
}
return Utilities.getNextVisualPositionFrom(
this, pos, b, a, direction, biasRet);
}

View File

@ -900,7 +900,7 @@ public class GlyphView extends View implements TabableView, Cloneable {
Position.Bias[] biasRet)
throws BadLocationException {
if (pos < -1) {
if (pos < -1 || pos > getDocument().getLength()) {
throw new BadLocationException("invalid position", pos);
}
return painter.getNextVisualPositionFrom(this, pos, b, a, direction, biasRet);

View File

@ -500,7 +500,7 @@ public abstract class View implements SwingConstants {
public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a,
int direction, Position.Bias[] biasRet)
throws BadLocationException {
if (pos < -1) {
if (pos < -1 || pos > getDocument().getLength()) {
// -1 is a reserved value, see the code below
throw new BadLocationException("Invalid position", pos);
}

View File

@ -1408,10 +1408,10 @@ public class BytePackedRaster extends SunWritableRaster {
}
}
int lastbit = (dataBitOffset
+ (height-1) * scanlineStride * 8
+ (width-1) * pixelBitStride
+ pixelBitStride - 1);
long lastbit = (long) dataBitOffset
+ (long) (height - 1) * (long) scanlineStride * 8
+ (long) (width - 1) * (long) pixelBitStride
+ (long) pixelBitStride - 1;
if (lastbit < 0 || lastbit / 8 >= data.length) {
throw new RasterFormatException("raster dimensions overflow " +
"array bounds");

View File

@ -581,6 +581,15 @@ public class DataFlavorUtil {
return comp;
}
// Next prefer text types
if (flavor1.isFlavorTextType()) {
return 1;
}
if (flavor2.isFlavorTextType()) {
return -1;
}
// Next, look for application/x-java-* types. Prefer unknown
// MIME types because if the user provides his own data flavor,
// it will likely be the most descriptive one.

View File

@ -425,7 +425,6 @@ Java_sun_font_FreetypeFontScaler_getFontMetricsNative(
jobject metrics;
jfloat ax, ay, dx, dy, bx, by, lx, ly, mx, my;
jfloat f0 = 0.0;
FT_Pos bmodifier = 0;
FTScalerContext *context =
(FTScalerContext*) jlong_to_ptr(pScalerContext);
FTScalerInfo *scalerInfo =
@ -458,43 +457,38 @@ Java_sun_font_FreetypeFontScaler_getFontMetricsNative(
So, we have to do adust them explicitly and stay consistent with what
freetype does to outlines. */
/* For bolding glyphs are not just widened. Height is also changed
(see ftsynth.c).
TODO: In vertical direction we could do better job and adjust metrics
proportionally to glyoh shape. */
if (context->doBold) {
bmodifier = FT_MulFix(
scalerInfo->face->units_per_EM,
scalerInfo->face->size->metrics.y_scale)/24;
}
/**** Note: only some metrics are affected by styling ***/
/* See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=657854 */
#define FT_MulFixFloatShift6(a, b) (((float) (a)) * ((float) (b)) / 65536.0 / 64.0)
/*
* See FreeType source code: src/base/ftobjs.c ft_recompute_scaled_metrics()
* http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=1659
*/
/* ascent */
ax = 0;
ay = -(jfloat) FT26Dot6ToFloat(FT_MulFix(
((jlong) scalerInfo->face->ascender + bmodifier/2),
ay = -(jfloat) (FT_MulFixFloatShift6(
((jlong) scalerInfo->face->ascender),
(jlong) scalerInfo->face->size->metrics.y_scale));
/* descent */
dx = 0;
dy = -(jfloat) FT26Dot6ToFloat(FT_MulFix(
((jlong) scalerInfo->face->descender + bmodifier/2),
dy = -(jfloat) (FT_MulFixFloatShift6(
((jlong) scalerInfo->face->descender),
(jlong) scalerInfo->face->size->metrics.y_scale));
/* baseline */
bx = by = 0;
/* leading */
lx = 0;
ly = (jfloat) FT26Dot6ToFloat(FT_MulFix(
(jlong) scalerInfo->face->height + bmodifier,
ly = (jfloat) (FT_MulFixFloatShift6(
(jlong) scalerInfo->face->height,
(jlong) scalerInfo->face->size->metrics.y_scale))
+ ay - dy;
/* max advance */
mx = (jfloat) FT26Dot6ToFloat(
scalerInfo->face->size->metrics.max_advance +
2*bmodifier +
OBLIQUE_MODIFIER(scalerInfo->face->size->metrics.height));
my = 0;

View File

@ -243,12 +243,22 @@ le_uint32 ContextualSubstitutionFormat1Subtable::process(const LETableReference
le_uint16 srSetCount = SWAPW(subRuleSetCount);
if (coverageIndex < srSetCount) {
LEReferenceToArrayOf<Offset> subRuleSetTableOffsetArrayRef(base, success,
&subRuleSetTableOffsetArray[coverageIndex], 1);
if (LE_FAILURE(success)) {
return 0;
}
Offset subRuleSetTableOffset = SWAPW(subRuleSetTableOffsetArray[coverageIndex]);
LEReferenceTo<SubRuleSetTable>
subRuleSetTable(base, success, (const SubRuleSetTable *) ((char *) this + subRuleSetTableOffset));
le_uint16 subRuleCount = SWAPW(subRuleSetTable->subRuleCount);
le_int32 position = glyphIterator->getCurrStreamPosition();
LEReferenceToArrayOf<Offset> subRuleTableOffsetArrayRef(base, success,
subRuleSetTable->subRuleTableOffsetArray, subRuleCount);
if (LE_FAILURE(success)) {
return 0;
}
for (le_uint16 subRule = 0; subRule < subRuleCount; subRule += 1) {
Offset subRuleTableOffset =
SWAPW(subRuleSetTable->subRuleTableOffsetArray[subRule]);
@ -301,34 +311,44 @@ le_uint32 ContextualSubstitutionFormat2Subtable::process(const LETableReference
glyphIterator->getCurrGlyphID(),
success);
if (setClass < scSetCount && subClassSetTableOffsetArray[setClass] != 0) {
Offset subClassSetTableOffset = SWAPW(subClassSetTableOffsetArray[setClass]);
LEReferenceTo<SubClassSetTable>
subClassSetTable(base, success, (const SubClassSetTable *) ((char *) this + subClassSetTableOffset));
le_uint16 subClassRuleCount = SWAPW(subClassSetTable->subClassRuleCount);
le_int32 position = glyphIterator->getCurrStreamPosition();
if (setClass < scSetCount) {
LEReferenceToArrayOf<Offset>
subClassSetTableOffsetArrayRef(base, success, subClassSetTableOffsetArray, setClass);
if (LE_FAILURE(success)) { return 0; }
if (subClassSetTableOffsetArray[setClass] != 0) {
for (le_uint16 scRule = 0; scRule < subClassRuleCount; scRule += 1) {
Offset subClassRuleTableOffset =
SWAPW(subClassSetTable->subClassRuleTableOffsetArray[scRule]);
LEReferenceTo<SubClassRuleTable>
subClassRuleTable(subClassSetTable, success, subClassRuleTableOffset);
le_uint16 matchCount = SWAPW(subClassRuleTable->glyphCount) - 1;
le_uint16 substCount = SWAPW(subClassRuleTable->substCount);
LEReferenceToArrayOf<le_uint16> classArray(base, success, subClassRuleTable->classArray, matchCount+1);
if (LE_FAILURE(success)) { return 0; }
if (matchGlyphClasses(classArray, matchCount, glyphIterator, classDefinitionTable, success)) {
LEReferenceToArrayOf<SubstitutionLookupRecord>
substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) &subClassRuleTable->classArray[matchCount], substCount);
applySubstitutionLookups(lookupProcessor, substLookupRecordArray, substCount, glyphIterator, fontInstance, position, success);
return matchCount + 1;
Offset subClassSetTableOffset = SWAPW(subClassSetTableOffsetArray[setClass]);
LEReferenceTo<SubClassSetTable>
subClassSetTable(base, success, (const SubClassSetTable *) ((char *) this + subClassSetTableOffset));
le_uint16 subClassRuleCount = SWAPW(subClassSetTable->subClassRuleCount);
le_int32 position = glyphIterator->getCurrStreamPosition();
LEReferenceToArrayOf<Offset>
subClassRuleTableOffsetArrayRef(base, success, subClassSetTable->subClassRuleTableOffsetArray, subClassRuleCount);
if (LE_FAILURE(success)) {
return 0;
}
for (le_uint16 scRule = 0; scRule < subClassRuleCount; scRule += 1) {
Offset subClassRuleTableOffset =
SWAPW(subClassSetTable->subClassRuleTableOffsetArray[scRule]);
LEReferenceTo<SubClassRuleTable>
subClassRuleTable(subClassSetTable, success, subClassRuleTableOffset);
le_uint16 matchCount = SWAPW(subClassRuleTable->glyphCount) - 1;
le_uint16 substCount = SWAPW(subClassRuleTable->substCount);
glyphIterator->setCurrStreamPosition(position);
LEReferenceToArrayOf<le_uint16> classArray(base, success, subClassRuleTable->classArray, matchCount+1);
if (LE_FAILURE(success)) { return 0; }
if (matchGlyphClasses(classArray, matchCount, glyphIterator, classDefinitionTable, success)) {
LEReferenceToArrayOf<SubstitutionLookupRecord>
substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) &subClassRuleTable->classArray[matchCount], substCount);
applySubstitutionLookups(lookupProcessor, substLookupRecordArray, substCount, glyphIterator, fontInstance, position, success);
return matchCount + 1;
}
glyphIterator->setCurrStreamPosition(position);
}
}
}
@ -442,13 +462,22 @@ le_uint32 ChainingContextualSubstitutionFormat1Subtable::process(const LETableRe
le_uint16 srSetCount = SWAPW(chainSubRuleSetCount);
if (coverageIndex < srSetCount) {
LEReferenceToArrayOf<Offset>
chainSubRuleSetTableOffsetArrayRef(base, success, chainSubRuleSetTableOffsetArray, coverageIndex);
if (LE_FAILURE(success)) {
return 0;
}
Offset chainSubRuleSetTableOffset = SWAPW(chainSubRuleSetTableOffsetArray[coverageIndex]);
LEReferenceTo<ChainSubRuleSetTable>
chainSubRuleSetTable(base, success, (const ChainSubRuleSetTable *) ((char *) this + chainSubRuleSetTableOffset));
le_uint16 chainSubRuleCount = SWAPW(chainSubRuleSetTable->chainSubRuleCount);
le_int32 position = glyphIterator->getCurrStreamPosition();
GlyphIterator tempIterator(*glyphIterator, emptyFeatureList);
LEReferenceToArrayOf<Offset>
chainSubRuleTableOffsetArrayRef(base, success, chainSubRuleSetTable->chainSubRuleTableOffsetArray, chainSubRuleCount);
if (LE_FAILURE(success)) {
return 0;
}
for (le_uint16 subRule = 0; subRule < chainSubRuleCount; subRule += 1) {
Offset chainSubRuleTableOffset =
SWAPW(chainSubRuleSetTable->chainSubRuleTableOffsetArray[subRule]);
@ -530,6 +559,11 @@ le_uint32 ChainingContextualSubstitutionFormat2Subtable::process(const LETableRe
le_int32 setClass = inputClassDefinitionTable->getGlyphClass(inputClassDefinitionTable,
glyphIterator->getCurrGlyphID(),
success);
LEReferenceToArrayOf<Offset>
chainSubClassSetTableOffsetArrayRef(base, success, chainSubClassSetTableOffsetArray, setClass);
if (LE_FAILURE(success)) {
return 0;
}
if (setClass < scSetCount && chainSubClassSetTableOffsetArray[setClass] != 0) {
Offset chainSubClassSetTableOffset = SWAPW(chainSubClassSetTableOffsetArray[setClass]);
@ -538,7 +572,11 @@ le_uint32 ChainingContextualSubstitutionFormat2Subtable::process(const LETableRe
le_uint16 chainSubClassRuleCount = SWAPW(chainSubClassSetTable->chainSubClassRuleCount);
le_int32 position = glyphIterator->getCurrStreamPosition();
GlyphIterator tempIterator(*glyphIterator, emptyFeatureList);
LEReferenceToArrayOf<Offset>
chainSubClassRuleTableOffsetArrayRef(base, success, chainSubClassSetTable->chainSubClassRuleTableOffsetArray, chainSubClassRuleCount);
if (LE_FAILURE(success)) {
return 0;
}
for (le_uint16 scRule = 0; scRule < chainSubClassRuleCount; scRule += 1) {
Offset chainSubClassRuleTableOffset =
SWAPW(chainSubClassSetTable->chainSubClassRuleTableOffsetArray[scRule]);
@ -603,12 +641,14 @@ le_uint32 ChainingContextualSubstitutionFormat3Subtable::process(const LETableRe
}
le_uint16 backtrkGlyphCount = SWAPW(backtrackGlyphCount);
LEReferenceToArrayOf<Offset> backtrackGlyphArrayRef(base, success, backtrackCoverageTableOffsetArray, backtrkGlyphCount);
if (LE_FAILURE(success)) {
return 0;
}
le_uint16 inputGlyphCount = (le_uint16) SWAPW(backtrackCoverageTableOffsetArray[backtrkGlyphCount]);
LEReferenceToArrayOf<Offset> inputCoverageTableOffsetArray(base, success, &backtrackCoverageTableOffsetArray[backtrkGlyphCount + 1], inputGlyphCount+2); // offset
if (LE_FAILURE(success)) { return 0; }
const le_uint16 lookaheadGlyphCount = (le_uint16) SWAPW(inputCoverageTableOffsetArray[inputGlyphCount]);
if( LE_FAILURE(success)) { return 0; }
LEReferenceToArrayOf<Offset> lookaheadCoverageTableOffsetArray(base, success, inputCoverageTableOffsetArray.getAlias(inputGlyphCount + 1, success), lookaheadGlyphCount+2);
if( LE_FAILURE(success) ) { return 0; }

View File

@ -136,7 +136,7 @@ public class CUPSPrinter {
/**
* Returns array of MediaSizeNames derived from PPD.
*/
public MediaSizeName[] getMediaSizeNames() {
MediaSizeName[] getMediaSizeNames() {
initMedia();
return cupsMediaSNames;
}
@ -145,7 +145,7 @@ public class CUPSPrinter {
/**
* Returns array of Custom MediaSizeNames derived from PPD.
*/
public CustomMediaSizeName[] getCustomMediaSizeNames() {
CustomMediaSizeName[] getCustomMediaSizeNames() {
initMedia();
return cupsCustomMediaSNames;
}
@ -157,7 +157,7 @@ public class CUPSPrinter {
/**
* Returns array of MediaPrintableArea derived from PPD.
*/
public MediaPrintableArea[] getMediaPrintableArea() {
MediaPrintableArea[] getMediaPrintableArea() {
initMedia();
return cupsMediaPrintables;
}
@ -165,7 +165,7 @@ public class CUPSPrinter {
/**
* Returns array of MediaTrays derived from PPD.
*/
public MediaTray[] getMediaTrays() {
MediaTray[] getMediaTrays() {
initMedia();
return cupsMediaTrays;
}

View File

@ -1002,7 +1002,9 @@ public class IPPPrintService implements PrintService, SunPrinterJobService {
public synchronized Class<?>[] getSupportedAttributeCategories() {
if (supportedCats != null) {
return supportedCats;
Class<?> [] copyCats = new Class<?>[supportedCats.length];
System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
return copyCats;
}
initAttributes();
@ -1065,7 +1067,9 @@ public class IPPPrintService implements PrintService, SunPrinterJobService {
supportedCats = new Class<?>[catList.size()];
catList.toArray(supportedCats);
return supportedCats;
Class<?>[] copyCats = new Class<?>[supportedCats.length];
System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
return copyCats;
}

View File

@ -52,6 +52,8 @@
*/
extern XErrorHandler current_native_xerror_handler;
Window get_xawt_root_shell(JNIEnv *env);
#endif /* !HEADLESS */
#ifndef INTERSECTS

View File

@ -2011,10 +2011,14 @@ static Bool exitSecondaryLoop = True;
* Toolkit thread to process PropertyNotify or SelectionNotify events.
*/
static Bool
secondary_loop_event(Display* dpy, XEvent* event, char* arg) {
return (event->type == SelectionNotify ||
event->type == SelectionClear ||
event->type == PropertyNotify) ? True : False;
secondary_loop_event(Display* dpy, XEvent* event, XPointer xawt_root_window) {
return (
event->type == SelectionNotify ||
event->type == SelectionClear ||
event->type == PropertyNotify ||
(event->type == ConfigureNotify
&& event->xany.window == *(Window*) xawt_root_window)
) ? True : False;
}
@ -2025,8 +2029,11 @@ Java_sun_awt_X11_XlibWrapper_XNextSecondaryLoopEvent(JNIEnv *env, jclass clazz,
AWT_CHECK_HAVE_LOCK_RETURN(JNI_FALSE);
exitSecondaryLoop = False;
Window xawt_root_window = get_xawt_root_shell(env);
while (!exitSecondaryLoop) {
if (XCheckIfEvent((Display*) jlong_to_ptr(display), (XEvent*) jlong_to_ptr(ptr), secondary_loop_event, NULL)) {
if (XCheckIfEvent((Display*) jlong_to_ptr(display),
(XEvent*) jlong_to_ptr(ptr), secondary_loop_event, (XPointer) &xawt_root_window)) {
return JNI_TRUE;
}
timeout = (timeout < AWT_SECONDARY_LOOP_TIMEOUT) ? (timeout << 1) : AWT_SECONDARY_LOOP_TIMEOUT;

View File

@ -670,7 +670,7 @@ Java_sun_java2d_windows_GDIRenderer_doFillPoly
if (ypoints != NULL) {
pPoints = TransformPoly(xpoints, ypoints, transx, transy,
tmpPts, &npoints, FALSE, FALSE);
env->ReleasePrimitiveArrayCritical(ypointsarray, xpoints, JNI_ABORT);
env->ReleasePrimitiveArrayCritical(ypointsarray, ypoints, JNI_ABORT);
}
env->ReleasePrimitiveArrayCritical(xpointsarray, xpoints, JNI_ABORT);
}

View File

@ -3936,7 +3936,6 @@ void AwtComponent::SendInputMethodEvent(jint id, jstring text,
DASSERT(stringCls);
CHECK_NULL(stringCls);
clauseReading = env->NewObjectArray(cClause, stringCls, NULL);
env->DeleteLocalRef(stringCls);
DASSERT(clauseReading);
CHECK_NULL(clauseReading);
for (int i=0; i<cClause; i++) env->SetObjectArrayElement(clauseReading, i, rgClauseReading[i]);

View File

@ -47,16 +47,12 @@ struct ReplaceTextStruct {
jfieldID AwtTextArea::scrollbarVisibilityID;
WNDPROC AwtTextArea::sm_pDefWindowProc = NULL;
/************************************************************************
* AwtTextArea methods
*/
AwtTextArea::AwtTextArea() {
m_bIgnoreEnChange = FALSE;
m_bCanUndo = FALSE;
m_hEditCtrl = NULL;
m_lHDeltaAccum = 0;
m_lVDeltaAccum = 0;
}
@ -67,10 +63,6 @@ AwtTextArea::~AwtTextArea()
void AwtTextArea::Dispose()
{
if (m_hEditCtrl != NULL) {
VERIFY(::DestroyWindow(m_hEditCtrl));
m_hEditCtrl = NULL;
}
AwtTextComponent::Dispose();
}
@ -91,10 +83,6 @@ void AwtTextArea::EditSetSel(CHARRANGE &cr) {
}
}
void AwtTextArea::EditGetSel(CHARRANGE &cr) {
SendMessage(EM_EXGETSEL, 0, reinterpret_cast<LPARAM>(&cr));
}
/* Count how many '\n's are there in jStr */
size_t AwtTextArea::CountNewLines(JNIEnv *env, jstring jStr, size_t maxlen)
{
@ -149,159 +137,6 @@ AwtTextArea::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) {
return retValue;
}
/*
* This routine is a window procedure for the subclass of the standard edit control
* used to generate context menu. RichEdit controls don't have built-in context menu.
* To implement this functionality we have to create an invisible edit control and
* forward WM_CONTEXTMENU messages from a RichEdit control to this helper edit control.
* While the edit control context menu is active we intercept the message generated in
* response to particular item selection and forward it back to the RichEdit control.
* (See AwtTextArea::WmContextMenu for more details).
*/
LRESULT
AwtTextArea::EditProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
static BOOL bContextMenuActive = FALSE;
LRESULT retValue = 0;
MsgRouting mr = mrDoDefault;
DASSERT(::IsWindow(::GetParent(hWnd)));
switch (message) {
case WM_UNDO:
case WM_CUT:
case WM_COPY:
case WM_PASTE:
case WM_CLEAR:
case EM_SETSEL:
if (bContextMenuActive) {
::SendMessage(::GetParent(hWnd), message, wParam, lParam);
mr = mrConsume;
}
break;
case WM_CONTEXTMENU:
bContextMenuActive = TRUE;
break;
}
if (mr == mrDoDefault) {
DASSERT(sm_pDefWindowProc != NULL);
retValue = ::CallWindowProc(sm_pDefWindowProc,
hWnd, message, wParam, lParam);
}
if (message == WM_CONTEXTMENU) {
bContextMenuActive = FALSE;
}
return retValue;
}
MsgRouting
AwtTextArea::WmContextMenu(HWND hCtrl, UINT xPos, UINT yPos) {
/* Use the system provided edit control class to generate context menu. */
if (m_hEditCtrl == NULL) {
DWORD dwStyle = WS_CHILD;
DWORD dwExStyle = 0;
m_hEditCtrl = ::CreateWindowEx(dwExStyle,
L"EDIT",
L"TEXT",
dwStyle,
0, 0, 0, 0,
GetHWnd(),
reinterpret_cast<HMENU>(
static_cast<INT_PTR>(
CreateControlID())),
AwtToolkit::GetInstance().GetModuleHandle(),
NULL);
DASSERT(m_hEditCtrl != NULL);
if (sm_pDefWindowProc == NULL) {
sm_pDefWindowProc = (WNDPROC)::GetWindowLongPtr(m_hEditCtrl,
GWLP_WNDPROC);
}
::SetLastError(0);
INT_PTR ret = ::SetWindowLongPtr(m_hEditCtrl, GWLP_WNDPROC,
(INT_PTR)AwtTextArea::EditProc);
DASSERT(ret != 0 || ::GetLastError() == 0);
}
/*
* Tricks on the edit control to ensure that its context menu has
* the correct set of enabled items according to the RichEdit state.
*/
::SetWindowText(m_hEditCtrl, TEXT("TEXT"));
if (m_bCanUndo == TRUE && SendMessage(EM_CANUNDO)) {
/* Enable 'Undo' item. */
::SendMessage(m_hEditCtrl, WM_CHAR, 'A', 0);
}
{
/*
* Initial selection for the edit control - (0,1).
* This enables 'Cut', 'Copy' and 'Delete' and 'Select All'.
*/
INT nStart = 0;
INT nEnd = 1;
if (SendMessage(EM_SELECTIONTYPE) == SEL_EMPTY) {
/*
* RichEdit selection is empty - clear selection of the edit control.
* This disables 'Cut', 'Copy' and 'Delete'.
*/
nStart = -1;
nEnd = 0;
} else {
CHARRANGE cr;
EditGetSel(cr);
/* Check if all the text is selected. */
if (cr.cpMin == 0) {
int len = ::GetWindowTextLength(GetHWnd());
if (cr.cpMin == 0 && cr.cpMax >= len) {
/*
* All the text is selected in RichEdit - select all the
* text in the edit control. This disables 'Select All'.
*/
nStart = 0;
nEnd = -1;
}
}
}
::SendMessage(m_hEditCtrl, EM_SETSEL, (WPARAM)nStart, (LPARAM)nEnd);
}
/* Disable 'Paste' item if the RichEdit control is read-only. */
::SendMessage(m_hEditCtrl, EM_SETREADONLY,
GetStyle() & ES_READONLY ? TRUE : FALSE, 0);
POINT p;
p.x = xPos;
p.y = yPos;
/*
* If the context menu is requested with SHIFT+F10 or VK_APPS key,
* we position its top left corner to the center of the RichEdit
* client rect.
*/
if (p.x == -1 && p.y == -1) {
RECT r;
VERIFY(::GetClientRect(GetHWnd(), &r));
p.x = (r.left + r.right) / 2;
p.y = (r.top + r.bottom) / 2;
VERIFY(::ClientToScreen(GetHWnd(), &p));
}
// The context menu steals focus from the proxy.
// So, set the focus-restore flag up.
SetRestoreFocus(TRUE);
::SendMessage(m_hEditCtrl, WM_CONTEXTMENU, (WPARAM)m_hEditCtrl, MAKELPARAM(p.x, p.y));
SetRestoreFocus(FALSE);
return mrConsume;
}
MsgRouting
AwtTextArea::WmNcHitTest(UINT x, UINT y, LRESULT& retVal)
{
@ -313,28 +148,9 @@ AwtTextArea::WmNcHitTest(UINT x, UINT y, LRESULT& retVal)
}
MsgRouting
AwtTextArea::WmNotify(UINT notifyCode)
{
if (notifyCode == EN_CHANGE) {
/*
* Ignore notifications if the text hasn't been changed.
* EN_CHANGE sent on character formatting changes as well.
*/
if (m_bIgnoreEnChange == FALSE) {
m_bCanUndo = TRUE;
DoCallback("valueChanged", "()V");
} else {
m_bCanUndo = FALSE;
}
}
return mrDoDefault;
}
MsgRouting
AwtTextArea::HandleEvent(MSG *msg, BOOL synthetic)
{
MsgRouting returnVal;
/*
* RichEdit 1.0 control starts internal message loop if the
* left mouse button is pressed while the cursor is not over
@ -486,26 +302,6 @@ AwtTextArea::HandleEvent(MSG *msg, BOOL synthetic)
}
delete msg;
return mrConsume;
} else if (msg->message == WM_RBUTTONUP ||
(msg->message == WM_SYSKEYDOWN && msg->wParam == VK_F10 &&
HIBYTE(::GetKeyState(VK_SHIFT)))) {
POINT p;
if (msg->message == WM_RBUTTONUP) {
VERIFY(::GetCursorPos(&p));
} else {
p.x = -1;
p.y = -1;
}
if (!::PostMessage(GetHWnd(), WM_CONTEXTMENU, (WPARAM)GetHWnd(),
MAKELPARAM(p.x, p.y))) {
JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
JNU_ThrowInternalError(env, "Message not posted, native event queue may be full.");
env->ExceptionDescribe();
env->ExceptionClear();
}
delete msg;
return mrConsume;
} else if (msg->message == WM_MOUSEWHEEL) {
// 4417236: If there is an old version of RichEd32.dll which
// does not provide the mouse wheel scrolling we have to
@ -596,15 +392,7 @@ AwtTextArea::HandleEvent(MSG *msg, BOOL synthetic)
// 4417236: end of fix
}
/*
* Store the 'synthetic' parameter so that the WM_PASTE security check
* happens only for synthetic events.
*/
m_synthetic = synthetic;
returnVal = AwtComponent::HandleEvent(msg, synthetic);
m_synthetic = FALSE;
return returnVal;
return AwtTextComponent::HandleEvent(msg, synthetic);
}

View File

@ -57,17 +57,11 @@ public:
static size_t GetALength(JNIEnv* env, jstring jStr, size_t maxlen);
LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK EditProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
MsgRouting WmEnable(BOOL fEnabled);
MsgRouting WmContextMenu(HWND hCtrl, UINT xPos, UINT yPos);
MsgRouting WmNotify(UINT notifyCode);
MsgRouting WmNcHitTest(UINT x, UINT y, LRESULT &retVal);
MsgRouting HandleEvent(MSG *msg, BOOL synthetic);
INLINE void SetIgnoreEnChange(BOOL b) { m_bIgnoreEnChange = b; }
virtual BOOL InheritsNativeMouseWheelBehavior();
virtual void Reshape(int x, int y, int w, int h);
@ -81,22 +75,7 @@ public:
protected:
void EditSetSel(CHARRANGE &cr);
void EditGetSel(CHARRANGE &cr);
private:
// RichEdit 1.0 control generates EN_CHANGE notifications not only
// on text changes, but also on any character formatting change.
// This flag is true when the latter case is detected.
BOOL m_bIgnoreEnChange;
// RichEdit 1.0 control undoes a character formatting change
// if it is the latest. We don't create our own undo buffer,
// but just prohibit undo in case if the latest operation
// is a formatting change.
BOOL m_bCanUndo;
HWND m_hEditCtrl;
static WNDPROC sm_pDefWindowProc;
LONG m_lHDeltaAccum;
LONG m_lVDeltaAccum;

View File

@ -66,6 +66,8 @@ AwtTextComponent::AwtTextComponent() {
m_lLastPos = -1;
m_isLFonly = FALSE;
m_EOLchecked = FALSE;
m_hEditCtrl = NULL;
m_bIgnoreEnChange = FALSE;
// javaEventsMask = 0; // accessibility support
}
@ -213,6 +215,16 @@ done:
return c;
}
void AwtTextComponent::Dispose()
{
if (m_hEditCtrl != NULL) {
VERIFY(::DestroyWindow(m_hEditCtrl));
m_hEditCtrl = NULL;
}
AwtComponent::Dispose();
}
LRESULT
AwtTextComponent::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) {
@ -322,7 +334,16 @@ MsgRouting
AwtTextComponent::WmNotify(UINT notifyCode)
{
if (notifyCode == EN_CHANGE) {
DoCallback("valueChanged", "()V");
/*
* Ignore notifications if the text hasn't been changed.
* EN_CHANGE sent on character formatting changes as well.
*/
if (m_bIgnoreEnChange == FALSE) {
m_bCanUndo = TRUE;
DoCallback("valueChanged", "()V");
} else {
m_bCanUndo = FALSE;
}
}
return mrDoDefault;
}
@ -337,6 +358,28 @@ AwtTextComponent::HandleEvent(MSG *msg, BOOL synthetic)
{
MsgRouting returnVal;
if (msg->message == WM_RBUTTONUP ||
(msg->message == WM_SYSKEYDOWN && msg->wParam == VK_F10 &&
HIBYTE(::GetKeyState(VK_SHIFT)))) {
POINT p;
if (msg->message == WM_RBUTTONUP) {
VERIFY(::GetCursorPos(&p));
} else {
p.x = -1;
p.y = -1;
}
if (!::PostMessage(GetHWnd(), WM_CONTEXTMENU, (WPARAM)GetHWnd(),
MAKELPARAM(p.x, p.y))) {
JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
JNU_ThrowInternalError(env, "Message not posted, native event queue may be full.");
env->ExceptionDescribe();
env->ExceptionClear();
}
delete msg;
return mrConsume;
}
/*
* Store the 'synthetic' parameter so that the WM_PASTE security check
* happens only for synthetic events.
@ -701,6 +744,10 @@ void AwtTextComponent::SetBackgroundColor(COLORREF c) {
SendMessage(EM_SETBKGNDCOLOR, (WPARAM)FALSE, (LPARAM)GetBackgroundColor());
}
void AwtTextComponent::EditGetSel(CHARRANGE &cr) {
SendMessage(EM_EXGETSEL, 0, reinterpret_cast<LPARAM>(&cr));
}
/************************************************************************
* WTextComponentPeer native methods
@ -983,6 +1030,161 @@ AwtTextComponent::OleCallback::GetContextMenu(WORD seltype,
}
/*
* This routine is a window procedure for the subclass of the standard edit control
* used to generate context menu. RichEdit controls don't have built-in context menu.
* To implement this functionality we have to create an invisible edit control and
* forward WM_CONTEXTMENU messages from a RichEdit control to this helper edit control.
* While the edit control context menu is active we intercept the message generated in
* response to particular item selection and forward it back to the RichEdit control.
* (See AwtTextArea::WmContextMenu for more details).
*/
WNDPROC AwtTextComponent::sm_pDefWindowProc = NULL;
LRESULT
AwtTextComponent::EditProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
static BOOL bContextMenuActive = FALSE;
LRESULT retValue = 0;
MsgRouting mr = mrDoDefault;
DASSERT(::IsWindow(::GetParent(hWnd)));
switch (message) {
case WM_UNDO:
case WM_CUT:
case WM_COPY:
case WM_PASTE:
case WM_CLEAR:
case EM_SETSEL:
if (bContextMenuActive) {
::SendMessage(::GetParent(hWnd), message, wParam, lParam);
mr = mrConsume;
}
break;
case WM_CONTEXTMENU:
bContextMenuActive = TRUE;
break;
}
if (mr == mrDoDefault) {
DASSERT(sm_pDefWindowProc != NULL);
retValue = ::CallWindowProc(sm_pDefWindowProc,
hWnd, message, wParam, lParam);
}
if (message == WM_CONTEXTMENU) {
bContextMenuActive = FALSE;
}
return retValue;
}
MsgRouting
AwtTextComponent::WmContextMenu(HWND hCtrl, UINT xPos, UINT yPos) {
/* Use the system provided edit control class to generate context menu. */
if (m_hEditCtrl == NULL) {
DWORD dwStyle = WS_CHILD;
DWORD dwExStyle = 0;
m_hEditCtrl = ::CreateWindowEx(dwExStyle,
L"EDIT",
L"TEXT",
dwStyle,
0, 0, 0, 0,
GetHWnd(),
reinterpret_cast<HMENU>(
static_cast<INT_PTR>(
CreateControlID())),
AwtToolkit::GetInstance().GetModuleHandle(),
NULL);
DASSERT(m_hEditCtrl != NULL);
if (sm_pDefWindowProc == NULL) {
sm_pDefWindowProc = (WNDPROC)::GetWindowLongPtr(m_hEditCtrl,
GWLP_WNDPROC);
}
::SetLastError(0);
INT_PTR ret = ::SetWindowLongPtr(m_hEditCtrl, GWLP_WNDPROC,
(INT_PTR)AwtTextArea::EditProc);
DASSERT(ret != 0 || ::GetLastError() == 0);
}
/*
* Tricks on the edit control to ensure that its context menu has
* the correct set of enabled items according to the RichEdit state.
*/
::SetWindowText(m_hEditCtrl, TEXT("TEXT"));
if (m_bCanUndo == TRUE && SendMessage(EM_CANUNDO)) {
/* Enable 'Undo' item. */
::SendMessage(m_hEditCtrl, WM_CHAR, 'A', 0);
}
{
/*
* Initial selection for the edit control - (0,1).
* This enables 'Cut', 'Copy' and 'Delete' and 'Select All'.
*/
INT nStart = 0;
INT nEnd = 1;
if (SendMessage(EM_SELECTIONTYPE) == SEL_EMPTY) {
/*
* RichEdit selection is empty - clear selection of the edit control.
* This disables 'Cut', 'Copy' and 'Delete'.
*/
nStart = -1;
nEnd = 0;
} else {
CHARRANGE cr;
EditGetSel(cr);
/* Check if all the text is selected. */
if (cr.cpMin == 0) {
int len = ::GetWindowTextLength(GetHWnd());
if (cr.cpMin == 0 && cr.cpMax >= len) {
/*
* All the text is selected in RichEdit - select all the
* text in the edit control. This disables 'Select All'.
*/
nStart = 0;
nEnd = -1;
}
}
}
::SendMessage(m_hEditCtrl, EM_SETSEL, (WPARAM)nStart, (LPARAM)nEnd);
}
/* Disable 'Paste' item if the RichEdit control is read-only. */
::SendMessage(m_hEditCtrl, EM_SETREADONLY,
GetStyle() & ES_READONLY ? TRUE : FALSE, 0);
POINT p;
p.x = xPos;
p.y = yPos;
/*
* If the context menu is requested with SHIFT+F10 or VK_APPS key,
* we position its top left corner to the center of the RichEdit
* client rect.
*/
if (p.x == -1 && p.y == -1) {
RECT r;
VERIFY(::GetClientRect(GetHWnd(), &r));
p.x = (r.left + r.right) / 2;
p.y = (r.top + r.bottom) / 2;
VERIFY(::ClientToScreen(GetHWnd(), &p));
}
// The context menu steals focus from the proxy.
// So, set the focus-restore flag up.
SetRestoreFocus(TRUE);
::SendMessage(m_hEditCtrl, WM_CONTEXTMENU, (WPARAM)m_hEditCtrl, MAKELPARAM(p.x, p.y));
SetRestoreFocus(FALSE);
return mrConsume;
}
//
// Accessibility support

View File

@ -47,6 +47,8 @@ public:
static AwtTextComponent* Create(jobject self, jobject parent, BOOL isMultiline);
virtual void Dispose();
virtual LPCTSTR GetClassName();
LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
@ -83,6 +85,8 @@ public:
MsgRouting HandleEvent(MSG *msg, BOOL synthetic);
MsgRouting WmPaste();
INLINE void SetIgnoreEnChange(BOOL b) { m_bIgnoreEnChange = b; }
virtual BOOL IsFocusingMouseMessage(MSG *pMsg);
/* To be fully implemented in a future release
@ -115,11 +119,24 @@ public:
INLINE VOID SetEndSelectionPos(LONG lPos) { m_lEndPos = lPos; }
INLINE VOID SetLastSelectionPos(LONG lPos) { m_lLastPos = lPos; }
void EditGetSel(CHARRANGE &cr);
// Used to prevent untrusted code from synthesizing a WM_PASTE message
// by posting a <CTRL>-V KeyEvent
BOOL m_synthetic;
LONG EditGetCharFromPos(POINT& pt);
// RichEdit 1.0 control generates EN_CHANGE notifications not only
// on text changes, but also on any character formatting change.
// This flag is true when the latter case is detected.
BOOL m_bIgnoreEnChange;
// RichEdit 1.0 control undoes a character formatting change
// if it is the latest. We don't create our own undo buffer,
// but just prohibit undo in case if the latest operation
// is a formatting change.
BOOL m_bCanUndo;
/*****************************************************************
* Inner class OleCallback declaration.
*/
@ -166,6 +183,13 @@ private:
static OleCallback sm_oleCallback;
static WNDPROC sm_pDefWindowProc;
HWND m_hEditCtrl;
static LRESULT CALLBACK EditProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
MsgRouting WmContextMenu(HWND hCtrl, UINT xPos, UINT yPos);
//
// Accessibility support
//

View File

@ -249,13 +249,7 @@ AwtTextField::HandleEvent(MSG *msg, BOOL synthetic)
}
}
/*
* Store the 'synthetic' parameter so that the WM_PASTE security check
* happens only for synthetic events.
*/
m_synthetic = synthetic;
returnVal = AwtComponent::HandleEvent(msg, synthetic);
m_synthetic = FALSE;
returnVal = AwtTextComponent::HandleEvent(msg, synthetic);
if(systemBeeperEnabled){
SystemParametersInfo(SPI_SETBEEP, 1, NULL, 0);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -213,6 +213,14 @@ SplashPaint(Splash * splash, HDC hdc)
void
SplashRedrawWindow(Splash * splash)
{
if (!SplashIsStillLooping(splash)) {
KillTimer(splash->hWnd, 0);
}
if (splash->currentFrame < 0) {
return;
}
SplashUpdateScreenData(splash);
if (splash->isLayered) {
BLENDFUNCTION bf;
@ -303,9 +311,6 @@ SplashRedrawWindow(Splash * splash)
time = 0;
SetTimer(splash->hWnd, 0, time, NULL);
}
else {
KillTimer(splash->hWnd, 0);
}
}
void SplashReconfigureNow(Splash * splash) {

View File

@ -509,7 +509,13 @@ public class LogRecord implements java.io.Serializable {
// If necessary, try to regenerate the resource bundle.
if (resourceBundleName != null) {
try {
resourceBundle = ResourceBundle.getBundle(resourceBundleName);
// use system class loader to ensure the ResourceBundle
// instance is a different instance than null loader uses
final ResourceBundle bundle =
ResourceBundle.getBundle(resourceBundleName,
Locale.getDefault(),
ClassLoader.getSystemClassLoader());
resourceBundle = bundle;
} catch (MissingResourceException ex) {
// This is not a good place to throw an exception,
// so we simply leave the resourceBundle null.

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -1937,6 +1937,9 @@ public class Logger {
}
setCallersClassLoaderRef(callersClass);
if (isSystemLogger && getCallersClassLoader() != null) {
checkPermission();
}
if (findResourceBundle(name, true) == null) {
// We've failed to find an expected ResourceBundle.
// unset the caller's ClassLoader since we were unable to find the
@ -2170,11 +2173,13 @@ public class Logger {
return trb;
}
final String rbName = isSystemLogger
? trb.resourceBundleName
// ancestor of a system logger is expected to be a system logger.
// ignore resource bundle name if it's not.
? (target.isSystemLogger ? trb.resourceBundleName : null)
: target.getResourceBundleName();
if (rbName != null) {
return LoggerBundle.get(rbName,
findResourceBundle(rbName, true));
findResourceBundle(rbName, true));
}
target = isSystemLogger ? target.parent : target.getParent();
}

View File

@ -25,9 +25,7 @@
package javax.naming.spi;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.*;
import java.net.MalformedURLException;
import javax.naming.*;
@ -625,15 +623,28 @@ public class NamingManager {
/**
* Creates an initial context using the specified environment
* properties.
*<p>
* If an InitialContextFactoryBuilder has been installed,
* it is used to create the factory for creating the initial context.
* Otherwise, the class specified in the
* <tt>Context.INITIAL_CONTEXT_FACTORY</tt> environment property is used.
* Note that an initial context factory (an object that implements the
* InitialContextFactory interface) must be public and must have a
* public constructor that accepts no arguments.
*
* <p>
* This is done as follows:
* <ul>
* <li>If an InitialContextFactoryBuilder has been installed,
* it is used to create the factory for creating the initial
* context</li>
* <li>Otherwise, the class specified in the
* <tt>Context.INITIAL_CONTEXT_FACTORY</tt> environment property
* is used
* <ul>
* <li>First, the {@linkplain java.util.ServiceLoader ServiceLoader}
* mechanism tries to locate an {@code InitialContextFactory}
* provider using the current thread's context class loader</li>
* <li>Failing that, this implementation tries to locate a suitable
* {@code InitialContextFactory} using a built-in mechanism
* <br>
* (Note that an initial context factory (an object that implements
* the InitialContextFactory interface) must be public and must have
* a public constructor that accepts no arguments)</li>
* </ul>
* </li>
* </ul>
* @param env The possibly null environment properties used when
* creating the context.
* @return A non-null initial context.
@ -649,11 +660,11 @@ public class NamingManager {
*/
public static Context getInitialContext(Hashtable<?,?> env)
throws NamingException {
InitialContextFactory factory;
InitialContextFactory factory = null;
InitialContextFactoryBuilder builder = getInitialContextFactoryBuilder();
if (builder == null) {
// No factory installed, use property
// No builder installed, use property
// Get initial context factory class name
String className = env != null ?
@ -666,16 +677,39 @@ public class NamingManager {
throw ne;
}
ServiceLoader<InitialContextFactory> loader =
ServiceLoader.load(InitialContextFactory.class);
Iterator<InitialContextFactory> iterator = loader.iterator();
try {
factory = (InitialContextFactory)
helper.loadClass(className).newInstance();
} catch(Exception e) {
while (iterator.hasNext()) {
InitialContextFactory f = iterator.next();
if (f.getClass().getName().equals(className)) {
factory = f;
break;
}
}
} catch (ServiceConfigurationError e) {
NoInitialContextException ne =
new NoInitialContextException(
"Cannot instantiate class: " + className);
new NoInitialContextException(
"Cannot load initial context factory "
+ "'" + className + "'");
ne.setRootCause(e);
throw ne;
}
if (factory == null) {
try {
factory = (InitialContextFactory)
helper.loadClass(className).newInstance();
} catch (Exception e) {
NoInitialContextException ne =
new NoInitialContextException(
"Cannot instantiate class: " + className);
ne.setRootCause(e);
throw ne;
}
}
} else {
factory = builder.createInitialContextFactory(env);
}

View File

@ -244,8 +244,11 @@ class Krb5Context implements GSSContextSpi {
* establishment.
*/
public final void requestCredDeleg(boolean value) throws GSSException {
if (state == STATE_NEW && isInitiator())
credDelegState = value;
if (state == STATE_NEW && isInitiator()) {
if (myCred == null || !(myCred instanceof Krb5ProxyCredential)) {
credDelegState = value;
}
}
}
/**

View File

@ -25,6 +25,8 @@ package com.sun.org.apache.xml.internal.security;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
@ -35,6 +37,7 @@ import javax.xml.parsers.DocumentBuilderFactory;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
@ -118,43 +121,50 @@ public class Init {
log.log(java.util.logging.Level.FINE, "Registering default algorithms");
}
try {
//
// Bind the default prefixes
//
ElementProxy.registerDefaultPrefixes();
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>(){
@Override public Void run() throws XMLSecurityException {
//
// Bind the default prefixes
//
ElementProxy.registerDefaultPrefixes();
//
// Set the default Transforms
//
Transform.registerDefaultAlgorithms();
//
// Set the default Transforms
//
Transform.registerDefaultAlgorithms();
//
// Set the default signature algorithms
//
SignatureAlgorithm.registerDefaultAlgorithms();
//
// Set the default signature algorithms
//
SignatureAlgorithm.registerDefaultAlgorithms();
//
// Set the default JCE algorithms
//
JCEMapper.registerDefaultAlgorithms();
//
// Set the default JCE algorithms
//
JCEMapper.registerDefaultAlgorithms();
//
// Set the default c14n algorithms
//
Canonicalizer.registerDefaultAlgorithms();
//
// Set the default c14n algorithms
//
Canonicalizer.registerDefaultAlgorithms();
//
// Register the default resolvers
//
ResourceResolver.registerDefaultResolvers();
//
// Register the default resolvers
//
ResourceResolver.registerDefaultResolvers();
//
// Register the default key resolvers
//
KeyResolver.registerDefaultResolvers();
} catch (Exception ex) {
log.log(java.util.logging.Level.SEVERE, ex.getMessage(), ex);
ex.printStackTrace();
//
// Register the default key resolvers
//
KeyResolver.registerDefaultResolvers();
return null;
}
});
} catch (PrivilegedActionException ex) {
XMLSecurityException xse = (XMLSecurityException)ex.getException();
log.log(java.util.logging.Level.SEVERE, xse.getMessage(), xse);
xse.printStackTrace();
}
}

View File

@ -27,6 +27,7 @@ import java.util.concurrent.ConcurrentHashMap;
import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Element;
@ -49,8 +50,11 @@ public class JCEMapper {
*
* @param id
* @param algorithm
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the JCE algorithm
*/
public static void register(String id, Algorithm algorithm) {
JavaUtils.checkRegisterPermission();
algorithmsMap.put(id, algorithm);
}
@ -296,8 +300,11 @@ public class JCEMapper {
/**
* Sets the default Provider for obtaining the security algorithms
* @param provider the default providerId.
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the JCE provider
*/
public static void setProviderId(String provider) {
JavaUtils.checkRegisterPermission();
providerName = provider;
}

View File

@ -37,6 +37,7 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@ -314,18 +315,21 @@ public class SignatureAlgorithm extends Algorithm {
}
/**
* Registers implementing class of the Transform algorithm with algorithmURI
* Registers implementing class of the SignatureAlgorithm with algorithmURI
*
* @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
* @param algorithmURI algorithmURI URI representation of <code>SignatureAlgorithm</code>.
* @param implementingClass <code>implementingClass</code> the implementing class of
* {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the signature algorithm
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
XMLSignatureException {
JavaUtils.checkRegisterPermission();
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
}
@ -352,15 +356,18 @@ public class SignatureAlgorithm extends Algorithm {
/**
* Registers implementing class of the Transform algorithm with algorithmURI
*
* @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
* @param algorithmURI algorithmURI URI representation of <code>SignatureAlgorithm</code>.
* @param implementingClass <code>implementingClass</code> the implementing class of
* {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the signature algorithm
*/
public static void register(String algorithmURI, Class<? extends SignatureAlgorithmSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
XMLSignatureException {
JavaUtils.checkRegisterPermission();
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
}

View File

@ -41,6 +41,7 @@ import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicaliz
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@ -142,10 +143,13 @@ public class Canonicalizer {
* @param algorithmURI
* @param implementingClass
* @throws AlgorithmAlreadyRegisteredException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the canonicalizer
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
JavaUtils.checkRegisterPermission();
// check whether URI is already registered
Class<? extends CanonicalizerSpi> registeredClass =
canonicalizerHash.get(algorithmURI);
@ -166,9 +170,12 @@ public class Canonicalizer {
* @param algorithmURI
* @param implementingClass
* @throws AlgorithmAlreadyRegisteredException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the canonicalizer
*/
public static void register(String algorithmURI, Class<CanonicalizerSpi> implementingClass)
public static void register(String algorithmURI, Class<? extends CanonicalizerSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
JavaUtils.checkRegisterPermission();
// check whether URI is already registered
Class<? extends CanonicalizerSpi> registeredClass = canonicalizerHash.get(algorithmURI);

View File

@ -42,6 +42,7 @@ import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@ -175,9 +176,12 @@ public class KeyResolver {
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the key resolver
*/
public static void register(String className, boolean globalResolver)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
JavaUtils.checkRegisterPermission();
KeyResolverSpi keyResolverSpi =
(KeyResolverSpi) Class.forName(className).newInstance();
keyResolverSpi.setGlobalResolver(globalResolver);
@ -195,8 +199,11 @@ public class KeyResolver {
*
* @param className
* @param globalResolver Whether the KeyResolverSpi is a global resolver or not
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the key resolver
*/
public static void registerAtStart(String className, boolean globalResolver) {
JavaUtils.checkRegisterPermission();
KeyResolverSpi keyResolverSpi = null;
Exception ex = null;
try {
@ -228,11 +235,14 @@ public class KeyResolver {
*
* @param keyResolverSpi a KeyResolverSpi instance to register
* @param start whether to register the KeyResolverSpi at the start of the list or not
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the key resolver
*/
public static void register(
KeyResolverSpi keyResolverSpi,
boolean start
) {
JavaUtils.checkRegisterPermission();
KeyResolver resolver = new KeyResolver(keyResolverSpi);
if (start) {
resolverVector.add(0, resolver);
@ -254,9 +264,12 @@ public class KeyResolver {
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the key resolver
*/
public static void registerClassNames(List<String> classNames)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
JavaUtils.checkRegisterPermission();
List<KeyResolver> keyResolverList = new ArrayList<KeyResolver>(classNames.size());
for (String className : classNames) {
KeyResolverSpi keyResolverSpi =

View File

@ -46,6 +46,7 @@ import com.sun.org.apache.xml.internal.security.transforms.implementations.Trans
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.HelperNodeList;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
@ -181,11 +182,14 @@ public final class Transform extends SignatureElementProxy {
* class of {@link TransformSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
* is already registered
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the transform
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
InvalidTransformException {
JavaUtils.checkRegisterPermission();
// are we already registered?
Class<? extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
if (transformSpi != null) {
@ -206,9 +210,12 @@ public final class Transform extends SignatureElementProxy {
* class of {@link TransformSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
* is already registered
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the transform
*/
public static void register(String algorithmURI, Class<? extends TransformSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException {
JavaUtils.checkRegisterPermission();
// are we already registered?
Class<? extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
if (transformSpi != null) {

View File

@ -468,9 +468,12 @@ public abstract class ElementProxy {
* @param namespace
* @param prefix
* @throws XMLSecurityException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the default prefix
*/
public static void setDefaultPrefix(String namespace, String prefix)
throws XMLSecurityException {
JavaUtils.checkRegisterPermission();
if (prefixMappings.containsValue(prefix)) {
String storedPrefix = prefixMappings.get(namespace);
if (!storedPrefix.equals(prefix)) {

View File

@ -28,6 +28,7 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecurityPermission;
/**
* A collection of different, general-purpose methods for JAVA-specific things
@ -39,6 +40,10 @@ public class JavaUtils {
private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(JavaUtils.class.getName());
private static final SecurityPermission REGISTER_PERMISSION =
new SecurityPermission(
"com.sun.org.apache.xml.internal.security.register");
private JavaUtils() {
// we don't allow instantiation
}
@ -146,6 +151,23 @@ public class JavaUtils {
return retBytes;
}
/**
* Throws a {@code SecurityException} if a security manager is installed
* and the caller is not allowed to register an implementation of an
* algorithm, transform, or other security sensitive XML Signature function.
*
* @throws SecurityException if a security manager is installed and the
* caller has not been granted the
* {@literal "com.sun.org.apache.xml.internal.security.register"}
* {@code SecurityPermission}
*/
public static void checkRegisterPermission() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(REGISTER_PERMISSION);
}
}
/**
* Converts an ASN.1 DSA value to a XML Signature DSA Value.
*

View File

@ -80,32 +80,44 @@ public class XMLUtils {
/**
* Set the prefix for the digital signature namespace
* @param prefix the new prefix for the digital signature namespace
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the prefix
*/
public static void setDsPrefix(String prefix) {
JavaUtils.checkRegisterPermission();
dsPrefix = prefix;
}
/**
* Set the prefix for the digital signature 1.1 namespace
* @param prefix the new prefix for the digital signature 1.1 namespace
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the prefix
*/
public static void setDs11Prefix(String prefix) {
JavaUtils.checkRegisterPermission();
ds11Prefix = prefix;
}
/**
* Set the prefix for the encryption namespace
* @param prefix the new prefix for the encryption namespace
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the prefix
*/
public static void setXencPrefix(String prefix) {
JavaUtils.checkRegisterPermission();
xencPrefix = prefix;
}
/**
* Set the prefix for the encryption namespace 1.1
* @param prefix the new prefix for the encryption namespace 1.1
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the prefix
*/
public static void setXenc11Prefix(String prefix) {
JavaUtils.checkRegisterPermission();
xenc11Prefix = prefix;
}

View File

@ -27,6 +27,7 @@ import java.util.List;
import java.util.Map;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverLocalFilesystem;
@ -199,9 +200,12 @@ public class ResourceResolver {
* the class cannot be registered.
*
* @param className the name of the ResourceResolverSpi class to be registered
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register a resource resolver
*/
@SuppressWarnings("unchecked")
public static void register(String className) {
JavaUtils.checkRegisterPermission();
try {
Class<ResourceResolverSpi> resourceResolverClass =
(Class<ResourceResolverSpi>) Class.forName(className);
@ -216,9 +220,12 @@ public class ResourceResolver {
* list. This method logs a warning if the class cannot be registered.
*
* @param className the name of the ResourceResolverSpi class to be registered
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register a resource resolver
*/
@SuppressWarnings("unchecked")
public static void registerAtStart(String className) {
JavaUtils.checkRegisterPermission();
try {
Class<ResourceResolverSpi> resourceResolverClass =
(Class<ResourceResolverSpi>) Class.forName(className);
@ -233,8 +240,11 @@ public class ResourceResolver {
* cannot be registered.
* @param className
* @param start
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register a resource resolver
*/
public static void register(Class<? extends ResourceResolverSpi> className, boolean start) {
JavaUtils.checkRegisterPermission();
try {
ResourceResolverSpi resourceResolverSpi = className.newInstance();
register(resourceResolverSpi, start);
@ -250,8 +260,11 @@ public class ResourceResolver {
* cannot be registered.
* @param resourceResolverSpi
* @param start
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register a resource resolver
*/
public static void register(ResourceResolverSpi resourceResolverSpi, boolean start) {
JavaUtils.checkRegisterPermission();
synchronized(resolverList) {
if (start) {
resolverList.add(0, new ResourceResolver(resourceResolverSpi));

View File

@ -53,7 +53,9 @@ public class StartManagementAgent {
public static void main(String[] args) throws Throwable {
ProcessThread processThread = null;
try {
System.out.println("Starting test application");
processThread = RunnerUtil.startApplication();
System.out.println("Application started");
runTests(processThread.getPid());
} catch (Throwable t) {
System.out.println("StartManagementAgent got unexpected exception: " + t);
@ -70,6 +72,7 @@ public class StartManagementAgent {
// Try calling with null argument
boolean exception = false;
try {
System.out.println("Starting management agent with null");
vm.startManagementAgent(null);
} catch (NullPointerException e) {
exception = true;
@ -86,6 +89,7 @@ public class StartManagementAgent {
}
p.put("com.sun.management.config.file", f.getAbsolutePath());
try {
System.out.println("Starting management agent with bogus port");
vm.startManagementAgent(p);
} catch(AttachOperationFailedException ex) {
// We expect parsing of "apa" above to fail, but if the file path
@ -93,6 +97,9 @@ public class StartManagementAgent {
if (!ex.getMessage().contains("Invalid com.sun.management.jmxremote.port number")) {
throw ex;
}
ex.printStackTrace(System.err);
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
@ -134,14 +141,19 @@ public class StartManagementAgent {
}
public static void testLocalAgent(VirtualMachine vm) throws Exception {
System.out.println("Getting VM properties");
Properties agentProps = vm.getAgentProperties();
String address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
if (address != null) {
throw new Exception("Local management agent already started");
}
System.out.println("Starting local agent");
String result = vm.startLocalManagementAgent();
System.out.println("Agent started");
// try to parse the return value as a JMXServiceURL
new JMXServiceURL(result);

View File

@ -26,7 +26,7 @@
@bug 8048887
@summary Tests SortingFTP for an exception caused by the tim-sort algo.
@author anton.tarasov: area=awt.focus
@run main JDK8040632
@run main JDK8048887
*/
import javax.swing.JFrame;

View File

@ -0,0 +1,32 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Portions Copyright (c) 2014 IBM Corporation
*/
public class TestDetectHeadless {
public static void main(String[] args) throws Exception {
Class.forName("javax.swing.plaf.basic.BasicInternalFrameTitlePane");
}
}

View File

@ -0,0 +1,47 @@
#!/bin/sh
#
# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
#
# Portions Copyright (c) 2014 IBM Corporation
#
# @test
# @bug 8058930
# @summary java.awt.GraphicsEnvironment.getHeadlessProperty() does not work for AIX
#
# @build TestDetectHeadless
# @run shell TestDetectHeadless.sh
OS=`uname -s`
case "$OS" in
Windows* | CYGWIN* )
echo "Passed"; exit 0 ;;
* ) unset DISPLAY ;;
esac
${TESTJAVA}/bin/java ${TESTVMOPTS} \
-cp ${TESTCLASSES} TestDetectHeadless
exit $?

View File

@ -22,6 +22,8 @@
*/
import com.oracle.testlibrary.jsr292.Helper;
import com.sun.management.HotSpotDiagnosticMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.function.Function;
@ -37,6 +39,8 @@ public abstract class LambdaFormTestCase {
private final static String METHOD_HANDLE_CLASS_NAME = "java.lang.invoke.MethodHandle";
private final static String INTERNAL_FORM_METHOD_NAME = "internalForm";
private static final double ITERATIONS_TO_CODE_CACHE_SIZE_RATIO
= 45 / (128.0 * 1024 * 1024);
/**
* Reflection link to {@code j.l.i.MethodHandle.internalForm} method. It is
@ -87,7 +91,35 @@ public abstract class LambdaFormTestCase {
boolean passed = true;
int testCounter = 0;
int failCounter = 0;
long iterations = Math.max(1, Helper.TEST_LIMIT / testMethods.size());
long testCaseNum = testMethods.size();
long iterations = Math.max(1, Helper.TEST_LIMIT / testCaseNum);
System.out.printf("Number of iterations according to -DtestLimit is %d (%d cases)%n",
iterations, iterations * testCaseNum);
HotSpotDiagnosticMXBean hsDiagBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
long codeCacheSize = Long.parseLong(
hsDiagBean.getVMOption("ReservedCodeCacheSize").getValue());
System.out.printf("Code cache size is %d bytes%n", codeCacheSize);
long iterationsByCodeCacheSize = (long) (codeCacheSize
* ITERATIONS_TO_CODE_CACHE_SIZE_RATIO);
long nonProfiledCodeCacheSize = Long.parseLong(
hsDiagBean.getVMOption("NonProfiledCodeHeapSize").getValue());
System.out.printf("Non-profiled code cache size is %d bytes%n", nonProfiledCodeCacheSize);
long iterationsByNonProfiledCodeCacheSize = (long) (nonProfiledCodeCacheSize
* ITERATIONS_TO_CODE_CACHE_SIZE_RATIO);
System.out.printf("Number of iterations limited by code cache size is %d (%d cases)%n",
iterationsByCodeCacheSize, iterationsByCodeCacheSize * testCaseNum);
System.out.printf("Number of iterations limited by non-profiled code cache size is %d (%d cases)%n",
iterationsByNonProfiledCodeCacheSize, iterationsByNonProfiledCodeCacheSize * testCaseNum);
iterations = Math.min(iterationsByCodeCacheSize,
Math.min(iterations, iterationsByNonProfiledCodeCacheSize));
if (iterations == 0) {
System.out.println("Warning: code cache size is too small to provide at"
+ " least one iteration! Test will try to do one iteration.");
iterations = 1;
}
System.out.printf("Number of iterations is set to %d (%d cases)%n",
iterations, iterations * testCaseNum);
System.out.flush();
for (long i = 0; i < iterations; i++) {
System.err.println(String.format("Iteration %d:", i));
for (TestMethods testMethod : testMethods) {

View File

@ -0,0 +1,87 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8048052
* @summary Test a series of methods which requires "setFactory" runtime permission
* @run main SetFactoryPermission success
* @run main/othervm/policy=policy.fail SetFactoryPermission fail
* @run main/othervm/policy=policy.success SetFactoryPermission success
*/
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.rmi.server.RMISocketFactory;
import java.security.AccessControlException;
public class SetFactoryPermission {
static boolean success = false;
interface Runner {
public void run() throws Exception;
}
public static void main (String[] args) throws Exception {
if (args.length > 0) {
success = System.getSecurityManager() == null || args[0].equals("success");
}
doTest(()->{
System.out.println("Verify URLConnection.setContentHandlerFactor()");
URLConnection.setContentHandlerFactory(null);
});
doTest(()->{
System.out.println("Verify URL.setURLStreamHandlerFactory()");
URL.setURLStreamHandlerFactory(null);
});
doTest(()->{
System.out.println("Verify ServerSocket.setSocketFactory()");
ServerSocket.setSocketFactory(null);
});
doTest(()->{
System.out.println("Verify Socket.setSocketImplFactory()");
Socket.setSocketImplFactory(null);
});
doTest(()->{
System.out.println("Verify RMISocketFactory.setSocketFactory()");
RMISocketFactory.setSocketFactory(null);
});
}
static void doTest(Runner func) throws Exception {
try {
func.run();
if (!success) {
throw new RuntimeException("AccessControlException is not thrown. Test failed");
}
} catch (SecurityException e) {
if (success) {
e.printStackTrace();
throw new RuntimeException("AccessControlException is thrown unexpectedly. Test failed");
}
}
}
}

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