This commit is contained in:
Qi Zuo 2010-10-18 11:13:35 -04:00
commit c15f563911
349 changed files with 14374 additions and 2678 deletions

View File

@ -87,3 +87,4 @@ e02b4d709e177d08d56130a4bc68061e4bbacc7d jdk7-b109
a6442d6bc38a44152e0662688213ce4d2701f42a jdk7-b110 a6442d6bc38a44152e0662688213ce4d2701f42a jdk7-b110
69f3edf083477955b5bd2f754252c7504167d8e1 jdk7-b111 69f3edf083477955b5bd2f754252c7504167d8e1 jdk7-b111
f960f117f1623629f64203e2b09a92a8f6f14ff5 jdk7-b112 f960f117f1623629f64203e2b09a92a8f6f14ff5 jdk7-b112
1fee41c7ed2b3388970a756a85aa693c0de8407a jdk7-b113

View File

@ -88,3 +88,4 @@ f8be576feefce0c6695f188ef97ec16b73ad9cfd jdk7-b104
9702d6fef68e17533ee7fcf5923b11ead3e912ce jdk7-b111 9702d6fef68e17533ee7fcf5923b11ead3e912ce jdk7-b111
b852103caf73da70068473777ae867a457bb3ae1 jdk7-b112 b852103caf73da70068473777ae867a457bb3ae1 jdk7-b112
c1df968c4527bfab5f97662a89245f15d12d378b jdk7-b113 c1df968c4527bfab5f97662a89245f15d12d378b jdk7-b113
27985a5c6e5268014d25d55886e0ecb96af4763d jdk7-b114

View File

@ -558,9 +558,12 @@ endif
# rule to test # rule to test
################################################################ ################################################################
.NOTPARALLEL: test .NOTPARALLEL: test_run
test: test_clean test_start test_summary test:
$(MAKE) test_run
test_run: test_clean test_start test_summary
test_start: test_start:
@$(ECHO) "Tests started at `$(DATE)`" @$(ECHO) "Tests started at `$(DATE)`"
@ -586,7 +589,7 @@ test_summary: $(OUTPUTDIR)/test_failures.txt
# Get failure list from log # Get failure list from log
$(OUTPUTDIR)/test_failures.txt: $(OUTPUTDIR)/test_log.txt $(OUTPUTDIR)/test_failures.txt: $(OUTPUTDIR)/test_log.txt
@$(RM) $@ @$(RM) $@
@( $(EGREP) '^FAILED:' $< || $(ECHO) "" ) > $@ @( $(EGREP) '^FAILED:' $< || $(ECHO) "" ) | $(NAWK) 'length>0' > $@
# Get log file of all tests run # Get log file of all tests run
JDK_TO_TEST := $(shell \ JDK_TO_TEST := $(shell \
@ -598,10 +601,11 @@ JDK_TO_TEST := $(shell \
$(ECHO) "$(PRODUCT_HOME)"; \ $(ECHO) "$(PRODUCT_HOME)"; \
fi \ fi \
) )
TEST_TARGETS=all
$(OUTPUTDIR)/test_log.txt: $(OUTPUTDIR)/test_log.txt:
$(RM) $@ $(RM) $@
( $(CD) test && \ ( $(CD) test && \
$(MAKE) NO_STOPPING=- PRODUCT_HOME=$(JDK_TO_TEST) \ $(MAKE) NO_STOPPING=- PRODUCT_HOME=$(JDK_TO_TEST) $(TEST_TARGETS) \
) | tee $@ ) | tee $@
################################################################ ################################################################
@ -614,7 +618,7 @@ include ./make/jprt.gmk
# PHONY # PHONY
################################################################ ################################################################
.PHONY: all test test_start test_summary test_clean \ .PHONY: all test test_run test_start test_summary test_clean \
generic_build_repo_series \ generic_build_repo_series \
what clobber insane \ what clobber insane \
dev dev-build dev-sanity dev-clobber \ dev dev-build dev-sanity dev-clobber \

View File

@ -87,3 +87,4 @@ c3dd858e09b20206459d9e7b0ead99d27ab00eab jdk7-b109
0e1f80fda2271f53d4bbb59ec3f301dfbcef6a0a jdk7-b110 0e1f80fda2271f53d4bbb59ec3f301dfbcef6a0a jdk7-b110
640fa4d4e2ad4c2d7e4815c955026740d8c52b7a jdk7-b111 640fa4d4e2ad4c2d7e4815c955026740d8c52b7a jdk7-b111
cc67fdc4fee9a5b25caee4e71b51a8ff24ae7d1a jdk7-b112 cc67fdc4fee9a5b25caee4e71b51a8ff24ae7d1a jdk7-b112
a89a6c5be9d1a754868d3d359cbf7ad36aa95631 jdk7-b113

View File

@ -122,3 +122,4 @@ cc4bb3022b3144dc5db0805b9ef6c7eff2aa3b81 jdk7-b109
2f25f2b8de2700a1822463b1bd3d02b5e218018f jdk7-b110 2f25f2b8de2700a1822463b1bd3d02b5e218018f jdk7-b110
07b042e13dde4f3479ba9ec55120fcd5e8623323 jdk7-b111 07b042e13dde4f3479ba9ec55120fcd5e8623323 jdk7-b111
5511edd5d719f3fc9fdd04879482026a3d2c8652 jdk7-b112 5511edd5d719f3fc9fdd04879482026a3d2c8652 jdk7-b112
beef35b96b81129c375d572357fb9548d9020db1 jdk7-b113

View File

@ -87,3 +87,4 @@ d42c4acb6424a094bdafe2ad9c8c1c7ca7fb7b7e jdk7-b104
d422dbdd09766269344b796b3a46a5b3f74557e1 jdk7-b110 d422dbdd09766269344b796b3a46a5b3f74557e1 jdk7-b110
8106c747067c905d814a737a57fea0e29057b33f jdk7-b111 8106c747067c905d814a737a57fea0e29057b33f jdk7-b111
1b05254242881527b4d5d711295c0fe708c8823a jdk7-b112 1b05254242881527b4d5d711295c0fe708c8823a jdk7-b112
bc0c84ce54c34d3e8b0604b94da0d7c75c26755e jdk7-b113

View File

@ -87,3 +87,4 @@ b1ca39340238a239ba6d8489ad5315215e1366ca jdk7-b108
95ecac35fb11530752bd0404c9bf02bcfb30990e jdk7-b110 95ecac35fb11530752bd0404c9bf02bcfb30990e jdk7-b110
2575ebca96c7fb1b78f6ae025a97321210aba309 jdk7-b111 2575ebca96c7fb1b78f6ae025a97321210aba309 jdk7-b111
8e0f0054817f0f73fb33e80fb1333fb45b1d513d jdk7-b112 8e0f0054817f0f73fb33e80fb1333fb45b1d513d jdk7-b112
d35c94fd22362f478f75b4bfcd2bef6a83cb9b3f jdk7-b113

View File

@ -87,3 +87,4 @@ ab0d3f54a63f2aadfcdd2e14b81f79362ce454e2 jdk7-b109
176586cd040e4dd17a5ff6e91f72df10d7442453 jdk7-b110 176586cd040e4dd17a5ff6e91f72df10d7442453 jdk7-b110
fb63a2688db807a73e2a3de7d9bab298f1bff0e8 jdk7-b111 fb63a2688db807a73e2a3de7d9bab298f1bff0e8 jdk7-b111
b53f226b1d91473ac54184afa827be07b87e0319 jdk7-b112 b53f226b1d91473ac54184afa827be07b87e0319 jdk7-b112
61d3b9fbb26bdef56cfa41b9af5bc312a22cbeb8 jdk7-b113

View File

@ -75,7 +75,6 @@ import_product -- copy in the product components \n\
import_fastdebug -- copy in the fastdebug components \n\ import_fastdebug -- copy in the fastdebug components \n\
import_debug -- copy in the debug components \n\ import_debug -- copy in the debug components \n\
modules -- build the jdk and jre module images (experimental) \n\ modules -- build the jdk and jre module images (experimental) \n\
sccs_get -- make sure all SCCS files are up-to-date (need SCCS) \n\
create_links -- create softlinks in Solaris 32bit build to 64bit dirs \n\ create_links -- create softlinks in Solaris 32bit build to 64bit dirs \n\
" "
@ -278,21 +277,6 @@ include $(BUILDDIR)/common/Sanity.gmk
$(OUTPUTDIR) $(TEMPDIR): $(OUTPUTDIR) $(TEMPDIR):
$(MKDIR) -p $@ $(MKDIR) -p $@
# cleanup everything. If the workspace is not being built by the control
# workspace, and if it is a Teamware workspace, then see if there are
# any files which are not under SCCS control.
clean clobber::
ifndef EXTERNALSANITYCONTROL
@if [ -d $(TOPDIR)/Codemgr_wsdata ]; then \
$(ECHO) '\nPerforming workspace scan for remnant files.\n' \
' Any files listed below are not under SCCS control in the workspace\n' \
' and you should review them and possibly remove them manually:' ; \
$(FIND) $(TOPDIR)/make $(TOPDIR)/src -type f | \
$(SED) 's+SCCS/[ps]\.++' | $(SORT) | $(UNIQ) -c | $(NAWK) '$$1<2 {print $$2;}' ; \
$(ECHO) 'End of workspace scan.' ; \
fi
endif
# this should be the last rule in this file: # this should be the last rule in this file:
all:: all::
@if [ -r $(WARNING_FILE) ]; then \ @if [ -r $(WARNING_FILE) ]; then \
@ -341,16 +325,70 @@ endif
include $(BUILDDIR)/common/internal/BinaryPlugs.gmk include $(BUILDDIR)/common/internal/BinaryPlugs.gmk
# #
# Get top level sccs_get rule # Test rule
# #
include $(BUILDDIR)/common/Rules-SCCS.gmk
.NOTPARALLEL: test_run
test:
$(MAKE) test_run
test_run: test_clean test_start test_summary
test_start:
@$(ECHO) "Tests started at `$(DATE)`"
test_clean:
$(RM) $(OUTPUTDIR)/test_failures.txt $(OUTPUTDIR)/test_log.txt
test_summary: $(OUTPUTDIR)/test_failures.txt
@$(ECHO) "#################################################"
@$(ECHO) "Tests completed at `$(DATE)`"
@( $(EGREP) '^TEST STATS:' $(OUTPUTDIR)/test_log.txt \
|| $(ECHO) "No TEST STATS seen in log" )
@$(ECHO) "For complete details see: $(OUTPUTDIR)/test_log.txt"
@$(ECHO) "#################################################"
@if [ -s $< ] ; then \
$(ECHO) "ERROR: Test failure count: `$(CAT) $< | $(WC) -l`"; \
$(CAT) $<; \
exit 1; \
else \
$(ECHO) "Success! No failures detected"; \
fi
# Get failure list from log
$(OUTPUTDIR)/test_failures.txt: $(OUTPUTDIR)/test_log.txt
@$(RM) $@
@( $(EGREP) '^FAILED:' $< || $(ECHO) "" ) | $(NAWK) 'length>0' > $@
# Get log file of all tests run
JDK_TO_TEST := $(shell \
if [ -d "$(ABS_OUTPUTDIR)/j2sdk-image" ] ; then \
$(ECHO) "$(ABS_OUTPUTDIR)/j2sdk-image"; \
elif [ -d "$(ABS_OUTPUTDIR)/bin" ] ; then \
$(ECHO) "$(ABS_OUTPUTDIR)"; \
elif [ "$(PRODUCT_HOME)" != "" -a -d "$(PRODUCT_HOME)/bin" ] ; then \
$(ECHO) "$(PRODUCT_HOME)"; \
fi \
)
TEST_TARGETS=jdk_all
$(OUTPUTDIR)/test_log.txt:
$(RM) $@
( $(CD) ../test && \
$(MAKE) NO_STOPPING=- PRODUCT_HOME=$(JDK_TO_TEST) $(TEST_TARGETS) \
) | tee $@
#
# JPRT rules # JPRT rules
#
include jprt.gmk include jprt.gmk
# #
# Phonies to avoid accidents. # Phonies to avoid accidents.
# #
.PHONY: all build clean clobber optimized debug fastdebug create_links \ .PHONY: all build clean clobber optimized debug fastdebug create_links \
import import_product import_fastdebug import_debug import import_product import_fastdebug import_debug \
test test_run test_start test_clean test_summary

View File

@ -76,7 +76,7 @@ cscope.out: cscope.files FRC
# What files should we include? A simple rule might be just those files under # What files should we include? A simple rule might be just those files under
# SCM control, however this would miss files we create like the opcodes and # SCM control, however this would miss files we create like the opcodes and
# CClassHeaders. The following attempts to find everything that is *useful*. # CClassHeaders. The following attempts to find everything that is *useful*.
# (.del files are created by sccsrm, demo directories contain many .java files # (demo directories contain many .java files
# that probably aren't useful for development, and the pkgarchive may contain # that probably aren't useful for development, and the pkgarchive may contain
# duplicates of files within the source hierarchy). The ordering of the .raw # duplicates of files within the source hierarchy). The ordering of the .raw
# file is an attempt to make cscope display the most relevant files first. # file is an attempt to make cscope display the most relevant files first.

View File

@ -334,7 +334,7 @@ DOCSDIR = $(OUTPUTDIR)/docs$(DOCSDIRSUFFIX)
DOCSDIRSUFFIX = DOCSDIRSUFFIX =
# The MESSAGE, WARNING and ERROR files are used to store sanityck and # The MESSAGE, WARNING and ERROR files are used to store sanityck and
# SCCS check messages, warnings and errors. # warnings and errors.
ifndef ERROR_FILE ifndef ERROR_FILE
ERROR_FILE = $(OUTPUTDIR)/sanityCheckErrors.txt ERROR_FILE = $(OUTPUTDIR)/sanityCheckErrors.txt
endif endif
@ -634,38 +634,6 @@ LINTFLAGS = $(LINTFLAGS_$(VARIANT)) $(LINTFLAGS_COMMON) \
VERSION_DEFINES = -DRELEASE='"$(RELEASE)"' VERSION_DEFINES = -DRELEASE='"$(RELEASE)"'
# Note: As a rule, GNU Make rules should not appear in any of the
# Defs*.gmk files. These were added for Kestrel-Solaris and do address
# a TeamWare bug. They should be moved elsewhere for Merlin.
#
# Override gnumake built-in rules which do sccs get operations badly.
# (They put the checked out code in the current directory, not in the
# directory of the original file.)
# Since this is a symptom of a teamware failure, complain and die on the spot.
# This message immediately goes to stdout and the build terminates.
define SCCS-trouble
$(error \
"ERROR: File $@ referenced while building in $(CURRENT_DIRECTORY) \
is out of date with respect to its SCCS file $<. \
This can happen from an unresolved Teamware conflict, a file movement, or \
a failure in which SCCS files are updated but the 'sccs get' was not done. \
You should double check for other out of date files in your workspace. \
Or run: cd $(TOPDIR) && $(MAKE) sccs_get")
endef
%:: s.%
@$(SCCS-trouble)
%:: SCCS/s.%
@$(SCCS-trouble)
@$(ECHO) " is out of date with respect to its SCCS file." >> $(WARNING_FILE)
@$(ECHO) " This file may be from an unresolved Teamware conflict." >> $(WARNING_FILE)
@$(ECHO) " This is also a symptom of a Teamware bringover/putback failure" >> $(WARNING_FILE)
@$(ECHO) " in which SCCS files are updated but not checked out." >> $(WARNING_FILE)
@$(ECHO) " Check for other out of date files in your workspace." >> $(WARNING_FILE)
@$(ECHO) "" >> $(WARNING_FILE)
@#exit 666
ifdef INSANE ifdef INSANE
export INSANE export INSANE
endif endif

View File

@ -1,70 +0,0 @@
#
# Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# 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.
#
#
# Only get these rules if SCCS is available
#
ifdef SCCS
# SCCS command to extract out latest source
SCCS_GET=$(SCCS) get -s
#
# Make sure all files in workspace are fresh
#
TEMP_ALL_FILES=$(JDK_TOPDIR)/temp_filelist
$(TEMP_ALL_FILES): $(JDK_TOPDIR)/Codemgr_wsdata/nametable
$(prep-target)
@$(CUT) -d' ' -f1 $< \
| $(GREP) -v '^VERSION' \
| $(GREP) -v '^deleted_files' \
| $(GREP) -v '^Codemgr_wsdata' > $@
sccs_get: $(TEMP_ALL_FILES)
@$(PRINTF) "Workspace has %d files\n" `$(CAT) $< | $(WC) -l`
@count=0; \
for i in `$(CAT) $<` ; do \
f=$(JDK_TOPDIR)/$$i; \
count=`$(EXPR) $$count '+' 1`; \
if [ `$(EXPR) $$count '%' 100` = 0 ] ; then \
$(PRINTF) "\rChecked $$count files"; \
fi; \
if [ ! -f $$f ] ; then \
$(PRINTF) "\r$(SCCS_GET) $$f\n"; \
(cd `$(DIRNAME) $$f` && $(SCCS_GET) `$(BASENAME) $$f`); \
elif /usr/bin/test $$f -ot `$(DIRNAME) $$f`/SCCS/s.`$(BASENAME) $$f` ; then \
$(PRINTF) "\r$(SCCS_GET) $$f\n"; \
(cd `$(DIRNAME) $$f` && $(SCCS_GET) `$(BASENAME) $$f`); \
fi; \
done; \
$(PRINTF) "\rChecked $$count files\n"
#
# Phonies to avoid accidents.
#
.PHONY: sccs_get
endif

View File

@ -33,7 +33,7 @@
# UTILS_COMMAND_PATH # UTILS_COMMAND_PATH
# /usr/bin/ # /usr/bin/
# UTILS_USR_BIN_PATH # UTILS_USR_BIN_PATH
# /usr/ccs/bin/ (sccs, m4, lex, yacc, as, ar, strip, mcs) # /usr/ccs/bin/ (m4, lex, yacc, as, ar, strip, mcs)
# UTILS_CCS_BIN_PATH # UTILS_CCS_BIN_PATH
# Dev Tools: zip, unzip, etc that we may have special versions of # Dev Tools: zip, unzip, etc that we may have special versions of
# UTILS_DEVTOOL_PATH # UTILS_DEVTOOL_PATH
@ -117,7 +117,6 @@ RC = $(UTILS_COMMAND_PATH)rc
RMDIR = $(UTILS_COMMAND_PATH)rmdir RMDIR = $(UTILS_COMMAND_PATH)rmdir
RPM = $(UTILS_COMMAND_PATH)rpm RPM = $(UTILS_COMMAND_PATH)rpm
RPMBUILD = $(UTILS_COMMAND_PATH)rpmbuild RPMBUILD = $(UTILS_COMMAND_PATH)rpmbuild
SCCS = $(UTILS_CCS_BIN_PATH)sccs
SED = $(UTILS_COMMAND_PATH)sed SED = $(UTILS_COMMAND_PATH)sed
SH = $(UTILS_COMMAND_PATH)sh SH = $(UTILS_COMMAND_PATH)sh
SHOWREV = $(UTILS_USR_BIN_PATH)showrev SHOWREV = $(UTILS_USR_BIN_PATH)showrev
@ -183,7 +182,7 @@ ifeq ($(PLATFORM),linux)
NAWK = $(USRBIN_PATH)gawk NAWK = $(USRBIN_PATH)gawk
# Intrinsic unix command, with backslash-escaped character interpretation # Intrinsic unix command, with backslash-escaped character interpretation
ECHO = /bin/echo -e ECHO = /bin/echo -e
# These are really in UTILS_USR_BIN_PATH on Linux (only sccs is not) # These are really in UTILS_USR_BIN_PATH on Linux
AR = $(UTILS_USR_BIN_PATH)ar AR = $(UTILS_USR_BIN_PATH)ar
AS = $(UTILS_USR_BIN_PATH)as AS = $(UTILS_USR_BIN_PATH)as
LD = $(UTILS_USR_BIN_PATH)ld LD = $(UTILS_USR_BIN_PATH)ld

View File

@ -219,7 +219,7 @@ else
PRODUCT_NAME = Java(TM) PRODUCT_NAME = Java(TM)
PRODUCT_SUFFIX = SE Runtime Environment PRODUCT_SUFFIX = SE Runtime Environment
JDK_RC_PLATFORM_NAME = Platform SE JDK_RC_PLATFORM_NAME = Platform SE
COMPANY_NAME = Oracle COMPANY_NAME = Oracle Corporation
endif endif
RUNTIME_NAME = $(PRODUCT_NAME) $(PRODUCT_SUFFIX) RUNTIME_NAME = $(PRODUCT_NAME) $(PRODUCT_SUFFIX)

View File

@ -284,6 +284,7 @@ JAVA_JAVA_java = \
java/util/concurrent/CancellationException.java \ java/util/concurrent/CancellationException.java \
java/util/concurrent/CompletionService.java \ java/util/concurrent/CompletionService.java \
java/util/concurrent/ConcurrentHashMap.java \ java/util/concurrent/ConcurrentHashMap.java \
java/util/concurrent/ConcurrentLinkedDeque.java \
java/util/concurrent/ConcurrentLinkedQueue.java \ java/util/concurrent/ConcurrentLinkedQueue.java \
java/util/concurrent/ConcurrentMap.java \ java/util/concurrent/ConcurrentMap.java \
java/util/concurrent/ConcurrentNavigableMap.java \ java/util/concurrent/ConcurrentNavigableMap.java \

View File

@ -25,43 +25,265 @@
# Properties for jprt # Properties for jprt
# Use whatever release that the submitted job requests # At submit time, the release supplied will be in jprt.submit.release
# and will be one of the official release names defined in jprt.
# jprt supports property value expansion using ${property.name} syntax.
# This tells jprt what default release we want to build
jprt.tools.default.release=${jprt.submit.release} jprt.tools.default.release=${jprt.submit.release}
# The different build flavors we want, we override here so we just get these 2 # The different build flavors we want, we override here so we just get these 2
jprt.build.flavors=product,fastdebug jprt.build.flavors=product,fastdebug
# Standard test target for everybody # Define the Windows we want (temporary)
jprt.test.targets=*-*-*-jvm98 jprt.my.windows.i586.jdk7b107=windows_i586_5.0
jprt.my.windows.i586.jdk7temp=windows_i586_5.0
jprt.my.windows.i586.jdk7=windows_i586_5.1
jprt.my.windows.i586=${jprt.my.windows.i586.${jprt.tools.default.release}}
# Test targets in test/Makefile (some longer running tests only test c2) # Standard list of jprt build targets for this source tree
jprt.make.rule.test.targets= \ jprt.build.targets= \
*-product-*-jdk_beans1, \ solaris_sparc_5.10-{product|fastdebug}, \
*-product-*-jdk_beans2, \ solaris_sparcv9_5.10-{product|fastdebug}, \
*-product-*-jdk_beans3, \ solaris_i586_5.10-{product|fastdebug}, \
*-product-*-jdk_io, \ solaris_x64_5.10-{product|fastdebug}, \
*-product-*-jdk_lang, \ linux_i586_2.6-{product|fastdebug}, \
*-product-*-jdk_management1, \ linux_x64_2.6-{product|fastdebug}, \
*-product-*-jdk_management2, \ ${jprt.my.windows.i586}-{product|fastdebug}, \
*-product-*-jdk_math, \ windows_x64_5.2-{product|fastdebug}
*-product-*-jdk_misc, \
*-product-*-jdk_net, \
*-product-*-jdk_nio1, \
*-product-*-jdk_nio2, \
*-product-*-jdk_nio3, \
*-product-*-jdk_security1, \
*-product-*-jdk_security2, \
*-product-*-jdk_security3, \
*-product-*-jdk_text, \
*-product-*-jdk_tools1, \
*-product-*-jdk_tools2, \
*-product-*-jdk_util
# Some of these are crashing Xvfb or windows manager, need dedicated DISPLAY per test batch # Standard vm test target
jprt2.make.rule.test.targets= \ jprt.test.targets= \
*-product-*-jdk_awt, \ solaris_sparc_5.10-product-c1-jvm98, \
*-product-*-jdk_rmi, \ solaris_sparcv9_5.10-product-c2-jvm98, \
*-product-*-jdk_swing, \ solaris_i586_5.10-product-c1-jvm98, \
solaris_x64_5.10-product-c2-jvm98, \
linux_i586_2.6-product-{c1|c2}-jvm98, \
linux_x64_2.6-product-c2-jvm98, \
${jprt.my.windows.i586}-product-c1-jvm98, \
windows_x64_5.2-product-c2-jvm98
# User can select the test set with jprt submit "-testset name" option
jprt.my.test.set=${jprt.test.set}
# Default jdk test targets in test/Makefile (no fastdebug & limited c2)
jprt.make.rule.default.test.targets= \
\
solaris_sparc_5.10-product-c1-jdk_beans1, \
solaris_sparcv9_5.10-product-c2-jdk_beans1, \
solaris_i586_5.10-product-c1-jdk_beans1, \
solaris_x64_5.10-product-c2-jdk_beans1, \
linux_i586_2.6-product-{c1|c2}-jdk_beans1, \
linux_x64_2.6-product-c2-jdk_beans1, \
${jprt.my.windows.i586}-product-c1-jdk_beans1, \
windows_x64_5.2-product-c2-jdk_beans1, \
\
solaris_sparc_5.10-product-c1-jdk_io, \
solaris_sparcv9_5.10-product-c2-jdk_io, \
solaris_i586_5.10-product-c1-jdk_io, \
solaris_x64_5.10-product-c2-jdk_io, \
linux_i586_2.6-product-{c1|c2}-jdk_io, \
linux_x64_2.6-product-c2-jdk_io, \
${jprt.my.windows.i586}-product-c1-jdk_io, \
windows_x64_5.2-product-c2-jdk_io, \
\
solaris_sparc_5.10-product-c1-jdk_lang, \
solaris_sparcv9_5.10-product-c2-jdk_lang, \
solaris_i586_5.10-product-c1-jdk_lang, \
solaris_x64_5.10-product-c2-jdk_lang, \
linux_i586_2.6-product-{c1|c2}-jdk_lang, \
linux_x64_2.6-product-c2-jdk_lang, \
${jprt.my.windows.i586}-product-c1-jdk_lang, \
windows_x64_5.2-product-c2-jdk_lang, \
\
solaris_sparc_5.10-product-c1-jdk_math, \
solaris_sparcv9_5.10-product-c2-jdk_math, \
solaris_i586_5.10-product-c1-jdk_math, \
solaris_x64_5.10-product-c2-jdk_math, \
linux_i586_2.6-product-{c1|c2}-jdk_math, \
linux_x64_2.6-product-c2-jdk_math, \
${jprt.my.windows.i586}-product-c1-jdk_math, \
windows_x64_5.2-product-c2-jdk_math, \
\
solaris_sparc_5.10-product-c1-jdk_misc, \
solaris_sparcv9_5.10-product-c2-jdk_misc, \
solaris_i586_5.10-product-c1-jdk_misc, \
solaris_x64_5.10-product-c2-jdk_misc, \
linux_i586_2.6-product-{c1|c2}-jdk_misc, \
linux_x64_2.6-product-c2-jdk_misc, \
${jprt.my.windows.i586}-product-c1-jdk_misc, \
windows_x64_5.2-product-c2-jdk_misc, \
\
solaris_sparc_5.10-product-c1-jdk_net, \
solaris_sparcv9_5.10-product-c2-jdk_net, \
solaris_i586_5.10-product-c1-jdk_net, \
solaris_x64_5.10-product-c2-jdk_net, \
linux_i586_2.6-product-{c1|c2}-jdk_net, \
linux_x64_2.6-product-c2-jdk_net, \
${jprt.my.windows.i586}-product-c1-jdk_net, \
windows_x64_5.2-product-c2-jdk_net, \
\
solaris_sparc_5.10-product-c1-jdk_nio1, \
solaris_sparcv9_5.10-product-c2-jdk_nio1, \
solaris_i586_5.10-product-c1-jdk_nio1, \
solaris_x64_5.10-product-c2-jdk_nio1, \
linux_i586_2.6-product-{c1|c2}-jdk_nio1, \
linux_x64_2.6-product-c2-jdk_nio1, \
${jprt.my.windows.i586}-product-c1-jdk_nio1, \
windows_x64_5.2-product-c2-jdk_nio1, \
\
solaris_sparc_5.10-product-c1-jdk_nio2, \
solaris_sparcv9_5.10-product-c2-jdk_nio2, \
solaris_i586_5.10-product-c1-jdk_nio2, \
solaris_x64_5.10-product-c2-jdk_nio2, \
linux_i586_2.6-product-{c1|c2}-jdk_nio2, \
linux_x64_2.6-product-c2-jdk_nio2, \
${jprt.my.windows.i586}-product-c1-jdk_nio2, \
windows_x64_5.2-product-c2-jdk_nio2, \
\
solaris_sparc_5.10-product-c1-jdk_nio3, \
solaris_sparcv9_5.10-product-c2-jdk_nio3, \
solaris_i586_5.10-product-c1-jdk_nio3, \
solaris_x64_5.10-product-c2-jdk_nio3, \
linux_i586_2.6-product-{c1|c2}-jdk_nio3, \
linux_x64_2.6-product-c2-jdk_nio3, \
${jprt.my.windows.i586}-product-c1-jdk_nio3, \
windows_x64_5.2-product-c2-jdk_nio3, \
\
solaris_sparc_5.10-product-c1-jdk_security1, \
solaris_sparcv9_5.10-product-c2-jdk_security1, \
solaris_i586_5.10-product-c1-jdk_security1, \
solaris_x64_5.10-product-c2-jdk_security1, \
linux_i586_2.6-product-{c1|c2}-jdk_security1, \
linux_x64_2.6-product-c2-jdk_security1, \
${jprt.my.windows.i586}-product-c1-jdk_security1, \
windows_x64_5.2-product-c2-jdk_security1, \
\
solaris_sparc_5.10-product-c1-jdk_text, \
solaris_sparcv9_5.10-product-c2-jdk_text, \
solaris_i586_5.10-product-c1-jdk_text, \
solaris_x64_5.10-product-c2-jdk_text, \
linux_i586_2.6-product-{c1|c2}-jdk_text, \
linux_x64_2.6-product-c2-jdk_text, \
${jprt.my.windows.i586}-product-c1-jdk_text, \
windows_x64_5.2-product-c2-jdk_text, \
\
solaris_sparc_5.10-product-c1-jdk_tools1, \
solaris_sparcv9_5.10-product-c2-jdk_tools1, \
solaris_i586_5.10-product-c1-jdk_tools1, \
solaris_x64_5.10-product-c2-jdk_tools1, \
linux_i586_2.6-product-{c1|c2}-jdk_tools1, \
linux_x64_2.6-product-c2-jdk_tools1, \
${jprt.my.windows.i586}-product-c1-jdk_tools1, \
windows_x64_5.2-product-c2-jdk_tools1, \
\
solaris_sparc_5.10-product-c1-jdk_util, \
solaris_sparcv9_5.10-product-c2-jdk_util, \
solaris_i586_5.10-product-c1-jdk_util, \
solaris_x64_5.10-product-c2-jdk_util, \
linux_i586_2.6-product-{c1|c2}-jdk_util, \
linux_x64_2.6-product-c2-jdk_util, \
${jprt.my.windows.i586}-product-c1-jdk_util, \
windows_x64_5.2-product-c2-jdk_util
# All jdk test targets in test/Makefile (still no fastdebug & limited c2)
jprt.make.rule.all.test.targets= \
\
${jprt.make.rule.default.test.targets}, \
\
solaris_sparc_5.10-product-c1-jdk_awt, \
solaris_sparcv9_5.10-product-c2-jdk_awt, \
solaris_i586_5.10-product-c1-jdk_awt, \
solaris_x64_5.10-product-c2-jdk_awt, \
linux_i586_2.6-product-{c1|c2}-jdk_awt, \
linux_x64_2.6-product-c2-jdk_awt, \
${jprt.my.windows.i586}-product-c1-jdk_awt, \
windows_x64_5.2-product-c2-jdk_awt, \
\
solaris_sparc_5.10-product-c1-jdk_beans2, \
solaris_sparcv9_5.10-product-c2-jdk_beans2, \
solaris_i586_5.10-product-c1-jdk_beans2, \
solaris_x64_5.10-product-c2-jdk_beans2, \
linux_i586_2.6-product-{c1|c2}-jdk_beans2, \
linux_x64_2.6-product-c2-jdk_beans2, \
${jprt.my.windows.i586}-product-c1-jdk_beans2, \
windows_x64_5.2-product-c2-jdk_beans2, \
\
solaris_sparc_5.10-product-c1-jdk_beans3, \
solaris_sparcv9_5.10-product-c2-jdk_beans3, \
solaris_i586_5.10-product-c1-jdk_beans3, \
solaris_x64_5.10-product-c2-jdk_beans3, \
linux_i586_2.6-product-{c1|c2}-jdk_beans3, \
linux_x64_2.6-product-c2-jdk_beans3, \
${jprt.my.windows.i586}-product-c1-jdk_beans3, \
windows_x64_5.2-product-c2-jdk_beans3, \
\
solaris_sparc_5.10-product-c1-jdk_management1, \
solaris_sparcv9_5.10-product-c2-jdk_management1, \
solaris_i586_5.10-product-c1-jdk_management1, \
solaris_x64_5.10-product-c2-jdk_management1, \
linux_i586_2.6-product-{c1|c2}-jdk_management1, \
linux_x64_2.6-product-c2-jdk_management1, \
${jprt.my.windows.i586}-product-c1-jdk_management1, \
windows_x64_5.2-product-c2-jdk_management1, \
\
solaris_sparc_5.10-product-c1-jdk_management2, \
solaris_sparcv9_5.10-product-c2-jdk_management2, \
solaris_i586_5.10-product-c1-jdk_management2, \
solaris_x64_5.10-product-c2-jdk_management2, \
linux_i586_2.6-product-{c1|c2}-jdk_management2, \
linux_x64_2.6-product-c2-jdk_management2, \
${jprt.my.windows.i586}-product-c1-jdk_management2, \
windows_x64_5.2-product-c2-jdk_management2, \
\
solaris_sparc_5.10-product-c1-jdk_rmi, \
solaris_sparcv9_5.10-product-c2-jdk_rmi, \
solaris_i586_5.10-product-c1-jdk_rmi, \
solaris_x64_5.10-product-c2-jdk_rmi, \
linux_i586_2.6-product-{c1|c2}-jdk_rmi, \
linux_x64_2.6-product-c2-jdk_rmi, \
${jprt.my.windows.i586}-product-c1-jdk_rmi, \
windows_x64_5.2-product-c2-jdk_rmi, \
\
solaris_sparc_5.10-product-c1-jdk_security2, \
solaris_sparcv9_5.10-product-c2-jdk_security2, \
solaris_i586_5.10-product-c1-jdk_security2, \
solaris_x64_5.10-product-c2-jdk_security2, \
linux_i586_2.6-product-{c1|c2}-jdk_security2, \
linux_x64_2.6-product-c2-jdk_security2, \
${jprt.my.windows.i586}-product-c1-jdk_security2, \
windows_x64_5.2-product-c2-jdk_security2, \
\
solaris_sparc_5.10-product-c1-jdk_security3, \
solaris_sparcv9_5.10-product-c2-jdk_security3, \
solaris_i586_5.10-product-c1-jdk_security3, \
solaris_x64_5.10-product-c2-jdk_security3, \
linux_i586_2.6-product-{c1|c2}-jdk_security3, \
linux_x64_2.6-product-c2-jdk_security3, \
${jprt.my.windows.i586}-product-c1-jdk_security3, \
windows_x64_5.2-product-c2-jdk_security3, \
\
solaris_sparc_5.10-product-c1-jdk_swing, \
solaris_sparcv9_5.10-product-c2-jdk_swing, \
solaris_i586_5.10-product-c1-jdk_swing, \
solaris_x64_5.10-product-c2-jdk_swing, \
linux_i586_2.6-product-{c1|c2}-jdk_swing, \
linux_x64_2.6-product-c2-jdk_swing, \
${jprt.my.windows.i586}-product-c1-jdk_swing, \
windows_x64_5.2-product-c2-jdk_swing, \
\
solaris_sparc_5.10-product-c1-jdk_tools2, \
solaris_sparcv9_5.10-product-c2-jdk_tools2, \
solaris_i586_5.10-product-c1-jdk_tools2, \
solaris_x64_5.10-product-c2-jdk_tools2, \
linux_i586_2.6-product-{c1|c2}-jdk_tools2, \
linux_x64_2.6-product-c2-jdk_tools2, \
${jprt.my.windows.i586}-product-c1-jdk_tools2, \
windows_x64_5.2-product-c2-jdk_tools2
# Select list to use (allow for testset to be empty too)
jprt.make.rule..test.targets=${jprt.make.rule.default.test.targets}
jprt.make.rule.test.targets=${jprt.make.rule.${jprt.my.test.set}.test.targets}
# Directories to be excluded from the source bundles # Directories to be excluded from the source bundles
jprt.bundle.exclude.src.dirs=build dist webrev jprt.bundle.exclude.src.dirs=build dist webrev

View File

@ -31,7 +31,7 @@ BUILDDIR = ..
PRODUCT = demos PRODUCT = demos
include $(BUILDDIR)/common/Defs.gmk include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = jni SUBDIRS = jni nio
SUBDIRS_desktop = applets jfc SUBDIRS_desktop = applets jfc
SUBDIRS_management = management SUBDIRS_management = management
SUBDIRS_misc = scripting SUBDIRS_misc = scripting

View File

@ -0,0 +1,39 @@
#
# Copyright (c) 1997, 2007, 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.
#
#
# Makefile for building the jfc demos
#
BUILDDIR = ../..
PRODUCT = demos
include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = zipfs
include $(BUILDDIR)/common/Subdirs.gmk
all build clean clobber::
$(SUBDIRS-loop)

View File

@ -0,0 +1,44 @@
#
# Copyright (c) 1997, 2002, 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.
#
#
# Makefile to build the ZipFileSystem demo.
#
BUILDDIR = ../../..
PRODUCT = demo/zipfs
DEMONAME = zipfs
include $(BUILDDIR)/common/Defs.gmk
DEMO_ROOT = $(SHARE_SRC)/demo/nio/$(DEMONAME)
DEMO_TOPFILES = ./README.txt
DEMO_SRCDIR = $(DEMO_ROOT)
DEMO_DESTDIR = $(DEMODIR)/nio/$(DEMONAME)
#
# Demo jar building rules.
#
include $(BUILDDIR)/common/Demo.gmk

View File

@ -80,7 +80,12 @@ vpath %.c $(SHARE_SRC)/native/$(PKGDIR)
vpath %.c $(SHARE_SRC)/native/sun/java2d vpath %.c $(SHARE_SRC)/native/sun/java2d
ifeq ($(PLATFORM), windows) ifeq ($(PLATFORM), windows)
OTHER_CFLAGS += -DCMS_IS_WINDOWS_ -Dsqrtf=sqrt OTHER_CFLAGS += -DCMS_IS_WINDOWS_
ifeq ($(COMPILER_VERSION), VS2003)
OTHER_CFLAGS += -Dsqrtf=sqrt
endif
OTHER_LDLIBS = $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib OTHER_LDLIBS = $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib
OTHER_INCLUDES += -I$(SHARE_SRC)/native/sun/java2d \ OTHER_INCLUDES += -I$(SHARE_SRC)/native/sun/java2d \
-I$(SHARE_SRC)/native/sun/awt/debug -I$(SHARE_SRC)/native/sun/awt/debug

View File

@ -525,7 +525,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
iMatchColumns = new Vector(10); iMatchColumns = new Vector(10);
for(int i = 0; i < 10 ; i++) { for(int i = 0; i < 10 ; i++) {
iMatchColumns.add(i,new Integer(-1)); iMatchColumns.add(i,Integer.valueOf(-1));
} }
strMatchColumns = new Vector(10); strMatchColumns = new Vector(10);
@ -889,7 +889,12 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
success = false; success = false;
} else { } else {
tWriter = (TransactionalWriter)rowSetWriter; tWriter = (TransactionalWriter)rowSetWriter;
((CachedRowSetWriter)tWriter).commit(this, updateOnInsert); if (tWriter instanceof CachedRowSetWriter) {
((CachedRowSetWriter)tWriter).commit(this, updateOnInsert);
} else {
tWriter.commit();
}
success = true; success = true;
} }
} }
@ -1294,7 +1299,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
tMap = new TreeMap(); tMap = new TreeMap();
for (int i = 0; i<numRows; i++) { for (int i = 0; i<numRows; i++) {
tMap.put(new Integer(i), rvh.get(i)); tMap.put(Integer.valueOf(i), rvh.get(i));
} }
return (tMap.values()); return (tMap.values());
@ -1806,7 +1811,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
return (byte)0; return (byte)0;
} }
try { try {
return ((new Byte(value.toString())).byteValue()); return ((Byte.valueOf(value.toString())).byteValue());
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.bytefail").toString(), throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.bytefail").toString(),
new Object[] {value.toString().trim(), columnIndex})); new Object[] {value.toString().trim(), columnIndex}));
@ -1850,7 +1855,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
} }
try { try {
return ((new Short(value.toString().trim())).shortValue()); return ((Short.valueOf(value.toString().trim())).shortValue());
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.shortfail").toString(), throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.shortfail").toString(),
new Object[] {value.toString().trim(), columnIndex})); new Object[] {value.toString().trim(), columnIndex}));
@ -1893,7 +1898,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
} }
try { try {
return ((new Integer(value.toString().trim())).intValue()); return ((Integer.valueOf(value.toString().trim())).intValue());
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.intfail").toString(), throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.intfail").toString(),
new Object[] {value.toString().trim(), columnIndex})); new Object[] {value.toString().trim(), columnIndex}));
@ -1936,7 +1941,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
return (long)0; return (long)0;
} }
try { try {
return ((new Long(value.toString().trim())).longValue()); return ((Long.valueOf(value.toString().trim())).longValue());
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.longfail").toString(), throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.longfail").toString(),
new Object[] {value.toString().trim(), columnIndex})); new Object[] {value.toString().trim(), columnIndex}));
@ -4014,18 +4019,18 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
try { try {
switch (trgType) { switch (trgType) {
case java.sql.Types.BIT: case java.sql.Types.BIT:
Integer i = new Integer(srcObj.toString().trim()); Integer i = Integer.valueOf(srcObj.toString().trim());
return i.equals(new Integer((int)0)) ? return i.equals(Integer.valueOf((int)0)) ?
new Boolean(false) : Boolean.valueOf(false) :
new Boolean(true); Boolean.valueOf(true);
case java.sql.Types.TINYINT: case java.sql.Types.TINYINT:
return new Byte(srcObj.toString().trim()); return Byte.valueOf(srcObj.toString().trim());
case java.sql.Types.SMALLINT: case java.sql.Types.SMALLINT:
return new Short(srcObj.toString().trim()); return Short.valueOf(srcObj.toString().trim());
case java.sql.Types.INTEGER: case java.sql.Types.INTEGER:
return new Integer(srcObj.toString().trim()); return Integer.valueOf(srcObj.toString().trim());
case java.sql.Types.BIGINT: case java.sql.Types.BIGINT:
return new Long(srcObj.toString().trim()); return Long.valueOf(srcObj.toString().trim());
case java.sql.Types.NUMERIC: case java.sql.Types.NUMERIC:
case java.sql.Types.DECIMAL: case java.sql.Types.DECIMAL:
return new BigDecimal(srcObj.toString().trim()); return new BigDecimal(srcObj.toString().trim());
@ -4037,7 +4042,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
case java.sql.Types.CHAR: case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR: case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: case java.sql.Types.LONGVARCHAR:
return new String(srcObj.toString()); return srcObj.toString();
default: default:
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.dtypemismt").toString()+ trgType); throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.dtypemismt").toString()+ trgType);
} }
@ -4134,7 +4139,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
case java.sql.Types.CHAR: case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR: case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: case java.sql.Types.LONGVARCHAR:
return new String(srcObj.toString()); return srcObj.toString();
default: default:
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.dtypemismt").toString()); throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.dtypemismt").toString());
} }
@ -4181,12 +4186,12 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
try { try {
switch (trgType) { switch (trgType) {
case java.sql.Types.BIT: case java.sql.Types.BIT:
Integer i = new Integer(srcObj.toString().trim()); Integer i = Integer.valueOf(srcObj.toString().trim());
return i.equals(new Integer((int)0)) ? return i.equals(Integer.valueOf((int)0)) ?
new Boolean(false) : Boolean.valueOf(false) :
new Boolean(true); Boolean.valueOf(true);
case java.sql.Types.BOOLEAN: case java.sql.Types.BOOLEAN:
return new Boolean(srcObj.toString().trim()); return Boolean.valueOf(srcObj.toString().trim());
default: default:
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.dtypemismt").toString()+ trgType); throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.dtypemismt").toString()+ trgType);
} }
@ -4260,7 +4265,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
checkIndex(columnIndex); checkIndex(columnIndex);
// make sure the cursor is on a valid row // make sure the cursor is on a valid row
checkCursor(); checkCursor();
Object obj = convertBoolean(new Boolean(x), Object obj = convertBoolean(Boolean.valueOf(x),
java.sql.Types.BIT, java.sql.Types.BIT,
RowSetMD.getColumnType(columnIndex)); RowSetMD.getColumnType(columnIndex));
@ -4296,7 +4301,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
// make sure the cursor is on a valid row // make sure the cursor is on a valid row
checkCursor(); checkCursor();
Object obj = convertNumeric(new Byte(x), Object obj = convertNumeric(Byte.valueOf(x),
java.sql.Types.TINYINT, java.sql.Types.TINYINT,
RowSetMD.getColumnType(columnIndex)); RowSetMD.getColumnType(columnIndex));
@ -4332,7 +4337,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
// make sure the cursor is on a valid row // make sure the cursor is on a valid row
checkCursor(); checkCursor();
Object obj = convertNumeric(new Short(x), Object obj = convertNumeric(Short.valueOf(x),
java.sql.Types.SMALLINT, java.sql.Types.SMALLINT,
RowSetMD.getColumnType(columnIndex)); RowSetMD.getColumnType(columnIndex));
@ -4367,7 +4372,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
checkIndex(columnIndex); checkIndex(columnIndex);
// make sure the cursor is on a valid row // make sure the cursor is on a valid row
checkCursor(); checkCursor();
Object obj = convertNumeric(new Integer(x), Object obj = convertNumeric(Integer.valueOf(x),
java.sql.Types.INTEGER, java.sql.Types.INTEGER,
RowSetMD.getColumnType(columnIndex)); RowSetMD.getColumnType(columnIndex));
@ -4403,7 +4408,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
// make sure the cursor is on a valid row // make sure the cursor is on a valid row
checkCursor(); checkCursor();
Object obj = convertNumeric(new Long(x), Object obj = convertNumeric(Long.valueOf(x),
java.sql.Types.BIGINT, java.sql.Types.BIGINT,
RowSetMD.getColumnType(columnIndex)); RowSetMD.getColumnType(columnIndex));
@ -6429,7 +6434,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
if (tabName == null) if (tabName == null)
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.tablename").toString()); throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.tablename").toString());
else else
tableName = new String(tabName); tableName = tabName;
} }
/** /**
@ -6940,7 +6945,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
} }
for( int i = 0;i < columnIdxes.length ;i++) { for( int i = 0;i < columnIdxes.length ;i++) {
iMatchColumns.set(i,new Integer(-1)); iMatchColumns.set(i,Integer.valueOf(-1));
} }
} }
@ -7049,7 +7054,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
} }
} }
for(int i = 0 ;i < columnIdxes.length; i++) { for(int i = 0 ;i < columnIdxes.length; i++) {
iMatchColumns.add(i,new Integer(columnIdxes[i])); iMatchColumns.add(i,Integer.valueOf(columnIdxes[i]));
} }
} }
@ -7104,7 +7109,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.matchcols1").toString()); throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.matchcols1").toString());
} else { } else {
// set iMatchColumn // set iMatchColumn
iMatchColumns.set(0, new Integer(columnIdx)); iMatchColumns.set(0, Integer.valueOf(columnIdx));
//strMatchColumn = null; //strMatchColumn = null;
} }
} }
@ -7126,7 +7131,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
*/ */
public void setMatchColumn(String columnName) throws SQLException { public void setMatchColumn(String columnName) throws SQLException {
// validate, if col is ok to be set // validate, if col is ok to be set
if(columnName.equals(null) || ((columnName = columnName.trim()) == "" )) { if(columnName == null || (columnName= columnName.trim()).equals("") ) {
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.matchcols2").toString()); throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.matchcols2").toString());
} else { } else {
// set strMatchColumn // set strMatchColumn
@ -7151,13 +7156,13 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
*/ */
public void unsetMatchColumn(int columnIdx) throws SQLException { public void unsetMatchColumn(int columnIdx) throws SQLException {
// check if we are unsetting the SAME column // check if we are unsetting the SAME column
if(! iMatchColumns.get(0).equals(new Integer(columnIdx) ) ) { if(! iMatchColumns.get(0).equals(Integer.valueOf(columnIdx) ) ) {
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.unsetmatch").toString()); throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.unsetmatch").toString());
} else if(strMatchColumns.get(0) != null) { } else if(strMatchColumns.get(0) != null) {
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.unsetmatch1").toString()); throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.unsetmatch1").toString());
} else { } else {
// that is, we are unsetting it. // that is, we are unsetting it.
iMatchColumns.set(0, new Integer(-1)); iMatchColumns.set(0, Integer.valueOf(-1));
} }
} }

View File

@ -499,7 +499,7 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C
if(onInsertRow) { if(onInsertRow) {
if(p != null) { if(p != null) {
bool = p.evaluate(new Integer(x),columnIndex); bool = p.evaluate(Integer.valueOf(x),columnIndex);
if(!bool) { if(!bool) {
throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString()); throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString());
@ -566,7 +566,7 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C
if(onInsertRow) { if(onInsertRow) {
if(p != null) { if(p != null) {
bool = p.evaluate(new Boolean(x) , columnIndex); bool = p.evaluate(Boolean.valueOf(x) , columnIndex);
if(!bool) { if(!bool) {
throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString()); throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString());
@ -634,7 +634,7 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C
if(onInsertRow) { if(onInsertRow) {
if(p != null) { if(p != null) {
bool = p.evaluate(new Byte(x),columnIndex); bool = p.evaluate(Byte.valueOf(x),columnIndex);
if(!bool) { if(!bool) {
throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString()); throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString());
@ -703,7 +703,7 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C
if(onInsertRow) { if(onInsertRow) {
if(p != null) { if(p != null) {
bool = p.evaluate(new Short(x), columnIndex); bool = p.evaluate(Short.valueOf(x), columnIndex);
if(!bool) { if(!bool) {
throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString()); throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString());
@ -771,7 +771,7 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C
if(onInsertRow) { if(onInsertRow) {
if(p != null) { if(p != null) {
bool = p.evaluate(new Long(x), columnIndex); bool = p.evaluate(Long.valueOf(x), columnIndex);
if(!bool) { if(!bool) {
throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString()); throw new SQLException(resBundle.handleGetObject("filteredrowsetimpl.notallowed").toString());
@ -1106,12 +1106,12 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C
public void updateBytes(int columnIndex , byte []x) throws SQLException { public void updateBytes(int columnIndex , byte []x) throws SQLException {
boolean bool; boolean bool;
String val = new String(); String val = "";
Byte [] obj_arr = new Byte[x.length]; Byte [] obj_arr = new Byte[x.length];
for(int i = 0; i < x.length; i++) { for(int i = 0; i < x.length; i++) {
obj_arr[i] = new Byte(x[i]); obj_arr[i] = Byte.valueOf(x[i]);
val = val.concat(obj_arr[i].toString()); val = val.concat(obj_arr[i].toString());
} }

View File

@ -215,7 +215,7 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
iMatchColumns = new Vector(10); iMatchColumns = new Vector(10);
for(int i = 0; i < 10 ; i++) { for(int i = 0; i < 10 ; i++) {
iMatchColumns.add(i,new Integer(-1)); iMatchColumns.add(i,Integer.valueOf(-1));
} }
strMatchColumns = new Vector(10); strMatchColumns = new Vector(10);
@ -288,7 +288,7 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
iMatchColumns = new Vector(10); iMatchColumns = new Vector(10);
for(int i = 0; i < 10 ; i++) { for(int i = 0; i < 10 ; i++) {
iMatchColumns.add(i,new Integer(-1)); iMatchColumns.add(i,Integer.valueOf(-1));
} }
strMatchColumns = new Vector(10); strMatchColumns = new Vector(10);
@ -375,7 +375,7 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
iMatchColumns = new Vector(10); iMatchColumns = new Vector(10);
for(int i = 0; i < 10 ; i++) { for(int i = 0; i < 10 ; i++) {
iMatchColumns.add(i,new Integer(-1)); iMatchColumns.add(i,Integer.valueOf(-1));
} }
strMatchColumns = new Vector(10); strMatchColumns = new Vector(10);
@ -465,7 +465,7 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
iMatchColumns = new Vector(10); iMatchColumns = new Vector(10);
for(int i = 0; i < 10 ; i++) { for(int i = 0; i < 10 ; i++) {
iMatchColumns.add(i,new Integer(-1)); iMatchColumns.add(i,Integer.valueOf(-1));
} }
strMatchColumns = new Vector(10); strMatchColumns = new Vector(10);
@ -3754,7 +3754,7 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
} }
for( int i = 0;i < columnIdxes.length ;i++) { for( int i = 0;i < columnIdxes.length ;i++) {
iMatchColumns.set(i,new Integer(-1)); iMatchColumns.set(i,Integer.valueOf(-1));
} }
} }
@ -3863,7 +3863,7 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
} }
} }
for(int i = 0 ;i < columnIdxes.length; i++) { for(int i = 0 ;i < columnIdxes.length; i++) {
iMatchColumns.add(i,new Integer(columnIdxes[i])); iMatchColumns.add(i,Integer.valueOf(columnIdxes[i]));
} }
} }
@ -3918,7 +3918,7 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols1").toString()); throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols1").toString());
} else { } else {
// set iMatchColumn // set iMatchColumn
iMatchColumns.set(0, new Integer(columnIdx)); iMatchColumns.set(0, Integer.valueOf(columnIdx));
//strMatchColumn = null; //strMatchColumn = null;
} }
} }
@ -3940,7 +3940,7 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
*/ */
public void setMatchColumn(String columnName) throws SQLException { public void setMatchColumn(String columnName) throws SQLException {
// validate, if col is ok to be set // validate, if col is ok to be set
if(columnName.equals(null) || ((columnName = columnName.trim()) == "" )) { if(columnName == null || (columnName= columnName.trim()).equals("")) {
throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols2").toString()); throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.matchcols2").toString());
} else { } else {
// set strMatchColumn // set strMatchColumn
@ -3965,13 +3965,13 @@ public class JdbcRowSetImpl extends BaseRowSet implements JdbcRowSet, Joinable {
*/ */
public void unsetMatchColumn(int columnIdx) throws SQLException { public void unsetMatchColumn(int columnIdx) throws SQLException {
// check if we are unsetting the SAME column // check if we are unsetting the SAME column
if(! iMatchColumns.get(0).equals(new Integer(columnIdx) ) ) { if(! iMatchColumns.get(0).equals(Integer.valueOf(columnIdx) ) ) {
throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.unsetmatch").toString()); throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.unsetmatch").toString());
} else if(strMatchColumns.get(0) != null) { } else if(strMatchColumns.get(0) != null) {
throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.usecolname").toString()); throw new SQLException(resBundle.handleGetObject("jdbcrowsetimpl.usecolname").toString());
} else { } else {
// that is, we are unsetting it. // that is, we are unsetting it.
iMatchColumns.set(0, new Integer(-1)); iMatchColumns.set(0, Integer.valueOf(-1));
} }
} }

View File

@ -33,6 +33,8 @@ import java.math.*;
import java.util.*; import java.util.*;
import javax.sql.rowset.*; import javax.sql.rowset.*;
import javax.sql.rowset.spi.SyncProvider;
import javax.sql.rowset.spi.SyncProviderException;
/** /**
* The standard implementation of the <code>JoinRowSet</code> * The standard implementation of the <code>JoinRowSet</code>
@ -550,7 +552,7 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet {
// This 'if' will be removed after all joins are implemented. // This 'if' will be removed after all joins are implemented.
throw new SQLException(resBundle.handleGetObject("joinrowsetimpl.notsupported").toString()); throw new SQLException(resBundle.handleGetObject("joinrowsetimpl.notsupported").toString());
} else { } else {
Integer Intgr = new Integer(JoinRowSet.INNER_JOIN); Integer Intgr = Integer.valueOf(JoinRowSet.INNER_JOIN);
vecJoinType.add(Intgr); vecJoinType.add(Intgr);
} }
} else { } else {
@ -874,8 +876,8 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet {
String strWhereClause = "Select "; String strWhereClause = "Select ";
String whereClause; String whereClause;
String tabName= null; String tabName= "";
String strTabName = null; String strTabName = "";
int sz,cols; int sz,cols;
int j; int j;
CachedRowSetImpl crs; CachedRowSetImpl crs;
@ -889,8 +891,6 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet {
// tableNameX.(rowsetX.getMatchColumnName()) == // tableNameX.(rowsetX.getMatchColumnName()) ==
// tableNameZ.(rowsetZ.getMatchColumnName())); // tableNameZ.(rowsetZ.getMatchColumnName()));
tabName = new String();
strTabName = new String();
sz = vecRowSetsInJOIN.size(); sz = vecRowSetsInJOIN.size();
for(int i=0;i<sz; i++) { for(int i=0;i<sz; i++) {
crs = (CachedRowSetImpl)vecRowSetsInJOIN.get(i); crs = (CachedRowSetImpl)vecRowSetsInJOIN.get(i);
@ -4311,6 +4311,27 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet {
return crsInternal.createCopySchema(); return crsInternal.createCopySchema();
} }
/**
* {@inheritDoc}
*/
public void setSyncProvider(String providerStr) throws SQLException {
crsInternal.setSyncProvider(providerStr);
}
/**
* {@inheritDoc}
*/
public void acceptChanges() throws SyncProviderException {
crsInternal.acceptChanges();
}
/**
* {@inheritDoc}
*/
public SyncProvider getSyncProvider() throws SQLException {
return crsInternal.getSyncProvider();
}
/** /**
* This method re populates the resBundle * This method re populates the resBundle
* during the deserialization process * during the deserialization process

View File

@ -338,11 +338,11 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
if (crs.rowDeleted()) { if (crs.rowDeleted()) {
// The row has been deleted. // The row has been deleted.
if (conflict = (deleteOriginalRow(crs, this.crsResolve)) == true) { if (conflict = (deleteOriginalRow(crs, this.crsResolve)) == true) {
status.add(rows, new Integer(SyncResolver.DELETE_ROW_CONFLICT)); status.add(rows, Integer.valueOf(SyncResolver.DELETE_ROW_CONFLICT));
} else { } else {
// delete happened without any occurrence of conflicts // delete happened without any occurrence of conflicts
// so update status accordingly // so update status accordingly
status.add(rows, new Integer(SyncResolver.NO_ROW_CONFLICT)); status.add(rows, Integer.valueOf(SyncResolver.NO_ROW_CONFLICT));
} }
} else if (crs.rowInserted()) { } else if (crs.rowInserted()) {
@ -350,20 +350,20 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
pstmtIns = con.prepareStatement(insertCmd); pstmtIns = con.prepareStatement(insertCmd);
if ( (conflict = insertNewRow(crs, pstmtIns, this.crsResolve)) == true) { if ( (conflict = insertNewRow(crs, pstmtIns, this.crsResolve)) == true) {
status.add(rows, new Integer(SyncResolver.INSERT_ROW_CONFLICT)); status.add(rows, Integer.valueOf(SyncResolver.INSERT_ROW_CONFLICT));
} else { } else {
// insert happened without any occurrence of conflicts // insert happened without any occurrence of conflicts
// so update status accordingly // so update status accordingly
status.add(rows, new Integer(SyncResolver.NO_ROW_CONFLICT)); status.add(rows, Integer.valueOf(SyncResolver.NO_ROW_CONFLICT));
} }
} else if (crs.rowUpdated()) { } else if (crs.rowUpdated()) {
// The row has been updated. // The row has been updated.
if ( conflict = (updateOriginalRow(crs)) == true) { if ( conflict = (updateOriginalRow(crs)) == true) {
status.add(rows, new Integer(SyncResolver.UPDATE_ROW_CONFLICT)); status.add(rows, Integer.valueOf(SyncResolver.UPDATE_ROW_CONFLICT));
} else { } else {
// update happened without any occurrence of conflicts // update happened without any occurrence of conflicts
// so update status accordingly // so update status accordingly
status.add(rows, new Integer(SyncResolver.NO_ROW_CONFLICT)); status.add(rows, Integer.valueOf(SyncResolver.NO_ROW_CONFLICT));
} }
} else { } else {
@ -375,7 +375,7 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
* that is fine. * that is fine.
**/ **/
int icolCount = crs.getMetaData().getColumnCount(); int icolCount = crs.getMetaData().getColumnCount();
status.add(rows, new Integer(SyncResolver.NO_ROW_CONFLICT)); status.add(rows, Integer.valueOf(SyncResolver.NO_ROW_CONFLICT));
this.crsResolve.moveToInsertRow(); this.crsResolve.moveToInsertRow();
for(int cols=0;cols<iColCount;cols++) { for(int cols=0;cols<iColCount;cols++) {
@ -398,7 +398,7 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
boolean boolConf = false; boolean boolConf = false;
for (int j=1;j<status.size();j++){ for (int j=1;j<status.size();j++){
// ignore status for index = 0 which is set to null // ignore status for index = 0 which is set to null
if(! ((status.get(j)).equals(new Integer(SyncResolver.NO_ROW_CONFLICT)))) { if(! ((status.get(j)).equals(Integer.valueOf(SyncResolver.NO_ROW_CONFLICT)))) {
// there is at least one conflict which needs to be resolved // there is at least one conflict which needs to be resolved
boolConf = true; boolConf = true;
break; break;
@ -541,7 +541,7 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
// how many fields need to be updated // how many fields need to be updated
int colsNotChanged = 0; int colsNotChanged = 0;
Vector cols = new Vector(); Vector cols = new Vector();
String updateExec = new String(updateCmd); String updateExec = updateCmd;
Object orig; Object orig;
Object curr; Object curr;
Object rsval; Object rsval;
@ -652,7 +652,7 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
updateExec += ", "; updateExec += ", ";
} }
updateExec += crs.getMetaData().getColumnName(i); updateExec += crs.getMetaData().getColumnName(i);
cols.add(new Integer(i)); cols.add(Integer.valueOf(i));
updateExec += " = ? "; updateExec += " = ? ";
first = false; first = false;
@ -698,7 +698,7 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
updateExec += ", "; updateExec += ", ";
} }
updateExec += crs.getMetaData().getColumnName(i); updateExec += crs.getMetaData().getColumnName(i);
cols.add(new Integer(i)); cols.add(Integer.valueOf(i));
updateExec += " = ? "; updateExec += " = ? ";
flag = false; flag = false;
} else { } else {
@ -1184,7 +1184,7 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
// trim all the leading and trailing whitespaces, // trim all the leading and trailing whitespaces,
// white spaces can never be catalog, schema or a table name. // white spaces can never be catalog, schema or a table name.
String cmd = new String(); String cmd = "";
catalog = catalog.trim(); catalog = catalog.trim();
schema = schema.trim(); schema = schema.trim();

View File

@ -248,7 +248,7 @@ public class WebRowSetXmlWriter implements XmlWriter, Serializable {
String strProvider = strProviderInstance.substring(0, (caller.getSyncProvider()).toString().indexOf("@")); String strProvider = strProviderInstance.substring(0, (caller.getSyncProvider()).toString().indexOf("@"));
propString("sync-provider-name", strProvider); propString("sync-provider-name", strProvider);
propString("sync-provider-vendor", "Sun Microsystems Inc."); propString("sync-provider-vendor", "Oracle Corporation");
propString("sync-provider-version", "1.0"); propString("sync-provider-version", "1.0");
propInteger("sync-provider-grade", caller.getSyncProvider().getProviderGrade()); propInteger("sync-provider-grade", caller.getSyncProvider().getProviderGrade());
propInteger("data-source-lock", caller.getSyncProvider().getDataSourceLock()); propInteger("data-source-lock", caller.getSyncProvider().getDataSourceLock());
@ -387,7 +387,7 @@ public class WebRowSetXmlWriter implements XmlWriter, Serializable {
if (caller.wasNull()) if (caller.wasNull())
writeNull(); writeNull();
else else
writeInteger(caller.getInt(idx)); writeInteger(i);
break; break;
case java.sql.Types.BIGINT: case java.sql.Types.BIGINT:
long l = caller.getLong(idx); long l = caller.getLong(idx);
@ -574,7 +574,7 @@ public class WebRowSetXmlWriter implements XmlWriter, Serializable {
} }
private void writeBoolean(boolean b) throws java.io.IOException { private void writeBoolean(boolean b) throws java.io.IOException {
writer.write(new Boolean(b).toString()); writer.write(Boolean.valueOf(b).toString());
} }
private void writeFloat(float f) throws java.io.IOException { private void writeFloat(float f) throws java.io.IOException {
@ -641,7 +641,7 @@ public class WebRowSetXmlWriter implements XmlWriter, Serializable {
return null; return null;
} }
char []charStr = s.toCharArray(); char []charStr = s.toCharArray();
String specialStr = new String(); String specialStr = "";
for(int i = 0; i < charStr.length; i++) { for(int i = 0; i < charStr.length; i++) {
if(charStr[i] == '&') { if(charStr[i] == '&') {

View File

@ -441,9 +441,9 @@ public class XmlReaderContentHandler extends DefaultHandler {
updates = new Vector(); updates = new Vector();
// start out with the empty string // start out with the empty string
columnValue = new String(""); columnValue = "";
propertyValue = new String(""); propertyValue = "";
metaDataValue = new String(""); metaDataValue = "";
nullVal = false; nullVal = false;
idx = 0; idx = 0;
@ -481,21 +481,21 @@ public class XmlReaderContentHandler extends DefaultHandler {
items = properties.length; items = properties.length;
for (i=0;i<items;i++) { for (i=0;i<items;i++) {
propMap.put(properties[i], new Integer(i)); propMap.put(properties[i], Integer.valueOf(i));
} }
colDefMap = new HashMap(); colDefMap = new HashMap();
items = colDef.length; items = colDef.length;
for (i=0;i<items;i++) { for (i=0;i<items;i++) {
colDefMap.put(colDef[i], new Integer(i)); colDefMap.put(colDef[i], Integer.valueOf(i));
} }
dataMap = new HashMap(); dataMap = new HashMap();
items = data.length; items = data.length;
for (i=0;i<items;i++) { for (i=0;i<items;i++) {
dataMap.put(data[i], new Integer(i)); dataMap.put(data[i], Integer.valueOf(i));
} }
//Initialize connection map here //Initialize connection map here
@ -686,7 +686,7 @@ public class XmlReaderContentHandler extends DefaultHandler {
} }
// propertyValue need to be reset to an empty string // propertyValue need to be reset to an empty string
propertyValue = new String(""); propertyValue = "";
setTag(-1); setTag(-1);
break; break;
case METADATA: case METADATA:
@ -710,7 +710,7 @@ public class XmlReaderContentHandler extends DefaultHandler {
} }
// metaDataValue needs to be reset to an empty string // metaDataValue needs to be reset to an empty string
metaDataValue = new String(""); metaDataValue = "";
} }
setTag(-1); setTag(-1);
break; break;
@ -736,7 +736,7 @@ public class XmlReaderContentHandler extends DefaultHandler {
insertValue(tempStr); insertValue(tempStr);
} }
// columnValue now need to be reset to the empty string // columnValue now need to be reset to the empty string
columnValue = new String(""); columnValue = "";
} catch (SQLException ex) { } catch (SQLException ex) {
throw new SAXException(MessageFormat.format(resBundle.handleGetObject("xmlrch.errinsert").toString(), ex.getMessage())); throw new SAXException(MessageFormat.format(resBundle.handleGetObject("xmlrch.errinsert").toString(), ex.getMessage()));
} }
@ -981,7 +981,7 @@ public class XmlReaderContentHandler extends DefaultHandler {
private boolean getBooleanValue(String s) { private boolean getBooleanValue(String s) {
return new Boolean(s).booleanValue(); return Boolean.valueOf(s).booleanValue();
} }
private java.math.BigDecimal getBigDecimalValue(String s) { private java.math.BigDecimal getBigDecimalValue(String s) {
@ -1316,7 +1316,7 @@ public class XmlReaderContentHandler extends DefaultHandler {
**/ **/
tempUpdate = tempUpdate.concat(new String(ch,start,len)); tempUpdate = tempUpdate.concat(new String(ch,start,len));
upd[0] = new Integer(idx); upd[0] = Integer.valueOf(idx);
upd[1] = tempUpdate; upd[1] = tempUpdate;
//updates.add(upd); //updates.add(upd);

View File

@ -93,14 +93,14 @@ public final class RIOptimisticProvider extends SyncProvider implements Serializ
private CachedRowSetWriter writer; private CachedRowSetWriter writer;
/** /**
* The unique provider indentifier. * The unique provider identifier.
*/ */
private String providerID = "com.sun.rowset.providers.RIOptimisticProvider"; private String providerID = "com.sun.rowset.providers.RIOptimisticProvider";
/** /**
* The vendor name of this SyncProvider implementation * The vendor name of this SyncProvider implementation
*/ */
private String vendorName = "Sun Microsystems Inc."; private String vendorName = "Oracle Corporation";
/** /**
* The version number of this SyncProvider implementation * The version number of this SyncProvider implementation
@ -236,8 +236,8 @@ public final class RIOptimisticProvider extends SyncProvider implements Serializ
} }
/** /**
* Returns the vendor name of the Reference Implemntation Optimistic * Returns the vendor name of the Reference Implementation Optimistic
* Syncchronication Provider * Synchronization Provider
* *
* @return the <code>String</code> detailing the vendor name of this * @return the <code>String</code> detailing the vendor name of this
* SyncProvider * SyncProvider

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -85,7 +85,7 @@ public final class RIXMLProvider extends SyncProvider {
/** /**
* The vendor name of this SyncProvider implementation. * The vendor name of this SyncProvider implementation.
*/ */
private String vendorName = "Sun Microsystems Inc."; private String vendorName = "Oracle Corporation";
/** /**
* The version number of this SyncProvider implementation. * The version number of this SyncProvider implementation.

View File

@ -43,7 +43,8 @@ public class Installer {
"servicetag.dir.path"; "servicetag.dir.path";
private static String SVCTAG_ENABLE_REGISTRATION = private static String SVCTAG_ENABLE_REGISTRATION =
"servicetag.registration.enabled"; "servicetag.registration.enabled";
private final static String SUN_VENDOR = "Sun Microsystems"; private final static String ORACLE = "Oracle";
private final static String SUN = "Sun Microsystems";
private final static String REGISTRATION_XML = "registration.xml"; private final static String REGISTRATION_XML = "registration.xml";
private final static String SERVICE_TAG_FILE = "servicetag"; private final static String SERVICE_TAG_FILE = "servicetag";
private final static String REGISTRATION_HTML_NAME = "register"; private final static String REGISTRATION_HTML_NAME = "register";
@ -84,9 +85,10 @@ public class Installer {
// Implementation of ServiceTag.getJavaServiceTag(String) method // Implementation of ServiceTag.getJavaServiceTag(String) method
static ServiceTag getJavaServiceTag(String source) throws IOException { static ServiceTag getJavaServiceTag(String source) throws IOException {
if (!System.getProperty("java.vendor").startsWith(SUN_VENDOR)) { String vendor = System.getProperty("java.vendor", "");
if (!vendor.startsWith(SUN) && !vendor.startsWith(ORACLE)) {
// Products bundling this implementation may run on // Products bundling this implementation may run on
// Mac OS which is not a Sun JDK // Mac OS which is not a Sun/Oracle JDK
return null; return null;
} }
boolean cleanup = false; boolean cleanup = false;
@ -365,7 +367,7 @@ public class Installer {
props.getProperty("servicetag.parent.name"), props.getProperty("servicetag.parent.name"),
props.getProperty("servicetag.parent.urn"), props.getProperty("servicetag.parent.urn"),
getProductDefinedId(), getProductDefinedId(),
SUN_VENDOR, System.getProperty("java.vendor"),
System.getProperty("os.arch"), System.getProperty("os.arch"),
getZoneName(), getZoneName(),
svcTagSource); svcTagSource);

View File

@ -80,12 +80,12 @@ import static com.sun.servicetag.RegistrationDocument.*;
* <tr> * <tr>
* <td><tt>systemManufacturer</tt></td> * <td><tt>systemManufacturer</tt></td>
* <td>System manufacturer</td> * <td>System manufacturer</td>
* <td> e.g. Sun Microsystems</td> * <td> e.g. Oracle Corporation</td>
* </tr> * </tr>
* <tr> * <tr>
* <td><tt>cpuManufacturer</tt></td> * <td><tt>cpuManufacturer</tt></td>
* <td>CPU manufacturer</td> * <td>CPU manufacturer</td>
* <td> e.g. Sun Microsystems</td> * <td> e.g. Oracle Corporation</td>
* </tr> * </tr>
* <tr> * <tr>
* <td><tt>serialNumber</tt></td> * <td><tt>serialNumber</tt></td>

View File

@ -90,7 +90,7 @@ public class Registry {
stclient = getWindowsStClientFile(); stclient = getWindowsStClientFile();
} else { } else {
if (isVerbose()) { if (isVerbose()) {
System.out.println("Running on non-Sun JDK"); System.out.println("Running on unsupported platform");
} }
} }
initialized = true; initialized = true;

View File

@ -44,6 +44,7 @@ import java.io.*;
* Solaris implementation of the SystemEnvironment class. * Solaris implementation of the SystemEnvironment class.
*/ */
class SolarisSystemEnvironment extends SystemEnvironment { class SolarisSystemEnvironment extends SystemEnvironment {
private static final String ORACLE = "Oracle Corporation";
SolarisSystemEnvironment() { SolarisSystemEnvironment() {
setHostId(getCommandOutput("/usr/bin/hostid")); setHostId(getCommandOutput("/usr/bin/hostid"));
setSystemModel(getCommandOutput("/usr/bin/uname", "-i")); setSystemModel(getCommandOutput("/usr/bin/uname", "-i"));
@ -59,7 +60,7 @@ class SolarisSystemEnvironment extends SystemEnvironment {
private String getSolarisCpuManufacturer() { private String getSolarisCpuManufacturer() {
// not fully accurate, this could be another manufacturer (fujitsu for example) // not fully accurate, this could be another manufacturer (fujitsu for example)
if ("sparc".equalsIgnoreCase(System.getProperty("os.arch"))) { if ("sparc".equalsIgnoreCase(System.getProperty("os.arch"))) {
return "Sun Microsystems, Inc"; return ORACLE;
} }
// if we're here, then we'll try smbios (type 4) // if we're here, then we'll try smbios (type 4)
@ -73,7 +74,7 @@ class SolarisSystemEnvironment extends SystemEnvironment {
private String getSolarisSystemManufacturer() { private String getSolarisSystemManufacturer() {
// not fully accurate, this could be another manufacturer (fujitsu for example) // not fully accurate, this could be another manufacturer (fujitsu for example)
if ("sparc".equalsIgnoreCase(System.getProperty("os.arch"))) { if ("sparc".equalsIgnoreCase(System.getProperty("os.arch"))) {
return "Sun Microsystems, Inc"; return ORACLE;
} }
// if we're here, then we'll try smbios (type 1) // if we're here, then we'll try smbios (type 1)
@ -117,7 +118,7 @@ class SolarisSystemEnvironment extends SystemEnvironment {
// ID SIZE TYPE // ID SIZE TYPE
// 1 150 SMB_TYPE_SYSTEM (system information) // 1 150 SMB_TYPE_SYSTEM (system information)
// //
// Manufacturer: Sun Microsystems // Manufacturer: Oracle Corporation
// Product: Sun Fire X4600 // Product: Sun Fire X4600
// Version: To Be Filled By O.E.M. // Version: To Be Filled By O.E.M.
// Serial Number: 00:14:4F:45:0C:2A // Serial Number: 00:14:4F:45:0C:2A

View File

@ -1068,7 +1068,7 @@ public class Dialog extends Window {
modalityPushed(); modalityPushed();
try { try {
EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
secondaryLoop = eventQueue.createSecondaryLoop(cond, modalFilter, 5000); secondaryLoop = eventQueue.createSecondaryLoop(cond, modalFilter, 0);
if (!secondaryLoop.enter()) { if (!secondaryLoop.enter()) {
secondaryLoop = null; secondaryLoop = null;
} }

View File

@ -142,6 +142,9 @@ public abstract class KeyboardFocusManager
public void removeLastFocusRequest(Component heavyweight) { public void removeLastFocusRequest(Component heavyweight) {
KeyboardFocusManager.removeLastFocusRequest(heavyweight); KeyboardFocusManager.removeLastFocusRequest(heavyweight);
} }
public void setMostRecentFocusOwner(Window window, Component component) {
KeyboardFocusManager.setMostRecentFocusOwner(window, component);
}
} }
); );
} }

View File

@ -51,7 +51,7 @@ import java.awt.Event;
* in the range from {@code ACTION_FIRST} to {@code ACTION_LAST}. * in the range from {@code ACTION_FIRST} to {@code ACTION_LAST}.
* *
* @see ActionListener * @see ActionListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/eventmodel.html">Tutorial: Java 1.1 Event Model</a> * @see <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/actionlistener.html">Tutorial: How to Write an Action Listener</a>
* *
* @author Carl Quinn * @author Carl Quinn
* @since 1.1 * @since 1.1

View File

@ -937,14 +937,22 @@ public abstract class SampleModel
int iArray[], DataBuffer data) { int iArray[], DataBuffer data) {
int pixels[]; int pixels[];
int Offset=0; int Offset=0;
int x1 = x + w;
int y1 = y + h;
if (x < 0 || x1 < x || x1 > width ||
y < 0 || y1 < y || y1 > height)
{
throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
}
if (iArray != null) if (iArray != null)
pixels = iArray; pixels = iArray;
else else
pixels = new int[w * h]; pixels = new int[w * h];
for(int i=y; i<(h+y); i++) { for(int i=y; i<y1; i++) {
for (int j=x; j<(w+x); j++) { for (int j=x; j<x1; j++) {
pixels[Offset++] = getSample(j, i, b, data); pixels[Offset++] = getSample(j, i, b, data);
} }
} }
@ -978,14 +986,22 @@ public abstract class SampleModel
DataBuffer data) { DataBuffer data) {
float pixels[]; float pixels[];
int Offset=0; int Offset=0;
int x1 = x + w;
int y1 = y + h;
if (x < 0 || x1 < x || x1 > width ||
y < 0 || y1 < y || y1 > height)
{
throw new ArrayIndexOutOfBoundsException("Invalid coordinates");
}
if (fArray != null) if (fArray != null)
pixels = fArray; pixels = fArray;
else else
pixels = new float[w * h]; pixels = new float[w * h];
for (int i=y; i<(h+y); i++) { for (int i=y; i<y1; i++) {
for (int j=x; j<(w+x); j++) { for (int j=x; j<x1; j++) {
pixels[Offset++] = getSampleFloat(j, i, b, data); pixels[Offset++] = getSampleFloat(j, i, b, data);
} }
} }
@ -1019,14 +1035,22 @@ public abstract class SampleModel
DataBuffer data) { DataBuffer data) {
double pixels[]; double pixels[];
int Offset=0; int Offset=0;
int x1 = x + w;
int y1 = y + h;
if (x < 0 || x1 < x || x1 > width ||
y < 0 || y1 < y || y1 > height)
{
throw new ArrayIndexOutOfBoundsException("Invalid coordinates");
}
if (dArray != null) if (dArray != null)
pixels = dArray; pixels = dArray;
else else
pixels = new double[w * h]; pixels = new double[w * h];
for (int i=y; i<(y+h); i++) { for (int i=y; i<y1; i++) {
for (int j=x; j<(x+w); j++) { for (int j=x; j<x1; j++) {
pixels[Offset++] = getSampleDouble(j, i, b, data); pixels[Offset++] = getSampleDouble(j, i, b, data);
} }
} }

View File

@ -176,8 +176,9 @@ public class EventSetDescriptor extends FeatureDescriptor {
setRemoveListenerMethod(getMethod(sourceClass, removeListenerMethodName, 1)); setRemoveListenerMethod(getMethod(sourceClass, removeListenerMethodName, 1));
// Be more forgiving of not finding the getListener method. // Be more forgiving of not finding the getListener method.
if (getListenerMethodName != null) { Method method = Introspector.findMethod(sourceClass, getListenerMethodName, 0);
setGetListenerMethod(Introspector.findInstanceMethod(sourceClass, getListenerMethodName)); if (method != null) {
setGetListenerMethod(method);
} }
} }

View File

@ -189,11 +189,13 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor {
indexedReadMethodName = Introspector.GET_PREFIX + getBaseName(); indexedReadMethodName = Introspector.GET_PREFIX + getBaseName();
} }
} }
indexedReadMethod = Introspector.findInstanceMethod(cls, indexedReadMethodName, int.class);
Class[] args = { int.class };
indexedReadMethod = Introspector.findMethod(cls, indexedReadMethodName, 1, args);
if (indexedReadMethod == null) { if (indexedReadMethod == null) {
// no "is" method, so look for a "get" method. // no "is" method, so look for a "get" method.
indexedReadMethodName = Introspector.GET_PREFIX + getBaseName(); indexedReadMethodName = Introspector.GET_PREFIX + getBaseName();
indexedReadMethod = Introspector.findInstanceMethod(cls, indexedReadMethodName, int.class); indexedReadMethod = Introspector.findMethod(cls, indexedReadMethodName, 1, args);
} }
setIndexedReadMethod0(indexedReadMethod); setIndexedReadMethod0(indexedReadMethod);
} }
@ -265,7 +267,9 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor {
if (indexedWriteMethodName == null) { if (indexedWriteMethodName == null) {
indexedWriteMethodName = Introspector.SET_PREFIX + getBaseName(); indexedWriteMethodName = Introspector.SET_PREFIX + getBaseName();
} }
indexedWriteMethod = Introspector.findInstanceMethod(cls, indexedWriteMethodName, int.class, type);
Class[] args = (type == null) ? null : new Class[] { int.class, type };
indexedWriteMethod = Introspector.findMethod(cls, indexedWriteMethodName, 2, args);
if (indexedWriteMethod != null) { if (indexedWriteMethod != null) {
if (!indexedWriteMethod.getReturnType().equals(void.class)) { if (!indexedWriteMethod.getReturnType().equals(void.class)) {
indexedWriteMethod = null; indexedWriteMethod = null;

View File

@ -28,7 +28,6 @@ package java.beans;
import com.sun.beans.WeakCache; import com.sun.beans.WeakCache;
import com.sun.beans.finder.BeanInfoFinder; import com.sun.beans.finder.BeanInfoFinder;
import com.sun.beans.finder.ClassFinder; import com.sun.beans.finder.ClassFinder;
import com.sun.beans.finder.MethodFinder;
import java.lang.ref.Reference; import java.lang.ref.Reference;
import java.lang.ref.SoftReference; import java.lang.ref.SoftReference;
@ -843,8 +842,8 @@ public class Introspector {
Method read = result.getReadMethod(); Method read = result.getReadMethod();
if (read == null && write != null) { if (read == null && write != null) {
read = findInstanceMethod(result.getClass0(), read = findMethod(result.getClass0(),
GET_PREFIX + NameGenerator.capitalize(result.getName())); GET_PREFIX + NameGenerator.capitalize(result.getName()), 0);
if (read != null) { if (read != null) {
try { try {
result.setReadMethod(read); result.setReadMethod(read);
@ -854,9 +853,9 @@ public class Introspector {
} }
} }
if (write == null && read != null) { if (write == null && read != null) {
write = findInstanceMethod(result.getClass0(), write = findMethod(result.getClass0(),
SET_PREFIX + NameGenerator.capitalize(result.getName()), SET_PREFIX + NameGenerator.capitalize(result.getName()), 1,
FeatureDescriptor.getReturnType(result.getClass0(), read)); new Class[] { FeatureDescriptor.getReturnType(result.getClass0(), read) });
if (write != null) { if (write != null) {
try { try {
result.setWriteMethod(write); result.setWriteMethod(write);
@ -1280,27 +1279,90 @@ public class Introspector {
// Package private support methods. // Package private support methods.
//====================================================================== //======================================================================
static Method findMethod(Class<?> type, String name, int args) { /**
for (Method method : type.getMethods()) { * Internal support for finding a target methodName with a given
if (method.getName().equals(name) && (args == method.getParameterTypes().length)) { * parameter list on a given class.
try { */
return MethodFinder.findAccessibleMethod(method); private static Method internalFindMethod(Class start, String methodName,
int argCount, Class args[]) {
// For overriden methods we need to find the most derived version.
// So we start with the given class and walk up the superclass chain.
Method method = null;
for (Class cl = start; cl != null; cl = cl.getSuperclass()) {
Method methods[] = getPublicDeclaredMethods(cl);
for (int i = 0; i < methods.length; i++) {
method = methods[i];
if (method == null) {
continue;
} }
catch (NoSuchMethodException exception) {
// continue search for a method with the specified count of parameters // make sure method signature matches.
Class params[] = FeatureDescriptor.getParameterTypes(start, method);
if (method.getName().equals(methodName) &&
params.length == argCount) {
if (args != null) {
boolean different = false;
if (argCount > 0) {
for (int j = 0; j < argCount; j++) {
if (params[j] != args[j]) {
different = true;
continue;
}
}
if (different) {
continue;
}
}
}
return method;
} }
} }
} }
return null; method = null;
// Now check any inherited interfaces. This is necessary both when
// the argument class is itself an interface, and when the argument
// class is an abstract class.
Class ifcs[] = start.getInterfaces();
for (int i = 0 ; i < ifcs.length; i++) {
// Note: The original implementation had both methods calling
// the 3 arg method. This is preserved but perhaps it should
// pass the args array instead of null.
method = internalFindMethod(ifcs[i], methodName, argCount, null);
if (method != null) {
break;
}
}
return method;
} }
static Method findInstanceMethod(Class<?> type, String name, Class<?>... args) { /**
try { * Find a target methodName on a given class.
return MethodFinder.findInstanceMethod(type, name, args); */
} static Method findMethod(Class cls, String methodName, int argCount) {
catch (NoSuchMethodException exception) { return findMethod(cls, methodName, argCount, null);
}
/**
* Find a target methodName with specific parameter list on a given class.
* <p>
* Used in the contructors of the EventSetDescriptor,
* PropertyDescriptor and the IndexedPropertyDescriptor.
* <p>
* @param cls The Class object on which to retrieve the method.
* @param methodName Name of the method.
* @param argCount Number of arguments for the desired method.
* @param args Array of argument types for the method.
* @return the method or null if not found
*/
static Method findMethod(Class cls, String methodName, int argCount,
Class args[]) {
if (methodName == null) {
return null; return null;
} }
return internalFindMethod(cls, methodName, argCount, args);
} }
/** /**

View File

@ -90,13 +90,13 @@ public class MethodDescriptor extends FeatureDescriptor {
// Find methods for up to 2 params. We are guessing here. // Find methods for up to 2 params. We are guessing here.
// This block should never execute unless the classloader // This block should never execute unless the classloader
// that loaded the argument classes disappears. // that loaded the argument classes disappears.
method = Introspector.findMethod(cls, name, i); method = Introspector.findMethod(cls, name, i, null);
if (method != null) { if (method != null) {
break; break;
} }
} }
} else { } else {
method = Statement.getMethod(cls, name, params); method = Introspector.findMethod(cls, name, params.length, params);
} }
setMethod(method); setMethod(method);
} }

View File

@ -112,7 +112,8 @@ public class PropertyDescriptor extends FeatureDescriptor {
// If this class or one of its base classes allow PropertyChangeListener, // If this class or one of its base classes allow PropertyChangeListener,
// then we assume that any properties we discover are "bound". // then we assume that any properties we discover are "bound".
// See Introspector.getTargetPropertyInfo() method. // See Introspector.getTargetPropertyInfo() method.
this.bound = null != Introspector.findInstanceMethod(beanClass, "addPropertyChangeListener", PropertyChangeListener.class); Class[] args = { PropertyChangeListener.class };
this.bound = null != Introspector.findMethod(beanClass, "addPropertyChangeListener", args.length, args);
} }
/** /**
@ -223,10 +224,10 @@ public class PropertyDescriptor extends FeatureDescriptor {
// property type is. For booleans, there can be "is" and "get" // property type is. For booleans, there can be "is" and "get"
// methods. If an "is" method exists, this is the official // methods. If an "is" method exists, this is the official
// reader method so look for this one first. // reader method so look for this one first.
readMethod = Introspector.findInstanceMethod(cls, readMethodName); readMethod = Introspector.findMethod(cls, readMethodName, 0);
if (readMethod == null) { if (readMethod == null) {
readMethodName = Introspector.GET_PREFIX + getBaseName(); readMethodName = Introspector.GET_PREFIX + getBaseName();
readMethod = Introspector.findInstanceMethod(cls, readMethodName); readMethod = Introspector.findMethod(cls, readMethodName, 0);
} }
try { try {
setReadMethod(readMethod); setReadMethod(readMethod);
@ -291,7 +292,8 @@ public class PropertyDescriptor extends FeatureDescriptor {
writeMethodName = Introspector.SET_PREFIX + getBaseName(); writeMethodName = Introspector.SET_PREFIX + getBaseName();
} }
writeMethod = Introspector.findInstanceMethod(cls, writeMethodName, type); Class[] args = (type == null) ? null : new Class[] { type };
writeMethod = Introspector.findMethod(cls, writeMethodName, 1, args);
if (writeMethod != null) { if (writeMethod != null) {
if (!writeMethod.getReturnType().equals(void.class)) { if (!writeMethod.getReturnType().equals(void.class)) {
writeMethod = null; writeMethod = null;

View File

@ -1101,22 +1101,12 @@ public final class System {
lineSeparator = props.getProperty("line.separator"); lineSeparator = props.getProperty("line.separator");
sun.misc.Version.init(); sun.misc.Version.init();
// Workaround until DownloadManager initialization is revisited.
// Make JavaLangAccess available early enough for internal
// Shutdown hooks to be registered
setJavaLangAccess();
// Gets and removes system properties that configure the Integer // Gets and removes system properties that configure the Integer
// cache used to support the object identity semantics of autoboxing. // cache used to support the object identity semantics of autoboxing.
// At this time, the size of the cache may be controlled by the // At this time, the size of the cache may be controlled by the
// vm option -XX:AutoBoxCacheMax=<size>. // vm option -XX:AutoBoxCacheMax=<size>.
Integer.getAndRemoveCacheProperties(); Integer.getAndRemoveCacheProperties();
// Load the zip library now in order to keep java.util.zip.ZipFile
// from trying to use itself to load this library later.
loadLibrary("zip");
FileInputStream fdIn = new FileInputStream(FileDescriptor.in); FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err); FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
@ -1124,6 +1114,10 @@ public final class System {
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true)); setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true)); setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
// Load the zip library now in order to keep java.util.zip.ZipFile
// from trying to use itself to load this library later.
loadLibrary("zip");
// Setup Java signal handlers for HUP, TERM, and INT (where available). // Setup Java signal handlers for HUP, TERM, and INT (where available).
Terminator.setup(); Terminator.setup();
@ -1153,6 +1147,9 @@ public final class System {
// way as other threads; we must do it ourselves here. // way as other threads; we must do it ourselves here.
Thread current = Thread.currentThread(); Thread current = Thread.currentThread();
current.getThreadGroup().add(current); current.getThreadGroup().add(current);
// register shared secrets
setJavaLangAccess();
} }
private static void setJavaLangAccess() { private static void setJavaLangAccess() {

View File

@ -677,19 +677,20 @@ class InetAddress implements java.io.Serializable {
static InetAddressImpl impl; static InetAddressImpl impl;
private static HashMap lookupTable = new HashMap(); private static HashMap<String, InetAddress[]> lookupTable
= new HashMap<String, InetAddress[]>();
/** /**
* Represents a cache entry * Represents a cache entry
*/ */
static final class CacheEntry { static final class CacheEntry {
CacheEntry(Object address, long expiration) { CacheEntry(InetAddress[] addresses, long expiration) {
this.address = address; this.addresses = addresses;
this.expiration = expiration; this.expiration = expiration;
} }
Object address; InetAddress[] addresses;
long expiration; long expiration;
} }
@ -698,7 +699,7 @@ class InetAddress implements java.io.Serializable {
* at creation time. * at creation time.
*/ */
static final class Cache { static final class Cache {
private LinkedHashMap cache; private LinkedHashMap<String, CacheEntry> cache;
private Type type; private Type type;
enum Type {Positive, Negative}; enum Type {Positive, Negative};
@ -708,7 +709,7 @@ class InetAddress implements java.io.Serializable {
*/ */
public Cache(Type type) { public Cache(Type type) {
this.type = type; this.type = type;
cache = new LinkedHashMap(); cache = new LinkedHashMap<String, CacheEntry>();
} }
private int getPolicy() { private int getPolicy() {
@ -724,7 +725,7 @@ class InetAddress implements java.io.Serializable {
* entry then for this host then the entry will be * entry then for this host then the entry will be
* replaced. * replaced.
*/ */
public Cache put(String host, Object address) { public Cache put(String host, InetAddress[] addresses) {
int policy = getPolicy(); int policy = getPolicy();
if (policy == InetAddressCachePolicy.NEVER) { if (policy == InetAddressCachePolicy.NEVER) {
return this; return this;
@ -736,12 +737,10 @@ class InetAddress implements java.io.Serializable {
// As we iterate in insertion order we can // As we iterate in insertion order we can
// terminate when a non-expired entry is found. // terminate when a non-expired entry is found.
LinkedList expired = new LinkedList(); LinkedList<String> expired = new LinkedList<String>();
Iterator i = cache.keySet().iterator();
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
while (i.hasNext()) { for (String key : cache.keySet()) {
String key = (String)i.next(); CacheEntry entry = cache.get(key);
CacheEntry entry = (CacheEntry)cache.get(key);
if (entry.expiration >= 0 && entry.expiration < now) { if (entry.expiration >= 0 && entry.expiration < now) {
expired.add(key); expired.add(key);
@ -750,9 +749,8 @@ class InetAddress implements java.io.Serializable {
} }
} }
i = expired.iterator(); for (String key : expired) {
while (i.hasNext()) { cache.remove(key);
cache.remove(i.next());
} }
} }
@ -766,7 +764,7 @@ class InetAddress implements java.io.Serializable {
} else { } else {
expiration = System.currentTimeMillis() + (policy * 1000); expiration = System.currentTimeMillis() + (policy * 1000);
} }
CacheEntry entry = new CacheEntry(address, expiration); CacheEntry entry = new CacheEntry(addresses, expiration);
cache.put(host, entry); cache.put(host, entry);
return this; return this;
} }
@ -780,7 +778,7 @@ class InetAddress implements java.io.Serializable {
if (policy == InetAddressCachePolicy.NEVER) { if (policy == InetAddressCachePolicy.NEVER) {
return null; return null;
} }
CacheEntry entry = (CacheEntry)cache.get(host); CacheEntry entry = cache.get(host);
// check if entry has expired // check if entry has expired
if (entry != null && policy != InetAddressCachePolicy.FOREVER) { if (entry != null && policy != InetAddressCachePolicy.FOREVER) {
@ -814,42 +812,41 @@ class InetAddress implements java.io.Serializable {
} }
/* /*
* Cache the given hostname and address. * Cache the given hostname and addresses.
*/ */
private static void cacheAddress(String hostname, Object address, private static void cacheAddresses(String hostname,
boolean success) { InetAddress[] addresses,
boolean success) {
hostname = hostname.toLowerCase(); hostname = hostname.toLowerCase();
synchronized (addressCache) { synchronized (addressCache) {
cacheInitIfNeeded(); cacheInitIfNeeded();
if (success) { if (success) {
addressCache.put(hostname, address); addressCache.put(hostname, addresses);
} else { } else {
negativeCache.put(hostname, address); negativeCache.put(hostname, addresses);
} }
} }
} }
/* /*
* Lookup hostname in cache (positive & negative cache). If * Lookup hostname in cache (positive & negative cache). If
* found return address, null if not found. * found return addresses, null if not found.
*/ */
private static Object getCachedAddress(String hostname) { private static InetAddress[] getCachedAddresses(String hostname) {
hostname = hostname.toLowerCase(); hostname = hostname.toLowerCase();
// search both positive & negative caches // search both positive & negative caches
synchronized (addressCache) { synchronized (addressCache) {
CacheEntry entry;
cacheInitIfNeeded(); cacheInitIfNeeded();
entry = addressCache.get(hostname); CacheEntry entry = addressCache.get(hostname);
if (entry == null) { if (entry == null) {
entry = negativeCache.get(hostname); entry = negativeCache.get(hostname);
} }
if (entry != null) { if (entry != null) {
return entry.address; return entry.addresses;
} }
} }
@ -911,7 +908,7 @@ class InetAddress implements java.io.Serializable {
static { static {
// create the impl // create the impl
impl = (new InetAddressImplFactory()).create(); impl = InetAddressImplFactory.create();
// get name service if provided and requested // get name service if provided and requested
String provider = null;; String provider = null;;
@ -931,7 +928,7 @@ class InetAddress implements java.io.Serializable {
} }
// if not designate any name services provider, // if not designate any name services provider,
// creat a default one // create a default one
if (nameServices.size() == 0) { if (nameServices.size() == 0) {
NameService ns = createNSProvider("default"); NameService ns = createNSProvider("default");
nameServices.add(ns); nameServices.add(ns);
@ -939,7 +936,7 @@ class InetAddress implements java.io.Serializable {
} }
/** /**
* Create an InetAddress based on the provided host name and IP address * Creates an InetAddress based on the provided host name and IP address.
* No name service is checked for the validity of the address. * No name service is checked for the validity of the address.
* *
* <p> The host name can either be a machine name, such as * <p> The host name can either be a machine name, such as
@ -1067,13 +1064,13 @@ class InetAddress implements java.io.Serializable {
boolean ipv6Expected = false; boolean ipv6Expected = false;
if (host.charAt(0) == '[') { if (host.charAt(0) == '[') {
// This is supposed to be an IPv6 litteral // This is supposed to be an IPv6 literal
if (host.length() > 2 && host.charAt(host.length()-1) == ']') { if (host.length() > 2 && host.charAt(host.length()-1) == ']') {
host = host.substring(1, host.length() -1); host = host.substring(1, host.length() -1);
ipv6Expected = true; ipv6Expected = true;
} else { } else {
// This was supposed to be a IPv6 address, but it's not! // This was supposed to be a IPv6 address, but it's not!
throw new UnknownHostException(host); throw new UnknownHostException(host + ": invalid IPv6 address");
} }
} }
@ -1180,8 +1177,6 @@ class InetAddress implements java.io.Serializable {
throws UnknownHostException { throws UnknownHostException {
/* If it gets here it is presumed to be a hostname */ /* If it gets here it is presumed to be a hostname */
/* Cache.get can return: null, unknownAddress, or InetAddress[] */ /* Cache.get can return: null, unknownAddress, or InetAddress[] */
Object obj = null;
Object objcopy = null;
/* make sure the connection to the host is allowed, before we /* make sure the connection to the host is allowed, before we
* give out a hostname * give out a hostname
@ -1193,26 +1188,23 @@ class InetAddress implements java.io.Serializable {
} }
} }
obj = getCachedAddress(host); InetAddress[] addresses = getCachedAddresses(host);
/* If no entry in cache, then do the host lookup */ /* If no entry in cache, then do the host lookup */
if (obj == null) { if (addresses == null) {
obj = getAddressFromNameService(host); addresses = getAddressesFromNameService(host);
} }
if (obj == unknown_array) if (addresses == unknown_array)
throw new UnknownHostException(host); throw new UnknownHostException(host);
/* Make a copy of the InetAddress array */ return addresses.clone();
objcopy = ((InetAddress [])obj).clone();
return (InetAddress [])objcopy;
} }
private static Object getAddressFromNameService(String host) private static InetAddress[] getAddressesFromNameService(String host)
throws UnknownHostException throws UnknownHostException
{ {
Object obj = null; InetAddress[] addresses = null;
boolean success = false; boolean success = false;
UnknownHostException ex = null; UnknownHostException ex = null;
@ -1226,16 +1218,16 @@ class InetAddress implements java.io.Serializable {
// would be blocked until the host is removed // would be blocked until the host is removed
// from the lookupTable. Then this thread // from the lookupTable. Then this thread
// should try to look up the addressCache. // should try to look up the addressCache.
// i) if it found the address in the // i) if it found the addresses in the
// addressCache, checkLookupTable() would // addressCache, checkLookupTable() would
// return the address. // return the addresses.
// ii) if it didn't find the address in the // ii) if it didn't find the addresses in the
// addressCache for any reason, // addressCache for any reason,
// it should add the host in the // it should add the host in the
// lookupTable and return null so the // lookupTable and return null so the
// following code would do a lookup itself. // following code would do a lookup itself.
if ((obj = checkLookupTable(host)) == null) { if ((addresses = checkLookupTable(host)) == null) {
// This is the first thread which looks up the address // This is the first thread which looks up the addresses
// this host or the cache entry for this host has been // this host or the cache entry for this host has been
// expired so this thread should do the lookup. // expired so this thread should do the lookup.
for (NameService nameService : nameServices) { for (NameService nameService : nameServices) {
@ -1246,26 +1238,26 @@ class InetAddress implements java.io.Serializable {
* allocating space when the lookup fails. * allocating space when the lookup fails.
*/ */
obj = nameService.lookupAllHostAddr(host); addresses = nameService.lookupAllHostAddr(host);
success = true; success = true;
break; break;
} catch (UnknownHostException uhe) { } catch (UnknownHostException uhe) {
if (host.equalsIgnoreCase("localhost")) { if (host.equalsIgnoreCase("localhost")) {
InetAddress[] local = new InetAddress[] { impl.loopbackAddress() }; InetAddress[] local = new InetAddress[] { impl.loopbackAddress() };
obj = local; addresses = local;
success = true; success = true;
break; break;
} }
else { else {
obj = unknown_array; addresses = unknown_array;
success = false; success = false;
ex = uhe; ex = uhe;
} }
} }
} }
// Cache the address. // Cache the addresses.
cacheAddress(host, obj, success); cacheAddresses(host, addresses, success);
// Delete the host from the lookupTable, and // Delete the host from the lookupTable, and
// notify all threads waiting for the monitor // notify all threads waiting for the monitor
// for lookupTable. // for lookupTable.
@ -1274,13 +1266,13 @@ class InetAddress implements java.io.Serializable {
throw ex; throw ex;
} }
return obj; return addresses;
} }
private static Object checkLookupTable(String host) { private static InetAddress[] checkLookupTable(String host) {
// make sure obj is null. // make sure addresses is null.
Object obj = null; InetAddress[] addresses = null;
synchronized (lookupTable) { synchronized (lookupTable) {
// If the host isn't in the lookupTable, add it in the // If the host isn't in the lookupTable, add it in the
@ -1288,11 +1280,11 @@ class InetAddress implements java.io.Serializable {
// the lookup. // the lookup.
if (lookupTable.containsKey(host) == false) { if (lookupTable.containsKey(host) == false) {
lookupTable.put(host, null); lookupTable.put(host, null);
return obj; return addresses;
} }
// If the host is in the lookupTable, it means that another // If the host is in the lookupTable, it means that another
// thread is trying to look up the address of this host. // thread is trying to look up the addresses of this host.
// This thread should wait. // This thread should wait.
while (lookupTable.containsKey(host)) { while (lookupTable.containsKey(host)) {
try { try {
@ -1302,18 +1294,18 @@ class InetAddress implements java.io.Serializable {
} }
} }
// The other thread has finished looking up the address of // The other thread has finished looking up the addresses of
// the host. This thread should retry to get the address // the host. This thread should retry to get the addresses
// from the addressCache. If it doesn't get the address from // from the addressCache. If it doesn't get the addresses from
// the cache, it will try to look up the address itself. // the cache, it will try to look up the addresses itself.
obj = getCachedAddress(host); addresses = getCachedAddresses(host);
if (obj == null) { if (addresses == null) {
synchronized (lookupTable) { synchronized (lookupTable) {
lookupTable.put(host, null); lookupTable.put(host, null);
} }
} }
return obj; return addresses;
} }
private static void updateLookupTable(String host) { private static void updateLookupTable(String host) {
@ -1396,15 +1388,20 @@ class InetAddress implements java.io.Serializable {
cachedLocalHost = null; cachedLocalHost = null;
} }
// we are calling getAddressFromNameService directly // we are calling getAddressesFromNameService directly
// to avoid getting localHost from cache // to avoid getting localHost from cache
if (ret == null) { if (ret == null) {
InetAddress[] localAddrs; InetAddress[] localAddrs;
try { try {
localAddrs = localAddrs =
(InetAddress[]) InetAddress.getAddressFromNameService(local); InetAddress.getAddressesFromNameService(local);
} catch (UnknownHostException uhe) { } catch (UnknownHostException uhe) {
throw new UnknownHostException(local + ": " + uhe.getMessage()); // Rethrow with a more informative error message.
UnknownHostException uhe2 =
new UnknownHostException(local + ": " +
uhe.getMessage());
uhe2.initCause(uhe);
throw uhe2;
} }
cachedLocalHost = localAddrs[0]; cachedLocalHost = localAddrs[0];
cacheTime = now; cacheTime = now;
@ -1434,8 +1431,8 @@ class InetAddress implements java.io.Serializable {
/* /*
* Load and instantiate an underlying impl class * Load and instantiate an underlying impl class
*/ */
static Object loadImpl(String implName) { static InetAddressImpl loadImpl(String implName) {
Object impl; Object impl = null;
/* /*
* Property "impl.prefix" will be prepended to the classname * Property "impl.prefix" will be prepended to the classname
@ -1446,7 +1443,6 @@ class InetAddress implements java.io.Serializable {
*/ */
String prefix = AccessController.doPrivileged( String prefix = AccessController.doPrivileged(
new GetPropertyAction("impl.prefix", "")); new GetPropertyAction("impl.prefix", ""));
impl = null;
try { try {
impl = Class.forName("java.net." + prefix + implName).newInstance(); impl = Class.forName("java.net." + prefix + implName).newInstance();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
@ -1471,7 +1467,7 @@ class InetAddress implements java.io.Serializable {
} }
} }
return impl; return (InetAddressImpl) impl;
} }
private void readObjectNoData (ObjectInputStream s) throws private void readObjectNoData (ObjectInputStream s) throws
@ -1498,13 +1494,8 @@ class InetAddress implements java.io.Serializable {
class InetAddressImplFactory { class InetAddressImplFactory {
static InetAddressImpl create() { static InetAddressImpl create() {
Object o; return InetAddress.loadImpl(isIPv6Supported() ?
if (isIPv6Supported()) { "Inet6AddressImpl" : "Inet4AddressImpl");
o = InetAddress.loadImpl("Inet6AddressImpl");
} else {
o = InetAddress.loadImpl("Inet4AddressImpl");
}
return (InetAddressImpl)o;
} }
static native boolean isIPv6Supported(); static native boolean isIPv6Supported();

View File

@ -0,0 +1,50 @@
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.file;
/**
* Checked exception thrown when a file system loop, or cycle, is encountered.
*
* @since 1.7
* @see Files#walkFileTree
*/
public class FileSystemLoopException
extends FileSystemException
{
private static final long serialVersionUID = 4843039591949217617L;
/**
* Constructs an instance of this class.
*
* @param file
* a string identifying the file causing the cycle or {@code null} if
* not known
*/
public FileSystemLoopException(String file) {
super(file);
}
}

View File

@ -38,7 +38,6 @@ import sun.nio.fs.BasicFileAttributesHolder;
class FileTreeWalker { class FileTreeWalker {
private final boolean followLinks; private final boolean followLinks;
private final boolean detectCycles;
private final LinkOption[] linkOptions; private final LinkOption[] linkOptions;
private final FileVisitor<? super Path> visitor; private final FileVisitor<? super Path> visitor;
private final int maxDepth; private final int maxDepth;
@ -48,17 +47,15 @@ class FileTreeWalker {
int maxDepth) int maxDepth)
{ {
boolean fl = false; boolean fl = false;
boolean dc = false;
for (FileVisitOption option: options) { for (FileVisitOption option: options) {
// will throw NPE if options contains null
switch (option) { switch (option) {
case FOLLOW_LINKS : fl = true; break; case FOLLOW_LINKS : fl = true; break;
case DETECT_CYCLES : dc = true; break;
default: default:
throw new AssertionError("Should not get here"); throw new AssertionError("Should not get here");
} }
} }
this.followLinks = fl; this.followLinks = fl;
this.detectCycles = fl | dc;
this.linkOptions = (fl) ? new LinkOption[0] : this.linkOptions = (fl) ? new LinkOption[0] :
new LinkOption[] { LinkOption.NOFOLLOW_LINKS }; new LinkOption[] { LinkOption.NOFOLLOW_LINKS };
this.visitor = visitor; this.visitor = visitor;
@ -68,13 +65,11 @@ class FileTreeWalker {
/** /**
* Walk file tree starting at the given file * Walk file tree starting at the given file
*/ */
void walk(Path start) { void walk(Path start) throws IOException {
FileVisitResult result = walk(start, FileVisitResult result = walk(start,
0, 0,
new ArrayList<AncestorDirectory>()); new ArrayList<AncestorDirectory>());
if (result == null) { Objects.nonNull(result, "FileVisitor returned null");
throw new NullPointerException("Visitor returned 'null'");
}
} }
/** /**
@ -88,11 +83,8 @@ class FileTreeWalker {
private FileVisitResult walk(Path file, private FileVisitResult walk(Path file,
int depth, int depth,
List<AncestorDirectory> ancestors) List<AncestorDirectory> ancestors)
throws IOException
{ {
// depth check
if (depth > maxDepth)
return FileVisitResult.CONTINUE;
// if attributes are cached then use them if possible // if attributes are cached then use them if possible
BasicFileAttributes attrs = null; BasicFileAttributes attrs = null;
if ((depth > 0) && if ((depth > 0) &&
@ -137,13 +129,13 @@ class FileTreeWalker {
return visitor.visitFileFailed(file, exc); return visitor.visitFileFailed(file, exc);
} }
// file is not a directory so invoke visitFile method // at maximum depth or file is not a directory
if (!attrs.isDirectory()) { if (depth >= maxDepth || !attrs.isDirectory()) {
return visitor.visitFile(file, attrs); return visitor.visitFile(file, attrs);
} }
// check for cycles // check for cycles when following links
if (detectCycles) { if (followLinks) {
Object key = attrs.fileKey(); Object key = attrs.fileKey();
// if this directory and ancestor has a file key then we compare // if this directory and ancestor has a file key then we compare
@ -153,19 +145,23 @@ class FileTreeWalker {
if (key != null && ancestorKey != null) { if (key != null && ancestorKey != null) {
if (key.equals(ancestorKey)) { if (key.equals(ancestorKey)) {
// cycle detected // cycle detected
return visitor.visitFile(file, attrs); return visitor.visitFileFailed(file,
new FileSystemLoopException(file.toString()));
} }
} else { } else {
boolean isSameFile = false;
try { try {
if (file.isSameFile(ancestor.file())) { isSameFile = file.isSameFile(ancestor.file());
// cycle detected
return visitor.visitFile(file, attrs);
}
} catch (IOException x) { } catch (IOException x) {
// ignore // ignore
} catch (SecurityException x) { } catch (SecurityException x) {
// ignore // ignore
} }
if (isSameFile) {
// cycle detected
return visitor.visitFileFailed(file,
new FileSystemLoopException(file.toString()));
}
} }
} }
@ -181,7 +177,7 @@ class FileTreeWalker {
try { try {
stream = file.newDirectoryStream(); stream = file.newDirectoryStream();
} catch (IOException x) { } catch (IOException x) {
return visitor.preVisitDirectoryFailed(file, x); return visitor.visitFileFailed(file, x);
} catch (SecurityException x) { } catch (SecurityException x) {
// ignore, as per spec // ignore, as per spec
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
@ -192,20 +188,14 @@ class FileTreeWalker {
// invoke preVisitDirectory and then visit each entry // invoke preVisitDirectory and then visit each entry
try { try {
result = visitor.preVisitDirectory(file); result = visitor.preVisitDirectory(file, attrs);
if (result != FileVisitResult.CONTINUE) { if (result != FileVisitResult.CONTINUE) {
return result; return result;
} }
// if an I/O occurs during iteration then a CME is thrown. We
// need to distinguish this from a CME thrown by the visitor.
boolean inAction = false;
try { try {
for (Path entry: stream) { for (Path entry: stream) {
inAction = true;
result = walk(entry, depth+1, ancestors); result = walk(entry, depth+1, ancestors);
inAction = false;
// returning null will cause NPE to be thrown // returning null will cause NPE to be thrown
if (result == null || result == FileVisitResult.TERMINATE) if (result == null || result == FileVisitResult.TERMINATE)
@ -215,17 +205,9 @@ class FileTreeWalker {
if (result == FileVisitResult.SKIP_SIBLINGS) if (result == FileVisitResult.SKIP_SIBLINGS)
break; break;
} }
} catch (ConcurrentModificationException x) { } catch (DirectoryIteratorException e) {
// if CME thrown because the iteration failed then remember // IOException will be notified to postVisitDirectory
// the IOException so that it is notified to postVisitDirectory ioe = e.getCause();
if (!inAction) {
// iteration failed
Throwable t = x.getCause();
if (t instanceof IOException)
ioe = (IOException)t;
}
if (ioe == null)
throw x;
} }
} finally { } finally {
try { try {
@ -238,7 +220,7 @@ class FileTreeWalker {
} finally { } finally {
// remove key from trail if doing cycle detection // remove key from trail if doing cycle detection
if (detectCycles) { if (followLinks) {
ancestors.remove(ancestors.size()-1); ancestors.remove(ancestors.size()-1);
} }
} }

View File

@ -37,9 +37,5 @@ public enum FileVisitOption {
/** /**
* Follow symbolic links. * Follow symbolic links.
*/ */
FOLLOW_LINKS, FOLLOW_LINKS;
/**
* Detect cycles in the file tree.
*/
DETECT_CYCLES;
} }

View File

@ -40,33 +40,28 @@ import java.io.IOException;
* Path start = ... * Path start = ...
* Files.walkFileTree(start, new SimpleFileVisitor&lt;Path&gt;() { * Files.walkFileTree(start, new SimpleFileVisitor&lt;Path&gt;() {
* &#64;Override * &#64;Override
* public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { * public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
* try { * throws IOException
* file.delete(); * {
* } catch (IOException exc) { * file.delete();
* // failed to delete, do error handling here
* }
* return FileVisitResult.CONTINUE; * return FileVisitResult.CONTINUE;
* } * }
* &#64;Override * &#64;Override
* public FileVisitResult postVisitDirectory(Path dir, IOException e) { * public FileVisitResult postVisitDirectory(Path dir, IOException e)
* if (e == null) { * throws IOException
* try { * {
* dir.delete(); * if (e != null) {
* } catch (IOException exc) {
* // failed to delete, do error handling here
* }
* } else {
* // directory iteration failed * // directory iteration failed
* throw e;
* } * }
* dir.delete();
* return FileVisitResult.CONTINUE; * return FileVisitResult.CONTINUE;
* } * }
* }); * });
* </pre> * </pre>
* <p> Furthermore, suppose we want to copy a file tree rooted at a source * <p> Furthermore, suppose we want to copy a file tree to a target location.
* directory to a target location. In that case, symbolic links should be * In that case, symbolic links should be followed and the target directory
* followed and the target directory should be created before the entries in * should be created before the entries in the directory are copied.
* the directory are copied.
* <pre> * <pre>
* final Path source = ... * final Path source = ...
* final Path target = ... * final Path target = ...
@ -74,25 +69,21 @@ import java.io.IOException;
* Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, * Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
* new SimpleFileVisitor&lt;Path&gt;() { * new SimpleFileVisitor&lt;Path&gt;() {
* &#64;Override * &#64;Override
* public FileVisitResult preVisitDirectory(Path dir) { * public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
* throws IOException
* {
* try { * try {
* dir.copyTo(target.resolve(source.relativize(dir))); * dir.copyTo(target.resolve(source.relativize(dir)));
* } catch (FileAlreadyExistsException e) { * } catch (FileAlreadyExistsException e) {
* // ignore * // ignore
* } catch (IOException e) {
* // copy failed, do error handling here
* // skip rest of directory and descendants
* return SKIP_SUBTREE;
* } * }
* return CONTINUE; * return CONTINUE;
* } * }
* &#64;Override * &#64;Override
* public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { * public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
* try { * throws IOException
* file.copyTo(target.resolve(source.relativize(file))); * {
* } catch (IOException e) { * file.copyTo(target.resolve(source.relativize(file)));
* // copy failed, do error handling here
* }
* return CONTINUE; * return CONTINUE;
* } * }
* }); * });
@ -114,22 +105,16 @@ public interface FileVisitor<T> {
* *
* @param dir * @param dir
* a reference to the directory * a reference to the directory
* @param attrs
* the directory's basic attributes
* *
* @return the visit result * @return the visit result
*/
FileVisitResult preVisitDirectory(T dir);
/**
* Invoked for a directory that could not be opened.
* *
* @param dir * @throws IOException
* a reference to the directory * if an I/O error occurs
* @param exc
* the I/O exception thrown from the attempt to open the directory
*
* @return the visit result
*/ */
FileVisitResult preVisitDirectoryFailed(T dir, IOException exc); FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs)
throws IOException;
/** /**
* Invoked for a file in a directory. * Invoked for a file in a directory.
@ -140,21 +125,30 @@ public interface FileVisitor<T> {
* the file's basic attributes * the file's basic attributes
* *
* @return the visit result * @return the visit result
*
* @throws IOException
* if an I/O error occurs
*/ */
FileVisitResult visitFile(T file, BasicFileAttributes attrs); FileVisitResult visitFile(T file, BasicFileAttributes attrs)
throws IOException;
/** /**
* Invoked for a file when its basic file attributes could not be read. * Invoked for a file that could not be visited. This method is invoked
* if the file's attributes could not be read, the file is a directory
* that could not be opened, and other reasons.
* *
* @param file * @param file
* a reference to the file * a reference to the file
* @param exc * @param exc
* the I/O exception thrown from the attempt to read the file * the I/O exception that prevented the file from being visited
* attributes
* *
* @return the visit result * @return the visit result
*
* @throws IOException
* if an I/O error occurs
*/ */
FileVisitResult visitFileFailed(T file, IOException exc); FileVisitResult visitFileFailed(T file, IOException exc)
throws IOException;
/** /**
* Invoked for a directory after entries in the directory, and all of their * Invoked for a directory after entries in the directory, and all of their
@ -171,6 +165,10 @@ public interface FileVisitor<T> {
* of the directory to complete prematurely * of the directory to complete prematurely
* *
* @return the visit result * @return the visit result
*
* @throws IOException
* if an I/O error occurs
*/ */
FileVisitResult postVisitDirectory(T dir, IOException exc); FileVisitResult postVisitDirectory(T dir, IOException exc)
throws IOException;
} }

View File

@ -135,9 +135,9 @@ public final class Files {
* FileVisitor} invoked for each file encountered. File tree traversal * FileVisitor} invoked for each file encountered. File tree traversal
* completes when all accessible files in the tree have been visited, or a * completes when all accessible files in the tree have been visited, or a
* visit method returns a result of {@link FileVisitResult#TERMINATE * visit method returns a result of {@link FileVisitResult#TERMINATE
* TERMINATE}. Where a visit method terminates due an uncaught error or * TERMINATE}. Where a visit method terminates due an {@code IOException},
* runtime exception then the traversal is terminated and the error or * an uncaught error, or runtime exception, then the traversal is terminated
* exception is propagated to the caller of this method. * and the error or exception is propagated to the caller of this method.
* *
* <p> For each file encountered this method attempts to gets its {@link * <p> For each file encountered this method attempts to gets its {@link
* java.nio.file.attribute.BasicFileAttributes}. If the file is not a * java.nio.file.attribute.BasicFileAttributes}. If the file is not a
@ -146,12 +146,10 @@ public final class Files {
* due to an I/O exception, then the {@link FileVisitor#visitFileFailed * due to an I/O exception, then the {@link FileVisitor#visitFileFailed
* visitFileFailed} method is invoked with the I/O exception. * visitFileFailed} method is invoked with the I/O exception.
* *
* <p> Where the file is a directory, this method attempts to open it by * <p> Where the file is a directory, and the directory could not be opened,
* invoking its {@link Path#newDirectoryStream newDirectoryStream} method. * then the {@code visitFileFailed} method is invoked with the I/O exception,
* Where the directory could not be opened, due to an {@code IOException}, * after which, the file tree walk continues, by default, at the next
* then the {@link FileVisitor#preVisitDirectoryFailed preVisitDirectoryFailed} * <em>sibling</em> of the directory.
* method is invoked with the I/O exception, after which, the file tree walk
* continues, by default, at the next <em>sibling</em> of the directory.
* *
* <p> Where the directory is opened successfully, then the entries in the * <p> Where the directory is opened successfully, then the entries in the
* directory, and their <em>descendants</em> are visited. When all entries * directory, and their <em>descendants</em> are visited. When all entries
@ -171,26 +169,25 @@ public final class Files {
* method is invoked as specified above). * method is invoked as specified above).
* *
* <p> If the {@code options} parameter contains the {@link * <p> If the {@code options} parameter contains the {@link
* FileVisitOption#DETECT_CYCLES DETECT_CYCLES} or {@link * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then this method keeps
* FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} options then this method keeps
* track of directories visited so that cycles can be detected. A cycle * track of directories visited so that cycles can be detected. A cycle
* arises when there is an entry in a directory that is an ancestor of the * arises when there is an entry in a directory that is an ancestor of the
* directory. Cycle detection is done by recording the {@link * directory. Cycle detection is done by recording the {@link
* java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories, * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories,
* or if file keys are not available, by invoking the {@link Path#isSameFile * or if file keys are not available, by invoking the {@link Path#isSameFile
* isSameFile} method to test if a directory is the same file as an * isSameFile} method to test if a directory is the same file as an
* ancestor. When a cycle is detected the {@link FileVisitor#visitFile * ancestor. When a cycle is detected it is treated as an I/O error, and the
* visitFile} is invoked with the attributes of the directory. The {@link * {@link FileVisitor#visitFileFailed visitFileFailed} method is invoked with
* java.nio.file.attribute.BasicFileAttributes#isDirectory isDirectory} * an instance of {@link FileSystemLoopException}.
* method may be used to test if the file is a directory and that a cycle is
* detected. The {@code preVisitDirectory} and {@code postVisitDirectory}
* methods are not invoked.
* *
* <p> The {@code maxDepth} parameter is the maximum number of levels of * <p> The {@code maxDepth} parameter is the maximum number of levels of
* directories to visit. A value of {@code 0} means that only the starting * directories to visit. A value of {@code 0} means that only the starting
* file is visited, unless denied by the security manager. A value of * file is visited, unless denied by the security manager. A value of
* {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all
* levels should be visited. * levels should be visited. The {@code visitFile} method is invoked for all
* files, including directories, encountered at {@code maxDepth}, unless the
* basic file attributes cannot be read, in which case the {@code
* visitFileFailed} method is invoked.
* *
* <p> If a visitor returns a result of {@code null} then {@code * <p> If a visitor returns a result of {@code null} then {@code
* NullPointerException} is thrown. * NullPointerException} is thrown.
@ -215,11 +212,14 @@ public final class Files {
* In the case of the default provider, the {@link * In the case of the default provider, the {@link
* SecurityManager#checkRead(String) checkRead} method is invoked * SecurityManager#checkRead(String) checkRead} method is invoked
* to check read access to the directory. * to check read access to the directory.
* @throws IOException
* If an I/O error is thrown by a visitor method
*/ */
public static void walkFileTree(Path start, public static void walkFileTree(Path start,
Set<FileVisitOption> options, Set<FileVisitOption> options,
int maxDepth, int maxDepth,
FileVisitor<? super Path> visitor) FileVisitor<? super Path> visitor)
throws IOException
{ {
if (maxDepth < 0) if (maxDepth < 0)
throw new IllegalArgumentException("'maxDepth' is negative"); throw new IllegalArgumentException("'maxDepth' is negative");
@ -245,8 +245,12 @@ public final class Files {
* In the case of the default provider, the {@link * In the case of the default provider, the {@link
* SecurityManager#checkRead(String) checkRead} method is invoked * SecurityManager#checkRead(String) checkRead} method is invoked
* to check read access to the directory. * to check read access to the directory.
* @throws IOException
* If an I/O error is thrown by a visitor method
*/ */
public static void walkFileTree(Path start, FileVisitor<? super Path> visitor) { public static void walkFileTree(Path start, FileVisitor<? super Path> visitor)
throws IOException
{
walkFileTree(start, walkFileTree(start,
EnumSet.noneOf(FileVisitOption.class), EnumSet.noneOf(FileVisitOption.class),
Integer.MAX_VALUE, Integer.MAX_VALUE,

View File

@ -27,7 +27,7 @@ package java.nio.file;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.io.IOException; import java.io.IOException;
import java.io.IOError; import java.util.Objects;
/** /**
* A simple visitor of files with default behavior to visit all files and to * A simple visitor of files with default behavior to visit all files and to
@ -47,14 +47,6 @@ public class SimpleFileVisitor<T> implements FileVisitor<T> {
protected SimpleFileVisitor() { protected SimpleFileVisitor() {
} }
/**
* Throws NullPointerException if obj is null.
*/
private static void checkNotNull(Object obj) {
if (obj == null)
throw new NullPointerException();
}
/** /**
* Invoked for a directory before entries in the directory are visited. * Invoked for a directory before entries in the directory are visited.
* *
@ -62,28 +54,14 @@ public class SimpleFileVisitor<T> implements FileVisitor<T> {
* CONTINUE}. * CONTINUE}.
*/ */
@Override @Override
public FileVisitResult preVisitDirectory(T dir) { public FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs)
checkNotNull(dir); throws IOException
{
Objects.nonNull(dir);
Objects.nonNull(attrs);
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
/**
* Invoked for a directory that could not be opened.
*
* <p> Unless overridden, this method throws {@link IOError} with the I/O
* exception as cause.
*
* @throws IOError
* with the I/O exception thrown when the attempt to open the
* directory failed
*/
@Override
public FileVisitResult preVisitDirectoryFailed(T dir, IOException exc) {
checkNotNull(dir);
checkNotNull(exc);
throw new IOError(exc);
}
/** /**
* Invoked for a file in a directory. * Invoked for a file in a directory.
* *
@ -91,27 +69,26 @@ public class SimpleFileVisitor<T> implements FileVisitor<T> {
* CONTINUE}. * CONTINUE}.
*/ */
@Override @Override
public FileVisitResult visitFile(T file, BasicFileAttributes attrs) { public FileVisitResult visitFile(T file, BasicFileAttributes attrs)
checkNotNull(file); throws IOException
checkNotNull(attrs); {
Objects.nonNull(file);
Objects.nonNull(attrs);
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
/** /**
* Invoked for a file when its basic file attributes could not be read. * Invoked for a file that could not be visited.
* *
* <p> Unless overridden, this method throws {@link IOError} with the I/O * <p> Unless overridden, this method re-throws the I/O exception that prevented
* exception as cause. * the file from being visited.
*
* @throws IOError
* with the I/O exception thrown when the attempt to read the file
* attributes failed
*/ */
@Override @Override
public FileVisitResult visitFileFailed(T file, IOException exc) { public FileVisitResult visitFileFailed(T file, IOException exc)
checkNotNull(file); throws IOException
checkNotNull(exc); {
throw new IOError(exc); Objects.nonNull(file);
throw exc;
} }
/** /**
@ -120,18 +97,16 @@ public class SimpleFileVisitor<T> implements FileVisitor<T> {
* *
* <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE
* CONTINUE} if the directory iteration completes without an I/O exception; * CONTINUE} if the directory iteration completes without an I/O exception;
* otherwise this method throws {@link IOError} with the I/O exception as * otherwise this method re-throws the I/O exception that caused the iteration
* cause. * of the directory to terminate prematurely.
*
* @throws IOError
* with the I/O exception thrown when iteration of the directory
* completed prematurely due to an I/O error
*/ */
@Override @Override
public FileVisitResult postVisitDirectory(T dir, IOException exc) { public FileVisitResult postVisitDirectory(T dir, IOException exc)
checkNotNull(dir); throws IOException
{
Objects.nonNull(dir);
if (exc != null) if (exc != null)
throw new IOError(exc); throw exc;
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
} }

View File

@ -3643,7 +3643,7 @@ public interface DatabaseMetaData extends Wrapper {
/** /**
* Retrieves whether a generated key will always be returned if the column * Retrieves whether a generated key will always be returned if the column
* name(s) or indexe(s) specified for the auto generated key column(s) * name(s) or index(es) specified for the auto generated key column(s)
* are valid and the statement succeeds. The key that is returned may or * are valid and the statement succeeds. The key that is returned may or
* may not be based on the column(s) for the auto generated key. * may not be based on the column(s) for the auto generated key.
* Consult your JDBC driver documentation for additional details. * Consult your JDBC driver documentation for additional details.

View File

@ -1051,9 +1051,9 @@ public interface Statement extends Wrapper, AutoCloseable {
/** /**
* Returns a value indicating whether this {@code Statement} will be * Returns a value indicating whether this {@code Statement} will be
* closed when all dependent objects such as resultsets are closed. * closed when all its dependent result sets are closed.
* @return {@code true} if the {@code Statement} will be closed when all * @return {@code true} if the {@code Statement} will be closed when all
* of its dependent objects are closed; {@code false} otherwise * of its dependent result sets are closed; {@code false} otherwise
* @throws SQLException if this method is called on a closed * @throws SQLException if this method is called on a closed
* {@code Statement} * {@code Statement}
* @since 1.7 * @since 1.7

View File

@ -569,6 +569,9 @@ public final class Locale implements Cloneable, Serializable {
* @exception NullPointerException thrown if any argument is null. * @exception NullPointerException thrown if any argument is null.
*/ */
public Locale(String language, String country, String variant) { public Locale(String language, String country, String variant) {
if (language== null || country == null || variant == null) {
throw new NullPointerException();
}
_baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant); _baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant);
_extensions = getCompatibilityExtensions(language, "", country, variant); _extensions = getCompatibilityExtensions(language, "", country, variant);
} }

View File

@ -292,16 +292,6 @@ public abstract class ResourceBundle {
private static final ConcurrentMap<CacheKey, BundleReference> cacheList private static final ConcurrentMap<CacheKey, BundleReference> cacheList
= new ConcurrentHashMap<CacheKey, BundleReference>(INITIAL_CACHE_SIZE); = new ConcurrentHashMap<CacheKey, BundleReference>(INITIAL_CACHE_SIZE);
/**
* This ConcurrentMap is used to keep multiple threads from loading the
* same bundle concurrently. The table entries are <CacheKey, Thread>
* where CacheKey is the key for the bundle that is under construction
* and Thread is the thread that is constructing the bundle.
* This list is manipulated in findBundleInCache and putBundleInCache.
*/
private static final ConcurrentMap<CacheKey, Thread> underConstruction
= new ConcurrentHashMap<CacheKey, Thread>();
/** /**
* Queue for reference objects referring to class loaders or bundles. * Queue for reference objects referring to class loaders or bundles.
*/ */
@ -1381,7 +1371,7 @@ public abstract class ResourceBundle {
boolean expiredBundle = false; boolean expiredBundle = false;
// First, look up the cache to see if it's in the cache, without // First, look up the cache to see if it's in the cache, without
// declaring beginLoading. // attempting to load bundle.
cacheKey.setLocale(targetLocale); cacheKey.setLocale(targetLocale);
ResourceBundle bundle = findBundleInCache(cacheKey, control); ResourceBundle bundle = findBundleInCache(cacheKey, control);
if (isValidBundle(bundle)) { if (isValidBundle(bundle)) {
@ -1408,56 +1398,25 @@ public abstract class ResourceBundle {
CacheKey constKey = (CacheKey) cacheKey.clone(); CacheKey constKey = (CacheKey) cacheKey.clone();
try { try {
// Try declaring loading. If beginLoading() returns true, bundle = loadBundle(cacheKey, formats, control, expiredBundle);
// then we can proceed. Otherwise, we need to take a look if (bundle != null) {
// at the cache again to see if someone else has loaded if (bundle.parent == null) {
// the bundle and put it in the cache while we've been bundle.setParent(parent);
// waiting for other loading work to complete.
while (!beginLoading(constKey)) {
bundle = findBundleInCache(cacheKey, control);
if (bundle == null) {
continue;
}
if (bundle == NONEXISTENT_BUNDLE) {
// If the bundle is NONEXISTENT_BUNDLE, the bundle doesn't exist.
return parent;
}
expiredBundle = bundle.expired;
if (!expiredBundle) {
if (bundle.parent == parent) {
return bundle;
}
BundleReference bundleRef = cacheList.get(cacheKey);
if (bundleRef != null && bundleRef.get() == bundle) {
cacheList.remove(cacheKey, bundleRef);
}
} }
bundle.locale = targetLocale;
bundle = putBundleInCache(cacheKey, bundle, control);
return bundle;
} }
try { // Put NONEXISTENT_BUNDLE in the cache as a mark that there's no bundle
bundle = loadBundle(cacheKey, formats, control, expiredBundle); // instance for the locale.
if (bundle != null) { putBundleInCache(cacheKey, NONEXISTENT_BUNDLE, control);
if (bundle.parent == null) {
bundle.setParent(parent);
}
bundle.locale = targetLocale;
bundle = putBundleInCache(cacheKey, bundle, control);
return bundle;
}
// Put NONEXISTENT_BUNDLE in the cache as a mark that there's no bundle
// instance for the locale.
putBundleInCache(cacheKey, NONEXISTENT_BUNDLE, control);
} finally {
endLoading(constKey);
}
} finally { } finally {
if (constKey.getCause() instanceof InterruptedException) { if (constKey.getCause() instanceof InterruptedException) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
} }
assert underConstruction.get(cacheKey) != Thread.currentThread();
return parent; return parent;
} }
@ -1465,7 +1424,6 @@ public abstract class ResourceBundle {
List<String> formats, List<String> formats,
Control control, Control control,
boolean reload) { boolean reload) {
assert underConstruction.get(cacheKey) == Thread.currentThread();
// Here we actually load the bundle in the order of formats // Here we actually load the bundle in the order of formats
// specified by the getFormats() value. // specified by the getFormats() value.
@ -1498,7 +1456,6 @@ public abstract class ResourceBundle {
break; break;
} }
} }
assert underConstruction.get(cacheKey) == Thread.currentThread();
return bundle; return bundle;
} }
@ -1529,57 +1486,6 @@ public abstract class ResourceBundle {
return true; return true;
} }
/**
* Declares the beginning of actual resource bundle loading. This method
* returns true if the declaration is successful and the current thread has
* been put in underConstruction. If someone else has already begun
* loading, this method waits until that loading work is complete and
* returns false.
*/
private static final boolean beginLoading(CacheKey constKey) {
Thread me = Thread.currentThread();
Thread worker;
// We need to declare by putting the current Thread (me) to
// underConstruction that we are working on loading the specified
// resource bundle. If we are already working the loading, it means
// that the resource loading requires a recursive call. In that case,
// we have to proceed. (4300693)
if (((worker = underConstruction.putIfAbsent(constKey, me)) == null)
|| worker == me) {
return true;
}
// If someone else is working on the loading, wait until
// the Thread finishes the bundle loading.
synchronized (worker) {
while (underConstruction.get(constKey) == worker) {
try {
worker.wait();
} catch (InterruptedException e) {
// record the interruption
constKey.setCause(e);
}
}
}
return false;
}
/**
* Declares the end of the bundle loading. This method calls notifyAll
* for those who are waiting for this completion.
*/
private static final void endLoading(CacheKey constKey) {
// Remove this Thread from the underConstruction map and wake up
// those who have been waiting for me to complete this bundle
// loading.
Thread me = Thread.currentThread();
assert (underConstruction.get(constKey) == me);
underConstruction.remove(constKey);
synchronized (me) {
me.notifyAll();
}
}
/** /**
* Throw a MissingResourceException with proper message * Throw a MissingResourceException with proper message
*/ */

File diff suppressed because it is too large Load Diff

View File

@ -28,9 +28,9 @@
* However, the following notice accompanied the original version of this * However, the following notice accompanied the original version of this
* file: * file:
* *
* Written by Doug Lea with assistance from members of JCP JSR-166 * Written by Doug Lea and Martin Buchholz with assistance from members of
* Expert Group and released to the public domain, as explained at * JCP JSR-166 Expert Group and released to the public domain, as explained
* http://creativecommons.org/licenses/publicdomain * at http://creativecommons.org/licenses/publicdomain
*/ */
package java.util.concurrent; package java.util.concurrent;
@ -53,7 +53,8 @@ import java.util.Queue;
* operations obtain elements at the head of the queue. * operations obtain elements at the head of the queue.
* A {@code ConcurrentLinkedQueue} is an appropriate choice when * A {@code ConcurrentLinkedQueue} is an appropriate choice when
* many threads will share access to a common collection. * many threads will share access to a common collection.
* This queue does not permit {@code null} elements. * Like most other concurrent collection implementations, this class
* does not permit the use of {@code null} elements.
* *
* <p>This implementation employs an efficient &quot;wait-free&quot; * <p>This implementation employs an efficient &quot;wait-free&quot;
* algorithm based on one described in <a * algorithm based on one described in <a
@ -61,14 +62,20 @@ import java.util.Queue;
* Fast, and Practical Non-Blocking and Blocking Concurrent Queue * Fast, and Practical Non-Blocking and Blocking Concurrent Queue
* Algorithms</a> by Maged M. Michael and Michael L. Scott. * Algorithms</a> by Maged M. Michael and Michael L. Scott.
* *
* <p>Iterators are <i>weakly consistent</i>, returning elements
* reflecting the state of the queue at some point at or since the
* creation of the iterator. They do <em>not</em> throw {@link
* ConcurrentModificationException}, and may proceed concurrently with
* other operations. Elements contained in the queue since the creation
* of the iterator will be returned exactly once.
*
* <p>Beware that, unlike in most collections, the {@code size} method * <p>Beware that, unlike in most collections, the {@code size} method
* is <em>NOT</em> a constant-time operation. Because of the * is <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these queues, determining the current number * asynchronous nature of these queues, determining the current number
* of elements requires a traversal of the elements. * of elements requires a traversal of the elements.
* *
* <p>This class and its iterator implement all of the * <p>This class and its iterator implement all of the <em>optional</em>
* <em>optional</em> methods of the {@link Collection} and {@link * methods of the {@link Queue} and {@link Iterator} interfaces.
* Iterator} interfaces.
* *
* <p>Memory consistency effects: As with other concurrent * <p>Memory consistency effects: As with other concurrent
* collections, actions in a thread prior to placing an object into a * collections, actions in a thread prior to placing an object into a
@ -132,9 +139,10 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
* *
* Both head and tail are permitted to lag. In fact, failing to * Both head and tail are permitted to lag. In fact, failing to
* update them every time one could is a significant optimization * update them every time one could is a significant optimization
* (fewer CASes). This is controlled by local "hops" variables * (fewer CASes). As with LinkedTransferQueue (see the internal
* that only trigger helping-CASes after experiencing multiple * documentation for that class), we use a slack threshold of two;
* lags. * that is, we update head/tail when the current pointer appears
* to be two or more steps away from the first/last node.
* *
* Since head and tail are updated concurrently and independently, * Since head and tail are updated concurrently and independently,
* it is possible for tail to lag behind head (why not)? * it is possible for tail to lag behind head (why not)?
@ -148,8 +156,8 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
* this is merely an optimization. * this is merely an optimization.
* *
* When constructing a Node (before enqueuing it) we avoid paying * When constructing a Node (before enqueuing it) we avoid paying
* for a volatile write to item by using lazySet instead of a * for a volatile write to item by using Unsafe.putObject instead
* normal write. This allows the cost of enqueue to be * of a normal write. This allows the cost of enqueue to be
* "one-and-a-half" CASes. * "one-and-a-half" CASes.
* *
* Both head and tail may or may not point to a Node with a * Both head and tail may or may not point to a Node with a
@ -161,38 +169,25 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
*/ */
private static class Node<E> { private static class Node<E> {
private volatile E item; volatile E item;
private volatile Node<E> next; volatile Node<E> next;
/**
* Constructs a new node. Uses relaxed write because item can
* only be seen after publication via casNext.
*/
Node(E item) { Node(E item) {
// Piggyback on imminent casNext() UNSAFE.putObject(this, itemOffset, item);
lazySetItem(item);
}
E getItem() {
return item;
} }
boolean casItem(E cmp, E val) { boolean casItem(E cmp, E val) {
return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val); return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
} }
void setItem(E val) {
item = val;
}
void lazySetItem(E val) {
UNSAFE.putOrderedObject(this, itemOffset, val);
}
void lazySetNext(Node<E> val) { void lazySetNext(Node<E> val) {
UNSAFE.putOrderedObject(this, nextOffset, val); UNSAFE.putOrderedObject(this, nextOffset, val);
} }
Node<E> getNext() {
return next;
}
boolean casNext(Node<E> cmp, Node<E> val) { boolean casNext(Node<E> cmp, Node<E> val) {
return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val); return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
} }
@ -219,7 +214,7 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
* - it is permitted for tail to lag behind head, that is, for tail * - it is permitted for tail to lag behind head, that is, for tail
* to not be reachable from head! * to not be reachable from head!
*/ */
private transient volatile Node<E> head = new Node<E>(null); private transient volatile Node<E> head;
/** /**
* A node from which the last node on list (that is, the unique * A node from which the last node on list (that is, the unique
@ -233,25 +228,41 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
* to not be reachable from head! * to not be reachable from head!
* - tail.next may or may not be self-pointing to tail. * - tail.next may or may not be self-pointing to tail.
*/ */
private transient volatile Node<E> tail = head; private transient volatile Node<E> tail;
/** /**
* Creates a {@code ConcurrentLinkedQueue} that is initially empty. * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
*/ */
public ConcurrentLinkedQueue() {} public ConcurrentLinkedQueue() {
head = tail = new Node<E>(null);
}
/** /**
* Creates a {@code ConcurrentLinkedQueue} * Creates a {@code ConcurrentLinkedQueue}
* initially containing the elements of the given collection, * initially containing the elements of the given collection,
* added in traversal order of the collection's iterator. * added in traversal order of the collection's iterator.
*
* @param c the collection of elements to initially contain * @param c the collection of elements to initially contain
* @throws NullPointerException if the specified collection or any * @throws NullPointerException if the specified collection or any
* of its elements are null * of its elements are null
*/ */
public ConcurrentLinkedQueue(Collection<? extends E> c) { public ConcurrentLinkedQueue(Collection<? extends E> c) {
for (E e : c) Node<E> h = null, t = null;
add(e); for (E e : c) {
checkNotNull(e);
Node<E> newNode = new Node<E>(e);
if (h == null)
h = t = newNode;
else {
t.lazySetNext(newNode);
t = newNode;
}
}
if (h == null)
h = t = new Node<E>(null);
head = h;
tail = t;
} }
// Have to override just to update the javadoc // Have to override just to update the javadoc
@ -266,13 +277,6 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
return offer(e); return offer(e);
} }
/**
* We don't bother to update head or tail pointers if fewer than
* HOPS links from "true" location. We assume that volatile
* writes are significantly more expensive than volatile reads.
*/
private static final int HOPS = 1;
/** /**
* Try to CAS head to p. If successful, repoint old head to itself * Try to CAS head to p. If successful, repoint old head to itself
* as sentinel for succ(), below. * as sentinel for succ(), below.
@ -288,7 +292,7 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
* stale pointer that is now off the list. * stale pointer that is now off the list.
*/ */
final Node<E> succ(Node<E> p) { final Node<E> succ(Node<E> p) {
Node<E> next = p.getNext(); Node<E> next = p.next;
return (p == next) ? head : next; return (p == next) ? head : next;
} }
@ -299,68 +303,75 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
* @throws NullPointerException if the specified element is null * @throws NullPointerException if the specified element is null
*/ */
public boolean offer(E e) { public boolean offer(E e) {
if (e == null) throw new NullPointerException(); checkNotNull(e);
Node<E> n = new Node<E>(e); final Node<E> newNode = new Node<E>(e);
retry:
for (;;) { for (Node<E> t = tail, p = t;;) {
Node<E> t = tail; Node<E> q = p.next;
Node<E> p = t; if (q == null) {
for (int hops = 0; ; hops++) { // p is last node
Node<E> next = succ(p); if (p.casNext(null, newNode)) {
if (next != null) { // Successful CAS is the linearization point
if (hops > HOPS && t != tail) // for e to become an element of this queue,
continue retry; // and for newNode to become "live".
p = next; if (p != t) // hop two nodes at a time
} else if (p.casNext(null, n)) { casTail(t, newNode); // Failure is OK.
if (hops >= HOPS)
casTail(t, n); // Failure is OK.
return true; return true;
} else {
p = succ(p);
} }
// Lost CAS race to another thread; re-read next
} }
else if (p == q)
// We have fallen off list. If tail is unchanged, it
// will also be off-list, in which case we need to
// jump to head, from which all live nodes are always
// reachable. Else the new tail is a better bet.
p = (t != (t = tail)) ? t : head;
else
// Check for tail updates after two hops.
p = (p != t && t != (t = tail)) ? t : q;
} }
} }
public E poll() { public E poll() {
Node<E> h = head; restartFromHead:
Node<E> p = h; for (;;) {
for (int hops = 0; ; hops++) { for (Node<E> h = head, p = h, q;;) {
E item = p.getItem(); E item = p.item;
if (item != null && p.casItem(item, null)) { if (item != null && p.casItem(item, null)) {
if (hops >= HOPS) { // Successful CAS is the linearization point
Node<E> q = p.getNext(); // for item to be removed from this queue.
updateHead(h, (q != null) ? q : p); if (p != h) // hop two nodes at a time
updateHead(h, ((q = p.next) != null) ? q : p);
return item;
} }
return item; else if ((q = p.next) == null) {
updateHead(h, p);
return null;
}
else if (p == q)
continue restartFromHead;
else
p = q;
} }
Node<E> next = succ(p);
if (next == null) {
updateHead(h, p);
break;
}
p = next;
} }
return null;
} }
public E peek() { public E peek() {
Node<E> h = head; restartFromHead:
Node<E> p = h;
E item;
for (;;) { for (;;) {
item = p.getItem(); for (Node<E> h = head, p = h, q;;) {
if (item != null) E item = p.item;
break; if (item != null || (q = p.next) == null) {
Node<E> next = succ(p); updateHead(h, p);
if (next == null) { return item;
break; }
else if (p == q)
continue restartFromHead;
else
p = q;
} }
p = next;
} }
updateHead(h, p);
return item;
} }
/** /**
@ -372,24 +383,20 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
* of losing a race to a concurrent poll(). * of losing a race to a concurrent poll().
*/ */
Node<E> first() { Node<E> first() {
Node<E> h = head; restartFromHead:
Node<E> p = h;
Node<E> result;
for (;;) { for (;;) {
E item = p.getItem(); for (Node<E> h = head, p = h, q;;) {
if (item != null) { boolean hasItem = (p.item != null);
result = p; if (hasItem || (q = p.next) == null) {
break; updateHead(h, p);
return hasItem ? p : null;
}
else if (p == q)
continue restartFromHead;
else
p = q;
} }
Node<E> next = succ(p);
if (next == null) {
result = null;
break;
}
p = next;
} }
updateHead(h, p);
return result;
} }
/** /**
@ -410,18 +417,20 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
* <em>NOT</em> a constant-time operation. Because of the * <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these queues, determining the current * asynchronous nature of these queues, determining the current
* number of elements requires an O(n) traversal. * number of elements requires an O(n) traversal.
* Additionally, if elements are added or removed during execution
* of this method, the returned result may be inaccurate. Thus,
* this method is typically not very useful in concurrent
* applications.
* *
* @return the number of elements in this queue * @return the number of elements in this queue
*/ */
public int size() { public int size() {
int count = 0; int count = 0;
for (Node<E> p = first(); p != null; p = succ(p)) { for (Node<E> p = first(); p != null; p = succ(p))
if (p.getItem() != null) { if (p.item != null)
// Collections.size() spec says to max out // Collection.size() spec says to max out
if (++count == Integer.MAX_VALUE) if (++count == Integer.MAX_VALUE)
break; break;
}
}
return count; return count;
} }
@ -436,9 +445,8 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
public boolean contains(Object o) { public boolean contains(Object o) {
if (o == null) return false; if (o == null) return false;
for (Node<E> p = first(); p != null; p = succ(p)) { for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.getItem(); E item = p.item;
if (item != null && if (item != null && o.equals(item))
o.equals(item))
return true; return true;
} }
return false; return false;
@ -459,7 +467,7 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
if (o == null) return false; if (o == null) return false;
Node<E> pred = null; Node<E> pred = null;
for (Node<E> p = first(); p != null; p = succ(p)) { for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.getItem(); E item = p.item;
if (item != null && if (item != null &&
o.equals(item) && o.equals(item) &&
p.casItem(item, null)) { p.casItem(item, null)) {
@ -473,6 +481,69 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
return false; return false;
} }
/**
* Appends all of the elements in the specified collection to the end of
* this queue, in the order that they are returned by the specified
* collection's iterator. Attempts to {@code addAll} of a queue to
* itself result in {@code IllegalArgumentException}.
*
* @param c the elements to be inserted into this queue
* @return {@code true} if this queue changed as a result of the call
* @throws NullPointerException if the specified collection or any
* of its elements are null
* @throws IllegalArgumentException if the collection is this queue
*/
public boolean addAll(Collection<? extends E> c) {
if (c == this)
// As historically specified in AbstractQueue#addAll
throw new IllegalArgumentException();
// Copy c into a private chain of Nodes
Node<E> beginningOfTheEnd = null, last = null;
for (E e : c) {
checkNotNull(e);
Node<E> newNode = new Node<E>(e);
if (beginningOfTheEnd == null)
beginningOfTheEnd = last = newNode;
else {
last.lazySetNext(newNode);
last = newNode;
}
}
if (beginningOfTheEnd == null)
return false;
// Atomically append the chain at the tail of this collection
for (Node<E> t = tail, p = t;;) {
Node<E> q = p.next;
if (q == null) {
// p is last node
if (p.casNext(null, beginningOfTheEnd)) {
// Successful CAS is the linearization point
// for all elements to be added to this queue.
if (!casTail(t, last)) {
// Try a little harder to update tail,
// since we may be adding many elements.
t = tail;
if (last.next == null)
casTail(t, last);
}
return true;
}
// Lost CAS race to another thread; re-read next
}
else if (p == q)
// We have fallen off list. If tail is unchanged, it
// will also be off-list, in which case we need to
// jump to head, from which all live nodes are always
// reachable. Else the new tail is a better bet.
p = (t != (t = tail)) ? t : head;
else
// Check for tail updates after two hops.
p = (p != t && t != (t = tail)) ? t : q;
}
}
/** /**
* Returns an array containing all of the elements in this queue, in * Returns an array containing all of the elements in this queue, in
* proper sequence. * proper sequence.
@ -490,7 +561,7 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
// Use ArrayList to deal with resizing. // Use ArrayList to deal with resizing.
ArrayList<E> al = new ArrayList<E>(); ArrayList<E> al = new ArrayList<E>();
for (Node<E> p = first(); p != null; p = succ(p)) { for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.getItem(); E item = p.item;
if (item != null) if (item != null)
al.add(item); al.add(item);
} }
@ -539,7 +610,7 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
int k = 0; int k = 0;
Node<E> p; Node<E> p;
for (p = first(); p != null && k < a.length; p = succ(p)) { for (p = first(); p != null && k < a.length; p = succ(p)) {
E item = p.getItem(); E item = p.item;
if (item != null) if (item != null)
a[k++] = (T)item; a[k++] = (T)item;
} }
@ -552,7 +623,7 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
// If won't fit, use ArrayList version // If won't fit, use ArrayList version
ArrayList<E> al = new ArrayList<E>(); ArrayList<E> al = new ArrayList<E>();
for (Node<E> q = first(); q != null; q = succ(q)) { for (Node<E> q = first(); q != null; q = succ(q)) {
E item = q.getItem(); E item = q.item;
if (item != null) if (item != null)
al.add(item); al.add(item);
} }
@ -561,7 +632,9 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
/** /**
* Returns an iterator over the elements in this queue in proper sequence. * Returns an iterator over the elements in this queue in proper sequence.
* The returned iterator is a "weakly consistent" iterator that * The elements will be returned in order from first (head) to last (tail).
*
* <p>The returned {@code Iterator} is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException * will never throw {@link java.util.ConcurrentModificationException
* ConcurrentModificationException}, * ConcurrentModificationException},
* and guarantees to traverse elements as they existed upon * and guarantees to traverse elements as they existed upon
@ -620,7 +693,7 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
nextItem = null; nextItem = null;
return x; return x;
} }
E item = p.getItem(); E item = p.item;
if (item != null) { if (item != null) {
nextNode = p; nextNode = p;
nextItem = item; nextItem = item;
@ -648,13 +721,13 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
Node<E> l = lastRet; Node<E> l = lastRet;
if (l == null) throw new IllegalStateException(); if (l == null) throw new IllegalStateException();
// rely on a future traversal to relink. // rely on a future traversal to relink.
l.setItem(null); l.item = null;
lastRet = null; lastRet = null;
} }
} }
/** /**
* Save the state to a stream (that is, serialize it). * Saves the state to a stream (that is, serializes it).
* *
* @serialData All of the elements (each an {@code E}) in * @serialData All of the elements (each an {@code E}) in
* the proper order, followed by a null * the proper order, followed by a null
@ -668,7 +741,7 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
// Write out all elements in the proper order. // Write out all elements in the proper order.
for (Node<E> p = first(); p != null; p = succ(p)) { for (Node<E> p = first(); p != null; p = succ(p)) {
Object item = p.getItem(); Object item = p.item;
if (item != null) if (item != null)
s.writeObject(item); s.writeObject(item);
} }
@ -678,25 +751,40 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
} }
/** /**
* Reconstitute the Queue instance from a stream (that is, * Reconstitutes the instance from a stream (that is, deserializes it).
* deserialize it).
* @param s the stream * @param s the stream
*/ */
private void readObject(java.io.ObjectInputStream s) private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException { throws java.io.IOException, ClassNotFoundException {
// Read in capacity, and any hidden stuff
s.defaultReadObject(); s.defaultReadObject();
head = new Node<E>(null);
tail = head; // Read in elements until trailing null sentinel found
// Read in all elements and place in queue Node<E> h = null, t = null;
for (;;) { Object item;
while ((item = s.readObject()) != null) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
E item = (E)s.readObject(); Node<E> newNode = new Node<E>((E) item);
if (item == null) if (h == null)
break; h = t = newNode;
else else {
offer(item); t.lazySetNext(newNode);
t = newNode;
}
} }
if (h == null)
h = t = new Node<E>(null);
head = h;
tail = t;
}
/**
* Throws NullPointerException if argument is null.
*
* @param v the element
*/
private static void checkNotNull(Object v) {
if (v == null)
throw new NullPointerException();
} }
// Unsafe mechanics // Unsafe mechanics
@ -715,10 +803,6 @@ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
} }
private void lazySetHead(Node<E> val) {
UNSAFE.putOrderedObject(this, headOffset, val);
}
static long objectFieldOffset(sun.misc.Unsafe UNSAFE, static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
String field, Class<?> klazz) { String field, Class<?> klazz) {
try { try {

View File

@ -42,7 +42,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionException;
@ -823,15 +822,13 @@ public class ForkJoinPool extends AbstractExecutorService {
(workerCounts & RUNNING_COUNT_MASK) <= 1); (workerCounts & RUNNING_COUNT_MASK) <= 1);
long startTime = untimed? 0 : System.nanoTime(); long startTime = untimed? 0 : System.nanoTime();
Thread.interrupted(); // clear/ignore interrupt Thread.interrupted(); // clear/ignore interrupt
if (eventCount != ec || w.runState != 0 || if (eventCount != ec || w.isTerminating())
runState >= TERMINATING) // recheck after clear break; // recheck after clear
break;
if (untimed) if (untimed)
LockSupport.park(w); LockSupport.park(w);
else { else {
LockSupport.parkNanos(w, SHRINK_RATE_NANOS); LockSupport.parkNanos(w, SHRINK_RATE_NANOS);
if (eventCount != ec || w.runState != 0 || if (eventCount != ec || w.isTerminating())
runState >= TERMINATING)
break; break;
if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS) if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
tryShutdownUnusedWorker(ec); tryShutdownUnusedWorker(ec);
@ -899,16 +896,23 @@ public class ForkJoinPool extends AbstractExecutorService {
UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc, UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
wc + (ONE_RUNNING|ONE_TOTAL))) { wc + (ONE_RUNNING|ONE_TOTAL))) {
ForkJoinWorkerThread w = null; ForkJoinWorkerThread w = null;
Throwable fail = null;
try { try {
w = factory.newThread(this); w = factory.newThread(this);
} finally { // adjust on null or exceptional factory return } catch (Throwable ex) {
if (w == null) { fail = ex;
decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
tryTerminate(false); // handle failure during shutdown
}
} }
if (w == null) if (w == null) { // null or exceptional factory return
decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
tryTerminate(false); // handle failure during shutdown
// If originating from an external caller,
// propagate exception, else ignore
if (fail != null && runState < TERMINATING &&
!(Thread.currentThread() instanceof
ForkJoinWorkerThread))
UNSAFE.throwException(fail);
break; break;
}
w.start(recordWorker(w), ueh); w.start(recordWorker(w), ueh);
if ((workerCounts >>> TOTAL_COUNT_SHIFT) >= pc) { if ((workerCounts >>> TOTAL_COUNT_SHIFT) >= pc) {
int c; // advance event count int c; // advance event count
@ -997,8 +1001,12 @@ public class ForkJoinPool extends AbstractExecutorService {
boolean active = w.active; boolean active = w.active;
boolean inactivate = false; boolean inactivate = false;
int pc = parallelism; int pc = parallelism;
int rs; while (w.runState == 0) {
while (w.runState == 0 && (rs = runState) < TERMINATING) { int rs = runState;
if (rs >= TERMINATING) { // propagate shutdown
w.shutdown();
break;
}
if ((inactivate || (active && (rs & ACTIVE_COUNT_MASK) >= pc)) && if ((inactivate || (active && (rs & ACTIVE_COUNT_MASK) >= pc)) &&
UNSAFE.compareAndSwapInt(this, runStateOffset, rs, rs - 1)) UNSAFE.compareAndSwapInt(this, runStateOffset, rs, rs - 1))
inactivate = active = w.active = false; inactivate = active = w.active = false;
@ -1126,6 +1134,7 @@ public class ForkJoinPool extends AbstractExecutorService {
return true; return true;
} }
/** /**
* Actions on transition to TERMINATING * Actions on transition to TERMINATING
* *
@ -1149,7 +1158,7 @@ public class ForkJoinPool extends AbstractExecutorService {
if (passes > 0 && !w.isTerminated()) { if (passes > 0 && !w.isTerminated()) {
w.cancelTasks(); w.cancelTasks();
LockSupport.unpark(w); LockSupport.unpark(w);
if (passes > 1) { if (passes > 1 && !w.isInterrupted()) {
try { try {
w.interrupt(); w.interrupt();
} catch (SecurityException ignore) { } catch (SecurityException ignore) {
@ -1725,6 +1734,13 @@ public class ForkJoinPool extends AbstractExecutorService {
return (runState & (TERMINATING|TERMINATED)) == TERMINATING; return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
} }
/**
* Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
*/
final boolean isAtLeastTerminating() {
return runState >= TERMINATING;
}
/** /**
* Returns {@code true} if this pool has been shut down. * Returns {@code true} if this pool has been shut down.
* *

View File

@ -55,10 +55,10 @@ import java.util.WeakHashMap;
* start other subtasks. As indicated by the name of this class, * start other subtasks. As indicated by the name of this class,
* many programs using {@code ForkJoinTask} employ only methods * many programs using {@code ForkJoinTask} employ only methods
* {@link #fork} and {@link #join}, or derivatives such as {@link * {@link #fork} and {@link #join}, or derivatives such as {@link
* #invokeAll}. However, this class also provides a number of other * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
* methods that can come into play in advanced usages, as well as * provides a number of other methods that can come into play in
* extension mechanics that allow support of new forms of fork/join * advanced usages, as well as extension mechanics that allow
* processing. * support of new forms of fork/join processing.
* *
* <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}. * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
* The efficiency of {@code ForkJoinTask}s stems from a set of * The efficiency of {@code ForkJoinTask}s stems from a set of
@ -250,7 +250,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
int s; // the odd construction reduces lock bias effects int s; // the odd construction reduces lock bias effects
while ((s = status) >= 0) { while ((s = status) >= 0) {
try { try {
synchronized(this) { synchronized (this) {
if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL)) if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
wait(); wait();
} }
@ -270,7 +270,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
int s; int s;
if ((s = status) >= 0) { if ((s = status) >= 0) {
try { try {
synchronized(this) { synchronized (this) {
if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL)) if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
wait(millis, 0); wait(millis, 0);
} }
@ -288,7 +288,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
private void externalAwaitDone() { private void externalAwaitDone() {
int s; int s;
while ((s = status) >= 0) { while ((s = status) >= 0) {
synchronized(this) { synchronized (this) {
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){ if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
boolean interrupted = false; boolean interrupted = false;
while (status >= 0) { while (status >= 0) {
@ -669,11 +669,34 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
setCompletion(NORMAL); setCompletion(NORMAL);
} }
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an
* exception
* @throws InterruptedException if the current thread is not a
* member of a ForkJoinPool and was interrupted while waiting
*/
public final V get() throws InterruptedException, ExecutionException { public final V get() throws InterruptedException, ExecutionException {
quietlyJoin(); int s;
if (Thread.interrupted()) if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
throw new InterruptedException(); quietlyJoin();
int s = status; s = status;
}
else {
while ((s = status) >= 0) {
synchronized (this) { // interruptible form of awaitDone
if (UNSAFE.compareAndSwapInt(this, statusOffset,
s, SIGNAL)) {
while (status >= 0)
wait();
}
}
}
}
if (s < NORMAL) { if (s < NORMAL) {
Throwable ex; Throwable ex;
if (s == CANCELLED) if (s == CANCELLED)
@ -684,6 +707,20 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
return getRawResult(); return getRawResult();
} }
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an
* exception
* @throws InterruptedException if the current thread is not a
* member of a ForkJoinPool and was interrupted while waiting
* @throws TimeoutException if the wait timed out
*/
public final V get(long timeout, TimeUnit unit) public final V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException { throws InterruptedException, ExecutionException, TimeoutException {
Thread t = Thread.currentThread(); Thread t = Thread.currentThread();
@ -725,7 +762,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
long ms = nt / 1000000; long ms = nt / 1000000;
int ns = (int) (nt % 1000000); int ns = (int) (nt % 1000000);
try { try {
synchronized(this) { synchronized (this) {
if (status >= 0) if (status >= 0)
wait(ms, ns); wait(ms, ns);
} }

View File

@ -778,11 +778,20 @@ public class ForkJoinWorkerThread extends Thread {
// status check methods used mainly by ForkJoinPool // status check methods used mainly by ForkJoinPool
final boolean isRunning() { return runState == 0; } final boolean isRunning() { return runState == 0; }
final boolean isTerminating() { return (runState & TERMINATING) != 0; }
final boolean isTerminated() { return (runState & TERMINATED) != 0; } final boolean isTerminated() { return (runState & TERMINATED) != 0; }
final boolean isSuspended() { return (runState & SUSPENDED) != 0; } final boolean isSuspended() { return (runState & SUSPENDED) != 0; }
final boolean isTrimmed() { return (runState & TRIMMED) != 0; } final boolean isTrimmed() { return (runState & TRIMMED) != 0; }
final boolean isTerminating() {
if ((runState & TERMINATING) != 0)
return true;
if (pool.isAtLeastTerminating()) { // propagate pool state
shutdown();
return true;
}
return false;
}
/** /**
* Sets state to TERMINATING. Does NOT unpark or interrupt * Sets state to TERMINATING. Does NOT unpark or interrupt
* to wake up if currently blocked. Callers must do so if desired. * to wake up if currently blocked. Callers must do so if desired.

View File

@ -138,7 +138,7 @@ package java.util.concurrent;
* if (right.tryUnfork()) // directly calculate if not stolen * if (right.tryUnfork()) // directly calculate if not stolen
* sum += right.atLeaf(right.lo, right.hi); * sum += right.atLeaf(right.lo, right.hi);
* else { * else {
* right.helpJoin(); * right.join();
* sum += right.result; * sum += right.result;
* } * }
* right = right.next; * right = right.next;

View File

@ -690,6 +690,11 @@ public class LogManager {
* Note that since untrusted code may create loggers with * Note that since untrusted code may create loggers with
* arbitrary names this method should not be relied on to * arbitrary names this method should not be relied on to
* find Loggers for security sensitive logging. * find Loggers for security sensitive logging.
* It is also important to note that the Logger associated with the
* String {@code name} may be garbage collected at any time if there
* is no strong reference to the Logger. The caller of this method
* must check the return value for null in order to properly handle
* the case where the Logger has been garbage collected.
* <p> * <p>
* @param name name of the logger * @param name name of the logger
* @return matching logger or null if none is found * @return matching logger or null if none is found
@ -713,6 +718,14 @@ public class LogManager {
* <p> * <p>
* Note: Loggers may be added dynamically as new classes are loaded. * Note: Loggers may be added dynamically as new classes are loaded.
* This method only reports on the loggers that are currently registered. * This method only reports on the loggers that are currently registered.
* It is also important to note that this method only returns the name
* of a Logger, not a strong reference to the Logger itself.
* The returned String does nothing to prevent the Logger from being
* garbage collected. In particular, if the returned name is passed
* to {@code LogManager.getLogger()}, then the caller must check the
* return value from {@code LogManager.getLogger()} for null to properly
* handle the case where the Logger has been garbage collected in the
* time since its name was returned by this method.
* <p> * <p>
* @return enumeration of logger name strings * @return enumeration of logger name strings
*/ */

View File

@ -42,7 +42,10 @@ import java.lang.ref.WeakReference;
* <p> * <p>
* Logger objects may be obtained by calls on one of the getLogger * Logger objects may be obtained by calls on one of the getLogger
* factory methods. These will either create a new Logger or * factory methods. These will either create a new Logger or
* return a suitable existing Logger. * return a suitable existing Logger. It is important to note that
* the Logger returned by one of the {@code getLogger} factory methods
* may be garbage collected at any time if a strong reference to the
* Logger is not kept.
* <p> * <p>
* Logging messages will be forwarded to registered Handler * Logging messages will be forwarded to registered Handler
* objects, which can forward the messages to a variety of * objects, which can forward the messages to a variety of
@ -210,7 +213,9 @@ public class Logger {
* who are making serious use of the logging package (for example * who are making serious use of the logging package (for example
* in products) should create and use their own Logger objects, * in products) should create and use their own Logger objects,
* with appropriate names, so that logging can be controlled on a * with appropriate names, so that logging can be controlled on a
* suitable per-Logger granularity. * suitable per-Logger granularity. Developers also need to keep a
* strong reference to their Logger objects to prevent them from
* being garbage collected.
* <p> * <p>
* @deprecated Initialization of this field is prone to deadlocks. * @deprecated Initialization of this field is prone to deadlocks.
* The field must be initialized by the Logger class initialization * The field must be initialized by the Logger class initialization
@ -287,6 +292,15 @@ public class Logger {
* based on the LogManager configuration and it will configured * based on the LogManager configuration and it will configured
* to also send logging output to its parent's Handlers. It will * to also send logging output to its parent's Handlers. It will
* be registered in the LogManager global namespace. * be registered in the LogManager global namespace.
* <p>
* Note: The LogManager may only retain a weak reference to the newly
* created Logger. It is important to understand that a previously
* created Logger with the given name may be garbage collected at any
* time if there is no strong reference to the Logger. In particular,
* this means that two back-to-back calls like
* {@code getLogger("MyLogger").log(...)} may use different Logger
* objects named "MyLogger" if there is no strong reference to the
* Logger named "MyLogger" elsewhere in the program.
* *
* @param name A name for the logger. This should * @param name A name for the logger. This should
* be a dot-separated name and should normally * be a dot-separated name and should normally
@ -311,6 +325,15 @@ public class Logger {
* output to its parent's Handlers. It will be registered in * output to its parent's Handlers. It will be registered in
* the LogManager global namespace. * the LogManager global namespace.
* <p> * <p>
* Note: The LogManager may only retain a weak reference to the newly
* created Logger. It is important to understand that a previously
* created Logger with the given name may be garbage collected at any
* time if there is no strong reference to the Logger. In particular,
* this means that two back-to-back calls like
* {@code getLogger("MyLogger", ...).log(...)} may use different Logger
* objects named "MyLogger" if there is no strong reference to the
* Logger named "MyLogger" elsewhere in the program.
* <p>
* If the named Logger already exists and does not yet have a * If the named Logger already exists and does not yet have a
* localization resource bundle then the given resource bundle * localization resource bundle then the given resource bundle
* name is used. If the named Logger already exists and has * name is used. If the named Logger already exists and has

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -734,7 +734,7 @@ public static final int ASCII_STREAM_PARAM = 2;
throw new SQLException("Set initParams() before setCommand"); throw new SQLException("Set initParams() before setCommand");
} }
params.clear(); params.clear();
command = new String(cmd); command = cmd;
} }
} }
@ -797,7 +797,7 @@ public static final int ASCII_STREAM_PARAM = 2;
throw new SQLException("Invalid url string detected. " + throw new SQLException("Invalid url string detected. " +
"Cannot be of length less than 1"); "Cannot be of length less than 1");
} else { } else {
URL = new String(url); URL = url;
} }
dataSource = null; dataSource = null;
@ -854,7 +854,7 @@ public static final int ASCII_STREAM_PARAM = 2;
} else if (name.equals("")) { } else if (name.equals("")) {
throw new SQLException("DataSource name cannot be empty string"); throw new SQLException("DataSource name cannot be empty string");
} else { } else {
dataSource = new String(name); dataSource = name;
} }
URL = null; URL = null;
@ -889,7 +889,7 @@ public static final int ASCII_STREAM_PARAM = 2;
{ {
username = null; username = null;
} else { } else {
username = new String(name); username = name;
} }
} }
@ -924,7 +924,7 @@ public static final int ASCII_STREAM_PARAM = 2;
{ {
password = null; password = null;
} else { } else {
password = new String(pass); password = pass;
} }
} }
@ -1563,13 +1563,13 @@ public static final int ASCII_STREAM_PARAM = 2;
nullVal = new Object[2]; nullVal = new Object[2];
nullVal[0] = null; nullVal[0] = null;
nullVal[1] = new Integer(sqlType); nullVal[1] = Integer.valueOf(sqlType);
if (params == null){ if (params == null){
throw new SQLException("Set initParams() before setNull"); throw new SQLException("Set initParams() before setNull");
} }
params.put(new Integer(parameterIndex - 1), nullVal); params.put(Integer.valueOf(parameterIndex - 1), nullVal);
} }
/** /**
@ -1644,14 +1644,14 @@ public static final int ASCII_STREAM_PARAM = 2;
nullVal = new Object[3]; nullVal = new Object[3];
nullVal[0] = null; nullVal[0] = null;
nullVal[1] = new Integer(sqlType); nullVal[1] = Integer.valueOf(sqlType);
nullVal[2] = new String(typeName); nullVal[2] = typeName;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setNull"); throw new SQLException("Set initParams() before setNull");
} }
params.put(new Integer(parameterIndex - 1), nullVal); params.put(Integer.valueOf(parameterIndex - 1), nullVal);
} }
@ -1686,7 +1686,7 @@ public static final int ASCII_STREAM_PARAM = 2;
throw new SQLException("Set initParams() before setNull"); throw new SQLException("Set initParams() before setNull");
} }
params.put(new Integer(parameterIndex - 1), new Boolean(x)); params.put(Integer.valueOf(parameterIndex - 1), Boolean.valueOf(x));
} }
/** /**
@ -1720,7 +1720,7 @@ public static final int ASCII_STREAM_PARAM = 2;
throw new SQLException("Set initParams() before setByte"); throw new SQLException("Set initParams() before setByte");
} }
params.put(new Integer(parameterIndex - 1), new Byte(x)); params.put(Integer.valueOf(parameterIndex - 1), Byte.valueOf(x));
} }
/** /**
@ -1754,7 +1754,7 @@ public static final int ASCII_STREAM_PARAM = 2;
throw new SQLException("Set initParams() before setShort"); throw new SQLException("Set initParams() before setShort");
} }
params.put(new Integer(parameterIndex - 1), new Short(x)); params.put(Integer.valueOf(parameterIndex - 1), Short.valueOf(x));
} }
/** /**
@ -1786,7 +1786,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setInt"); throw new SQLException("Set initParams() before setInt");
} }
params.put(new Integer(parameterIndex - 1), new Integer(x)); params.put(Integer.valueOf(parameterIndex - 1), Integer.valueOf(x));
} }
/** /**
@ -1818,7 +1818,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setLong"); throw new SQLException("Set initParams() before setLong");
} }
params.put(new Integer(parameterIndex - 1), new Long(x)); params.put(Integer.valueOf(parameterIndex - 1), Long.valueOf(x));
} }
/** /**
@ -1850,7 +1850,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setFloat"); throw new SQLException("Set initParams() before setFloat");
} }
params.put(new Integer(parameterIndex - 1), new Float(x)); params.put(Integer.valueOf(parameterIndex - 1), new Float(x));
} }
/** /**
@ -1882,7 +1882,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setDouble"); throw new SQLException("Set initParams() before setDouble");
} }
params.put(new Integer(parameterIndex - 1), new Double(x)); params.put(Integer.valueOf(parameterIndex - 1), new Double(x));
} }
/** /**
@ -1914,7 +1914,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setBigDecimal"); throw new SQLException("Set initParams() before setBigDecimal");
} }
params.put(new Integer(parameterIndex - 1), x); params.put(Integer.valueOf(parameterIndex - 1), x);
} }
/** /**
@ -1948,7 +1948,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setString"); throw new SQLException("Set initParams() before setString");
} }
params.put(new Integer(parameterIndex - 1), x); params.put(Integer.valueOf(parameterIndex - 1), x);
} }
/** /**
@ -1982,7 +1982,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setBytes"); throw new SQLException("Set initParams() before setBytes");
} }
params.put(new Integer(parameterIndex - 1), x); params.put(Integer.valueOf(parameterIndex - 1), x);
} }
/** /**
@ -2024,7 +2024,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setDate"); throw new SQLException("Set initParams() before setDate");
} }
params.put(new Integer(parameterIndex - 1), x); params.put(Integer.valueOf(parameterIndex - 1), x);
} }
/** /**
@ -2069,7 +2069,7 @@ public static final int ASCII_STREAM_PARAM = 2;
throw new SQLException("Set initParams() before setTime"); throw new SQLException("Set initParams() before setTime");
} }
params.put(new Integer(parameterIndex - 1), x); params.put(Integer.valueOf(parameterIndex - 1), x);
} }
/** /**
@ -2112,7 +2112,7 @@ public static final int ASCII_STREAM_PARAM = 2;
throw new SQLException("Set initParams() before setTimestamp"); throw new SQLException("Set initParams() before setTimestamp");
} }
params.put(new Integer(parameterIndex - 1), x); params.put(Integer.valueOf(parameterIndex - 1), x);
} }
/** /**
@ -2185,14 +2185,14 @@ public static final int ASCII_STREAM_PARAM = 2;
asciiStream = new Object[3]; asciiStream = new Object[3];
asciiStream[0] = x; asciiStream[0] = x;
asciiStream[1] = new Integer(length); asciiStream[1] = Integer.valueOf(length);
asciiStream[2] = new Integer(ASCII_STREAM_PARAM); asciiStream[2] = Integer.valueOf(ASCII_STREAM_PARAM);
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setAsciiStream"); throw new SQLException("Set initParams() before setAsciiStream");
} }
params.put(new Integer(parameterIndex - 1), asciiStream); params.put(Integer.valueOf(parameterIndex - 1), asciiStream);
} }
/** /**
@ -2290,13 +2290,13 @@ public static final int ASCII_STREAM_PARAM = 2;
binaryStream = new Object[3]; binaryStream = new Object[3];
binaryStream[0] = x; binaryStream[0] = x;
binaryStream[1] = new Integer(length); binaryStream[1] = Integer.valueOf(length);
binaryStream[2] = new Integer(BINARY_STREAM_PARAM); binaryStream[2] = Integer.valueOf(BINARY_STREAM_PARAM);
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setBinaryStream"); throw new SQLException("Set initParams() before setBinaryStream");
} }
params.put(new Integer(parameterIndex - 1), binaryStream); params.put(Integer.valueOf(parameterIndex - 1), binaryStream);
} }
@ -2396,12 +2396,12 @@ public static final int ASCII_STREAM_PARAM = 2;
unicodeStream = new Object[3]; unicodeStream = new Object[3];
unicodeStream[0] = x; unicodeStream[0] = x;
unicodeStream[1] = new Integer(length); unicodeStream[1] = Integer.valueOf(length);
unicodeStream[2] = new Integer(UNICODE_STREAM_PARAM); unicodeStream[2] = Integer.valueOf(UNICODE_STREAM_PARAM);
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setUnicodeStream"); throw new SQLException("Set initParams() before setUnicodeStream");
} }
params.put(new Integer(parameterIndex - 1), unicodeStream); params.put(Integer.valueOf(parameterIndex - 1), unicodeStream);
} }
/** /**
@ -2475,11 +2475,11 @@ public static final int ASCII_STREAM_PARAM = 2;
charStream = new Object[2]; charStream = new Object[2];
charStream[0] = reader; charStream[0] = reader;
charStream[1] = new Integer(length); charStream[1] = Integer.valueOf(length);
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setCharacterStream"); throw new SQLException("Set initParams() before setCharacterStream");
} }
params.put(new Integer(parameterIndex - 1), charStream); params.put(Integer.valueOf(parameterIndex - 1), charStream);
} }
/** /**
@ -2591,12 +2591,12 @@ public static final int ASCII_STREAM_PARAM = 2;
obj = new Object[3]; obj = new Object[3];
obj[0] = x; obj[0] = x;
obj[1] = new Integer(targetSqlType); obj[1] = Integer.valueOf(targetSqlType);
obj[2] = new Integer(scale); obj[2] = Integer.valueOf(scale);
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setObject"); throw new SQLException("Set initParams() before setObject");
} }
params.put(new Integer(parameterIndex - 1), obj); params.put(Integer.valueOf(parameterIndex - 1), obj);
} }
/** /**
@ -2654,11 +2654,11 @@ public static final int ASCII_STREAM_PARAM = 2;
obj = new Object[2]; obj = new Object[2];
obj[0] = x; obj[0] = x;
obj[1] = new Integer(targetSqlType); obj[1] = Integer.valueOf(targetSqlType);
if (params == null){ if (params == null){
throw new SQLException("Set initParams() before setObject"); throw new SQLException("Set initParams() before setObject");
} }
params.put(new Integer(parameterIndex - 1), obj); params.put(Integer.valueOf(parameterIndex - 1), obj);
} }
/** /**
@ -2726,7 +2726,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if (params == null) { if (params == null) {
throw new SQLException("Set initParams() before setObject"); throw new SQLException("Set initParams() before setObject");
} }
params.put(new Integer(parameterIndex - 1), x); params.put(Integer.valueOf(parameterIndex - 1), x);
} }
/** /**
@ -2773,7 +2773,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if (params == null) { if (params == null) {
throw new SQLException("Set initParams() before setRef"); throw new SQLException("Set initParams() before setRef");
} }
params.put(new Integer(parameterIndex - 1), new SerialRef(ref)); params.put(Integer.valueOf(parameterIndex - 1), new SerialRef(ref));
} }
/** /**
@ -2817,7 +2817,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setBlob"); throw new SQLException("Set initParams() before setBlob");
} }
params.put(new Integer(parameterIndex - 1), new SerialBlob(x)); params.put(Integer.valueOf(parameterIndex - 1), new SerialBlob(x));
} }
/** /**
@ -2862,7 +2862,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setClob"); throw new SQLException("Set initParams() before setClob");
} }
params.put(new Integer(parameterIndex - 1), new SerialClob(x)); params.put(Integer.valueOf(parameterIndex - 1), new SerialClob(x));
} }
/** /**
@ -2910,7 +2910,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if (params == null){ if (params == null){
throw new SQLException("Set initParams() before setArray"); throw new SQLException("Set initParams() before setArray");
} }
params.put(new Integer(parameterIndex - 1), new SerialArray(array)); params.put(Integer.valueOf(parameterIndex - 1), new SerialArray(array));
} }
/** /**
@ -2975,7 +2975,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setDate"); throw new SQLException("Set initParams() before setDate");
} }
params.put(new Integer(parameterIndex - 1), date); params.put(Integer.valueOf(parameterIndex - 1), date);
} }
/** /**
@ -3041,7 +3041,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setTime"); throw new SQLException("Set initParams() before setTime");
} }
params.put(new Integer(parameterIndex - 1), time); params.put(Integer.valueOf(parameterIndex - 1), time);
} }
/** /**
@ -3107,7 +3107,7 @@ public static final int ASCII_STREAM_PARAM = 2;
if(params == null){ if(params == null){
throw new SQLException("Set initParams() before setTimestamp"); throw new SQLException("Set initParams() before setTimestamp");
} }
params.put(new Integer(parameterIndex - 1), timestamp); params.put(Integer.valueOf(parameterIndex - 1), timestamp);
} }
/** /**
@ -3181,7 +3181,7 @@ public static final int ASCII_STREAM_PARAM = 2;
Object[] paramsArray = new Object[params.size()]; Object[] paramsArray = new Object[params.size()];
for (int i = 0; i < params.size(); i++) { for (int i = 0; i < params.size(); i++) {
paramsArray[i] = params.get(new Integer(i)); paramsArray[i] = params.get(Integer.valueOf(i));
if (paramsArray[i] == null) { if (paramsArray[i] == null) {
throw new SQLException("missing parameter: " + (i + 1)); throw new SQLException("missing parameter: " + (i + 1));
} //end if } //end if

View File

@ -39,7 +39,7 @@ import javax.sql.rowset.spi.*;
* <code>CachedRowSet</code> must implement. * <code>CachedRowSet</code> must implement.
* <P> * <P>
* The reference implementation of the <code>CachedRowSet</code> interface provided * The reference implementation of the <code>CachedRowSet</code> interface provided
* by Sun Microsystems is a standard implementation. Developers may use this implementation * by Oracle Corporation is a standard implementation. Developers may use this implementation
* just as it is, they may extend it, or they may choose to write their own implementations * just as it is, they may extend it, or they may choose to write their own implementations
* of this interface. * of this interface.
* <P> * <P>
@ -1623,4 +1623,3 @@ public interface CachedRowSet extends RowSet, Joinable {
public boolean previousPage() throws SQLException; public boolean previousPage() throws SQLException;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -306,9 +306,9 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
public void setColumnLabel(int columnIndex, String label) throws SQLException { public void setColumnLabel(int columnIndex, String label) throws SQLException {
checkColRange(columnIndex); checkColRange(columnIndex);
if (label != null) { if (label != null) {
colInfo[columnIndex].columnLabel = new String(label); colInfo[columnIndex].columnLabel = label;
} else { } else {
colInfo[columnIndex].columnLabel = new String(""); colInfo[columnIndex].columnLabel = "";
} }
} }
@ -326,9 +326,9 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
public void setColumnName(int columnIndex, String columnName) throws SQLException { public void setColumnName(int columnIndex, String columnName) throws SQLException {
checkColRange(columnIndex); checkColRange(columnIndex);
if (columnName != null) { if (columnName != null) {
colInfo[columnIndex].columnName = new String(columnName); colInfo[columnIndex].columnName = columnName;
} else { } else {
colInfo[columnIndex].columnName = new String(""); colInfo[columnIndex].columnName = "";
} }
} }
@ -348,9 +348,9 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
public void setSchemaName(int columnIndex, String schemaName) throws SQLException { public void setSchemaName(int columnIndex, String schemaName) throws SQLException {
checkColRange(columnIndex); checkColRange(columnIndex);
if (schemaName != null ) { if (schemaName != null ) {
colInfo[columnIndex].schemaName = new String(schemaName); colInfo[columnIndex].schemaName = schemaName;
} else { } else {
colInfo[columnIndex].schemaName = new String(""); colInfo[columnIndex].schemaName = "";
} }
} }
@ -411,9 +411,9 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
public void setTableName(int columnIndex, String tableName) throws SQLException { public void setTableName(int columnIndex, String tableName) throws SQLException {
checkColRange(columnIndex); checkColRange(columnIndex);
if (tableName != null) { if (tableName != null) {
colInfo[columnIndex].tableName = new String(tableName); colInfo[columnIndex].tableName = tableName;
} else { } else {
colInfo[columnIndex].tableName = new String(""); colInfo[columnIndex].tableName = "";
} }
} }
@ -432,9 +432,9 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
public void setCatalogName(int columnIndex, String catalogName) throws SQLException { public void setCatalogName(int columnIndex, String catalogName) throws SQLException {
checkColRange(columnIndex); checkColRange(columnIndex);
if (catalogName != null) if (catalogName != null)
colInfo[columnIndex].catName = new String(catalogName); colInfo[columnIndex].catName = catalogName;
else else
colInfo[columnIndex].catName = new String(""); colInfo[columnIndex].catName = "";
} }
/** /**
@ -474,9 +474,9 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
throws SQLException { throws SQLException {
checkColRange(columnIndex); checkColRange(columnIndex);
if (typeName != null) { if (typeName != null) {
colInfo[columnIndex].colTypeName = new String(typeName); colInfo[columnIndex].colTypeName = typeName;
} else { } else {
colInfo[columnIndex].colTypeName = new String(""); colInfo[columnIndex].colTypeName = "";
} }
} }
@ -827,7 +827,7 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
* or the given column number is out of bounds * or the given column number is out of bounds
*/ */
public String getColumnClassName(int columnIndex) throws SQLException { public String getColumnClassName(int columnIndex) throws SQLException {
String className = (new String()).getClass().getName(); String className = String.class.getName();
int sqlType = getColumnType(columnIndex); int sqlType = getColumnType(columnIndex);
@ -835,65 +835,62 @@ public class RowSetMetaDataImpl implements RowSetMetaData, Serializable {
case Types.NUMERIC: case Types.NUMERIC:
case Types.DECIMAL: case Types.DECIMAL:
className = (new java.math.BigDecimal(0)).getClass().getName (); className = java.math.BigDecimal.class.getName();
break; break;
case Types.BIT: case Types.BIT:
className = (new Boolean(false)).getClass().getName (); className = java.lang.Boolean.class.getName();
break; break;
case Types.TINYINT: case Types.TINYINT:
className = (new Byte("0")).getClass().getName (); className = java.lang.Byte.class.getName();
break; break;
case Types.SMALLINT: case Types.SMALLINT:
className = (new Short("0")).getClass().getName (); className = java.lang.Short.class.getName();
break; break;
case Types.INTEGER: case Types.INTEGER:
className = (new Integer(0)).getClass().getName (); className = java.lang.Integer.class.getName();
break; break;
case Types.BIGINT: case Types.BIGINT:
className = (new Long(0)).getClass().getName (); className = java.lang.Long.class.getName();
break; break;
case Types.REAL: case Types.REAL:
className = (new Float(0)).getClass().getName (); className = java.lang.Float.class.getName();
break; break;
case Types.FLOAT: case Types.FLOAT:
case Types.DOUBLE: case Types.DOUBLE:
className = (new Double(0)).getClass().getName(); className = java.lang.Double.class.getName();
break; break;
case Types.BINARY: case Types.BINARY:
case Types.VARBINARY: case Types.VARBINARY:
case Types.LONGVARBINARY: case Types.LONGVARBINARY:
byte[] b = {}; className = "byte[]";
className = (b.getClass()).getName();
break; break;
case Types.DATE: case Types.DATE:
className = (new java.sql.Date(123456)).getClass().getName (); className = java.sql.Date.class.getName();
break; break;
case Types.TIME: case Types.TIME:
className = (new java.sql.Time(123456)).getClass().getName (); className = java.sql.Time.class.getName();
break; break;
case Types.TIMESTAMP: case Types.TIMESTAMP:
className = (new java.sql.Timestamp(123456)).getClass().getName (); className = java.sql.Timestamp.class.getName();
break; break;
case Types.BLOB: case Types.BLOB:
byte[] blob = {}; className = java.sql.Blob.class.getName();
className = (blob.getClass()).getName();
break; break;
case Types.CLOB: case Types.CLOB:
char[] c = {}; className = java.sql.Clob.class.getName();
className = (c.getClass()).getName();
break; break;
} }

View File

@ -29,7 +29,6 @@ import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import javax.sql.rowset.RowSetFactory;
/** /**
* A factory API that enables applications to obtain a * A factory API that enables applications to obtain a
@ -82,15 +81,15 @@ public class RowSetProvider {
* the <code>RowSetFactory</code> implementation class to load:</p> * the <code>RowSetFactory</code> implementation class to load:</p>
* <ul> * <ul>
* <li> * <li>
* The System property {@code javax.sql.rowset.RowsetFactory}. For example: * The System property {@code javax.sql.rowset.RowSetFactory}. For example:
* <ul> * <ul>
* <li> * <li>
* -Djavax.sql.rowset.RowsetFactory=com.sun.rowset.RowSetFactoryImpl * -Djavax.sql.rowset.RowSetFactory=com.sun.rowset.RowSetFactoryImpl
* </li> * </li>
* </ul> * </ul>
* <li> * <li>
* The ServiceLocator API. The ServiceLocator API will look * The {@link ServiceLoader} API. The {@code ServiceLoader} API will look
* for a classname in the file * for a class name in the file
* {@code META-INF/services/javax.sql.rowset.RowSetFactory} * {@code META-INF/services/javax.sql.rowset.RowSetFactory}
* in jars available to the runtime. For example, to have the the RowSetFactory * in jars available to the runtime. For example, to have the the RowSetFactory
* implementation {@code com.sun.rowset.RowSetFactoryImpl } loaded, the * implementation {@code com.sun.rowset.RowSetFactoryImpl } loaded, the
@ -271,7 +270,7 @@ public class RowSetProvider {
/** /**
* Returns the requested System Property. If a {@code SecurityException} * Returns the requested System Property. If a {@code SecurityException}
* occurs, just return NULL * occurs, just return NULL
* @param propName - System property to retreive * @param propName - System property to retrieve
* @return The System property value or NULL if the property does not exist * @return The System property value or NULL if the property does not exist
* or a {@code SecurityException} occurs. * or a {@code SecurityException} occurs.
*/ */

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -115,7 +115,7 @@ import org.xml.sax.*;
* &lt;<font color=red>url</font>&gt;jdbc:thin:oracle&lt;<font color=red>/url</font>&gt; * &lt;<font color=red>url</font>&gt;jdbc:thin:oracle&lt;<font color=red>/url</font>&gt;
* &lt;<font color=red>sync-provider</font>&gt; * &lt;<font color=red>sync-provider</font>&gt;
* &lt;<font color=red>sync-provider-name</font>&gt;.com.rowset.provider.RIOptimisticProvider&lt;<font color=red>/sync-provider-name</font>&gt; * &lt;<font color=red>sync-provider-name</font>&gt;.com.rowset.provider.RIOptimisticProvider&lt;<font color=red>/sync-provider-name</font>&gt;
* &lt;<font color=red>sync-provider-vendor</font>&gt;Sun Microsystems&lt;<font color=red>/sync-provider-vendor</font>&gt; * &lt;<font color=red>sync-provider-vendor</font>&gt;Oracle Corporation&lt;<font color=red>/sync-provider-vendor</font>&gt;
* &lt;<font color=red>sync-provider-version</font>&gt;1.0&lt;<font color=red>/sync-provider-name</font>&gt; * &lt;<font color=red>sync-provider-version</font>&gt;1.0&lt;<font color=red>/sync-provider-name</font>&gt;
* &lt;<font color=red>sync-provider-grade</font>&gt;LOW&lt;<font color=red>/sync-provider-grade</font>&gt; * &lt;<font color=red>sync-provider-grade</font>&gt;LOW&lt;<font color=red>/sync-provider-grade</font>&gt;
* &lt;<font color=red>data-source-lock</font>&gt;NONE&lt;<font color=red>/data-source-lock</font>&gt; * &lt;<font color=red>data-source-lock</font>&gt;NONE&lt;<font color=red>/data-source-lock</font>&gt;
@ -489,7 +489,7 @@ public interface WebRowSet extends CachedRowSet {
* tags and their valid values for a <code>WebRowSet</code> implementation. * tags and their valid values for a <code>WebRowSet</code> implementation.
*/ */
public static String PUBLIC_XML_SCHEMA = public static String PUBLIC_XML_SCHEMA =
"--//Sun Microsystems, Inc.//XSD Schema//EN"; "--//Oracle Corporation//XSD Schema//EN";
/** /**
* The URL for the XML Schema definition file that defines the XML tags and * The URL for the XML Schema definition file that defines the XML tags and

View File

@ -3,10 +3,10 @@
# Optimistic synchonriztaion provider # Optimistic synchonriztaion provider
rowset.provider.classname.0=com.sun.rowset.providers.RIOptimisticProvider rowset.provider.classname.0=com.sun.rowset.providers.RIOptimisticProvider
rowset.provider.vendor.0=Sun Microsystems Inc rowset.provider.vendor.0=Oracle Corporation
rowset.provider.version.0=1.0 rowset.provider.version.0=1.0
# XML Provider using standard XML schema # XML Provider using standard XML schema
rowset.provider.classname.1=com.sun.rowset.providers.RIXMLProvider rowset.provider.classname.1=com.sun.rowset.providers.RIXMLProvider
rowset.provider.vendor.1=Sun Microsystems Inc. rowset.provider.vendor.1=Oracle Corporation
rowset.provider.version.1=1.0 rowset.provider.version.1=1.0

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -137,7 +137,7 @@ public class SQLOutputImpl implements SQLOutput {
* values of a UDT to the database. * values of a UDT to the database.
*/ */
public void writeBoolean(boolean x) throws SQLException { public void writeBoolean(boolean x) throws SQLException {
attribs.add(new Boolean(x)); attribs.add(Boolean.valueOf(x));
} }
/** /**
@ -151,7 +151,7 @@ public class SQLOutputImpl implements SQLOutput {
* values of a UDT to the database. * values of a UDT to the database.
*/ */
public void writeByte(byte x) throws SQLException { public void writeByte(byte x) throws SQLException {
attribs.add(new Byte(x)); attribs.add(Byte.valueOf(x));
} }
/** /**
@ -165,7 +165,7 @@ public class SQLOutputImpl implements SQLOutput {
* values of a UDT to the database. * values of a UDT to the database.
*/ */
public void writeShort(short x) throws SQLException { public void writeShort(short x) throws SQLException {
attribs.add(new Short(x)); attribs.add(Short.valueOf(x));
} }
/** /**
@ -179,7 +179,7 @@ public class SQLOutputImpl implements SQLOutput {
* values of a UDT to the database. * values of a UDT to the database.
*/ */
public void writeInt(int x) throws SQLException { public void writeInt(int x) throws SQLException {
attribs.add(new Integer(x)); attribs.add(Integer.valueOf(x));
} }
/** /**
@ -193,7 +193,7 @@ public class SQLOutputImpl implements SQLOutput {
* values of a UDT to the database. * values of a UDT to the database.
*/ */
public void writeLong(long x) throws SQLException { public void writeLong(long x) throws SQLException {
attribs.add(new Long(x)); attribs.add(Long.valueOf(x));
} }
/** /**

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -77,7 +77,7 @@ public class SerialRef implements Ref, Serializable, Cloneable {
throw new SQLException("Cannot instantiate a SerialRef object " + throw new SQLException("Cannot instantiate a SerialRef object " +
"that returns a null base type name"); "that returns a null base type name");
} else { } else {
baseTypeName = new String(ref.getBaseTypeName()); baseTypeName = ref.getBaseTypeName();
} }
} }
@ -110,7 +110,7 @@ public class SerialRef implements Ref, Serializable, Cloneable {
throws SerialException throws SerialException
{ {
map = new Hashtable(map); map = new Hashtable(map);
if (!object.equals(null)) { if (object != null) {
return map.get(object); return map.get(object);
} else { } else {
throw new SerialException("The object is not set"); throw new SerialException("The object is not set");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -94,7 +94,7 @@ public class SerialStruct implements Struct, Serializable, Cloneable {
try { try {
// get the type name // get the type name
SQLTypeName = new String(in.getSQLTypeName()); SQLTypeName = in.getSQLTypeName();
System.out.println("SQLTypeName: " + SQLTypeName); System.out.println("SQLTypeName: " + SQLTypeName);
// get the attributes of the struct // get the attributes of the struct
@ -137,7 +137,7 @@ public class SerialStruct implements Struct, Serializable, Cloneable {
try { try {
//set the type name //set the type name
SQLTypeName = new String(in.getSQLTypeName()); SQLTypeName = in.getSQLTypeName();
Vector tmp = new Vector(); Vector tmp = new Vector();
in.writeSQL(new SQLOutputImpl(tmp, map)); in.writeSQL(new SQLOutputImpl(tmp, map));
@ -247,7 +247,7 @@ public class SerialStruct implements Struct, Serializable, Cloneable {
} }
/** /**
* The identifier that assists in the serialization of this * The identifier that assists in the serialization of this
* <code>SerialStruct</code> object. * <code>SerialStruct</code> object.
*/ */
static final long serialVersionUID = -8322445504027483372L; static final long serialVersionUID = -8322445504027483372L;

View File

@ -125,12 +125,12 @@ import javax.naming.*;
* *
* # Optimistic synchronization provider * # Optimistic synchronization provider
* rowset.provider.classname.0=com.sun.rowset.providers.RIOptimisticProvider * rowset.provider.classname.0=com.sun.rowset.providers.RIOptimisticProvider
* rowset.provider.vendor.0=Sun Microsystems Inc * rowset.provider.vendor.0=Oracle Corporation
* rowset.provider.version.0=1.0 * rowset.provider.version.0=1.0
* *
* # XML Provider using standard XML schema * # XML Provider using standard XML schema
* rowset.provider.classname.1=com.sun.rowset.providers.RIXMLProvider * rowset.provider.classname.1=com.sun.rowset.providers.RIXMLProvider
* rowset.provider.vendor.1=Sun Microsystems Inc. * rowset.provider.vendor.1=Oracle Corporation
* rowset.provider.version.1=1.0 * rowset.provider.version.1=1.0
* </PRE> * </PRE>
* The <code>SyncFactory</code> checks this file and registers the * The <code>SyncFactory</code> checks this file and registers the
@ -369,7 +369,7 @@ public class SyncFactory {
try { try {
// check if user is supplying his Synchronisation Provider // check if user is supplying his Synchronisation Provider
// Implementation if not use Sun's implementation. // Implementation if not using Oracle's implementation.
// properties.load(new FileInputStream(ROWSET_PROPERTIES)); // properties.load(new FileInputStream(ROWSET_PROPERTIES));
// The rowset.properties needs to be in jdk/jre/lib when // The rowset.properties needs to be in jdk/jre/lib when

View File

@ -91,8 +91,8 @@ import javax.sql.*;
* </pre> * </pre>
* <p> * <p>
* A vendor can register a <code>SyncProvider</code> implementation class name * A vendor can register a <code>SyncProvider</code> implementation class name
* with Sun Microsystems, Inc. by sending email to jdbc@sun.com. * with Oracle Corporation by sending email to jdbc@sun.com.
* Sun will maintain a database listing the * Oracle will maintain a database listing the
* available <code>SyncProvider</code> implementations for use with compliant * available <code>SyncProvider</code> implementations for use with compliant
* <code>RowSet</code> implementations. This database will be similar to the * <code>RowSet</code> implementations. This database will be similar to the
* one already maintained to list available JDBC drivers. * one already maintained to list available JDBC drivers.

View File

@ -8,7 +8,7 @@
<meta name="GENERATOR" <meta name="GENERATOR"
content="Mozilla/4.79 [en] (Windows NT 5.0; U) [Netscape]"> content="Mozilla/4.79 [en] (Windows NT 5.0; U) [Netscape]">
<!-- <!--
Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it This code is free software; you can redistribute it and/or modify it
@ -199,7 +199,7 @@ specification for further details.
Vendors may develop a <tt>SyncProvider</tt> implementation with any one of the possible Vendors may develop a <tt>SyncProvider</tt> implementation with any one of the possible
levels of synchronization, thus giving <code>RowSet</code> objects a choice of levels of synchronization, thus giving <code>RowSet</code> objects a choice of
synchronization mechanisms. A vendor can make its implementation available by synchronization mechanisms. A vendor can make its implementation available by
registering the fully qualified class name with Sun Microsystems at registering the fully qualified class name with Oracle Corporation at
<code>jdbc@sun.com</code>. This process is discussed in further detail below. <code>jdbc@sun.com</code>. This process is discussed in further detail below.
<P> <P>

View File

@ -1464,8 +1464,8 @@ public class GroupLayout implements LayoutManager2 {
* &lt;= {@code pref} &lt;= {@code max}. * &lt;= {@code pref} &lt;= {@code max}.
* <p> * <p>
* Similarly any methods that take a {@code Component} throw a * Similarly any methods that take a {@code Component} throw a
* {@code NullPointerException} if passed {@code null} and any methods * {@code IllegalArgumentException} if passed {@code null} and any methods
* that take a {@code Group} throw an {@code IllegalArgumentException} if * that take a {@code Group} throw an {@code NullPointerException} if
* passed {@code null}. * passed {@code null}.
* *
* @see #createSequentialGroup * @see #createSequentialGroup

View File

@ -4787,6 +4787,17 @@ public abstract class JComponent extends Container implements Serializable,
* @see RepaintManager#addDirtyRegion * @see RepaintManager#addDirtyRegion
*/ */
public void repaint(long tm, int x, int y, int width, int height) { public void repaint(long tm, int x, int y, int width, int height) {
Container p = this;
while ((p = p.getParent()) instanceof JComponent) {
JComponent jp = (JComponent) p;
if (jp.isPaintingOrigin()) {
Rectangle rectangle = SwingUtilities.convertRectangle(
this, new Rectangle(x, y, width, height), jp);
jp.repaint(tm,
rectangle.x, rectangle.y, rectangle.width, rectangle.height);
return;
}
}
RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height); RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height);
} }

View File

@ -215,7 +215,8 @@ public class JDesktopPane extends JLayeredPane implements Accessible
/** /**
* Sets the <code>DesktopManger</code> that will handle * Sets the <code>DesktopManger</code> that will handle
* desktop-specific UI actions. * desktop-specific UI actions. This may be overridden by
* {@code LookAndFeel}.
* *
* @param d the <code>DesktopManager</code> to use * @param d the <code>DesktopManager</code> to use
* *

View File

@ -25,17 +25,17 @@
package javax.swing; package javax.swing;
import sun.awt.AWTAccessor;
import javax.swing.plaf.LayerUI; import javax.swing.plaf.LayerUI;
import javax.swing.border.Border;
import java.awt.*; import java.awt.*;
import java.awt.event.*; import java.awt.event.*;
import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener; import java.beans.PropertyChangeListener;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
@ -156,8 +156,6 @@ public final class JLayer<V extends Component>
private LayerUI<? super V> layerUI; private LayerUI<? super V> layerUI;
private JPanel glassPane; private JPanel glassPane;
private boolean isPainting; private boolean isPainting;
private static final DefaultLayerLayout sharedLayoutInstance =
new DefaultLayerLayout();
private long eventMask; private long eventMask;
private static final LayerEventController eventController = private static final LayerEventController eventController =
@ -165,7 +163,7 @@ public final class JLayer<V extends Component>
/** /**
* Creates a new {@code JLayer} object with a {@code null} view component * Creates a new {@code JLayer} object with a {@code null} view component
* and {@code null} {@link javax.swing.plaf.LayerUI}. * and default {@link javax.swing.plaf.LayerUI}.
* *
* @see #setView * @see #setView
* @see #setUI * @see #setUI
@ -176,14 +174,14 @@ public final class JLayer<V extends Component>
/** /**
* Creates a new {@code JLayer} object * Creates a new {@code JLayer} object
* with {@code null} {@link javax.swing.plaf.LayerUI}. * with default {@link javax.swing.plaf.LayerUI}.
* *
* @param view the component to be decorated by this {@code JLayer} * @param view the component to be decorated by this {@code JLayer}
* *
* @see #setUI * @see #setUI
*/ */
public JLayer(V view) { public JLayer(V view) {
this(view, null); this(view, new LayerUI<V>());
} }
/** /**
@ -195,7 +193,6 @@ public final class JLayer<V extends Component>
* to be used by this {@code JLayer} * to be used by this {@code JLayer}
*/ */
public JLayer(V view, LayerUI<V> ui) { public JLayer(V view, LayerUI<V> ui) {
setLayout(sharedLayoutInstance);
setGlassPane(createGlassPane()); setGlassPane(createGlassPane());
setView(view); setView(view);
setUI(ui); setUI(ui);
@ -279,10 +276,15 @@ public final class JLayer<V extends Component>
*/ */
public void setGlassPane(JPanel glassPane) { public void setGlassPane(JPanel glassPane) {
Component oldGlassPane = getGlassPane(); Component oldGlassPane = getGlassPane();
boolean isGlassPaneVisible = false;
if (oldGlassPane != null) { if (oldGlassPane != null) {
isGlassPaneVisible = oldGlassPane.isVisible();
super.remove(oldGlassPane); super.remove(oldGlassPane);
} }
if (glassPane != null) { if (glassPane != null) {
AWTAccessor.getComponentAccessor().setMixingCutoutShape(glassPane,
new Rectangle());
glassPane.setVisible(isGlassPaneVisible);
super.addImpl(glassPane, null, 0); super.addImpl(glassPane, null, 0);
} }
this.glassPane = glassPane; this.glassPane = glassPane;
@ -302,6 +304,40 @@ public final class JLayer<V extends Component>
return new DefaultLayerGlassPane(); return new DefaultLayerGlassPane();
} }
/**
* Sets the layout manager for this container. This method is
* overridden to prevent the layout manager from being set.
* <p/>Note: If {@code mgr} is non-{@code null}, this
* method will throw an exception as layout managers are not supported on
* a {@code JLayer}.
*
* @param mgr the specified layout manager
* @exception IllegalArgumentException this method is not supported
*/
public void setLayout(LayoutManager mgr) {
if (mgr != null) {
throw new IllegalArgumentException("JLayer.setLayout() not supported");
}
}
/**
* A non-{@code null] border, or non-zero insets, isn't supported, to prevent the geometry
* of this component from becoming complex enough to inhibit
* subclassing of {@code LayerUI} class. To create a {@code JLayer} with a border,
* add it to a {@code JPanel} that has a border.
* <p/>Note: If {@code border} is non-{@code null}, this
* method will throw an exception as borders are not supported on
* a {@code JLayer}.
*
* @param border the {@code Border} to set
* @exception IllegalArgumentException this method is not supported
*/
public void setBorder(Border border) {
if (border != null) {
throw new IllegalArgumentException("JLayer.setBorder() not supported");
}
}
/** /**
* This method is not supported by {@code JLayer} * This method is not supported by {@code JLayer}
* and always throws {@code UnsupportedOperationException} * and always throws {@code UnsupportedOperationException}
@ -340,6 +376,32 @@ public final class JLayer<V extends Component>
setGlassPane(null); setGlassPane(null);
} }
/**
* Always returns {@code true} to cause painting to originate from {@code JLayer},
* or one of its ancestors.
*
* @return true
* @see JComponent#isPaintingOrigin()
*/
boolean isPaintingOrigin() {
return true;
}
/**
* Delegates repainting to {@link javax.swing.plaf.LayerUI#repaint} method.
*
* @param tm this parameter is not used
* @param x the x value of the dirty region
* @param y the y value of the dirty region
* @param width the width of the dirty region
* @param height the height of the dirty region
*/
public void repaint(long tm, int x, int y, int width, int height) {
if (getUI() != null) {
getUI().repaint(tm, x, y, width, height, this);
}
}
/** /**
* Delegates all painting to the {@link javax.swing.plaf.LayerUI} object. * Delegates all painting to the {@link javax.swing.plaf.LayerUI} object.
* *
@ -364,14 +426,18 @@ public final class JLayer<V extends Component>
} }
/** /**
* To enable the correct painting of the {@code glassPane} and view component, * The {@code JLayer} overrides the default implementation of
* the {@code JLayer} overrides the default implementation of * this method (in {@code JComponent}) to return {@code false}.
* this method to return {@code false} when the {@code glassPane} is visible. * This ensures
* that the drawing machinery will call the {@code JLayer}'s
* {@code paint}
* implementation rather than messaging the {@code JLayer}'s
* children directly.
* *
* @return false if {@code JLayer}'s {@code glassPane} is visible * @return false
*/ */
public boolean isOptimizedDrawingEnabled() { public boolean isOptimizedDrawingEnabled() {
return glassPane == null || !glassPane.isVisible(); return false;
} }
/** /**
@ -461,17 +527,16 @@ public final class JLayer<V extends Component>
/** /**
* Returns the preferred size of the viewport for a view component. * Returns the preferred size of the viewport for a view component.
* <p/> * <p/>
* If the ui delegate of this layer is not {@code null}, this method delegates its * If the view component of this layer implements {@link Scrollable}, this method delegates its
* implementation to the {@code LayerUI.getPreferredScrollableViewportSize(JLayer)} * implementation to the view component.
* *
* @return the preferred size of the viewport for a view component * @return the preferred size of the viewport for a view component
* *
* @see Scrollable * @see Scrollable
* @see LayerUI#getPreferredScrollableViewportSize(JLayer)
*/ */
public Dimension getPreferredScrollableViewportSize() { public Dimension getPreferredScrollableViewportSize() {
if (getUI() != null) { if (getView() instanceof Scrollable) {
return getUI().getPreferredScrollableViewportSize(this); return ((Scrollable)getView()).getPreferredScrollableViewportSize();
} }
return getPreferredSize(); return getPreferredSize();
} }
@ -481,18 +546,17 @@ public final class JLayer<V extends Component>
* that display logical rows or columns in order to completely expose * that display logical rows or columns in order to completely expose
* one block of rows or columns, depending on the value of orientation. * one block of rows or columns, depending on the value of orientation.
* <p/> * <p/>
* If the ui delegate of this layer is not {@code null}, this method delegates its * If the view component of this layer implements {@link Scrollable}, this method delegates its
* implementation to the {@code LayerUI.getScrollableBlockIncrement(JLayer,Rectangle,int,int)} * implementation to the view component.
* *
* @return the "block" increment for scrolling in the specified direction * @return the "block" increment for scrolling in the specified direction
* *
* @see Scrollable * @see Scrollable
* @see LayerUI#getScrollableBlockIncrement(JLayer, Rectangle, int, int)
*/ */
public int getScrollableBlockIncrement(Rectangle visibleRect, public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation, int direction) { int orientation, int direction) {
if (getUI() != null) { if (getView() instanceof Scrollable) {
return getUI().getScrollableBlockIncrement(this, visibleRect, return ((Scrollable)getView()).getScrollableBlockIncrement(visibleRect,
orientation, direction); orientation, direction);
} }
return (orientation == SwingConstants.VERTICAL) ? visibleRect.height : return (orientation == SwingConstants.VERTICAL) ? visibleRect.height :
@ -504,17 +568,16 @@ public final class JLayer<V extends Component>
* determine the height of the layer, unless the preferred height * determine the height of the layer, unless the preferred height
* of the layer is smaller than the height of the viewport. * of the layer is smaller than the height of the viewport.
* <p/> * <p/>
* If the ui delegate of this layer is not null, this method delegates its * If the view component of this layer implements {@link Scrollable}, this method delegates its
* implementation to the {@code LayerUI.getScrollableTracksViewportHeight(JLayer)} * implementation to the view component.
* *
* @return whether the layer should track the height of the viewport * @return whether the layer should track the height of the viewport
* *
* @see Scrollable * @see Scrollable
* @see LayerUI#getScrollableTracksViewportHeight(JLayer)
*/ */
public boolean getScrollableTracksViewportHeight() { public boolean getScrollableTracksViewportHeight() {
if (getUI() != null) { if (getView() instanceof Scrollable) {
return getUI().getScrollableTracksViewportHeight(this); return ((Scrollable)getView()).getScrollableTracksViewportHeight();
} }
return false; return false;
} }
@ -524,17 +587,16 @@ public final class JLayer<V extends Component>
* determine the width of the layer, unless the preferred width * determine the width of the layer, unless the preferred width
* of the layer is smaller than the width of the viewport. * of the layer is smaller than the width of the viewport.
* <p/> * <p/>
* If the ui delegate of this layer is not null, this method delegates its * If the view component of this layer implements {@link Scrollable}, this method delegates its
* implementation to the {@code LayerUI.getScrollableTracksViewportWidth(JLayer)} * implementation to the view component.
* *
* @return whether the layer should track the width of the viewport * @return whether the layer should track the width of the viewport
* *
* @see Scrollable * @see Scrollable
* @see LayerUI#getScrollableTracksViewportWidth(JLayer)
*/ */
public boolean getScrollableTracksViewportWidth() { public boolean getScrollableTracksViewportWidth() {
if (getUI() != null) { if (getView() instanceof Scrollable) {
return getUI().getScrollableTracksViewportWidth(this); return ((Scrollable)getView()).getScrollableTracksViewportWidth();
} }
return false; return false;
} }
@ -549,20 +611,19 @@ public final class JLayer<V extends Component>
* Scrolling containers, like {@code JScrollPane}, will use this method * Scrolling containers, like {@code JScrollPane}, will use this method
* each time the user requests a unit scroll. * each time the user requests a unit scroll.
* <p/> * <p/>
* If the ui delegate of this layer is not {@code null}, this method delegates its * If the view component of this layer implements {@link Scrollable}, this method delegates its
* implementation to the {@code LayerUI.getScrollableUnitIncrement(JLayer,Rectangle,int,int)} * implementation to the view component.
* *
* @return The "unit" increment for scrolling in the specified direction. * @return The "unit" increment for scrolling in the specified direction.
* This value should always be positive. * This value should always be positive.
* *
* @see Scrollable * @see Scrollable
* @see LayerUI#getScrollableUnitIncrement(JLayer, Rectangle, int, int)
*/ */
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation,
int direction) { int direction) {
if (getUI() != null) { if (getView() instanceof Scrollable) {
return getUI().getScrollableUnitIncrement( return ((Scrollable) getView()).getScrollableUnitIncrement(
this, visibleRect, orientation, direction); visibleRect, orientation, direction);
} }
return 1; return 1;
} }
@ -594,6 +655,16 @@ public final class JLayer<V extends Component>
eventController.updateAWTEventListener(eventMask, 0); eventController.updateAWTEventListener(eventMask, 0);
} }
/**
* Delegates its functionality to the {@link javax.swing.plaf.LayerUI#doLayout(JLayer)} method,
* if {@code LayerUI} is set.
*/
public void doLayout() {
if (getUI() != null) {
getUI().doLayout(this);
}
}
/** /**
* static AWTEventListener to be shared with all AbstractLayerUIs * static AWTEventListener to be shared with all AbstractLayerUIs
*/ */
@ -625,8 +696,8 @@ public final class JLayer<V extends Component>
JLayer l = (JLayer) component; JLayer l = (JLayer) component;
LayerUI ui = l.getUI(); LayerUI ui = l.getUI();
if (ui != null && if (ui != null &&
isEventEnabled(l.getLayerEventMask(), isEventEnabled(l.getLayerEventMask(), event.getID()) &&
event.getID())) { (!(event instanceof InputEvent) || !((InputEvent)event).isConsumed())) {
ui.eventDispatched(event, l); ui.eventDispatched(event, l);
} }
} }
@ -758,82 +829,4 @@ public final class JLayer<V extends Component>
return super.contains(x, y); return super.contains(x, y);
} }
} }
/**
* The default layout manager for the {@link javax.swing.JLayer}.<br/>
* It places the glassPane on top of the view component
* and makes it the same size as {@code JLayer},
* it also makes the view component the same size but minus layer's insets<br/>
*/
private static class DefaultLayerLayout implements LayoutManager, Serializable {
/**
* {@inheritDoc}
*/
public void layoutContainer(Container parent) {
JLayer layer = (JLayer) parent;
Component view = layer.getView();
Component glassPane = layer.getGlassPane();
if (view != null) {
Insets insets = layer.getInsets();
view.setLocation(insets.left, insets.top);
view.setSize(layer.getWidth() - insets.left - insets.right,
layer.getHeight() - insets.top - insets.bottom);
}
if (glassPane != null) {
glassPane.setLocation(0, 0);
glassPane.setSize(layer.getWidth(), layer.getHeight());
}
}
/**
* {@inheritDoc}
*/
public Dimension minimumLayoutSize(Container parent) {
JLayer layer = (JLayer) parent;
Insets insets = layer.getInsets();
Dimension ret = new Dimension(insets.left + insets.right,
insets.top + insets.bottom);
Component view = layer.getView();
if (view != null) {
Dimension size = view.getMinimumSize();
ret.width += size.width;
ret.height += size.height;
}
if (ret.width == 0 || ret.height == 0) {
ret.width = ret.height = 4;
}
return ret;
}
/**
* {@inheritDoc}
*/
public Dimension preferredLayoutSize(Container parent) {
JLayer layer = (JLayer) parent;
Insets insets = layer.getInsets();
Dimension ret = new Dimension(insets.left + insets.right,
insets.top + insets.bottom);
Component view = layer.getView();
if (view != null) {
Dimension size = view.getPreferredSize();
if (size.width > 0 && size.height > 0) {
ret.width += size.width;
ret.height += size.height;
}
}
return ret;
}
/**
* {@inheritDoc}
*/
public void addLayoutComponent(String name, Component comp) {
}
/**
* {@inheritDoc}
*/
public void removeLayoutComponent(Component comp) {
}
}
} }

View File

@ -4574,9 +4574,8 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
* @see TableColumnModelListener * @see TableColumnModelListener
*/ */
public void columnMoved(TableColumnModelEvent e) { public void columnMoved(TableColumnModelEvent e) {
// If I'm currently editing, then I should stop editing if (isEditing() && !getCellEditor().stopCellEditing()) {
if (isEditing()) { getCellEditor().cancelCellEditing();
removeEditor();
} }
repaint(); repaint();
} }
@ -4593,8 +4592,8 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
* @see TableColumnModelListener * @see TableColumnModelListener
*/ */
public void columnMarginChanged(ChangeEvent e) { public void columnMarginChanged(ChangeEvent e) {
if (isEditing()) { if (isEditing() && !getCellEditor().stopCellEditing()) {
removeEditor(); getCellEditor().cancelCellEditing();
} }
TableColumn resizingColumn = getResizingColumn(); TableColumn resizingColumn = getResizingColumn();
// Need to do this here, before the parent's // Need to do this here, before the parent's

View File

@ -459,7 +459,7 @@ public class ToolTipManager extends MouseAdapter implements MouseMotionListener
if (insideComponent == null) { if (insideComponent == null) {
// Drag exit // Drag exit
} }
if (window != null && event.getSource() == window) { if (window != null && event.getSource() == window && insideComponent != null) {
// if we get an exit and have a heavy window // if we get an exit and have a heavy window
// we need to check if it if overlapping the inside component // we need to check if it if overlapping the inside component
Container insideComponentWindow = insideComponent.getTopLevelAncestor(); Container insideComponentWindow = insideComponent.getTopLevelAncestor();

View File

@ -599,104 +599,6 @@ public class LayerUI<V extends Component>
public void applyPropertyChange(PropertyChangeEvent evt, JLayer<? extends V> l) { public void applyPropertyChange(PropertyChangeEvent evt, JLayer<? extends V> l) {
} }
/**
* Returns the preferred size of the viewport for a view component.
*
* @param l the {@code JLayer} component where this UI delegate is being installed
* @return the preferred size of the viewport for a view component
* @see Scrollable#getPreferredScrollableViewportSize()
*/
public Dimension getPreferredScrollableViewportSize(JLayer<? extends V> l) {
if (l.getView() instanceof Scrollable) {
return ((Scrollable)l.getView()).getPreferredScrollableViewportSize();
}
return l.getPreferredSize();
}
/**
* Returns a scroll increment, which is required for components
* that display logical rows or columns in order to completely expose
* one block of rows or columns, depending on the value of orientation.
*
* @param l the {@code JLayer} component where this UI delegate is being installed
* @param visibleRect The view area visible within the viewport
* @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
* @param direction Less than zero to scroll up/left, greater than zero for down/right.
* @return the "block" increment for scrolling in the specified direction
* @see Scrollable#getScrollableBlockIncrement(Rectangle, int, int)
*/
public int getScrollableBlockIncrement(JLayer<? extends V> l,
Rectangle visibleRect,
int orientation, int direction) {
if (l.getView() instanceof Scrollable) {
return ((Scrollable)l.getView()).getScrollableBlockIncrement(
visibleRect,orientation, direction);
}
return (orientation == SwingConstants.VERTICAL) ? visibleRect.height :
visibleRect.width;
}
/**
* Returns {@code false} to indicate that the height of the viewport does not
* determine the height of the layer, unless the preferred height
* of the layer is smaller than the height of the viewport.
*
* @param l the {@code JLayer} component where this UI delegate is being installed
* @return whether the layer should track the height of the viewport
* @see Scrollable#getScrollableTracksViewportHeight()
*/
public boolean getScrollableTracksViewportHeight(JLayer<? extends V> l) {
if (l.getView() instanceof Scrollable) {
return ((Scrollable)l.getView()).getScrollableTracksViewportHeight();
}
return false;
}
/**
* Returns {@code false} to indicate that the width of the viewport does not
* determine the width of the layer, unless the preferred width
* of the layer is smaller than the width of the viewport.
*
* @param l the {@code JLayer} component where this UI delegate is being installed
* @return whether the layer should track the width of the viewport
* @see Scrollable
* @see LayerUI#getScrollableTracksViewportWidth(JLayer)
*/
public boolean getScrollableTracksViewportWidth(JLayer<? extends V> l) {
if (l.getView() instanceof Scrollable) {
return ((Scrollable)l.getView()).getScrollableTracksViewportWidth();
}
return false;
}
/**
* Returns a scroll increment, which is required for components
* that display logical rows or columns in order to completely expose
* one new row or column, depending on the value of orientation.
* Ideally, components should handle a partially exposed row or column
* by returning the distance required to completely expose the item.
* <p>
* Scrolling containers, like JScrollPane, will use this method
* each time the user requests a unit scroll.
*
* @param l the {@code JLayer} component where this UI delegate is being installed
* @param visibleRect The view area visible within the viewport
* @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
* @param direction Less than zero to scroll up/left, greater than zero for down/right.
* @return The "unit" increment for scrolling in the specified direction.
* This value should always be positive.
* @see Scrollable#getScrollableUnitIncrement(Rectangle, int, int)
*/
public int getScrollableUnitIncrement(JLayer<? extends V> l,
Rectangle visibleRect,
int orientation, int direction) {
if (l.getView() instanceof Scrollable) {
return ((Scrollable)l.getView()).getScrollableUnitIncrement(
visibleRect, orientation, direction);
}
return 1;
}
/** /**
* If the {@code JLayer}'s view component is not {@code null}, * If the {@code JLayer}'s view component is not {@code null},
* this calls the view's {@code getBaseline()} method. * this calls the view's {@code getBaseline()} method.
@ -718,7 +620,7 @@ public class LayerUI<V extends Component>
/** /**
* If the {@code JLayer}'s view component is not {@code null}, * If the {@code JLayer}'s view component is not {@code null},
* this calls the view's {@code getBaselineResizeBehavior()} method. * this returns the result of the view's {@code getBaselineResizeBehavior()} method.
* Otherwise, the default implementation is called. * Otherwise, the default implementation is called.
* *
* @param c {@code JLayer} to return baseline resize behavior for * @param c {@code JLayer} to return baseline resize behavior for
@ -732,4 +634,90 @@ public class LayerUI<V extends Component>
} }
return super.getBaselineResizeBehavior(c); return super.getBaselineResizeBehavior(c);
} }
/**
* Causes the passed instance of {@code JLayer} to lay out its components.
*
* @param l the {@code JLayer} component where this UI delegate is being installed
*/
public void doLayout(JLayer<? extends V> l) {
Component view = l.getView();
if (view != null) {
view.setBounds(0, 0, l.getWidth(), l.getHeight());
}
Component glassPane = l.getGlassPane();
if (glassPane != null) {
glassPane.setBounds(0, 0, l.getWidth(), l.getHeight());
}
}
/**
* If the {@code JLayer}'s view component is not {@code null},
* this returns the result of the view's {@code getPreferredSize()} method.
* Otherwise, the default implementation is used.
*
* @param c {@code JLayer} to return preferred size for
* @return preferred size for the passed {@code JLayer}
*/
public Dimension getPreferredSize(JComponent c) {
JLayer l = (JLayer) c;
Component view = l.getView();
if (view != null) {
return view.getPreferredSize();
}
return super.getPreferredSize(c);
}
/**
* If the {@code JLayer}'s view component is not {@code null},
* this returns the result of the view's {@code getMinimalSize()} method.
* Otherwise, the default implementation is used.
*
* @param c {@code JLayer} to return preferred size for
* @return minimal size for the passed {@code JLayer}
*/
public Dimension getMinimumSize(JComponent c) {
JLayer l = (JLayer) c;
Component view = l.getView();
if (view != null) {
return view.getMinimumSize();
}
return super.getMinimumSize(c);
}
/**
* If the {@code JLayer}'s view component is not {@code null},
* this returns the result of the view's {@code getMaximumSize()} method.
* Otherwise, the default implementation is used.
*
* @param c {@code JLayer} to return preferred size for
* @return maximun size for the passed {@code JLayer}
*/
public Dimension getMaximumSize(JComponent c) {
JLayer l = (JLayer) c;
Component view = l.getView();
if (view != null) {
return view.getMaximumSize();
}
return super.getMaximumSize(c);
}
/**
* Adds the specified region to the dirty region list if the component
* is showing. The component will be repainted after all of the
* currently pending events have been dispatched.
* <p/>
* This method is to be overridden when the dirty region needs to be changed.
*
* @param tm this parameter is not used
* @param x the x value of the dirty region
* @param y the y value of the dirty region
* @param width the width of the dirty region
* @param height the height of the dirty region
* @see java.awt.Component#isShowing
* @see RepaintManager#addDirtyRegion
*/
public void repaint(long tm, int x, int y, int width, int height, JLayer<? extends V> l) {
RepaintManager.currentManager(l).addDirtyRegion(l, x, y, width, height);
}
} }

View File

@ -1603,6 +1603,7 @@ public class BasicScrollBarUI
BoundedRangeModel newModel = (BoundedRangeModel)e.getNewValue(); BoundedRangeModel newModel = (BoundedRangeModel)e.getNewValue();
oldModel.removeChangeListener(modelListener); oldModel.removeChangeListener(modelListener);
newModel.addChangeListener(modelListener); newModel.addChangeListener(modelListener);
scrollBarValue = scrollbar.getValue();
scrollbar.repaint(); scrollbar.repaint();
scrollbar.revalidate(); scrollbar.revalidate();
} else if ("orientation" == propertyName) { } else if ("orientation" == propertyName) {

View File

@ -144,7 +144,7 @@ public class MetalComboBoxUI extends BasicComboBoxUI {
*/ */
public int getBaseline(JComponent c, int width, int height) { public int getBaseline(JComponent c, int width, int height) {
int baseline; int baseline;
if (MetalLookAndFeel.usingOcean()) { if (MetalLookAndFeel.usingOcean() && height >= 4) {
height -= 4; height -= 4;
baseline = super.getBaseline(c, width, height); baseline = super.getBaseline(c, width, height);
if (baseline >= 0) { if (baseline >= 0) {

View File

@ -115,6 +115,9 @@ public class SynthTabbedPaneUI extends BasicTabbedPaneUI
return new SynthTabbedPaneUI(); return new SynthTabbedPaneUI();
} }
private SynthTabbedPaneUI() {
}
private boolean scrollableTabLayoutEnabled() { private boolean scrollableTabLayoutEnabled() {
return (tabPane.getTabLayoutPolicy() == JTabbedPane.SCROLL_TAB_LAYOUT); return (tabPane.getTabLayoutPolicy() == JTabbedPane.SCROLL_TAB_LAYOUT);
} }

View File

@ -344,6 +344,11 @@ public final class AWTAccessor {
* Removes the last focus request for the heavyweight from the queue. * Removes the last focus request for the heavyweight from the queue.
*/ */
void removeLastFocusRequest(Component heavyweight); void removeLastFocusRequest(Component heavyweight);
/*
* Sets the most recent focus owner in the window.
*/
void setMostRecentFocusOwner(Window window, Component component);
} }
/* /*

View File

@ -70,7 +70,10 @@ public abstract class EmbeddedFrame extends Frame
// JDK 1.1 compatibility // JDK 1.1 compatibility
private static final long serialVersionUID = 2967042741780317130L; private static final long serialVersionUID = 2967042741780317130L;
// Use these in traverseOut method to determine directions /*
* The constants define focus traversal directions.
* Use them in {@code traverseIn}, {@code traverseOut} methods.
*/
protected static final boolean FORWARD = true; protected static final boolean FORWARD = true;
protected static final boolean BACKWARD = false; protected static final boolean BACKWARD = false;
@ -283,6 +286,41 @@ public abstract class EmbeddedFrame extends Frame
return false; return false;
} }
/**
* This method is called by the embedder when we should receive focus as element
* of the traversal chain. The method requests focus on:
* 1. the first Component of this EmbeddedFrame if user moves focus forward
* in the focus traversal cycle.
* 2. the last Component of this EmbeddedFrame if user moves focus backward
* in the focus traversal cycle.
*
* The direction parameter specifies which of the two mentioned cases is
* happening. Use FORWARD and BACKWARD constants defined in the EmbeddedFrame class
* to avoid confusing boolean values.
*
* A concrete implementation of this method is defined in the platform-dependent
* subclasses.
*
* @param direction FORWARD or BACKWARD
* @return true, if the EmbeddedFrame wants to get focus, false otherwise.
*/
public boolean traverseIn(boolean direction) {
Component comp = null;
if (direction == FORWARD) {
comp = getFocusTraversalPolicy().getFirstComponent(this);
} else {
comp = getFocusTraversalPolicy().getLastComponent(this);
}
if (comp != null) {
// comp.requestFocus(); - Leads to a hung.
AWTAccessor.getKeyboardFocusManagerAccessor().setMostRecentFocusOwner(this, comp);
synthesizeWindowActivation(true);
}
return (null != comp);
}
/** /**
* This method is called from dispatchKeyEvent in the following two cases: * This method is called from dispatchKeyEvent in the following two cases:
* 1. The focus is on the first Component of this EmbeddedFrame and we are * 1. The focus is on the first Component of this EmbeddedFrame and we are

View File

@ -55,6 +55,9 @@ public class HttpClient extends NetworkClient {
// Http data we send with the headers // Http data we send with the headers
PosterOutputStream poster = null; PosterOutputStream poster = null;
// true if we are in streaming mode (fixed length or chunked)
boolean streaming;
// if we've had one io error // if we've had one io error
boolean failedOnce = false; boolean failedOnce = false;
@ -275,6 +278,10 @@ public class HttpClient extends NetworkClient {
ret.cachedHttpClient = true; ret.cachedHttpClient = true;
assert ret.inCache; assert ret.inCache;
ret.inCache = false; ret.inCache = false;
PlatformLogger logger = HttpURLConnection.getHttpLogger();
if (logger.isLoggable(PlatformLogger.FINEST)) {
logger.finest("KeepAlive stream retrieved from the cache, " + ret);
}
} }
} else { } else {
// We cannot return this connection to the cache as it's // We cannot return this connection to the cache as it's
@ -545,6 +552,13 @@ public class HttpClient extends NetworkClient {
serverOutput.flush(); serverOutput.flush();
} }
public void writeRequests(MessageHeader head,
PosterOutputStream pos,
boolean streaming) throws IOException {
this.streaming = streaming;
writeRequests(head, pos);
}
/** Parse the first line of the HTTP request. It usually looks /** Parse the first line of the HTTP request. It usually looks
something like: "HTTP/1.0 <number> comment\r\n". */ something like: "HTTP/1.0 <number> comment\r\n". */
@ -577,11 +591,11 @@ public class HttpClient extends NetworkClient {
closeServer(); closeServer();
cachedHttpClient = false; cachedHttpClient = false;
if (!failedOnce && requests != null) { if (!failedOnce && requests != null) {
if (httpuc.getRequestMethod().equals("POST") && !retryPostProp) { failedOnce = true;
if (httpuc.getRequestMethod().equals("POST") && (!retryPostProp || streaming)) {
// do not retry the request // do not retry the request
} else { } else {
// try once more // try once more
failedOnce = true;
openServer(); openServer();
if (needsTunneling()) { if (needsTunneling()) {
httpuc.doTunneling(); httpuc.doTunneling();
@ -684,10 +698,10 @@ public class HttpClient extends NetworkClient {
} }
} else if (nread != 8) { } else if (nread != 8) {
if (!failedOnce && requests != null) { if (!failedOnce && requests != null) {
if (httpuc.getRequestMethod().equals("POST") && !retryPostProp) { failedOnce = true;
if (httpuc.getRequestMethod().equals("POST") && (!retryPostProp || streaming)) {
// do not retry the request // do not retry the request
} else { } else {
failedOnce = true;
closeServer(); closeServer();
cachedHttpClient = false; cachedHttpClient = false;
openServer(); openServer();

View File

@ -494,7 +494,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
if (logger.isLoggable(PlatformLogger.FINE)) { if (logger.isLoggable(PlatformLogger.FINE)) {
logger.fine(requests.toString()); logger.fine(requests.toString());
} }
http.writeRequests(requests, poster); http.writeRequests(requests, poster, streaming());
if (ps.checkError()) { if (ps.checkError()) {
String proxyHost = http.getProxyHostUsed(); String proxyHost = http.getProxyHostUsed();
int proxyPort = http.getProxyPortUsed(); int proxyPort = http.getProxyPortUsed();
@ -2825,6 +2825,38 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
} }
} }
/* skip() calls read() in order to ensure that entire response gets
* cached. same implementation as InputStream.skip */
private byte[] skipBuffer;
private static final int SKIP_BUFFER_SIZE = 8096;
@Override
public long skip (long n) throws IOException {
long remaining = n;
int nr;
if (skipBuffer == null)
skipBuffer = new byte[SKIP_BUFFER_SIZE];
byte[] localSkipBuffer = skipBuffer;
if (n <= 0) {
return 0;
}
while (remaining > 0) {
nr = read(localSkipBuffer, 0,
(int) Math.min(SKIP_BUFFER_SIZE, remaining));
if (nr < 0) {
break;
}
remaining -= nr;
}
return n - remaining;
}
@Override @Override
public void close () throws IOException { public void close () throws IOException {
try { try {

View File

@ -281,7 +281,7 @@ public final class KeyTool {
RFC("rfc", null, "output in RFC style"), RFC("rfc", null, "output in RFC style"),
SIGALG("sigalg", "<sigalg>", "signature algorithm name"), SIGALG("sigalg", "<sigalg>", "signature algorithm name"),
SRCALIAS("srcalias", "<srcalias>", "source alias"), SRCALIAS("srcalias", "<srcalias>", "source alias"),
SRCKEYPASS("srckeypass", "<arg>", "source keystore password"), SRCKEYPASS("srckeypass", "<arg>", "source key password"),
SRCKEYSTORE("srckeystore", "<srckeystore>", "source keystore name"), SRCKEYSTORE("srckeystore", "<srckeystore>", "source keystore name"),
SRCPROTECTED("srcprotected", null, "source keystore password protected"), SRCPROTECTED("srcprotected", null, "source keystore password protected"),
SRCPROVIDERNAME("srcprovidername", "<srcprovidername>", "source keystore provider name"), SRCPROVIDERNAME("srcprovidername", "<srcprovidername>", "source keystore provider name"),

View File

@ -116,11 +116,9 @@ public class Resources extends java.util.ListResourceBundle {
{"X.509 extension", {"X.509 extension",
"X.509 extension"}, //-ext "X.509 extension"}, //-ext
{"output file name", {"output file name",
"output file name"}, //-file "output file name"}, //-file and -outfile
{"input file name", {"input file name",
"input file name"}, //-file "input file name"}, //-file and -infile
{"input file name",
"input file name"}, //-infile
{"key algorithm name", {"key algorithm name",
"key algorithm name"}, //-keyalg "key algorithm name"}, //-keyalg
{"key password", {"key password",
@ -133,8 +131,6 @@ public class Resources extends java.util.ListResourceBundle {
"new password"}, //-new "new password"}, //-new
{"do not prompt", {"do not prompt",
"do not prompt"}, //-noprompt "do not prompt"}, //-noprompt
{"output file name",
"output file name"}, //-outfile
{"password through protected mechanism", {"password through protected mechanism",
"password through protected mechanism"}, //-protected "password through protected mechanism"}, //-protected
{"provider argument", {"provider argument",
@ -151,8 +147,8 @@ public class Resources extends java.util.ListResourceBundle {
"signature algorithm name"}, //-sigalg "signature algorithm name"}, //-sigalg
{"source alias", {"source alias",
"source alias"}, //-srcalias "source alias"}, //-srcalias
{"source keystore password", {"source key password",
"source keystore password"}, //-srckeypass "source key password"}, //-srckeypass
{"source keystore name", {"source keystore name",
"source keystore name"}, //-srckeystore "source keystore name"}, //-srckeystore
{"source keystore password protected", {"source keystore password protected",
@ -276,8 +272,6 @@ public class Resources extends java.util.ListResourceBundle {
"Alias <{0}> has no certificate"}, "Alias <{0}> has no certificate"},
{"Key pair not generated, alias <alias> already exists", {"Key pair not generated, alias <alias> already exists",
"Key pair not generated, alias <{0}> already exists"}, "Key pair not generated, alias <{0}> already exists"},
{"Cannot derive signature algorithm",
"Cannot derive signature algorithm"},
{"Generating keysize bit keyAlgName key pair and self-signed certificate (sigAlgName) with a validity of validality days\n\tfor: x500Name", {"Generating keysize bit keyAlgName key pair and self-signed certificate (sigAlgName) with a validity of validality days\n\tfor: x500Name",
"Generating {0} bit {1} key pair and self-signed certificate ({2}) with a validity of {3} days\n\tfor: {4}"}, "Generating {0} bit {1} key pair and self-signed certificate ({2}) with a validity of {3} days\n\tfor: {4}"},
{"Enter key password for <alias>", "Enter key password for <{0}>"}, {"Enter key password for <alias>", "Enter key password for <{0}>"},
@ -321,8 +315,6 @@ public class Resources extends java.util.ListResourceBundle {
{"Failed to parse input", "Failed to parse input"}, {"Failed to parse input", "Failed to parse input"},
{"Empty input", "Empty input"}, {"Empty input", "Empty input"},
{"Not X.509 certificate", "Not X.509 certificate"}, {"Not X.509 certificate", "Not X.509 certificate"},
{"Cannot derive signature algorithm",
"Cannot derive signature algorithm"},
{"alias has no public key", "{0} has no public key"}, {"alias has no public key", "{0} has no public key"},
{"alias has no X.509 certificate", "{0} has no X.509 certificate"}, {"alias has no X.509 certificate", "{0} has no X.509 certificate"},
{"New certificate (self-signed):", "New certificate (self-signed):"}, {"New certificate (self-signed):", "New certificate (self-signed):"},
@ -552,7 +544,6 @@ public class Resources extends java.util.ListResourceBundle {
{"package name", "package name"}, {"package name", "package name"},
{"policy type", "policy type"}, {"policy type", "policy type"},
{"property name", "property name"}, {"property name", "property name"},
{"provider name", "provider name"},
{"Principal List", "Principal List"}, {"Principal List", "Principal List"},
{"Permission List", "Permission List"}, {"Permission List", "Permission List"},
{"Code Base", "Code Base"}, {"Code Base", "Code Base"},

View File

@ -64,12 +64,14 @@ public final class BaseLocale {
public static BaseLocale getInstance(String language, String script, String region, String variant) { public static BaseLocale getInstance(String language, String script, String region, String variant) {
// JDK uses deprecated ISO639.1 language codes for he, yi and id // JDK uses deprecated ISO639.1 language codes for he, yi and id
if (AsciiUtil.caseIgnoreMatch(language, "he")) { if (language != null) {
language = "iw"; if (AsciiUtil.caseIgnoreMatch(language, "he")) {
} else if (AsciiUtil.caseIgnoreMatch(language, "yi")) { language = "iw";
language = "ji"; } else if (AsciiUtil.caseIgnoreMatch(language, "yi")) {
} else if (AsciiUtil.caseIgnoreMatch(language, "id")) { language = "ji";
language = "in"; } else if (AsciiUtil.caseIgnoreMatch(language, "id")) {
language = "in";
}
} }
Key key = new Key(language, script, region, variant); Key key = new Key(language, script, region, variant);

View File

@ -0,0 +1,664 @@
/*
* Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.net.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.nio.file.StandardOpenOption.*;
import static java.nio.file.StandardCopyOption.*;
/*
* ZipFileSystem usage demo
*
* java [-cp .../zipfs.jar:./] Demo action ZipfileName [...]
*
* To deploy the provider, either copy the zipfs.jar into JDK/JRE
* extensions directory or add
* <JDK_HOME>/demo/nio/ZipFileSystem/zipfs.jar
* into your class path as showed above.
*
* @author Xueming Shen
*/
public class Demo {
static enum Action {
rename, // <java Demo rename zipfile src dst>
// rename entry src to dst inside zipfile
movein, // <java Demo movein zipfile src dst>
// move an external src file into zipfile
// as entry dst
moveout, // <java Demo moveout zipfile src dst>
// move a zipfile entry src out to dst
copy, // <java Demo copy zipfile src dst>
// copy entry src to dst inside zipfile
copyin, // <java Demo copyin zipfile src dst>
// copy an external src file into zipfile
// as entry dst
copyout, // <java Demo copyout zipfile src dst>
// copy zipfile entry src" out to file dst
zzmove, // <java Demo zzmove zfsrc zfdst path>
// move entry path/dir from zfsrc to zfdst
zzcopy, // <java Demo zzcopy zfsrc zfdst path>
// copy path from zipfile zfsrc to zipfile
// zfdst
attrs, // <java Demo attrs zipfile path>
// printout the attributes of entry path
attrsspace, // <java Demo attrsspace zipfile path>
// printout the storespace attrs of entry path
setmtime, // <java Demo setmtime zipfile "MM/dd/yy-HH:mm:ss" path...>
// set the lastModifiedTime of entry path
lsdir, // <java Demo lsdir zipfile dir>
// list dir's direct child files/dirs
mkdir, // <java Demo mkdir zipfile dir>
mkdirs, // <java Demo mkdirs zipfile dir>
rmdirs, // <java Demo rmdirs zipfile dir>
list, // <java Demo list zipfile [dir]>
// recursively list all entries of dir
// via DirectoryStream
tlist, // <java Demo tlist zipfile [dir]>
// list with buildDirTree=true
vlist, // <java Demo vlist zipfile [dir]>
// recursively verbose list all entries of
// dir via DirectoryStream
walk, // <java Demo walk zipfile [dir]>
// recursively walk all entries of dir
// via Files.walkFileTree
twalk, // <java Demo twalk zipfile [dir]>
// walk with buildDirTree=true
extract, // <java Demo extract zipfile file [...]>
update, // <java Demo extract zipfile file [...]>
delete, // <java Demo delete zipfile file [...]>
add, // <java Demo add zipfile file [...]>
create, // <java Demo create zipfile file [...]>
// create a new zipfile if it doesn't exit
// and then add the file(s) into it.
attrs2, // <java Demo attrs2 zipfile file [...]>
// test different ways to print attrs
}
public static void main(String[] args) throws Throwable {
Action action = Action.valueOf(args[0]);;
Map<String, Object> env = env = new HashMap<String, Object>();
if (action == Action.create)
env.put("createNew", true);
if (action == Action.tlist || action == Action.twalk)
env.put("buildDirTree", true);
FileSystem fs = FileSystems.newFileSystem(
URI.create("zip" + Paths.get(args[1]).toUri().toString().substring(4)),
env,
null);
try {
FileSystem fs2;
Path path, src, dst;
boolean isRename = false;
switch (action) {
case rename:
src = fs.getPath(args[2]);
dst = fs.getPath(args[3]);
src.moveTo(dst);
break;
case moveout:
src = fs.getPath(args[2]);
dst = Paths.get(args[3]);
src.moveTo(dst);
break;
case movein:
src = Paths.get(args[2]);
dst = fs.getPath(args[3]);
src.moveTo(dst);
break;
case copy:
src = fs.getPath(args[2]);
dst = fs.getPath(args[3]);
src.copyTo(dst);
break;
case copyout:
src = fs.getPath(args[2]);
dst = Paths.get(args[3]);
src.copyTo(dst);
break;
case copyin:
src = Paths.get(args[2]);
dst = fs.getPath(args[3]);
src.copyTo(dst);
break;
case zzmove:
fs2 = FileSystems.newFileSystem(
URI.create("zip" + Paths.get(args[2]).toUri().toString().substring(4)),
env,
null);
//sf1.getPath(args[3]).moveTo(fs2.getPath(args[3]));
z2zmove(fs, fs2, args[3]);
fs2.close();
break;
case zzcopy:
fs2 = FileSystems.newFileSystem(
URI.create("zip" + Paths.get(args[2]).toUri().toString().substring(4)),
env,
null);
//sf1.getPath(args[3]).copyTo(fs2.getPath(args[3]));
z2zcopy(fs, fs2, args[3]);
fs2.close();
break;
case attrs:
for (int i = 2; i < args.length; i++) {
path = fs.getPath(args[i]);
System.out.println(
Attributes.readBasicFileAttributes(path).toString());
}
break;
case setmtime:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
Date newDatetime = df.parse(args[2]);
for (int i = 3; i < args.length; i++) {
path = fs.getPath(args[i]);
path.setAttribute("lastModifiedTime",
FileTime.fromMillis(newDatetime.getTime()));
System.out.println(
Attributes.readBasicFileAttributes(path).toString());
}
break;
case attrsspace:
path = fs.getPath("/");
FileStore fstore = path.getFileStore();
//System.out.println(fstore.getFileStoreAttributeView(FileStoreSpaceAttributeView.class)
// .readAttributes());
// or
System.out.printf("filestore[%s]%n", fstore.name());
System.out.printf(" totalSpace: %d%n",
(Long)fstore.getAttribute("space:totalSpace"));
System.out.printf(" usableSpace: %d%n",
(Long)fstore.getAttribute("space:usableSpace"));
System.out.printf(" unallocSpace: %d%n",
(Long)fstore.getAttribute("space:unallocatedSpace"));
break;
case list:
case tlist:
if (args.length < 3)
list(fs.getPath("/"), false);
else
list(fs.getPath(args[2]), false);
break;
case vlist:
if (args.length < 3)
list(fs.getPath("/"), true);
else
list(fs.getPath(args[2]), true);
break;
case twalk:
case walk:
walk(fs.getPath((args.length > 2)? args[2] : "/"));
break;
case extract:
if (args.length == 2) {
extract(fs, "/");
} else {
for (int i = 2; i < args.length; i++) {
extract(fs, args[i]);
}
}
break;
case delete:
for (int i = 2; i < args.length; i++)
fs.getPath(args[i]).delete();
break;
case create:
case add:
case update:
for (int i = 2; i < args.length; i++) {
update(fs, args[i]);
}
break;
case lsdir:
path = fs.getPath(args[2]);
final String fStr = (args.length > 3)?args[3]:"";
DirectoryStream<Path> ds = path.newDirectoryStream(
new DirectoryStream.Filter<Path>() {
public boolean accept(Path path) {
return path.toString().contains(fStr);
}
});
for (Path p : ds)
System.out.println(p);
break;
case mkdir:
fs.getPath(args[2]).createDirectory();
break;
case mkdirs:
mkdirs(fs.getPath(args[2]));
break;
case attrs2:
for (int i = 2; i < args.length; i++) {
path = fs.getPath(args[i]);
System.out.println("-------(1)---------");
System.out.println(
Attributes.readBasicFileAttributes(path).toString());
System.out.println("-------(2)---------");
Map<String, ?> map = path.readAttributes("zip:*");
for (Map.Entry<String, ?> e : map.entrySet()) {
System.out.printf(" %s : %s%n", e.getKey(), e.getValue());
}
System.out.println("-------(3)---------");
map = path.readAttributes("size,lastModifiedTime,isDirectory");
for (Map.Entry<String, ?> e : map.entrySet()) {
System.out.printf(" %s : %s%n", e.getKey(), e.getValue());
}
}
break;
}
} catch (Exception x) {
x.printStackTrace();
} finally {
if (fs != null)
fs.close();
}
}
private static byte[] getBytes(String name) {
return name.getBytes();
}
private static String getString(byte[] name) {
return new String(name);
}
private static void walk(Path path) throws IOException
{
Files.walkFileTree(
path,
new SimpleFileVisitor<Path>() {
private int indent = 0;
private void indent() {
int n = 0;
while (n++ < indent)
System.out.printf(" ");
}
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs)
{
indent();
System.out.printf("%s%n", file.getName().toString());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs)
{
indent();
System.out.printf("[%s]%n", dir.toString());
indent += 2;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException ioe)
{
indent -= 2;
return FileVisitResult.CONTINUE;
}
});
}
private static void update(FileSystem fs, String path) throws Throwable{
Path src = FileSystems.getDefault().getPath(path);
if (Boolean.TRUE.equals(src.getAttribute("isDirectory"))) {
DirectoryStream<Path> ds = src.newDirectoryStream();
for (Path child : ds)
update(fs, child.toString());
ds.close();
} else {
Path dst = fs.getPath(path);
Path parent = dst.getParent();
if (parent != null && parent.notExists())
mkdirs(parent);
src.copyTo(dst, REPLACE_EXISTING);
}
}
private static void extract(FileSystem fs, String path) throws Throwable{
Path src = fs.getPath(path);
if (Boolean.TRUE.equals(src.getAttribute("isDirectory"))) {
DirectoryStream<Path> ds = src.newDirectoryStream();
for (Path child : ds)
extract(fs, child.toString());
ds.close();
} else {
if (path.startsWith("/"))
path = path.substring(1);
Path dst = FileSystems.getDefault().getPath(path);
Path parent = dst.getParent();
if (parent.notExists())
mkdirs(parent);
src.copyTo(dst, REPLACE_EXISTING);
}
}
// use DirectoryStream
private static void z2zcopy(FileSystem src, FileSystem dst, String path)
throws IOException
{
Path srcPath = src.getPath(path);
Path dstPath = dst.getPath(path);
if (Boolean.TRUE.equals(srcPath.getAttribute("isDirectory"))) {
if (!dstPath.exists()) {
try {
mkdirs(dstPath);
} catch (FileAlreadyExistsException x) {}
}
DirectoryStream<Path> ds = srcPath.newDirectoryStream();
for (Path child : ds) {
z2zcopy(src, dst,
path + (path.endsWith("/")?"":"/") + child.getName());
}
ds.close();
} else {
//System.out.println("copying..." + path);
srcPath.copyTo(dstPath);
}
}
// use TreeWalk to move
private static void z2zmove(FileSystem src, FileSystem dst, String path)
throws IOException
{
final Path srcPath = src.getPath(path).toAbsolutePath();
final Path dstPath = dst.getPath(path).toAbsolutePath();
Files.walkFileTree(srcPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs)
{
Path dst = srcPath.relativize(file);
dst = dstPath.resolve(dst);
try {
Path parent = dstPath.getParent();
if (parent != null && parent.notExists())
mkdirs(parent);
file.moveTo(dst);
} catch (IOException x) {
x.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs)
{
Path dst = srcPath.relativize(dir);
dst = dstPath.resolve(dst);
try {
if (dst.notExists())
mkdirs(dst);
} catch (IOException x) {
x.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException ioe)
throws IOException
{
try {
dir.delete();
} catch (IOException x) {
//x.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
});
}
private static void mkdirs(Path path) throws IOException {
path = path.toAbsolutePath();
Path parent = path.getParent();
if (parent != null) {
if (parent.notExists())
mkdirs(parent);
}
path.createDirectory();
}
private static void rmdirs(Path path) throws IOException {
while (path != null && path.getNameCount() != 0) {
path.delete();
path = path.getParent();
}
}
private static void list(Path path, boolean verbose ) throws IOException {
if (verbose)
System.out.println(Attributes.readBasicFileAttributes(path).toString());
else
System.out.printf(" %s%n", path.toString());
if (path.notExists())
return;
if (Attributes.readBasicFileAttributes(path).isDirectory()) {
DirectoryStream<Path> ds = path.newDirectoryStream();
for (Path child : ds)
list(child, verbose);
ds.close();
}
}
// check the content of two paths are equal
private static void checkEqual(Path src, Path dst) throws IOException
{
//System.out.printf("checking <%s> vs <%s>...%n",
// src.toString(), dst.toString());
//streams
InputStream isSrc = src.newInputStream();
InputStream isDst = dst.newInputStream();
byte[] bufSrc = new byte[8192];
byte[] bufDst = new byte[8192];
try {
int nSrc = 0;
while ((nSrc = isSrc.read(bufSrc)) != -1) {
int nDst = 0;
while (nDst < nSrc) {
int n = isDst.read(bufDst, nDst, nSrc - nDst);
if (n == -1) {
System.out.printf("checking <%s> vs <%s>...%n",
src.toString(), dst.toString());
throw new RuntimeException("CHECK FAILED!");
}
nDst += n;
}
while (--nSrc >= 0) {
if (bufSrc[nSrc] != bufDst[nSrc]) {
System.out.printf("checking <%s> vs <%s>...%n",
src.toString(), dst.toString());
throw new RuntimeException("CHECK FAILED!");
}
nSrc--;
}
}
} finally {
isSrc.close();
isDst.close();
}
// channels
SeekableByteChannel chSrc = src.newByteChannel();
SeekableByteChannel chDst = dst.newByteChannel();
if (chSrc.size() != chDst.size()) {
System.out.printf("src[%s].size=%d, dst[%s].size=%d%n",
chSrc.toString(), chSrc.size(),
chDst.toString(), chDst.size());
throw new RuntimeException("CHECK FAILED!");
}
ByteBuffer bbSrc = ByteBuffer.allocate(8192);
ByteBuffer bbDst = ByteBuffer.allocate(8192);
try {
int nSrc = 0;
while ((nSrc = chSrc.read(bbSrc)) != -1) {
int nDst = chDst.read(bbDst);
if (nSrc != nDst) {
System.out.printf("checking <%s> vs <%s>...%n",
src.toString(), dst.toString());
throw new RuntimeException("CHECK FAILED!");
}
while (--nSrc >= 0) {
if (bbSrc.get(nSrc) != bbDst.get(nSrc)) {
System.out.printf("checking <%s> vs <%s>...%n",
src.toString(), dst.toString());
throw new RuntimeException("CHECK FAILED!");
}
nSrc--;
}
bbSrc.flip();
bbDst.flip();
}
} catch (IOException x) {
x.printStackTrace();
} finally {
chSrc.close();
chDst.close();
}
}
private static void fchCopy(Path src, Path dst) throws IOException
{
Set<OpenOption> read = new HashSet<>();
read.add(READ);
Set<OpenOption> openwrite = new HashSet<>();
openwrite.add(CREATE_NEW);
openwrite.add(WRITE);
FileChannel srcFc = src.getFileSystem()
.provider()
.newFileChannel(src, read);
FileChannel dstFc = dst.getFileSystem()
.provider()
.newFileChannel(dst, openwrite);
try {
ByteBuffer bb = ByteBuffer.allocate(8192);
while (srcFc.read(bb) >= 0) {
bb.flip();
dstFc.write(bb);
bb.clear();
}
} finally {
srcFc.close();
dstFc.close();
}
}
private static void chCopy(Path src, Path dst) throws IOException
{
Set<OpenOption> read = new HashSet<>();
read.add(READ);
Set<OpenOption> openwrite = new HashSet<>();
openwrite.add(CREATE_NEW);
openwrite.add(WRITE);
SeekableByteChannel srcCh = src.newByteChannel(read);
SeekableByteChannel dstCh = dst.newByteChannel(openwrite);
try {
ByteBuffer bb = ByteBuffer.allocate(8192);
while (srcCh.read(bb) >= 0) {
bb.flip();
dstCh.write(bb);
bb.clear();
}
} finally {
srcCh.close();
dstCh.close();
}
}
private static void streamCopy(Path src, Path dst) throws IOException
{
InputStream isSrc = src.newInputStream();
OutputStream osDst = dst.newOutputStream();
byte[] buf = new byte[8192];
try {
int n = 0;
while ((n = isSrc.read(buf)) != -1) {
osDst.write(buf, 0, n);
}
} finally {
isSrc.close();
osDst.close();
}
}
}

View File

@ -0,0 +1,3 @@
com.sun.nio.zipfs.ZipFileSystemProvider
com.sun.nio.zipfs.JarFileSystemProvider

View File

@ -0,0 +1,29 @@
ZipFileSystem is a file system provider that treats the contents of a zip or
JAR file as a java.nio.file.FileSystem.
To deploy the provider you must copy zipfs.jar into your extensions
directory or else add <JDK_HOME>/demo/nio/ZipFileSystem/zipfs.jar
to your class path.
The factory methods defined by the java.nio.file.FileSystems class can be
used to create a FileSystem, eg:
// use file type detection
Map<String,?> env = Collections.emptyMap();
Path jarfile = Path.get("foo.jar");
FileSystem fs = FileSystems.newFileSystem(jarfile, env);
-or
// locate file system by URI
Map<String,?> env = Collections.emptyMap();
URI uri = URI.create("zip:///mydir/foo.jar");
FileSystem fs = FileSystems.newFileSystem(uri, env);
Once a FileSystem is created then classes in the java.nio.file package
can be used to access files in the zip/JAR file, eg:
Path mf = fs.getPath("/META-INF/MANIFEST.MF");
InputStream in = mf.newInputStream();

View File

@ -0,0 +1,71 @@
/*
* Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sun.nio.zipfs;
import java.nio.file.*;
import java.nio.file.spi.*;
import java.nio.file.attribute.*;
import java.nio.file.spi.FileSystemProvider;
import java.net.URI;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class JarFileSystemProvider extends ZipFileSystemProvider
{
@Override
public String getScheme() {
return "jar";
}
@Override
protected Path uriToPath(URI uri) {
String scheme = uri.getScheme();
if ((scheme == null) || !scheme.equalsIgnoreCase(getScheme())) {
throw new IllegalArgumentException("URI scheme is not '" + getScheme() + "'");
}
try {
String uristr = uri.toString();
int end = uristr.indexOf("!/");
uristr = uristr.substring(4, (end == -1) ? uristr.length() : end);
uri = new URI(uristr);
return Paths.get(new URI("file", uri.getHost(), uri.getPath(), null))
.toAbsolutePath();
} catch (URISyntaxException e) {
throw new AssertionError(e); //never thrown
}
}
}

View File

@ -0,0 +1,160 @@
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sun.nio.zipfs;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;
/**
* Utility class for zipfile name and comment decoding and encoding
*
* @author Xueming Shen
*/
final class ZipCoder {
String toString(byte[] ba, int length) {
CharsetDecoder cd = decoder().reset();
int len = (int)(length * cd.maxCharsPerByte());
char[] ca = new char[len];
if (len == 0)
return new String(ca);
ByteBuffer bb = ByteBuffer.wrap(ba, 0, length);
CharBuffer cb = CharBuffer.wrap(ca);
CoderResult cr = cd.decode(bb, cb, true);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
cr = cd.flush(cb);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
return new String(ca, 0, cb.position());
}
String toString(byte[] ba) {
return toString(ba, ba.length);
}
byte[] getBytes(String s) {
CharsetEncoder ce = encoder().reset();
char[] ca = s.toCharArray();
int len = (int)(ca.length * ce.maxBytesPerChar());
byte[] ba = new byte[len];
if (len == 0)
return ba;
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(ca);
CoderResult cr = ce.encode(cb, bb, true);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
cr = ce.flush(bb);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
if (bb.position() == ba.length) // defensive copy?
return ba;
else
return Arrays.copyOf(ba, bb.position());
}
// assume invoked only if "this" is not utf8
byte[] getBytesUTF8(String s) {
if (isutf8)
return getBytes(s);
if (utf8 == null)
utf8 = new ZipCoder(Charset.forName("UTF-8"));
return utf8.getBytes(s);
}
String toStringUTF8(byte[] ba, int len) {
if (isutf8)
return toString(ba, len);
if (utf8 == null)
utf8 = new ZipCoder(Charset.forName("UTF-8"));
return utf8.toString(ba, len);
}
boolean isUTF8() {
return isutf8;
}
private Charset cs;
private boolean isutf8;
private ZipCoder utf8;
private ZipCoder(Charset cs) {
this.cs = cs;
this.isutf8 = cs.name().equals("UTF-8");
}
static ZipCoder get(Charset charset) {
return new ZipCoder(charset);
}
static ZipCoder get(String csn) {
try {
return new ZipCoder(Charset.forName(csn));
} catch (Throwable t) {
t.printStackTrace();
}
return new ZipCoder(Charset.defaultCharset());
}
private final ThreadLocal<CharsetDecoder> decTL = new ThreadLocal<>();
private final ThreadLocal<CharsetEncoder> encTL = new ThreadLocal<>();
private CharsetDecoder decoder() {
CharsetDecoder dec = decTL.get();
if (dec == null) {
dec = cs.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
decTL.set(dec);
}
return dec;
}
private CharsetEncoder encoder() {
CharsetEncoder enc = encTL.get();
if (enc == null) {
enc = cs.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
encTL.set(enc);
}
return enc;
}
}

View File

@ -0,0 +1,261 @@
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sun.nio.zipfs;
import java.nio.ByteBuffer;
/**
*
* @author Xueming Shen
*/
class ZipConstants {
/*
* Compression methods
*/
static final int METHOD_STORED = 0;
static final int METHOD_DEFLATED = 8;
static final int METHOD_DEFLATED64 = 9;
static final int METHOD_BZIP2 = 12;
static final int METHOD_LZMA = 14;
static final int METHOD_LZ77 = 19;
/*
* General purpose big flag
*/
static final int FLAG_ENCRYPTED = 0x01;
static final int FLAG_DATADESCR = 0x08; // crc, size and csize in dd
static final int FLAG_EFS = 0x800; // If this bit is set the filename and
// comment fields for this file must be
// encoded using UTF-8.
/*
* Header signatures
*/
static long LOCSIG = 0x04034b50L; // "PK\003\004"
static long EXTSIG = 0x08074b50L; // "PK\007\008"
static long CENSIG = 0x02014b50L; // "PK\001\002"
static long ENDSIG = 0x06054b50L; // "PK\005\006"
/*
* Header sizes in bytes (including signatures)
*/
static final int LOCHDR = 30; // LOC header size
static final int EXTHDR = 16; // EXT header size
static final int CENHDR = 46; // CEN header size
static final int ENDHDR = 22; // END header size
/*
* Local file (LOC) header field offsets
*/
static final int LOCVER = 4; // version needed to extract
static final int LOCFLG = 6; // general purpose bit flag
static final int LOCHOW = 8; // compression method
static final int LOCTIM = 10; // modification time
static final int LOCCRC = 14; // uncompressed file crc-32 value
static final int LOCSIZ = 18; // compressed size
static final int LOCLEN = 22; // uncompressed size
static final int LOCNAM = 26; // filename length
static final int LOCEXT = 28; // extra field length
/*
* Extra local (EXT) header field offsets
*/
static final int EXTCRC = 4; // uncompressed file crc-32 value
static final int EXTSIZ = 8; // compressed size
static final int EXTLEN = 12; // uncompressed size
/*
* Central directory (CEN) header field offsets
*/
static final int CENVEM = 4; // version made by
static final int CENVER = 6; // version needed to extract
static final int CENFLG = 8; // encrypt, decrypt flags
static final int CENHOW = 10; // compression method
static final int CENTIM = 12; // modification time
static final int CENCRC = 16; // uncompressed file crc-32 value
static final int CENSIZ = 20; // compressed size
static final int CENLEN = 24; // uncompressed size
static final int CENNAM = 28; // filename length
static final int CENEXT = 30; // extra field length
static final int CENCOM = 32; // comment length
static final int CENDSK = 34; // disk number start
static final int CENATT = 36; // internal file attributes
static final int CENATX = 38; // external file attributes
static final int CENOFF = 42; // LOC header offset
/*
* End of central directory (END) header field offsets
*/
static final int ENDSUB = 8; // number of entries on this disk
static final int ENDTOT = 10; // total number of entries
static final int ENDSIZ = 12; // central directory size in bytes
static final int ENDOFF = 16; // offset of first CEN header
static final int ENDCOM = 20; // zip file comment length
/*
* ZIP64 constants
*/
static final long ZIP64_ENDSIG = 0x06064b50L; // "PK\006\006"
static final long ZIP64_LOCSIG = 0x07064b50L; // "PK\006\007"
static final int ZIP64_ENDHDR = 56; // ZIP64 end header size
static final int ZIP64_LOCHDR = 20; // ZIP64 end loc header size
static final int ZIP64_EXTHDR = 24; // EXT header size
static final int ZIP64_EXTID = 0x0001; // Extra field Zip64 header ID
static final int ZIP64_MINVAL32 = 0xFFFF;
static final long ZIP64_MINVAL = 0xFFFFFFFFL;
/*
* Zip64 End of central directory (END) header field offsets
*/
static final int ZIP64_ENDLEN = 4; // size of zip64 end of central dir
static final int ZIP64_ENDVEM = 12; // version made by
static final int ZIP64_ENDVER = 14; // version needed to extract
static final int ZIP64_ENDNMD = 16; // number of this disk
static final int ZIP64_ENDDSK = 20; // disk number of start
static final int ZIP64_ENDTOD = 24; // total number of entries on this disk
static final int ZIP64_ENDTOT = 32; // total number of entries
static final int ZIP64_ENDSIZ = 40; // central directory size in bytes
static final int ZIP64_ENDOFF = 48; // offset of first CEN header
static final int ZIP64_ENDEXT = 56; // zip64 extensible data sector
/*
* Zip64 End of central directory locator field offsets
*/
static final int ZIP64_LOCDSK = 4; // disk number start
static final int ZIP64_LOCOFF = 8; // offset of zip64 end
static final int ZIP64_LOCTOT = 16; // total number of disks
/*
* Zip64 Extra local (EXT) header field offsets
*/
static final int ZIP64_EXTCRC = 4; // uncompressed file crc-32 value
static final int ZIP64_EXTSIZ = 8; // compressed size, 8-byte
static final int ZIP64_EXTLEN = 16; // uncompressed size, 8-byte
/*
* Extra field header ID
*/
static final int EXTID_ZIP64 = 0x0001; // ZIP64
static final int EXTID_NTFS = 0x000a; // NTFS
static final int EXTID_UNIX = 0x000d; // UNIX
/*
* fields access methods
*/
///////////////////////////////////////////////////////
static final int CH(byte[] b, int n) {
return b[n] & 0xff;
}
static final int SH(byte[] b, int n) {
return (b[n] & 0xff) | ((b[n + 1] & 0xff) << 8);
}
static final long LG(byte[] b, int n) {
return ((SH(b, n)) | (SH(b, n + 2) << 16)) & 0xffffffffL;
}
static final long LL(byte[] b, int n) {
return (LG(b, n)) | (LG(b, n + 4) << 32);
}
static final long GETSIG(byte[] b) {
return LG(b, 0);
}
// local file (LOC) header fields
static final long LOCSIG(byte[] b) { return LG(b, 0); } // signature
static final int LOCVER(byte[] b) { return SH(b, 4); } // version needed to extract
static final int LOCFLG(byte[] b) { return SH(b, 6); } // general purpose bit flags
static final int LOCHOW(byte[] b) { return SH(b, 8); } // compression method
static final long LOCTIM(byte[] b) { return LG(b, 10);} // modification time
static final long LOCCRC(byte[] b) { return LG(b, 14);} // crc of uncompressed data
static final long LOCSIZ(byte[] b) { return LG(b, 18);} // compressed data size
static final long LOCLEN(byte[] b) { return LG(b, 22);} // uncompressed data size
static final int LOCNAM(byte[] b) { return SH(b, 26);} // filename length
static final int LOCEXT(byte[] b) { return SH(b, 28);} // extra field length
// extra local (EXT) header fields
static final long EXTCRC(byte[] b) { return LG(b, 4);} // crc of uncompressed data
static final long EXTSIZ(byte[] b) { return LG(b, 8);} // compressed size
static final long EXTLEN(byte[] b) { return LG(b, 12);} // uncompressed size
// end of central directory header (END) fields
static final int ENDSUB(byte[] b) { return SH(b, 8); } // number of entries on this disk
static final int ENDTOT(byte[] b) { return SH(b, 10);} // total number of entries
static final long ENDSIZ(byte[] b) { return LG(b, 12);} // central directory size
static final long ENDOFF(byte[] b) { return LG(b, 16);} // central directory offset
static final int ENDCOM(byte[] b) { return SH(b, 20);} // size of zip file comment
static final int ENDCOM(byte[] b, int off) { return SH(b, off + 20);}
// zip64 end of central directory recoder fields
static final long ZIP64_ENDTOD(byte[] b) { return LL(b, 24);} // total number of entries on disk
static final long ZIP64_ENDTOT(byte[] b) { return LL(b, 32);} // total number of entries
static final long ZIP64_ENDSIZ(byte[] b) { return LL(b, 40);} // central directory size
static final long ZIP64_ENDOFF(byte[] b) { return LL(b, 48);} // central directory offset
static final long ZIP64_LOCOFF(byte[] b) { return LL(b, 8);} // zip64 end offset
//////////////////////////////////////////
static final int CH(ByteBuffer b, int pos) {
return b.get(pos) & 0xff;
}
static final int SH(ByteBuffer b, int pos) {
return b.getShort(pos) & 0xffff;
}
static final long LG(ByteBuffer b, int pos) {
return b.getInt(pos) & 0xffffffffL;
}
// central directory header (END) fields
static final long CENSIG(ByteBuffer b, int pos) { return LG(b, pos + 0); }
static final int CENVEM(ByteBuffer b, int pos) { return SH(b, pos + 4); }
static final int CENVER(ByteBuffer b, int pos) { return SH(b, pos + 6); }
static final int CENFLG(ByteBuffer b, int pos) { return SH(b, pos + 8); }
static final int CENHOW(ByteBuffer b, int pos) { return SH(b, pos + 10);}
static final long CENTIM(ByteBuffer b, int pos) { return LG(b, pos + 12);}
static final long CENCRC(ByteBuffer b, int pos) { return LG(b, pos + 16);}
static final long CENSIZ(ByteBuffer b, int pos) { return LG(b, pos + 20);}
static final long CENLEN(ByteBuffer b, int pos) { return LG(b, pos + 24);}
static final int CENNAM(ByteBuffer b, int pos) { return SH(b, pos + 28);}
static final int CENEXT(ByteBuffer b, int pos) { return SH(b, pos + 30);}
static final int CENCOM(ByteBuffer b, int pos) { return SH(b, pos + 32);}
static final int CENDSK(ByteBuffer b, int pos) { return SH(b, pos + 34);}
static final int CENATT(ByteBuffer b, int pos) { return SH(b, pos + 36);}
static final long CENATX(ByteBuffer b, int pos) { return LG(b, pos + 38);}
static final long CENOFF(ByteBuffer b, int pos) { return LG(b, pos + 42);}
/* The END header is followed by a variable length comment of size < 64k. */
static final long END_MAXLEN = 0xFFFF + ENDHDR;
static final int READBLOCKSZ = 128;
}

View File

@ -0,0 +1,109 @@
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sun.nio.zipfs;
import java.nio.file.DirectoryStream;
import java.nio.file.ClosedDirectoryStreamException;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.io.IOException;
import static com.sun.nio.zipfs.ZipUtils.*;
/**
*
* @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal
*/
public class ZipDirectoryStream implements DirectoryStream<Path> {
private final ZipFileSystem zipfs;
private final byte[] path;
private final DirectoryStream.Filter<? super Path> filter;
private volatile boolean isClosed;
private volatile Iterator<Path> itr;
ZipDirectoryStream(ZipPath zipPath,
DirectoryStream.Filter<? super java.nio.file.Path> filter)
throws IOException
{
this.zipfs = zipPath.getFileSystem();
this.path = zipPath.getResolvedPath();
this.filter = filter;
// sanity check
if (!zipfs.isDirectory(path))
throw new NotDirectoryException(zipPath.toString());
}
@Override
public synchronized Iterator<Path> iterator() {
if (isClosed)
throw new ClosedDirectoryStreamException();
if (itr != null)
throw new IllegalStateException("Iterator has already been returned");
try {
itr = zipfs.iteratorOf(path, filter);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return new Iterator<Path>() {
private Path next;
@Override
public boolean hasNext() {
if (isClosed)
return false;
return itr.hasNext();
}
@Override
public synchronized Path next() {
if (isClosed)
throw new NoSuchElementException();
return itr.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public synchronized void close() throws IOException {
isClosed = true;
}
}

View File

@ -0,0 +1,185 @@
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sun.nio.zipfs;
import java.nio.file.ReadOnlyFileSystemException;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.attribute.FileTime;
import java.io.IOException;
import java.util.LinkedHashMap;
/*
* @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal
*/
public class ZipFileAttributeView implements BasicFileAttributeView
{
private static enum AttrID {
size,
creationTime,
lastAccessTime,
lastModifiedTime,
isDirectory,
isRegularFile,
isSymbolicLink,
isOther,
fileKey,
compressedSize,
crc,
method
};
private final ZipPath path;
private final boolean isZipView;
private ZipFileAttributeView(ZipPath path, boolean isZipView) {
this.path = path;
this.isZipView = isZipView;
}
static <V extends FileAttributeView> V get(ZipPath path, Class<V> type) {
if (type == null)
throw new NullPointerException();
if (type == BasicFileAttributeView.class)
return (V)new ZipFileAttributeView(path, false);
if (type == ZipFileAttributeView.class)
return (V)new ZipFileAttributeView(path, true);
return null;
}
static ZipFileAttributeView get(ZipPath path, String type) {
if (type == null)
throw new NullPointerException();
if (type.equals("basic"))
return new ZipFileAttributeView(path, false);
if (type.equals("zip"))
return new ZipFileAttributeView(path, true);
return null;
}
@Override
public String name() {
return isZipView ? "zip" : "basic";
}
public ZipFileAttributes readAttributes() throws IOException
{
return path.getAttributes();
}
@Override
public void setTimes(FileTime lastModifiedTime,
FileTime lastAccessTime,
FileTime createTime)
throws IOException
{
path.setTimes(lastModifiedTime, lastAccessTime, createTime);
}
void setAttribute(String attribute, Object value)
throws IOException
{
try {
if (AttrID.valueOf(attribute) == AttrID.lastModifiedTime)
setTimes ((FileTime)value, null, null);
return;
} catch (IllegalArgumentException x) {}
throw new UnsupportedOperationException("'" + attribute +
"' is unknown or read-only attribute");
}
public Object getAttribute(String attribute, boolean domap)
throws IOException
{
ZipFileAttributes zfas = readAttributes();
if (!domap) {
try {
return attribute(AttrID.valueOf(attribute), zfas);
} catch (IllegalArgumentException x) {}
return null;
}
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
if ("*".equals(attribute)) {
for (AttrID id : AttrID.values()) {
try {
map.put(id.name(), attribute(id, zfas));
} catch (IllegalArgumentException x) {}
}
} else {
String[] as = attribute.split(",");
for (String a : as) {
try {
map.put(a, attribute(AttrID.valueOf(a), zfas));
} catch (IllegalArgumentException x) {}
}
}
return map;
}
Object attribute(AttrID id, ZipFileAttributes zfas) {
switch (id) {
case size:
return zfas.size();
case creationTime:
return zfas.creationTime();
case lastAccessTime:
return zfas.lastAccessTime();
case lastModifiedTime:
return zfas.lastModifiedTime();
case isDirectory:
return zfas.isDirectory();
case isRegularFile:
return zfas.isRegularFile();
case isSymbolicLink:
return zfas.isSymbolicLink();
case isOther:
return zfas.isOther();
case fileKey:
return zfas.fileKey();
case compressedSize:
if (isZipView)
return zfas.compressedSize();
break;
case crc:
if (isZipView)
return zfas.crc();
break;
case method:
if (isZipView)
return zfas.method();
break;
}
return null;
}
}

View File

@ -0,0 +1,156 @@
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sun.nio.zipfs;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.Formatter;
import static com.sun.nio.zipfs.ZipUtils.*;
/**
*
* @author Xueming Shen, Rajendra Gutupalli,Jaya Hangal
*/
public class ZipFileAttributes implements BasicFileAttributes
{
private final ZipFileSystem.Entry e;
ZipFileAttributes(ZipFileSystem.Entry e) {
this.e = e;
}
///////// basic attributes ///////////
@Override
public FileTime creationTime() {
if (e.ctime != -1)
return FileTime.fromMillis(dosToJavaTime(e.ctime));
return null;
}
@Override
public boolean isDirectory() {
return e.isDir();
}
@Override
public boolean isOther() {
return false;
}
@Override
public boolean isRegularFile() {
return !e.isDir();
}
@Override
public FileTime lastAccessTime() {
if (e.atime != -1)
return FileTime.fromMillis(dosToJavaTime(e.atime));
return null;
}
@Override
public FileTime lastModifiedTime() {
return FileTime.fromMillis(dosToJavaTime(e.mtime));
}
@Override
public long size() {
return e.size;
}
@Override
public boolean isSymbolicLink() {
return false;
}
@Override
public Object fileKey() {
return null;
}
///////// zip entry attributes ///////////
public byte[] name() {
return Arrays.copyOf(e.name, e.name.length);
}
public long compressedSize() {
return e.csize;
}
public long crc() {
return e.crc;
}
public int method() {
return e.method;
}
public byte[] extra() {
if (e.extra != null)
return Arrays.copyOf(e.extra, e.extra.length);
return null;
}
public byte[] comment() {
if (e.comment != null)
return Arrays.copyOf(e.comment, e.comment.length);
return null;
}
public String toString() {
StringBuilder sb = new StringBuilder();
Formatter fm = new Formatter(sb);
fm.format("[/%s]%n", new String(e.name)); // TBD encoding
fm.format(" creationTime : %s%n", creationTime());
if (lastAccessTime() != null)
fm.format(" lastAccessTime : %tc%n", lastAccessTime().toMillis());
else
fm.format(" lastAccessTime : null%n");
fm.format(" lastModifiedTime: %tc%n", lastModifiedTime().toMillis());
fm.format(" isRegularFile : %b%n", isRegularFile());
fm.format(" isDirectory : %b%n", isDirectory());
fm.format(" isSymbolicLink : %b%n", isSymbolicLink());
fm.format(" isOther : %b%n", isOther());
fm.format(" fileKey : %s%n", fileKey());
fm.format(" size : %d%n", size());
fm.format(" compressedSize : %d%n", compressedSize());
fm.format(" crc : %x%n", crc());
fm.format(" method : %d%n", method());
fm.close();
return sb.toString();
}
}

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