diff --git a/.hgtags b/.hgtags index 24dc9213f13fbcadddfb2807883e1d9b4f333064..3b04251d1366f87fc9ba3f2cd032993f78825f07 100644 --- a/.hgtags +++ b/.hgtags @@ -93,3 +93,4 @@ e250cef36ea05e627e7e6f7d75e5e19f529e2ba3 jdk7-b114 1657ed4e1d86c8aa2028ab5a41f9da1ac4a369f8 jdk7-b116 3e6726bbf80a4254ecd01051c8ed77ee19325e46 jdk7-b117 b357910aa04aead2a16b6d6ff395a8df4b51d1dd jdk7-b118 +37d74e29687cf07c2bf9411af58c7e42440855c3 jdk7-b120 diff --git a/make/Makefile b/make/Makefile index 63e7803ffe344ab0b49a3c3563956c9e81ec00a0..9ec690639a90405ec9d5eb9cdffb1ce90db361c6 100644 --- a/make/Makefile +++ b/make/Makefile @@ -1,5 +1,5 @@ # -# Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1995, 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 @@ -243,6 +243,11 @@ SUBDIRS = tools java javax sun com SUBDIRS_tools = launchers SUBDIRS_misc = org sunw jpda mkdemo mksample +# Alternate classes implementation +ifndef OPENJDK + SUBDIRS_misc += altclasses +endif + include $(BUILDDIR)/common/Subdirs.gmk all build:: diff --git a/make/altclasses/Makefile b/make/altclasses/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..201752071d4ae5c1ba9a2d11b3da44ffc6429041 --- /dev/null +++ b/make/altclasses/Makefile @@ -0,0 +1,84 @@ +# +# 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. +# + +# +# Makefile for building alternate runtime classes (not used by default) +# + +BUILDDIR = .. + +PRODUCT = altclasses + +include $(BUILDDIR)/common/Defs.gmk + +# Root of alternate class sources + +ALTCLASSES_SRCDIR = $(CLOSED_SRC)/share/altclasses + +# Alternate runtime classes + +ALTRT_JAR_FILE = $(LIBDIR)/alt-rt.jar +ALTRT_JAR_SOURCE_FILE = $(TEMPDIR)/alt-rt.jarsrclist +ALTRT_JAR_SOURCES = $(wildcard $(ALTCLASSES_SRCDIR)/java/*/*.java) + +# Use a special file suffix for the file that holds the source list + +.SUFFIXES: .jarsrclist + +# Build rules + +all build: + @if [ -d $(ALTCLASSES_SRCDIR) ] ; then \ + $(MAKE) $(ALTRT_JAR_FILE); \ + fi + +# Source list file creation + +$(ALTRT_JAR_SOURCE_FILE): $(ALTRT_JAR_SOURCES) FRC + $(prep-target) + $(ECHO) $(ALTRT_JAR_SOURCES) > $@ + +clean clobber:: + $(RM) $(ALTRT_JAR_FILE) $(ALTRT_JAR_SOURCE_FILE) + $(RM) -r $(ALTRT_JAR_SOURCE_FILE).classes + +include $(BUILDDIR)/common/Classes.gmk + +# Pattern rule to turn a source list file into a jar file +$(LIBDIR)/%.jar : $(TEMPDIR)/%.jarsrclist + $(prep-target) + $(RM) -r $(<).classes + $(MKDIR) -p $(<).classes + $(JAVAC_CMD) -implicit:none -d $(<).classes @$< + $(BOOT_JAR_CMD) cf $@ -C $(<).classes . $(BOOT_JAR_JFLAGS) + +# Force target + +FRC: + +# Non file targets + +.PHONY: all build clean clobber + diff --git a/make/mkdemo/nio/zipfs/Makefile b/make/mkdemo/nio/zipfs/Makefile index 16e71a9ba45d7372db23f76b8857a43d8812a9a4..a2405030dc1b8e66e390f5ff3bcb657b2111a78f 100644 --- a/make/mkdemo/nio/zipfs/Makefile +++ b/make/mkdemo/nio/zipfs/Makefile @@ -42,3 +42,10 @@ DEMO_DESTDIR = $(DEMODIR)/nio/$(DEMONAME) # include $(BUILDDIR)/common/Demo.gmk +#EXTJAR = $(EXTDIR)/$(DEMONAME).jar +# +#all : build $(EXTJAR) +# +#$(EXTJAR) : $(DEMO_JAR) +# $(prep-target) +# $(CP) $(DEMO_JAR) $(EXTJAR) diff --git a/make/sun/xawt/mapfile-vers b/make/sun/xawt/mapfile-vers index fa5fe360ffc626ae25098661b2fea1142e6006bf..0d951efff1d200ae6110026c0a6594869d5de64b 100644 --- a/make/sun/xawt/mapfile-vers +++ b/make/sun/xawt/mapfile-vers @@ -429,6 +429,7 @@ SUNWprivate_1.1 { Java_com_sun_java_swing_plaf_gtk_GTKStyle_nativeGetClassValue; Java_com_sun_java_swing_plaf_gtk_GTKStyle_nativeGetPangoFontName; + Java_sun_awt_X11_GtkFileDialogPeer_initIDs; Java_sun_awt_X11_GtkFileDialogPeer_run; Java_sun_awt_X11_GtkFileDialogPeer_quit; diff --git a/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java b/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java index 477806bd912f6e2cf851683107bfee938524f699..a782e8631e5a935c9dec9b3dba9813b0b7ca35a0 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java +++ b/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java @@ -25,8 +25,10 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; /** * Adaptive coding. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Attribute.java b/src/share/classes/com/sun/java/util/jar/pack/Attribute.java index b662ebb9683ddfd1e5e4c6ccb8f3c29744fd32b1..7b838f26d022ddc35c6ec27787cf7ff5cb94d75b 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Attribute.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Attribute.java @@ -25,9 +25,17 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; -import com.sun.java.util.jar.pack.ConstantPool.*; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Represents an attribute in a class-file. diff --git a/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java b/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java index 1c8266cd69f579b65f9b9c8fcd9f6d79e79d0a3c..7af5e38019d3ab1b3197d7ec4fc64b1bd8d87deb 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java +++ b/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java @@ -25,12 +25,28 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; -import java.util.jar.*; -import com.sun.java.util.jar.pack.Package.Class; -import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.Package.Class.Field; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FilterInputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.jar.Pack200; /** * Define the structure and ordering of "bands" in a packed file. @@ -1629,7 +1645,7 @@ class BandStructure implements Constants { } } - protected void setConstantValueIndex(Class.Field f) { + protected void setConstantValueIndex(com.sun.java.util.jar.pack.Package.Class.Field f) { Index ix = null; if (f != null) { byte tag = f.getLiteralTag(); diff --git a/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java b/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java index fd28171a75b7c95eff0997d6f678c96c732ccb44..a1bce52a5e2b8e60587b248638b271372bc051ed 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java +++ b/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -25,12 +25,19 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; +import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; +import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; +import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; -import com.sun.tools.classfile.AttributeException; +import java.io.DataInputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Map; /** * Reader for a class file that is being incorporated into a package. @@ -422,7 +429,7 @@ class ClassReader implements Constants { readCode(m.code); } catch (Instruction.FormatException iie) { String message = iie.getMessage() + " in " + h; - throw new ClassReader.ClassFormatException(message); + throw new ClassReader.ClassFormatException(message, iie); } } else { assert(h == cls); @@ -477,9 +484,13 @@ class ClassReader implements Constants { // (Later, ics may be transferred to the pkg.) } - class ClassFormatException extends IOException { + static class ClassFormatException extends IOException { public ClassFormatException(String message) { super(message); } + + public ClassFormatException(String message, Throwable cause) { + super(message, cause); + } } } diff --git a/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java b/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java index 516954c937a67e19c4b28f52111880d2d132dffc..a4ceff5768665b480255ba4fe3a047f008be89c4 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java +++ b/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java @@ -25,11 +25,19 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; + +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.ConstantPool.NumberEntry; import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.List; /** * Writer for a class file that is incorporated into a package. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Code.java b/src/share/classes/com/sun/java/util/jar/pack/Code.java index 3461d44293c171b69d229c54c85a142c9e000dbf..e6272f57a5bb528260c62818e9b5ef2454b8de13 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Code.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Code.java @@ -25,10 +25,10 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; import com.sun.java.util.jar.pack.Package.Class; import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Collection; /** * Represents a chunk of bytecodes. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Coding.java b/src/share/classes/com/sun/java/util/jar/pack/Coding.java index 6e72d1baae8def13ab5aa316cb4ba9d817992b08..a35261f5db91bdcc65f79f786d29b19bc1cab487 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Coding.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Coding.java @@ -25,8 +25,10 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; /** * Define the conversions between sequences of small integers and raw bytes. diff --git a/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java b/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java index 2f1f3e1b83900f3d014ac1c6fb4011688db7739e..61a6710a6f6d202208132ad92440b27d25e04122 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java +++ b/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java @@ -25,9 +25,17 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; -import java.util.zip.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.zip.Deflater; +import java.util.zip.DeflaterOutputStream; /** * Heuristic chooser of basic encodings. diff --git a/src/share/classes/com/sun/java/util/jar/pack/CodingMethod.java b/src/share/classes/com/sun/java/util/jar/pack/CodingMethod.java index 75f32a86118524d2d159299ba71266ce15c4ee5f..d0b1d9d9604a0cb436e58ed817ba17d5e44cca4d 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/CodingMethod.java +++ b/src/share/classes/com/sun/java/util/jar/pack/CodingMethod.java @@ -25,7 +25,9 @@ package com.sun.java.util.jar.pack; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; /** * Interface for encoding and decoding int arrays using bytewise codes. diff --git a/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java b/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java index ac6199abe25e3dee29c821326bf683110e2f13a2..abafbd92b4096c644fdb74e7616a0c4844ed5b4d 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java +++ b/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java @@ -25,7 +25,14 @@ package com.sun.java.util.jar.pack; -import java.util.*; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; /** * Representation of constant pool entries and indexes. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Constants.java b/src/share/classes/com/sun/java/util/jar/pack/Constants.java index 19ce04cf559612e4574d7dfc965a0e309a17e301..512dac7972fd09d803639a6a27c900ab081ddc91 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Constants.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Constants.java @@ -25,7 +25,8 @@ package com.sun.java.util.jar.pack; -import java.util.*; +import java.util.Arrays; +import java.util.List; /** * Shared constants diff --git a/src/share/classes/com/sun/java/util/jar/pack/Driver.java b/src/share/classes/com/sun/java/util/jar/pack/Driver.java index 2630febb7c35c721c54154cd3525f1fe03e28d9f..a7c47a8a8cc6b6e1f4f01031d73e5264927e4e06 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Driver.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Driver.java @@ -25,11 +25,32 @@ package com.sun.java.util.jar.pack; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; import java.text.MessageFormat; -import java.util.*; -import java.util.jar.*; -import java.util.zip.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Properties; +import java.util.ResourceBundle; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.jar.Pack200; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; /** Command line interface for Pack200. */ diff --git a/src/share/classes/com/sun/java/util/jar/pack/Fixups.java b/src/share/classes/com/sun/java/util/jar/pack/Fixups.java index 3cb47069c8f3ee9334995202219f144cb58be8ee..77815b43b2275f05e88d3e872326fd465e09aab4 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Fixups.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Fixups.java @@ -25,9 +25,11 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; -import com.sun.java.util.jar.pack.ConstantPool.*; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import java.util.AbstractCollection; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; /** * Collection of relocatable constant pool references. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Histogram.java b/src/share/classes/com/sun/java/util/jar/pack/Histogram.java index 1c03e592b0260e936b79371c39737de404fd921d..92cf6e4e918b36184eaa2b538966d607a43b27cf 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Histogram.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Histogram.java @@ -25,8 +25,10 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.util.Arrays; /** * Histogram derived from an integer array of events (int[]). diff --git a/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java b/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java index c6d9608518014840ae2750f3dcd118ee42436091..2ea9f4d4721c091b9e7a561576a5d0ed3ad796df 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java +++ b/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java @@ -26,10 +26,18 @@ package com.sun.java.util.jar.pack; -import java.nio.*; -import java.io.*; -import java.util.jar.*; -import java.util.zip.*; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.jar.JarOutputStream; +import java.util.jar.Pack200; +import java.util.zip.CRC32; +import java.util.zip.Deflater; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; class NativeUnpack { // Pointer to the native unpacker obj diff --git a/src/share/classes/com/sun/java/util/jar/pack/Package.java b/src/share/classes/com/sun/java/util/jar/pack/Package.java index 29d217687c49b1283ad03ba864bff6d24543509f..981bd53b75c67adbabb9ec9b02df6619e4bda90a 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Package.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Package.java @@ -26,11 +26,32 @@ package com.sun.java.util.jar.pack; import com.sun.java.util.jar.pack.Attribute.Layout; +import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; +import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.ConstantPool.LiteralEntry; +import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.SequenceInputStream; import java.lang.reflect.Modifier; -import java.util.*; -import java.util.jar.*; -import java.io.*; -import com.sun.java.util.jar.pack.ConstantPool.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; +import java.util.jar.JarFile; /** * Define the main data structure transmitted by pack/unpack. diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java b/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java index 73efca5ca85e0f518663fc06d140a252643f29c2..be8ba0d008b0c0d7ac134d115ddcf42df05b579b 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java @@ -25,12 +25,18 @@ package com.sun.java.util.jar.pack; +import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; +import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.ConstantPool.MemberEntry; +import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; +import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; import java.io.*; import java.util.*; import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.File; import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; /** * Reader for a package file. diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java b/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java index 55b64cce5e851ca2bfa1072f419a17a088f524d3..cbfcb8aacfd0a13fbf283ffafc0e8d40fa6d91a0 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java @@ -25,12 +25,30 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; +import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; +import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.ConstantPool.IndexGroup; +import com.sun.java.util.jar.pack.ConstantPool.MemberEntry; +import com.sun.java.util.jar.pack.ConstantPool.NumberEntry; +import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; +import com.sun.java.util.jar.pack.ConstantPool.StringEntry; import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.File; import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; /** * Writer for a package file. diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java b/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java index a45a4bcba094a4bf207784c789e40fac5ffbb6a7..7e2f6a27c02f7bf6de89b495442783ff90980586 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java @@ -26,10 +26,27 @@ package com.sun.java.util.jar.pack; import com.sun.java.util.jar.pack.Attribute.Layout; -import java.util.*; -import java.util.jar.*; -import java.io.*; import java.beans.PropertyChangeListener; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.SortedMap; +import java.util.TimeZone; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarInputStream; +import java.util.jar.Pack200; /* @@ -614,10 +631,14 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer { List scanJar(JarFile jf) throws IOException { // Collect jar entries, preserving order. List inFiles = new ArrayList<>(); - for (JarEntry je : Collections.list(jf.entries())) { - InFile inFile = new InFile(jf, je); - assert(je.isDirectory() == inFile.name.endsWith("/")); - inFiles.add(inFile); + try { + for (JarEntry je : Collections.list(jf.entries())) { + InFile inFile = new InFile(jf, je); + assert(je.isDirectory() == inFile.name.endsWith("/")); + inFiles.add(inFile); + } + } catch (IllegalStateException ise) { + throw new IOException(ise.getLocalizedMessage(), ise); } return inFiles; } diff --git a/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java b/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java index 599d86fa6b2604e632257dd83ccb84d947673be0..3e5ecf170c3dd31b3279d4e0ee3cabef46302923 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java @@ -25,8 +25,12 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.HashSet; /** * Population-based coding. diff --git a/src/share/classes/com/sun/java/util/jar/pack/PropMap.java b/src/share/classes/com/sun/java/util/jar/pack/PropMap.java index 78c709f343d554c5b2c25699a10574f29c9cd734..3072ef394eb0ddb53027fcf227063e94d821a539 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PropMap.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PropMap.java @@ -25,13 +25,24 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.util.jar.*; -import java.util.jar.Pack200; -import java.util.zip.*; -import java.io.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.jar.Pack200; /** * Control block for publishing Pack200 options to the other classes. */ diff --git a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java index 11c8abf07f16d2d0c66b7763b9114313d5d3dcef..a0c1e4d26ef457e873c5ce658fb66974b38077ca 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java +++ b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java @@ -25,11 +25,25 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.util.jar.*; -import java.util.zip.*; -import java.io.*; import java.beans.PropertyChangeListener; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashSet; +import java.util.Iterator; +import java.util.SortedMap; +import java.util.TimeZone; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; +import java.util.jar.JarOutputStream; +import java.util.jar.Pack200; +import java.util.zip.CRC32; +import java.util.zip.CheckedOutputStream; +import java.util.zip.ZipEntry; /* * Implementation of the Pack provider. @@ -92,7 +106,13 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker { * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ - public void unpack(InputStream in0, JarOutputStream out) throws IOException { + public void unpack(InputStream in, JarOutputStream out) throws IOException { + if (in == null) { + throw new NullPointerException("null input"); + } + if (out == null) { + throw new NullPointerException("null output"); + } assert(Utils.currentInstance.get() == null); TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null @@ -102,18 +122,18 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker { Utils.currentInstance.set(this); if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC")); final int verbose = props.getInteger(Utils.DEBUG_VERBOSE); - BufferedInputStream in = new BufferedInputStream(in0); - if (Utils.isJarMagic(Utils.readMagic(in))) { + BufferedInputStream in0 = new BufferedInputStream(in); + if (Utils.isJarMagic(Utils.readMagic(in0))) { if (verbose > 0) Utils.log.info("Copying unpacked JAR file..."); - Utils.copyJarFile(new JarInputStream(in), out); + Utils.copyJarFile(new JarInputStream(in0), out); } else if (props.getBoolean(Utils.DEBUG_DISABLE_NATIVE)) { - (new DoUnpack()).run(in, out); - in.close(); + (new DoUnpack()).run(in0, out); + in0.close(); Utils.markJarFile(out); } else { - (new NativeUnpack(this)).run(in, out); - in.close(); + (new NativeUnpack(this)).run(in0, out); + in0.close(); Utils.markJarFile(out); } } finally { @@ -132,6 +152,12 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker { * @exception IOException if an error is encountered. */ public void unpack(File in, JarOutputStream out) throws IOException { + if (in == null) { + throw new NullPointerException("null input"); + } + if (out == null) { + throw new NullPointerException("null output"); + } // Use the stream-based implementation. // %%% Reconsider if native unpacker learns to memory-map the file. FileInputStream instr = new FileInputStream(in); diff --git a/src/share/classes/com/sun/java/util/jar/pack/Utils.java b/src/share/classes/com/sun/java/util/jar/pack/Utils.java index 84f65ac2ccfcbbbc769f769e95b43eeef2c6b8da..d14d59926ca60471f10e6b7b2f150ce2bfc105b7 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Utils.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Utils.java @@ -25,18 +25,27 @@ package com.sun.java.util.jar.pack; -import com.sun.java.util.jar.pack.Attribute.Layout; import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; import com.sun.java.util.jar.pack.ConstantPool.LiteralEntry; import com.sun.java.util.jar.pack.ConstantPool.MemberEntry; import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; -import java.util.*; -import java.util.jar.*; -import java.util.zip.*; -import java.io.*; - +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Date; +import java.util.Enumeration; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarInputStream; +import java.util.jar.JarOutputStream; +import java.util.zip.ZipEntry; import sun.util.logging.PlatformLogger; class Utils { diff --git a/src/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java b/src/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java index ba3165c2a7cb5587af005b605cd27e24dadf5673..ba0714116087e2f28e0292c454b8b7347efb661f 100644 --- a/src/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java +++ b/src/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -45,6 +45,8 @@ import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.MBeanPermission; import javax.management.MBeanServer; +import javax.management.MBeanServerDelegate; +import javax.management.MBeanServerNotification; import javax.management.Notification; import javax.management.NotificationBroadcaster; import javax.management.NotificationFilter; @@ -272,6 +274,7 @@ public class ServerNotifForwarder { nr = notifBuffer.fetchNotifications(bufferFilter, startSequenceNumber, t, maxNotifications); + snoopOnUnregister(nr); } catch (InterruptedException ire) { nr = new NotificationResult(0L, 0L, new TargetedNotification[0]); } @@ -283,6 +286,34 @@ public class ServerNotifForwarder { return nr; } + // The standard RMI connector client will register a listener on the MBeanServerDelegate + // in order to be told when MBeans are unregistered. We snoop on fetched notifications + // so that we can know too, and remove the corresponding entry from the listenerMap. + // See 6957378. + private void snoopOnUnregister(NotificationResult nr) { + Set delegateSet = listenerMap.get(MBeanServerDelegate.DELEGATE_NAME); + if (delegateSet == null || delegateSet.isEmpty()) { + return; + } + for (TargetedNotification tn : nr.getTargetedNotifications()) { + Integer id = tn.getListenerID(); + for (IdAndFilter idaf : delegateSet) { + if (idaf.id == id) { + // This is a notification from the MBeanServerDelegate. + Notification n = tn.getNotification(); + if (n instanceof MBeanServerNotification && + n.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) { + MBeanServerNotification mbsn = (MBeanServerNotification) n; + ObjectName gone = mbsn.getMBeanName(); + synchronized (listenerMap) { + listenerMap.remove(gone); + } + } + } + } + } + } + public void terminate() { if (logger.traceOn()) { logger.trace("terminate", "Be called."); @@ -418,10 +449,12 @@ public class ServerNotifForwarder { return this.filter; } + @Override public int hashCode() { return id.hashCode(); } + @Override public boolean equals(Object o) { return ((o instanceof IdAndFilter) && ((IdAndFilter) o).getId().equals(getId())); diff --git a/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java b/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java index 265b44a62766efdaa99f5dee4e7732a6bba0f1c1..acf7479fc0163036935bb4f5824ede9676cae829 100644 --- a/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java +++ b/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java @@ -27,7 +27,6 @@ package com.sun.rowset; import java.io.*; import java.util.*; -import java.lang.*; /** * This class is used to help in localization of resources, @@ -42,28 +41,28 @@ public class JdbcRowSetResourceBundle implements Serializable { * This String variable stores the location * of the resource bundle location. */ - static String fileName; + private static String fileName; /** * This variable will hold the PropertyResourceBundle * of the text to be internationalized. */ - transient PropertyResourceBundle propResBundle; + private transient PropertyResourceBundle propResBundle; /** * The constructor initializes to this object * */ - static JdbcRowSetResourceBundle jpResBundle; + private static volatile JdbcRowSetResourceBundle jpResBundle; /** - * The varible which will represent the properties + * The variable which will represent the properties * the suffix or extension of the resource bundle. **/ private static final String PROPERTIES = "properties"; /** - * The varibale to represent underscore + * The variable to represent underscore **/ private static final String UNDERSCORE = "_"; diff --git a/src/share/classes/com/sun/security/auth/NTDomainPrincipal.java b/src/share/classes/com/sun/security/auth/NTDomainPrincipal.java index 9464da9d3656f8714bedb36e3a2a63a386325629..9afbfead1a71bdef136068e1b8ccb62d72da1f00 100644 --- a/src/share/classes/com/sun/security/auth/NTDomainPrincipal.java +++ b/src/share/classes/com/sun/security/auth/NTDomainPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -68,7 +68,7 @@ public class NTDomainPrincipal implements Principal, java.io.Serializable { if (name == null) { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("invalid null input: value", + ("invalid.null.input.value", "sun.security.util.AuthResources")); Object[] source = {"name"}; throw new NullPointerException(form.format(source)); @@ -99,7 +99,7 @@ public class NTDomainPrincipal implements Principal, java.io.Serializable { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("NTDomainPrincipal: name", + ("NTDomainPrincipal.name", "sun.security.util.AuthResources")); Object[] source = {name}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/NTNumericCredential.java b/src/share/classes/com/sun/security/auth/NTNumericCredential.java index f1cfc37a35d7befe1ad6ad5b8edb9dca16578c1c..b574f8cde9fbd6675f10c14317f92b77cf07cc45 100644 --- a/src/share/classes/com/sun/security/auth/NTNumericCredential.java +++ b/src/share/classes/com/sun/security/auth/NTNumericCredential.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -70,7 +70,7 @@ public class NTNumericCredential { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("NTNumericCredential: name", + ("NTNumericCredential.name", "sun.security.util.AuthResources")); Object[] source = {Long.toString(impersonationToken)}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/NTSid.java b/src/share/classes/com/sun/security/auth/NTSid.java index 9868075be2b7a2aca11a060ae1b02eaa577d3177..0720c5ec3fbcb5129fef8718b7f494e9daee6ec2 100644 --- a/src/share/classes/com/sun/security/auth/NTSid.java +++ b/src/share/classes/com/sun/security/auth/NTSid.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -73,7 +73,7 @@ public class NTSid implements Principal, java.io.Serializable { if (stringSid == null) { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("invalid null input: value", + ("invalid.null.input.value", "sun.security.util.AuthResources")); Object[] source = {"stringSid"}; throw new NullPointerException(form.format(source)); @@ -81,7 +81,7 @@ public class NTSid implements Principal, java.io.Serializable { if (stringSid.length() == 0) { throw new IllegalArgumentException (sun.security.util.ResourcesMgr.getString - ("Invalid NTSid value", + ("Invalid.NTSid.value", "sun.security.util.AuthResources")); } sid = new String(stringSid); @@ -108,7 +108,7 @@ public class NTSid implements Principal, java.io.Serializable { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("NTSid: name", + ("NTSid.name", "sun.security.util.AuthResources")); Object[] source = {sid}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/NTSidDomainPrincipal.java b/src/share/classes/com/sun/security/auth/NTSidDomainPrincipal.java index 52c58281eeb01604d02139313ab026b450572327..0182c345dfd241e4a2aea3df3a92f9ee651a3290 100644 --- a/src/share/classes/com/sun/security/auth/NTSidDomainPrincipal.java +++ b/src/share/classes/com/sun/security/auth/NTSidDomainPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -73,7 +73,7 @@ public class NTSidDomainPrincipal extends NTSid { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("NTSidDomainPrincipal: name", + ("NTSidDomainPrincipal.name", "sun.security.util.AuthResources")); Object[] source = {getName()}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/NTSidGroupPrincipal.java b/src/share/classes/com/sun/security/auth/NTSidGroupPrincipal.java index 9a947e29bab979aa2eb96f77d2557848e2d80ece..66df636ba647659d24a396dfa6d5a371fe9b4e65 100644 --- a/src/share/classes/com/sun/security/auth/NTSidGroupPrincipal.java +++ b/src/share/classes/com/sun/security/auth/NTSidGroupPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -68,7 +68,7 @@ public class NTSidGroupPrincipal extends NTSid { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("NTSidGroupPrincipal: name", + ("NTSidGroupPrincipal.name", "sun.security.util.AuthResources")); Object[] source = {getName()}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/NTSidPrimaryGroupPrincipal.java b/src/share/classes/com/sun/security/auth/NTSidPrimaryGroupPrincipal.java index 4b28aa7b41a0b371de33fea789676c2927dd89b9..10055e5c29f15303720d683c6defee707b5b035d 100644 --- a/src/share/classes/com/sun/security/auth/NTSidPrimaryGroupPrincipal.java +++ b/src/share/classes/com/sun/security/auth/NTSidPrimaryGroupPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -70,7 +70,7 @@ public class NTSidPrimaryGroupPrincipal extends NTSid { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("NTSidPrimaryGroupPrincipal: name", + ("NTSidPrimaryGroupPrincipal.name", "sun.security.util.AuthResources")); Object[] source = {getName()}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/NTSidUserPrincipal.java b/src/share/classes/com/sun/security/auth/NTSidUserPrincipal.java index ee69b6f8fbaf5db9101405520e7d2488e09093a5..c7f8f9b4afe8aff194a14765393908c2f1e2ac20 100644 --- a/src/share/classes/com/sun/security/auth/NTSidUserPrincipal.java +++ b/src/share/classes/com/sun/security/auth/NTSidUserPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -67,7 +67,7 @@ public class NTSidUserPrincipal extends NTSid { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("NTSidUserPrincipal: name", + ("NTSidUserPrincipal.name", "sun.security.util.AuthResources")); Object[] source = {getName()}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/NTUserPrincipal.java b/src/share/classes/com/sun/security/auth/NTUserPrincipal.java index 490a30c186d081bfa73bddb38690b76ca43cb567..c5d424866072eb9d564f71873e9a9ca2701560ce 100644 --- a/src/share/classes/com/sun/security/auth/NTUserPrincipal.java +++ b/src/share/classes/com/sun/security/auth/NTUserPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -64,7 +64,7 @@ public class NTUserPrincipal implements Principal, java.io.Serializable { if (name == null) { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("invalid null input: value", + ("invalid.null.input.value", "sun.security.util.AuthResources")); Object[] source = {"name"}; throw new NullPointerException(form.format(source)); @@ -93,7 +93,7 @@ public class NTUserPrincipal implements Principal, java.io.Serializable { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("NTUserPrincipal: name", + ("NTUserPrincipal.name", "sun.security.util.AuthResources")); Object[] source = {name}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/PolicyFile.java b/src/share/classes/com/sun/security/auth/PolicyFile.java index 724df824f94ccbc1a0fccd91e213e5ee798d9521..fa9caf79e53501cb486d731895ede0e905a01770 100644 --- a/src/share/classes/com/sun/security/auth/PolicyFile.java +++ b/src/share/classes/com/sun/security/auth/PolicyFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -490,9 +490,9 @@ public class PolicyFile extends javax.security.auth.Policy { } } catch (PolicyParser.ParsingException pe) { System.err.println(AUTH_POLICY + - rb.getString(": error parsing ") + policy); + rb.getString(".error.parsing.") + policy); System.err.println(AUTH_POLICY + - rb.getString(": ") + + rb.getString("COLON") + pe.getMessage()); if (debug != null) pe.printStackTrace(); @@ -635,16 +635,16 @@ public class PolicyFile extends javax.security.auth.Policy { } catch (java.lang.reflect.InvocationTargetException ite) { System.err.println (AUTH_POLICY + - rb.getString(": error adding Permission ") + + rb.getString(".error.adding.Permission.") + pe.permission + - rb.getString(" ") + + rb.getString("SPACE") + ite.getTargetException()); } catch (Exception e) { System.err.println (AUTH_POLICY + - rb.getString(": error adding Permission ") + + rb.getString(".error.adding.Permission.") + pe.permission + - rb.getString(" ") + + rb.getString("SPACE") + e); } } @@ -652,9 +652,9 @@ public class PolicyFile extends javax.security.auth.Policy { } catch (Exception e) { System.err.println (AUTH_POLICY + - rb.getString(": error adding Entry ") + + rb.getString(".error.adding.Entry.") + ge + - rb.getString(" ") + + rb.getString("SPACE") + e); } @@ -1373,18 +1373,18 @@ public class PolicyFile extends javax.security.auth.Policy { public String toString(){ StringBuffer sb = new StringBuffer(); - sb.append(rb.getString("(")); + sb.append(rb.getString("LPARAM")); sb.append(getCodeSource()); sb.append("\n"); for (int j = 0; j < permissions.size(); j++) { Permission p = permissions.elementAt(j); - sb.append(rb.getString(" ")); - sb.append(rb.getString(" ")); + sb.append(rb.getString("SPACE")); + sb.append(rb.getString("SPACE")); sb.append(p); - sb.append(rb.getString("\n")); + sb.append(rb.getString("NEWLINE")); } - sb.append(rb.getString(")")); - sb.append(rb.getString("\n")); + sb.append(rb.getString("RPARAM")); + sb.append(rb.getString("NEWLINE")); return sb.toString(); } @@ -1415,7 +1415,7 @@ class PolicyPermissions extends PermissionCollection { if (isReadOnly()) throw new SecurityException (PolicyFile.rb.getString - ("attempt to add a Permission to a readonly PermissionCollection")); + ("attempt.to.add.a.Permission.to.a.readonly.PermissionCollection")); if (perms == null) { if (additionalPerms == null) diff --git a/src/share/classes/com/sun/security/auth/PolicyParser.java b/src/share/classes/com/sun/security/auth/PolicyParser.java index 045d6dc509809c0d03e69a7538bad6134730f59d..e4168e4072c3d9353b83933f11969a2d6d2163de 100644 --- a/src/share/classes/com/sun/security/auth/PolicyParser.java +++ b/src/share/classes/com/sun/security/auth/PolicyParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -300,7 +300,7 @@ class PolicyParser { keyStoreType = match("quoted string"); } else { throw new ParsingException(st.lineno(), - rb.getString("expected keystore type")); + rb.getString("expected.keystore.type")); } } @@ -368,8 +368,8 @@ class PolicyParser { "WILDCARD class but no WILDCARD name"); throw new ParsingException (st.lineno(), - rb.getString("can not specify Principal with a ") + - rb.getString("wildcard class without a wildcard name")); + rb.getString("can.not.specify.Principal.with.a.") + + rb.getString("wildcard.class.without.a.wildcard.name")); } try { @@ -389,7 +389,7 @@ class PolicyParser { } else { throw new ParsingException(st.lineno(), - rb.getString("expected codeBase or SignedBy")); + rb.getString("expected.codeBase.or.SignedBy")); } } @@ -397,7 +397,7 @@ class PolicyParser { if (principals == null) { throw new ParsingException (st.lineno(), - rb.getString("only Principal-based grant entries permitted")); + rb.getString("only.Principal.based.grant.entries.permitted")); } e.principals = principals; @@ -416,7 +416,7 @@ class PolicyParser { } else { throw new ParsingException(st.lineno(), - rb.getString("expected permission entry")); + rb.getString("expected.permission.entry")); } } match("}"); @@ -522,12 +522,12 @@ class PolicyParser { switch (lookahead) { case StreamTokenizer.TT_NUMBER: throw new ParsingException(st.lineno(), expect, - rb.getString("number ") + + rb.getString("number.") + String.valueOf(st.nval)); case StreamTokenizer.TT_EOF: throw new ParsingException - (rb.getString("expected ") + expect + - rb.getString(", read end of file")); + (rb.getString("expected.") + expect + + rb.getString(".read.end.of.file")); case StreamTokenizer.TT_WORD: if (expect.equalsIgnoreCase(st.sval)) { lookahead = st.nextToken(); @@ -603,11 +603,11 @@ class PolicyParser { switch (lookahead) { case StreamTokenizer.TT_NUMBER: throw new ParsingException(st.lineno(), ";", - rb.getString("number ") + + rb.getString("number.") + String.valueOf(st.nval)); case StreamTokenizer.TT_EOF: throw new ParsingException - (rb.getString("expected ';', read end of file")); + (rb.getString("expected.read.end.of.file")); default: lookahead = st.nextToken(); } @@ -942,13 +942,13 @@ class PolicyParser { } public ParsingException(int line, String msg) { - super(rb.getString("line ") + line + rb.getString(": ") + msg); + super(rb.getString("line.") + line + rb.getString("COLON") + msg); } public ParsingException(int line, String expect, String actual) { - super(rb.getString("line ") + line + rb.getString(": expected '") + - expect + rb.getString("', found '") + actual + - rb.getString("'")); + super(rb.getString("line.") + line + rb.getString(".expected.") + + expect + rb.getString(".found.") + actual + + rb.getString("QUOTE")); } } diff --git a/src/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java b/src/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java index 40fe122aa06a5864c327b7044b9af96a11072e79..66943aaa71a7e111493fd22b515bc4724dc0c2a4 100644 --- a/src/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java +++ b/src/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -89,7 +89,7 @@ public class SolarisNumericGroupPrincipal implements */ public SolarisNumericGroupPrincipal(String name, boolean primaryGroup) { if (name == null) - throw new NullPointerException(rb.getString("provided null name")); + throw new NullPointerException(rb.getString("provided.null.name")); this.name = name; this.primaryGroup = primaryGroup; @@ -165,9 +165,9 @@ public class SolarisNumericGroupPrincipal implements public String toString() { return((primaryGroup ? rb.getString - ("SolarisNumericGroupPrincipal [Primary Group]: ") + name : + ("SolarisNumericGroupPrincipal.Primary.Group.") + name : rb.getString - ("SolarisNumericGroupPrincipal [Supplementary Group]: ") + name)); + ("SolarisNumericGroupPrincipal.Supplementary.Group.") + name)); } /** diff --git a/src/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java b/src/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java index 7a8b2f88743da54f718cdb6cf6bfe64a0909949d..5623239666e990712e5393fd4b004b6035cad821 100644 --- a/src/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java +++ b/src/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -80,7 +80,7 @@ public class SolarisNumericUserPrincipal implements */ public SolarisNumericUserPrincipal(String name) { if (name == null) - throw new NullPointerException(rb.getString("provided null name")); + throw new NullPointerException(rb.getString("provided.null.name")); this.name = name; } @@ -134,7 +134,7 @@ public class SolarisNumericUserPrincipal implements * SolarisNumericUserPrincipal. */ public String toString() { - return(rb.getString("SolarisNumericUserPrincipal: ") + name); + return(rb.getString("SolarisNumericUserPrincipal.") + name); } /** diff --git a/src/share/classes/com/sun/security/auth/SolarisPrincipal.java b/src/share/classes/com/sun/security/auth/SolarisPrincipal.java index e5340a9ca70588643a37b1e229b65a01029d4103..406692c7687aef9664437c7a4657b0dc4eec1065 100644 --- a/src/share/classes/com/sun/security/auth/SolarisPrincipal.java +++ b/src/share/classes/com/sun/security/auth/SolarisPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -76,7 +76,7 @@ public class SolarisPrincipal implements Principal, java.io.Serializable { */ public SolarisPrincipal(String name) { if (name == null) - throw new NullPointerException(rb.getString("provided null name")); + throw new NullPointerException(rb.getString("provided.null.name")); this.name = name; } @@ -100,7 +100,7 @@ public class SolarisPrincipal implements Principal, java.io.Serializable { * @return a string representation of this SolarisPrincipal. */ public String toString() { - return(rb.getString("SolarisPrincipal: ") + name); + return(rb.getString("SolarisPrincipal.") + name); } /** diff --git a/src/share/classes/com/sun/security/auth/SubjectCodeSource.java b/src/share/classes/com/sun/security/auth/SubjectCodeSource.java index 295af7ce5df9cd929d08662fe2c3e8df5f9ce1e6..d149aacbad790c3e4a5216119e5e764f711cc78d 100644 --- a/src/share/classes/com/sun/security/auth/SubjectCodeSource.java +++ b/src/share/classes/com/sun/security/auth/SubjectCodeSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -395,7 +395,7 @@ class SubjectCodeSource extends CodeSource implements java.io.Serializable { principals.listIterator(); while (li.hasNext()) { PolicyParser.PrincipalEntry pppe = li.next(); - returnMe = returnMe + rb.getString("\n") + + returnMe = returnMe + rb.getString("NEWLINE") + pppe.principalClass + " " + pppe.principalName; } diff --git a/src/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java b/src/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java index 4dd4466c0fa76261c1fa724446bd2430ef0d8197..5c4260b5ccce9dae2bac78d2aad7c3c5c4e7157b 100644 --- a/src/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java +++ b/src/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -77,7 +77,7 @@ public class UnixNumericGroupPrincipal implements if (name == null) { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("invalid null input: value", + ("invalid.null.input.value", "sun.security.util.AuthResources")); Object[] source = {"name"}; throw new NullPointerException(form.format(source)); @@ -159,14 +159,14 @@ public class UnixNumericGroupPrincipal implements if (primaryGroup) { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("UnixNumericGroupPrincipal [Primary Group]: name", + ("UnixNumericGroupPrincipal.Primary.Group.name", "sun.security.util.AuthResources")); Object[] source = {name}; return form.format(source); } else { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("UnixNumericGroupPrincipal [Supplementary Group]: name", + ("UnixNumericGroupPrincipal.Supplementary.Group.name", "sun.security.util.AuthResources")); Object[] source = {name}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java b/src/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java index d167c75847493efd32d77743d5f34fc40f932449..bb15312b60258a00cccfcca5e767128df14ecd97 100644 --- a/src/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java +++ b/src/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -67,7 +67,7 @@ public class UnixNumericUserPrincipal implements if (name == null) { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("invalid null input: value", + ("invalid.null.input.value", "sun.security.util.AuthResources")); Object[] source = {"name"}; throw new NullPointerException(form.format(source)); @@ -127,7 +127,7 @@ public class UnixNumericUserPrincipal implements public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("UnixNumericUserPrincipal: name", + ("UnixNumericUserPrincipal.name", "sun.security.util.AuthResources")); Object[] source = {name}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/UnixPrincipal.java b/src/share/classes/com/sun/security/auth/UnixPrincipal.java index 24a88bb1d9cb02076a37e2907e5511a4567f9e59..67d9133ef0391a6057d892ff01ea7e290bcef096 100644 --- a/src/share/classes/com/sun/security/auth/UnixPrincipal.java +++ b/src/share/classes/com/sun/security/auth/UnixPrincipal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -64,7 +64,7 @@ public class UnixPrincipal implements Principal, java.io.Serializable { if (name == null) { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("invalid null input: value", + ("invalid.null.input.value", "sun.security.util.AuthResources")); Object[] source = {"name"}; throw new NullPointerException(form.format(source)); @@ -94,7 +94,7 @@ public class UnixPrincipal implements Principal, java.io.Serializable { public String toString() { java.text.MessageFormat form = new java.text.MessageFormat (sun.security.util.ResourcesMgr.getString - ("UnixPrincipal: name", + ("UnixPrincipal.name", "sun.security.util.AuthResources")); Object[] source = {name}; return form.format(source); diff --git a/src/share/classes/com/sun/security/auth/X500Principal.java b/src/share/classes/com/sun/security/auth/X500Principal.java index 568d536d62105b0629ca03ba81393422804de45c..cb48043aea47d70225e0498d3191e2dfd0b5e8f8 100644 --- a/src/share/classes/com/sun/security/auth/X500Principal.java +++ b/src/share/classes/com/sun/security/auth/X500Principal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -87,7 +87,7 @@ public class X500Principal implements Principal, java.io.Serializable { */ public X500Principal(String name) { if (name == null) - throw new NullPointerException(rb.getString("provided null name")); + throw new NullPointerException(rb.getString("provided.null.name")); try { thisX500Name = new X500Name(name); diff --git a/src/share/classes/com/sun/security/auth/login/ConfigFile.java b/src/share/classes/com/sun/security/auth/login/ConfigFile.java index 2db246171b0bd3780a695947ecea3c7a34142bb0..ad186566fee5d16f13c063c4b273104f5ab33e55 100644 --- a/src/share/classes/com/sun/security/auth/login/ConfigFile.java +++ b/src/share/classes/com/sun/security/auth/login/ConfigFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -190,7 +190,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { } catch (PropertyExpander.ExpandException peee) { MessageFormat form = new MessageFormat (ResourcesMgr.getString - ("Unable to properly expand config", + ("Unable.to.properly.expand.config", "sun.security.util.AuthResources")); Object[] source = {extra_config}; throw new IOException(form.format(source)); @@ -206,7 +206,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { } else { MessageFormat form = new MessageFormat (ResourcesMgr.getString - ("extra_config (No such file or directory)", + ("extra.config.No.such.file.or.directory.", "sun.security.util.AuthResources")); Object[] source = {extra_config}; throw new IOException(form.format(source)); @@ -243,7 +243,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { } catch (PropertyExpander.ExpandException peee) { MessageFormat form = new MessageFormat (ResourcesMgr.getString - ("Unable to properly expand config", + ("Unable.to.properly.expand.config", "sun.security.util.AuthResources")); Object[] source = {config_url}; throw new IOException(form.format(source)); @@ -286,7 +286,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { debugConfig.println(fnfe.toString()); } throw new IOException(ResourcesMgr.getString - ("Configuration Error:\n\tNo such file or directory", + ("Configuration.Error.No.such.file.or.directory", "sun.security.util.AuthResources")); } finally { if (isr != null) { @@ -426,7 +426,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL; else { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\tInvalid control flag, flag", + ("Configuration.Error.Invalid.control.flag.flag", "sun.security.util.AuthResources")); Object[] source = {sflag}; throw new IOException(form.format(source)); @@ -474,8 +474,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { // add this configuration entry if (newConfig.containsKey(appName)) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\t" + - "Can not specify multiple entries for appName", + ("Configuration.Error.Can.not.specify.multiple.entries.for.appName", "sun.security.util.AuthResources")); Object[] source = {appName}; throw new IOException(form.format(source)); @@ -491,8 +490,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { case StreamTokenizer.TT_EOF: MessageFormat form1 = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\texpected [expect], " + - "read [end of file]", + ("Configuration.Error.expected.expect.read.end.of.file.", "sun.security.util.AuthResources")); Object[] source1 = {expect}; throw new IOException(form1.format(source1)); @@ -508,8 +506,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { lookahead = nextToken(); } else { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\tLine line: " + - "expected [expect], found [value]", + ("Configuration.Error.Line.line.expected.expect.found.value.", "sun.security.util.AuthResources")); Object[] source = {new Integer(linenum), expect, st.sval}; throw new IOException(form.format(source)); @@ -522,7 +519,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { lookahead = nextToken(); } else { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\tLine line: expected [expect]", + ("Configuration.Error.Line.line.expected.expect.", "sun.security.util.AuthResources")); Object[] source = {new Integer(linenum), expect, st.sval}; throw new IOException(form.format(source)); @@ -535,7 +532,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { lookahead = nextToken(); } else { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\tLine line: expected [expect]", + ("Configuration.Error.Line.line.expected.expect.", "sun.security.util.AuthResources")); Object[] source = {new Integer(linenum), expect, st.sval}; throw new IOException(form.format(source)); @@ -548,7 +545,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { lookahead = nextToken(); } else { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\tLine line: expected [expect]", + ("Configuration.Error.Line.line.expected.expect.", "sun.security.util.AuthResources")); Object[] source = {new Integer(linenum), expect, st.sval}; throw new IOException(form.format(source)); @@ -561,7 +558,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { lookahead = nextToken(); } else { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\tLine line: expected [expect]", + ("Configuration.Error.Line.line.expected.expect.", "sun.security.util.AuthResources")); Object[] source = {new Integer(linenum), expect, st.sval}; throw new IOException(form.format(source)); @@ -570,8 +567,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { default: MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\tLine line: " + - "expected [expect], found [value]", + ("Configuration.Error.Line.line.expected.expect.found.value.", "sun.security.util.AuthResources")); Object[] source = {new Integer(linenum), expect, st.sval}; throw new IOException(form.format(source)); @@ -667,8 +663,7 @@ public class ConfigFile extends javax.security.auth.login.Configuration { if (s == null || s.length() == 0) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("Configuration Error:\n\tLine line: " + - "system property [value] expanded to empty value", + ("Configuration.Error.Line.line.system.property.value.expanded.to.empty.value", "sun.security.util.AuthResources")); Object[] source = {new Integer(linenum), value}; throw new IOException(form.format(source)); diff --git a/src/share/classes/com/sun/security/auth/module/JndiLoginModule.java b/src/share/classes/com/sun/security/auth/module/JndiLoginModule.java index b37d874758b093915a5bede11c41df792cf8167d..59a19849df426db4cfc2ac903f0128ceeec2f742 100644 --- a/src/share/classes/com/sun/security/auth/module/JndiLoginModule.java +++ b/src/share/classes/com/sun/security/auth/module/JndiLoginModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -686,9 +686,9 @@ public class JndiLoginModule implements LoginModule { Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback(protocol + " " - + rb.getString("username: ")); + + rb.getString("username.")); callbacks[1] = new PasswordCallback(protocol + " " + - rb.getString("password: "), + rb.getString("password."), false); try { diff --git a/src/share/classes/com/sun/security/auth/module/KeyStoreLoginModule.java b/src/share/classes/com/sun/security/auth/module/KeyStoreLoginModule.java index c6c6f8d09bd461f219a157bacdf062a4b6bba880..ff6185e3877d6f58dae127552d2ed9b8b125402f 100644 --- a/src/share/classes/com/sun/security/auth/module/KeyStoreLoginModule.java +++ b/src/share/classes/com/sun/security/auth/module/KeyStoreLoginModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -150,7 +150,7 @@ public class KeyStoreLoginModule implements LoginModule { private static final TextOutputCallback bannerCallback = new TextOutputCallback (TextOutputCallback.INFORMATION, - rb.getString("Please enter keystore information")); + rb.getString("Please.enter.keystore.information")); private final ConfirmationCallback confirmationCallback = new ConfirmationCallback (ConfirmationCallback.INFORMATION, @@ -364,10 +364,10 @@ public class KeyStoreLoginModule implements LoginModule { NameCallback aliasCallback; if (keyStoreAlias == null || keyStoreAlias.length() == 0) { aliasCallback = new NameCallback( - rb.getString("Keystore alias: ")); + rb.getString("Keystore.alias.")); } else { aliasCallback = - new NameCallback(rb.getString("Keystore alias: "), + new NameCallback(rb.getString("Keystore.alias."), keyStoreAlias); } @@ -379,11 +379,11 @@ public class KeyStoreLoginModule implements LoginModule { break; case NORMAL: keyPassCallback = new PasswordCallback - (rb.getString("Private key password (optional): "), false); + (rb.getString("Private.key.password.optional."), false); // fall thru case TOKEN: storePassCallback = new PasswordCallback - (rb.getString("Keystore password: "), false); + (rb.getString("Keystore.password."), false); break; } prompt(aliasCallback, storePassCallback, keyPassCallback); diff --git a/src/share/classes/com/sun/security/auth/module/Krb5LoginModule.java b/src/share/classes/com/sun/security/auth/module/Krb5LoginModule.java index 02ac9c6f1bcc0bc17fcfee0dcf8540f71623cd60..c9499f1d1a0f528ed61cebc8ba95c1e2f60ce427 100644 --- a/src/share/classes/com/sun/security/auth/module/Krb5LoginModule.java +++ b/src/share/classes/com/sun/security/auth/module/Krb5LoginModule.java @@ -27,7 +27,6 @@ package com.sun.security.auth.module; import java.io.*; -import java.net.*; import java.text.MessageFormat; import java.util.*; @@ -38,9 +37,6 @@ import javax.security.auth.login.*; import javax.security.auth.spi.*; import sun.security.krb5.*; -import sun.security.krb5.Config; -import sun.security.krb5.RealmException; -import sun.security.util.AuthResources; import sun.security.jgss.krb5.Krb5Util; import sun.security.krb5.Credentials; import sun.misc.HexDumpEncoder; @@ -685,32 +681,27 @@ public class Krb5LoginModule implements LoginModule { } } + + KrbAsReqBuilder builder; // We can't get the key from the keytab so prompt if (encKeys == null) { promptForPass(getPasswdFromSharedState); - - encKeys = EncryptionKey.acquireSecretKeys( - password, principal.getSalt()); - + builder = new KrbAsReqBuilder(principal, password); if (isInitiator) { - if (debug) - System.out.println("Acquire TGT using AS Exchange"); - cred = Credentials.acquireTGT(principal, - encKeys, password); - // update keys after pre-auth - encKeys = EncryptionKey.acquireSecretKeys(password, - principal.getSalt()); + // XXX Even if isInitiator=false, it might be + // better to do an AS-REQ so that keys can be + // updated with PA info + cred = builder.action().getCreds(); } + encKeys = builder.getKeys(); } else { + builder = new KrbAsReqBuilder(principal, encKeys); if (isInitiator) { - if (debug) - System.out.println("Acquire TGT using AS Exchange"); - cred = Credentials.acquireTGT(principal, - encKeys, password); + cred = builder.action().getCreds(); } } + builder.destroy(); - // Get the TGT using AS Exchange if (debug) { System.out.println("principal is " + principal); HexDumpEncoder hd = new HexDumpEncoder(); @@ -780,7 +771,7 @@ public class Krb5LoginModule implements LoginModule { Callback[] callbacks = new Callback[1]; MessageFormat form = new MessageFormat( rb.getString( - "Kerberos username [[defUsername]]: ")); + "Kerberos.username.defUsername.")); Object[] source = {defUsername}; callbacks[0] = new NameCallback(form.format(source)); callbackHandler.handle(callbacks); @@ -835,7 +826,7 @@ public class Krb5LoginModule implements LoginModule { String userName = krb5PrincName.toString(); MessageFormat form = new MessageFormat( rb.getString( - "Kerberos password for [username]: ")); + "Kerberos.password.for.username.")); Object[] source = {userName}; callbacks[0] = new PasswordCallback( form.format(source), diff --git a/src/share/classes/com/sun/security/auth/module/LdapLoginModule.java b/src/share/classes/com/sun/security/auth/module/LdapLoginModule.java index ce7fa887fa21083cf77ecc8450fa99937b425c80..dbea72c5b93017bc74a582752267c6185800e79d 100644 --- a/src/share/classes/com/sun/security/auth/module/LdapLoginModule.java +++ b/src/share/classes/com/sun/security/auth/module/LdapLoginModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -969,8 +969,8 @@ public class LdapLoginModule implements LoginModule { "to acquire authentication information from the user"); Callback[] callbacks = new Callback[2]; - callbacks[0] = new NameCallback(rb.getString("username: ")); - callbacks[1] = new PasswordCallback(rb.getString("password: "), false); + callbacks[0] = new NameCallback(rb.getString("username.")); + callbacks[1] = new PasswordCallback(rb.getString("password."), false); try { callbackHandler.handle(callbacks); diff --git a/src/share/classes/com/sun/servicetag/SunConnection.java b/src/share/classes/com/sun/servicetag/SunConnection.java index 3a8983f9b6c0b483f00383ec73a430c6c3d0cc53..cc78ef16f8b1f8a0dcceba71c7e9b06ebac7256d 100644 --- a/src/share/classes/com/sun/servicetag/SunConnection.java +++ b/src/share/classes/com/sun/servicetag/SunConnection.java @@ -51,8 +51,8 @@ import javax.net.ssl.HttpsURLConnection; */ class SunConnection { - private static String JDK_REGISTRATION_URL = "https://inventory.sun.com/"; - private static String SANDBOX_TESTING_URL = "https://inventory-beta.sun.com/"; + private static String JDK_REGISTRATION_URL = "https://hs-ws1.oracle.com/"; + private static String SANDBOX_TESTING_URL = "https://hs-ws1-tst.oracle.com/"; private static String REGISTRATION_WEB_PATH = "RegistrationWeb/register"; // System properties for testing diff --git a/src/share/classes/com/sun/servicetag/resources/register.html b/src/share/classes/com/sun/servicetag/resources/register.html index cc1dee262ec143d17ac00fc55bd6dddba7f391c8..42cfa4b09064c61f41228270033ec4c4e8343b72 100644 --- a/src/share/classes/com/sun/servicetag/resources/register.html +++ b/src/share/classes/com/sun/servicetag/resources/register.html @@ -64,7 +64,7 @@ a:visited,a:visited code{color:#917E9C}

Product registration is FREE, quick and easy!

-

All you need is a Sun Developer Network or other Sun Online account. If you don't already have one, you will be prompted to create one.

+

All you need is an Oracle.com account. If you don't already have one, you will be prompted to create one.

@@ -83,9 +83,9 @@ a:visited,a:visited code{color:#917E9C}

Oracle Corporation respects your privacy. We will use your personal information for communications - and management of your Sun Online Account, the services - and applications you access using your Sun Online Account, - and the products and systems you register with your Sun Online Account.

+ and management of your Oracle.com account, the services + and applications you access using your Oracle.com account, + and the products and systems you register with your Oracle.com account.

For more information on the data that will be collected as part of the registration process and how it will be managed
see http://java.sun.com/javase/registration/JDKRegistrationPrivacy.html.
diff --git a/src/share/classes/com/sun/servicetag/resources/register_ja.html b/src/share/classes/com/sun/servicetag/resources/register_ja.html index 3da70723ef8bc40f306d7a029607fa97d8f84023..7c36d0ec982b922960f38d28ea1a27c1077b524d 100644 --- a/src/share/classes/com/sun/servicetag/resources/register_ja.html +++ b/src/share/classes/com/sun/servicetag/resources/register_ja.html @@ -59,7 +59,7 @@ a:visited,a:visited code{color:#917E9C}

製品登録は無料であり、迅速で簡単です。

-

必要になるのは、Sun 開発者向けネットワークアカウントまたはその他の Sun オンラインアカウントだけです。 まだアカウントがない場合は、アカウントの作成が求められます。

+

必要になるのは、Oracle.com アカウントだけです。 まだアカウントがない場合は、アカウントの作成が求められます。

diff --git a/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html b/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html index f5bad110b4fb42bd01ef0fe856b6e469aa47edff..86a289141d1fdb7fc7a74e44cf1bca66b92261ad 100644 --- a/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html +++ b/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html @@ -60,7 +60,7 @@ a:visited,a:visited code{color:#917E9C}

产品注册是免费的,即快速又轻松!

-

您需要具有 Sun 开发者网络或其他 Sun 联机帐户。如果您没有,系统将提示您创建一个。

+

您需要具有 Oracle.com 帐户。如果您没有,系统将提示您创建一个。

@@ -75,7 +75,7 @@ a:visited,a:visited code{color:#917E9C}
  -

Oracle Corporation は、お客様のプライバシーを尊重します。 お客様の個人情報は、お客様の Sun オンラインアカウント、お客様が Sun オンラインアカウントを使用してアクセスするサービスとアプリケーション、およびお客様が Sun オンラインアカウントで登録する製品とシステムの通信と管理に使用します。

+

Oracle Corporation は、お客様のプライバシーを尊重します。 お客様の個人情報は、お客様の Oracle.com アカウント、お客様が Oracle.com アカウントを使用してアクセスするサービスとアプリケーション、およびお客様が Oracle.com アカウントで登録する製品とシステムの通信と管理に使用します。

登録の際に収集されるデータや、それらがどのように管理されるかについての詳細は、
http://java.sun.com/javase/ja/registration/JDKRegistrationPrivacy.html を参照してください。

Oracle のプライバシーポリシーについての詳細は、http://www.oracle.com/html/privacy.html を参照するか、お問い合わせフォームからお問い合わせください。

diff --git a/src/share/classes/java/awt/Component.java b/src/share/classes/java/awt/Component.java index f8bdac15d408678cc4dc03a70c69de30c6aa8270..cff463b3526c0d7eadf1ddabfdc061189f3faf23 100644 --- a/src/share/classes/java/awt/Component.java +++ b/src/share/classes/java/awt/Component.java @@ -2154,6 +2154,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * * @param d the dimension specifying the new size * of this component + * @throws NullPointerException if {@code d} is {@code null} * @see #setSize * @see #setBounds * @see #invalidate @@ -2351,6 +2352,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * invalidates the component hierarchy. * * @param r the new bounding rectangle for this component + * @throws NullPointerException if {@code r} is {@code null} * @see #getBounds * @see #setLocation(int, int) * @see #setLocation(Point) @@ -4545,6 +4547,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * where the point's x and y coordinates are defined * to be relative to the coordinate system of this component. * @param p the point + * @throws NullPointerException if {@code p} is {@code null} * @see #getComponentAt(Point) * @since JDK1.1 */ @@ -5879,7 +5882,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * @exception ClassCastException if listenerType * doesn't specify a class or interface that implements * java.util.EventListener - * + * @throws NullPointerException if {@code listenerType} is {@code null} * @see #getComponentListeners * @see #getFocusListeners * @see #getHierarchyListeners @@ -8038,6 +8041,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * Prints a listing of this component to the specified output * stream. * @param out a print stream + * @throws NullPointerException if {@code out} is {@code null} * @since JDK1.0 */ public void list(PrintStream out) { @@ -8050,6 +8054,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * @param out a print stream * @param indent number of spaces to indent * @see java.io.PrintStream#println(java.lang.Object) + * @throws NullPointerException if {@code out} is {@code null} * @since JDK1.0 */ public void list(PrintStream out, int indent) { @@ -8062,6 +8067,7 @@ public abstract class Component implements ImageObserver, MenuContainer, /** * Prints a listing to the specified print writer. * @param out the print writer to print to + * @throws NullPointerException if {@code out} is {@code null} * @since JDK1.1 */ public void list(PrintWriter out) { @@ -8073,6 +8079,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * the specified print writer. * @param out the print writer to print to * @param indent the number of spaces to indent + * @throws NullPointerException if {@code out} is {@code null} * @see java.io.PrintStream#println(java.lang.Object) * @since JDK1.1 */ diff --git a/src/share/classes/java/awt/Container.java b/src/share/classes/java/awt/Container.java index bf635fd45acd364b4e9298ee55f93d9c4307d2c1..a7ee77e16cbf5a711e34256fade7a0d46796b97e 100644 --- a/src/share/classes/java/awt/Container.java +++ b/src/share/classes/java/awt/Container.java @@ -1231,6 +1231,7 @@ public class Container extends Component { * reflect the changes. * * @param comp the component to be removed + * @throws NullPointerException if {@code comp} is {@code null} * @see #add * @see #invalidate * @see #validate @@ -2154,6 +2155,7 @@ public class Container extends Component { * @exception ClassCastException if listenerType * doesn't specify a class or interface that implements * java.util.EventListener + * @exception NullPointerException if {@code listenerType} is {@code null} * * @see #getContainerListeners * @@ -2705,6 +2707,7 @@ public class Container extends Component { * If there is no child component at the requested point and the * point is within the bounds of the container the container itself * is returned. + * @throws NullPointerException if {@code p} is {@code null} * @see Component#contains * @see #getComponentAt * @since 1.2 @@ -2969,6 +2972,7 @@ public class Container extends Component { * * @param out a print stream * @param indent the number of spaces to indent + * @throws NullPointerException if {@code out} is {@code null} * @see Component#list(java.io.PrintStream, int) * @since JDK1.0 */ @@ -2995,6 +2999,7 @@ public class Container extends Component { * * @param out a print writer * @param indent the number of spaces to indent + * @throws NullPointerException if {@code out} is {@code null} * @see Component#list(java.io.PrintWriter, int) * @since JDK1.1 */ diff --git a/src/share/classes/java/awt/ScrollPane.java b/src/share/classes/java/awt/ScrollPane.java index 6a06acb5403bc6d4cb96bda60b8e6919c32cd55a..104318abf6f292f7b2c05ec014accca1e612b484 100644 --- a/src/share/classes/java/awt/ScrollPane.java +++ b/src/share/classes/java/awt/ScrollPane.java @@ -377,6 +377,7 @@ public class ScrollPane extends Container implements Accessible { * This is a convenience method which interfaces with the Adjustable * objects which represent the state of the scrollbars. * @param p the Point representing the position to scroll to + * @throws NullPointerException if {@code p} is {@code null} */ public void setScrollPosition(Point p) { setScrollPosition(p.x, p.y); diff --git a/src/share/classes/java/awt/Window.java b/src/share/classes/java/awt/Window.java index 7dce80e9564de856c0cab5f1bfddfee284375171..03dbd535e9f0d5f146c83ba2ad6247399096e1e6 100644 --- a/src/share/classes/java/awt/Window.java +++ b/src/share/classes/java/awt/Window.java @@ -1888,6 +1888,7 @@ public class Window extends Container implements Accessible { * @exception ClassCastException if listenerType * doesn't specify a class or interface that implements * java.util.EventListener + * @exception NullPointerException if {@code listenerType} is {@code null} * * @see #getWindowListeners * @since 1.3 diff --git a/src/share/classes/java/io/ByteArrayInputStream.java b/src/share/classes/java/io/ByteArrayInputStream.java index 5cef38ddd6c76ca35916c54435504add6f8b0357..11207aad9c518bffaeab668514eed5817546406a 100644 --- a/src/share/classes/java/io/ByteArrayInputStream.java +++ b/src/share/classes/java/io/ByteArrayInputStream.java @@ -179,11 +179,14 @@ class ByteArrayInputStream extends InputStream { } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } + if (pos >= count) { return -1; } - if (pos + len > count) { - len = count - pos; + + int avail = count - pos; + if (len > avail) { + len = avail; } if (len <= 0) { return 0; @@ -206,14 +209,13 @@ class ByteArrayInputStream extends InputStream { * @return the actual number of bytes skipped. */ public synchronized long skip(long n) { - if (pos + n > count) { - n = count - pos; + long k = count - pos; + if (n < k) { + k = n < 0 ? 0 : n; } - if (n < 0) { - return 0; - } - pos += n; - return n; + + pos += k; + return k; } /** diff --git a/src/share/classes/java/lang/StackTraceElement.java b/src/share/classes/java/lang/StackTraceElement.java index 549af16b1017064efb4d763a6e38180acd615208..b95587d71850fff19924f59799e25a89ac8351a1 100644 --- a/src/share/classes/java/lang/StackTraceElement.java +++ b/src/share/classes/java/lang/StackTraceElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -25,6 +25,8 @@ package java.lang; +import java.util.Objects; + /** * An element in a stack trace, as returned by {@link * Throwable#getStackTrace()}. Each element represents a single stack frame. @@ -53,26 +55,21 @@ public final class StackTraceElement implements java.io.Serializable { * @param methodName the name of the method containing the execution point * represented by the stack trace element * @param fileName the name of the file containing the execution point - * represented by the stack trace element, or null if + * represented by the stack trace element, or {@code null} if * this information is unavailable * @param lineNumber the line number of the source line containing the * execution point represented by this stack trace element, or * a negative number if this information is unavailable. A value * of -2 indicates that the method containing the execution point * is a native method - * @throws NullPointerException if declaringClass or - * methodName is null + * @throws NullPointerException if {@code declaringClass} or + * {@code methodName} is null * @since 1.5 */ public StackTraceElement(String declaringClass, String methodName, String fileName, int lineNumber) { - if (declaringClass == null) - throw new NullPointerException("Declaring class is null"); - if (methodName == null) - throw new NullPointerException("Method name is null"); - - this.declaringClass = declaringClass; - this.methodName = methodName; + this.declaringClass = Objects.nonNull(declaringClass, "Declaring class is null"); + this.methodName = Objects.nonNull(methodName, "Method name is null"); this.fileName = fileName; this.lineNumber = lineNumber; } @@ -80,13 +77,13 @@ public final class StackTraceElement implements java.io.Serializable { /** * Returns the name of the source file containing the execution point * represented by this stack trace element. Generally, this corresponds - * to the SourceFile attribute of the relevant class + * to the {@code SourceFile} attribute of the relevant {@code class} * file (as per The Java Virtual Machine Specification, Section * 4.7.7). In some systems, the name may refer to some source code unit * other than a file, such as an entry in source repository. * * @return the name of the file containing the execution point - * represented by this stack trace element, or null if + * represented by this stack trace element, or {@code null} if * this information is unavailable. */ public String getFileName() { @@ -96,8 +93,8 @@ public final class StackTraceElement implements java.io.Serializable { /** * Returns the line number of the source line containing the execution * point represented by this stack trace element. Generally, this is - * derived from the LineNumberTable attribute of the relevant - * class file (as per The Java Virtual Machine + * derived from the {@code LineNumberTable} attribute of the relevant + * {@code class} file (as per The Java Virtual Machine * Specification, Section 4.7.8). * * @return the line number of the source line containing the execution @@ -112,7 +109,7 @@ public final class StackTraceElement implements java.io.Serializable { * Returns the fully qualified name of the class containing the * execution point represented by this stack trace element. * - * @return the fully qualified name of the Class containing + * @return the fully qualified name of the {@code Class} containing * the execution point represented by this stack trace element. */ public String getClassName() { @@ -123,8 +120,8 @@ public final class StackTraceElement implements java.io.Serializable { * Returns the name of the method containing the execution point * represented by this stack trace element. If the execution point is * contained in an instance or class initializer, this method will return - * the appropriate special method name, <init> or - * <clinit>, as per Section 3.9 of The Java Virtual + * the appropriate special method name, {@code } or + * {@code }, as per Section 3.9 of The Java Virtual * Machine Specification. * * @return the name of the method containing the execution point @@ -138,7 +135,7 @@ public final class StackTraceElement implements java.io.Serializable { * Returns true if the method containing the execution point * represented by this stack trace element is a native method. * - * @return true if the method containing the execution point + * @return {@code true} if the method containing the execution point * represented by this stack trace element is a native method. */ public boolean isNativeMethod() { @@ -151,21 +148,21 @@ public final class StackTraceElement implements java.io.Serializable { * examples may be regarded as typical: *
    *
  • - * "MyClass.mash(MyClass.java:9)" - Here, "MyClass" + * {@code "MyClass.mash(MyClass.java:9)"} - Here, {@code "MyClass"} * is the fully-qualified name of the class containing the * execution point represented by this stack trace element, - * "mash" is the name of the method containing the execution - * point, "MyClass.java" is the source file containing the - * execution point, and "9" is the line number of the source + * {@code "mash"} is the name of the method containing the execution + * point, {@code "MyClass.java"} is the source file containing the + * execution point, and {@code "9"} is the line number of the source * line containing the execution point. *
  • - * "MyClass.mash(MyClass.java)" - As above, but the line + * {@code "MyClass.mash(MyClass.java)"} - As above, but the line * number is unavailable. *
  • - * "MyClass.mash(Unknown Source)" - As above, but neither + * {@code "MyClass.mash(Unknown Source)"} - As above, but neither * the file name nor the line number are available. *
  • - * "MyClass.mash(Native Method)" - As above, but neither + * {@code "MyClass.mash(Native Method)"} - As above, but neither * the file name nor the line number are available, and the method * containing the execution point is known to be a native method. *
@@ -181,25 +178,21 @@ public final class StackTraceElement implements java.io.Serializable { /** * Returns true if the specified object is another - * StackTraceElement instance representing the same execution - * point as this instance. Two stack trace elements a and - * b are equal if and only if: + * {@code StackTraceElement} instance representing the same execution + * point as this instance. Two stack trace elements {@code a} and + * {@code b} are equal if and only if: *
      *     equals(a.getFileName(), b.getFileName()) &&
      *     a.getLineNumber() == b.getLineNumber()) &&
      *     equals(a.getClassName(), b.getClassName()) &&
      *     equals(a.getMethodName(), b.getMethodName())
      * 
- * where equals is defined as: - *
-     *     static boolean equals(Object a, Object b) {
-     *         return a==b || (a != null && a.equals(b));
-     *     }
-     * 
+ * where {@code equals} has the semantics of {@link + * java.util.Objects#equals(Object, Object) Objects.equals}. * * @param obj the object to be compared with this stack trace element. * @return true if the specified object is another - * StackTraceElement instance representing the same + * {@code StackTraceElement} instance representing the same * execution point as this instance. */ public boolean equals(Object obj) { @@ -208,12 +201,10 @@ public final class StackTraceElement implements java.io.Serializable { if (!(obj instanceof StackTraceElement)) return false; StackTraceElement e = (StackTraceElement)obj; - return e.declaringClass.equals(declaringClass) && e.lineNumber == lineNumber - && eq(methodName, e.methodName) && eq(fileName, e.fileName); - } - - private static boolean eq(Object a, Object b) { - return a==b || (a != null && a.equals(b)); + return e.declaringClass.equals(declaringClass) && + e.lineNumber == lineNumber && + Objects.equals(methodName, e.methodName) && + Objects.equals(fileName, e.fileName); } /** @@ -221,7 +212,7 @@ public final class StackTraceElement implements java.io.Serializable { */ public int hashCode() { int result = 31*declaringClass.hashCode() + methodName.hashCode(); - result = 31*result + (fileName == null ? 0 : fileName.hashCode()); + result = 31*result + Objects.hashCode(fileName); result = 31*result + lineNumber; return result; } diff --git a/src/share/classes/java/lang/Thread.java b/src/share/classes/java/lang/Thread.java index c3592cf5cf35748c41d056dbb1e0749e8126cd49..545cef6fcef9ec0f8853a826f2939a6d1ad8e905 100644 --- a/src/share/classes/java/lang/Thread.java +++ b/src/share/classes/java/lang/Thread.java @@ -229,7 +229,7 @@ class Thread implements Runnable { * after setting this thread's interrupt status. */ private volatile Interruptible blocker; - private Object blockerLock = new Object(); + private final Object blockerLock = new Object(); /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code */ @@ -688,16 +688,19 @@ class Thread implements Runnable { throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started - * so that it can be added to the group's list of threads. */ + * so that it can be added to the group's list of threads + * and the group's unstarted count can be decremented. */ group.threadStarting(this); - boolean failed = true; + boolean started = false; try { start0(); - failed = false; + started = true; } finally { try { - group.threadStarted(this, failed); + if (!started) { + group.threadStartFailed(this); + } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ @@ -955,7 +958,7 @@ class Thread implements Runnable { Interruptible b = blocker; if (b != null) { interrupt0(); // Just to set the interrupt flag - b.interrupt(); + b.interrupt(this); return; } } diff --git a/src/share/classes/java/lang/ThreadGroup.java b/src/share/classes/java/lang/ThreadGroup.java index 1b14570cee3837be7dbf8a49abc73e80bebb1f55..8bfc3bc4832904392f8fd8cc8a1be04178bd62be 100644 --- a/src/share/classes/java/lang/ThreadGroup.java +++ b/src/share/classes/java/lang/ThreadGroup.java @@ -870,9 +870,16 @@ class ThreadGroup implements Thread.UncaughtExceptionHandler { /** * Notifies the group that the thread {@code t} is about to be * started and adds the thread to this thread group. + * + * The thread is now a fully fledged member of the group, even though + * it hasn't been started yet. It will prevent the group from being + * destroyed so the unstarted Threads count is decremented. */ void threadStarting(Thread t) { - add(t); + synchronized (this) { + add(t); + nUnstartedThreads--; + } } /** @@ -907,12 +914,10 @@ class ThreadGroup implements Thread.UncaughtExceptionHandler { } /** - * Notifies the group that the thread {@code t} has completed + * Notifies the group that the thread {@code t} has failed * an attempt to start. * - *

If the thread has been started successfully - * then the group has its unstarted Threads count decremented. - * Otherwise the state of this thread group is rolled back as if the + *

The state of this thread group is rolled back as if the * attempt to start the thread has never occurred. The thread is again * considered an unstarted member of the thread group, and a subsequent * attempt to start the thread is permitted. @@ -923,16 +928,10 @@ class ThreadGroup implements Thread.UncaughtExceptionHandler { * @param failed * true if the thread could not be started successfully */ - void threadStarted(Thread t, boolean failed) { + void threadStartFailed(Thread t) { synchronized(this) { - if (failed) { - remove(t); - } else { - if (destroyed) { - return; - } - nUnstartedThreads--; - } + remove(t); + nUnstartedThreads++; } } diff --git a/src/share/classes/java/lang/Throwable.java b/src/share/classes/java/lang/Throwable.java index 0073d3f3c3d5a7b190dc76d50e9bdcf1574a9c27..16070c82a7c4eb92390594e8bbb1b73a99ca8c20 100644 --- a/src/share/classes/java/lang/Throwable.java +++ b/src/share/classes/java/lang/Throwable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 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 @@ -169,6 +169,36 @@ public class Throwable implements Serializable { */ private String detailMessage; + /** + * A shared value for an empty stack. + */ + private static final StackTraceElement[] EMPTY_STACK = new StackTraceElement[0]; + + /* + * To allow Throwable objects to be made immutable and safely + * reused by the JVM, such as OutOfMemoryErrors, fields of + * Throwable that are writable in response to user actions, cause + * and suppressedExceptions obey the following protocol: + * + * 1) The fields are initialized to a non-null sentinel value + * which indicates the value has logically not been set. + * + * 2) Writing a null to the field indicates further writes + * are forbidden + * + * 3) The sentinel value may be replaced with another non-null + * value. + * + * For example, implementations of the HotSpot JVM have + * preallocated OutOfMemoryError objects to provide for better + * diagnosability of that situation. These objects are created + * without calling the constructor for that class and the fields + * in question are initialized to null. To support this + * capability, any new fields added to Throwable that require + * being initialized to a non-null value require a coordinated JVM + * change. + */ + /** * The throwable that caused this throwable to get thrown, or null if this * throwable was not caused by another throwable, or if the causative @@ -188,32 +218,30 @@ public class Throwable implements Serializable { * @since 1.4 */ private StackTraceElement[] stackTrace; - /* - * This field is lazily initialized on first use or serialization and - * nulled out when fillInStackTrace is called. - */ + + // Setting this static field introduces an acceptable + // initialization dependency on a few java.util classes. + private static final List SUPPRESSED_SENTINEL = + Collections.unmodifiableList(new ArrayList(0)); /** - * The list of suppressed exceptions, as returned by - * {@link #getSuppressedExceptions()}. + * The list of suppressed exceptions, as returned by {@link + * #getSuppressed()}. The list is initialized to a zero-element + * unmodifiable sentinel list. When a serialized Throwable is + * read in, if the {@code suppressedExceptions} field points to a + * zero-element list, the field is reset to the sentinel value. * * @serial * @since 1.7 */ - private List suppressedExceptions = null; - /* - * This field is lazily initialized when the first suppressed - * exception is added. - * - * OutOfMemoryError is preallocated in the VM for better OOM - * diagnosability during VM initialization. Constructor can't - * be not invoked. If a new field to be added in the future must - * be initialized to non-null, it requires a synchronized VM change. - */ + private List suppressedExceptions = SUPPRESSED_SENTINEL; /** Message for trying to suppress a null exception. */ private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception."; + /** Message for trying to suppress oneself. */ + private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted"; + /** Caption for labeling causative exception stack traces */ private static final String CAUSE_CAPTION = "Caused by: "; @@ -572,7 +600,7 @@ public class Throwable implements Serializable { s.println("\tat " + traceElement); // Print suppressed exceptions, if any - for (Throwable se : getSuppressedExceptions()) + for (Throwable se : getSuppressed()) se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu); // Print cause, if any @@ -613,7 +641,7 @@ public class Throwable implements Serializable { s.println(prefix + "\t... " + framesInCommon + " more"); // Print suppressed exceptions, if any - for (Throwable se : getSuppressedExceptions()) + for (Throwable se : getSuppressed()) se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, prefix +"\t", dejaVu); @@ -780,25 +808,58 @@ public class Throwable implements Serializable { */ native StackTraceElement getStackTraceElement(int index); + /** + * Read a {@code Throwable} from a stream, enforcing + * well-formedness constraints on fields. Null entries and + * self-pointers are not allowed in the list of {@code + * suppressedExceptions}. Null entries are not allowed for stack + * trace elements. + * + * Note that there are no constraints on the value the {@code + * cause} field can hold; both {@code null} and {@code this} are + * valid values for the field. + */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // read in all fields - List suppressed = null; - if (suppressedExceptions != null && - !suppressedExceptions.isEmpty()) { // Copy Throwables to new list - suppressed = new ArrayList(); - for (Throwable t : suppressedExceptions) { - if (t == null) - throw new NullPointerException(NULL_CAUSE_MESSAGE); - suppressed.add(t); + if (suppressedExceptions != null) { + List suppressed = null; + if (suppressedExceptions.isEmpty()) { + // Use the sentinel for a zero-length list + suppressed = SUPPRESSED_SENTINEL; + } else { // Copy Throwables to new list + suppressed = new ArrayList(1); + for (Throwable t : suppressedExceptions) { + // Enforce constraints on suppressed exceptions in + // case of corrupt or malicious stream. + if (t == null) + throw new NullPointerException(NULL_CAUSE_MESSAGE); + if (t == this) + throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); + suppressed.add(t); + } + } + suppressedExceptions = suppressed; + } // else a null suppressedExceptions field remains null + + if (stackTrace != null) { + for (StackTraceElement ste : stackTrace) { + if (ste == null) + throw new NullPointerException("null StackTraceElement in serial stream. "); } + } else { + // A null stackTrace field in the serial form can result from + // an exception serialized without that field in older JDK releases. + stackTrace = EMPTY_STACK; } - suppressedExceptions = suppressed; + } + /** + * Write a {@code Throwable} object to a stream. + */ private synchronized void writeObject(ObjectOutputStream s) - throws IOException - { + throws IOException { getOurStackTrace(); // Ensure that stackTrace field is initialized. s.defaultWriteObject(); } @@ -808,6 +869,14 @@ public class Throwable implements Serializable { * were suppressed, typically by the {@code try}-with-resources * statement, in order to deliver this exception. * + * If the first exception to be suppressed is {@code null}, that + * indicates suppressed exception information will not be + * recorded for this exception. Subsequent calls to this method + * will not record any suppressed exceptions. Otherwise, + * attempting to suppress {@code null} after an exception has + * already been successfully suppressed results in a {@code + * NullPointerException}. + * *

Note that when one exception {@linkplain * #initCause(Throwable) causes} another exception, the first * exception is usually caught and then the second exception is @@ -819,20 +888,35 @@ public class Throwable implements Serializable { * * @param exception the exception to be added to the list of * suppressed exceptions - * @throws NullPointerException if {@code exception} is null * @throws IllegalArgumentException if {@code exception} is this * throwable; a throwable cannot suppress itself. + * @throws NullPointerException if {@code exception} is null and + * an exception has already been suppressed by this exception * @since 1.7 */ - public synchronized void addSuppressedException(Throwable exception) { - if (exception == null) - throw new NullPointerException(NULL_CAUSE_MESSAGE); + public final synchronized void addSuppressed(Throwable exception) { if (exception == this) - throw new IllegalArgumentException("Self-suppression not permitted"); + throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); + + if (exception == null) { + if (suppressedExceptions == SUPPRESSED_SENTINEL) { + suppressedExceptions = null; // No suppression information recorded + return; + } else + throw new NullPointerException(NULL_CAUSE_MESSAGE); + } else { + assert exception != null && exception != this; + + if (suppressedExceptions == null) // Suppressed exceptions not recorded + return; + + if (suppressedExceptions == SUPPRESSED_SENTINEL) + suppressedExceptions = new ArrayList(1); - if (suppressedExceptions == null) - suppressedExceptions = new ArrayList(); - suppressedExceptions.add(exception); + assert suppressedExceptions != SUPPRESSED_SENTINEL; + + suppressedExceptions.add(exception); + } } private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0]; @@ -842,12 +926,15 @@ public class Throwable implements Serializable { * suppressed, typically by the {@code try}-with-resources * statement, in order to deliver this exception. * + * If no exceptions were suppressed, an empty array is returned. + * * @return an array containing all of the exceptions that were * suppressed to deliver this exception. * @since 1.7 */ - public synchronized Throwable[] getSuppressedExceptions() { - if (suppressedExceptions == null) + public final synchronized Throwable[] getSuppressed() { + if (suppressedExceptions == SUPPRESSED_SENTINEL || + suppressedExceptions == null) return EMPTY_THROWABLE_ARRAY; else return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY); diff --git a/src/share/classes/java/nio/channels/spi/AbstractInterruptibleChannel.java b/src/share/classes/java/nio/channels/spi/AbstractInterruptibleChannel.java index 7ed7f09d79e20499b0f78d4f7c3d384655362744..a5160452c40700830de4e081184b86dae414d914 100644 --- a/src/share/classes/java/nio/channels/spi/AbstractInterruptibleChannel.java +++ b/src/share/classes/java/nio/channels/spi/AbstractInterruptibleChannel.java @@ -88,7 +88,7 @@ public abstract class AbstractInterruptibleChannel implements Channel, InterruptibleChannel { - private Object closeLock = new Object(); + private final Object closeLock = new Object(); private volatile boolean open = true; /** @@ -142,7 +142,7 @@ public abstract class AbstractInterruptibleChannel // -- Interruption machinery -- private Interruptible interruptor; - private volatile boolean interrupted = false; + private volatile Thread interrupted; /** * Marks the beginning of an I/O operation that might block indefinitely. @@ -155,12 +155,12 @@ public abstract class AbstractInterruptibleChannel protected final void begin() { if (interruptor == null) { interruptor = new Interruptible() { - public void interrupt() { + public void interrupt(Thread target) { synchronized (closeLock) { if (!open) return; - interrupted = true; open = false; + interrupted = target; try { AbstractInterruptibleChannel.this.implCloseChannel(); } catch (IOException x) { } @@ -168,8 +168,9 @@ public abstract class AbstractInterruptibleChannel }}; } blockedOn(interruptor); - if (Thread.currentThread().isInterrupted()) - interruptor.interrupt(); + Thread me = Thread.currentThread(); + if (me.isInterrupted()) + interruptor.interrupt(me); } /** @@ -195,12 +196,13 @@ public abstract class AbstractInterruptibleChannel throws AsynchronousCloseException { blockedOn(null); - if (completed) { - interrupted = false; - return; + Thread interrupted = this.interrupted; + if (interrupted != null && interrupted == Thread.currentThread()) { + interrupted = null; + throw new ClosedByInterruptException(); } - if (interrupted) throw new ClosedByInterruptException(); - if (!open) throw new AsynchronousCloseException(); + if (!completed && !open) + throw new AsynchronousCloseException(); } diff --git a/src/share/classes/java/nio/channels/spi/AbstractSelector.java b/src/share/classes/java/nio/channels/spi/AbstractSelector.java index c7e40b254afca71c96c6c58077ea20ef7ace7983..0e4487ada089f6b442b7e333793266f57ce665b7 100644 --- a/src/share/classes/java/nio/channels/spi/AbstractSelector.java +++ b/src/share/classes/java/nio/channels/spi/AbstractSelector.java @@ -206,13 +206,14 @@ public abstract class AbstractSelector protected final void begin() { if (interruptor == null) { interruptor = new Interruptible() { - public void interrupt() { + public void interrupt(Thread ignore) { AbstractSelector.this.wakeup(); }}; } AbstractInterruptibleChannel.blockedOn(interruptor); - if (Thread.currentThread().isInterrupted()) - interruptor.interrupt(); + Thread me = Thread.currentThread(); + if (me.isInterrupted()) + interruptor.interrupt(me); } /** diff --git a/src/share/classes/java/util/TreeMap.java b/src/share/classes/java/util/TreeMap.java index 884905014b3917bfc98f43e224c3625d80222c54..b0c9aa7d67a781c473e38c1576bbcaf8b8962eb6 100644 --- a/src/share/classes/java/util/TreeMap.java +++ b/src/share/classes/java/util/TreeMap.java @@ -32,25 +32,26 @@ package java.util; * creation time, depending on which constructor is used. * *

This implementation provides guaranteed log(n) time cost for the - * containsKey, get, put and remove + * {@code containsKey}, {@code get}, {@code put} and {@code remove} * operations. Algorithms are adaptations of those in Cormen, Leiserson, and - * Rivest's Introduction to Algorithms. + * Rivest's Introduction to Algorithms. * - *

Note that the ordering maintained by a sorted map (whether or not an - * explicit comparator is provided) must be consistent with equals if - * this sorted map is to correctly implement the Map interface. (See - * Comparable or Comparator for a precise definition of - * consistent with equals.) This is so because the Map - * interface is defined in terms of the equals operation, but a map performs - * all key comparisons using its compareTo (or compare) - * method, so two keys that are deemed equal by this method are, from the - * standpoint of the sorted map, equal. The behavior of a sorted map - * is well-defined even if its ordering is inconsistent with equals; it - * just fails to obey the general contract of the Map interface. + *

Note that the ordering maintained by a tree map, like any sorted map, and + * whether or not an explicit comparator is provided, must be consistent + * with {@code equals} if this sorted map is to correctly implement the + * {@code Map} interface. (See {@code Comparable} or {@code Comparator} for a + * precise definition of consistent with equals.) This is so because + * the {@code Map} interface is defined in terms of the {@code equals} + * operation, but a sorted map performs all key comparisons using its {@code + * compareTo} (or {@code compare}) method, so two keys that are deemed equal by + * this method are, from the standpoint of the sorted map, equal. The behavior + * of a sorted map is well-defined even if its ordering is + * inconsistent with {@code equals}; it just fails to obey the general contract + * of the {@code Map} interface. * *

Note that this implementation is not synchronized. * If multiple threads access a map concurrently, and at least one of the - * threads modifies the map structurally, it must be synchronized + * threads modifies the map structurally, it must be synchronized * externally. (A structural modification is any operation that adds or * deletes one or more mappings; merely changing the value associated * with an existing key is not a structural modification.) This is @@ -62,11 +63,11 @@ package java.util; * unsynchronized access to the map:

  *   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
* - *

The iterators returned by the iterator method of the collections + *

The iterators returned by the {@code iterator} method of the collections * returned by all of this class's "collection view methods" are - * fail-fast: if the map is structurally modified at any time after the - * iterator is created, in any way except through the iterator's own - * remove method, the iterator will throw a {@link + * fail-fast: if the map is structurally modified at any time after + * the iterator is created, in any way except through the iterator's own + * {@code remove} method, the iterator will throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the future. @@ -74,16 +75,16 @@ package java.util; *

Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators - * throw ConcurrentModificationException on a best-effort basis. + * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this - * exception for its correctness: the fail-fast behavior of iterators - * should be used only to detect bugs. + * exception for its correctness: the fail-fast behavior of iterators + * should be used only to detect bugs. * - *

All Map.Entry pairs returned by methods in this class + *

All {@code Map.Entry} pairs returned by methods in this class * and its views represent snapshots of mappings at the time they were - * produced. They do not support the Entry.setValue + * produced. They do not support the {@code Entry.setValue} * method. (Note however that it is possible to change mappings in the - * associated map using put.) + * associated map using {@code put}.) * *

This class is a member of the * @@ -130,13 +131,13 @@ public class TreeMap * Constructs a new, empty tree map, using the natural ordering of its * keys. All keys inserted into the map must implement the {@link * Comparable} interface. Furthermore, all such keys must be - * mutually comparable: k1.compareTo(k2) must not throw - * a ClassCastException for any keys k1 and - * k2 in the map. If the user attempts to put a key into the + * mutually comparable: {@code k1.compareTo(k2)} must not throw + * a {@code ClassCastException} for any keys {@code k1} and + * {@code k2} in the map. If the user attempts to put a key into the * map that violates this constraint (for example, the user attempts to * put a string key into a map whose keys are integers), the - * put(Object key, Object value) call will throw a - * ClassCastException. + * {@code put(Object key, Object value)} call will throw a + * {@code ClassCastException}. */ public TreeMap() { comparator = null; @@ -144,16 +145,16 @@ public class TreeMap /** * Constructs a new, empty tree map, ordered according to the given - * comparator. All keys inserted into the map must be mutually - * comparable by the given comparator: comparator.compare(k1, - * k2) must not throw a ClassCastException for any keys - * k1 and k2 in the map. If the user attempts to put - * a key into the map that violates this constraint, the put(Object - * key, Object value) call will throw a - * ClassCastException. + * comparator. All keys inserted into the map must be mutually + * comparable by the given comparator: {@code comparator.compare(k1, + * k2)} must not throw a {@code ClassCastException} for any keys + * {@code k1} and {@code k2} in the map. If the user attempts to put + * a key into the map that violates this constraint, the {@code put(Object + * key, Object value)} call will throw a + * {@code ClassCastException}. * * @param comparator the comparator that will be used to order this map. - * If null, the {@linkplain Comparable natural + * If {@code null}, the {@linkplain Comparable natural * ordering} of the keys will be used. */ public TreeMap(Comparator comparator) { @@ -162,12 +163,12 @@ public class TreeMap /** * Constructs a new tree map containing the same mappings as the given - * map, ordered according to the natural ordering of its keys. + * map, ordered according to the natural ordering of its keys. * All keys inserted into the new map must implement the {@link * Comparable} interface. Furthermore, all such keys must be - * mutually comparable: k1.compareTo(k2) must not throw - * a ClassCastException for any keys k1 and - * k2 in the map. This method runs in n*log(n) time. + * mutually comparable: {@code k1.compareTo(k2)} must not throw + * a {@code ClassCastException} for any keys {@code k1} and + * {@code k2} in the map. This method runs in n*log(n) time. * * @param m the map whose mappings are to be placed in this map * @throws ClassCastException if the keys in m are not {@link Comparable}, @@ -210,11 +211,11 @@ public class TreeMap } /** - * Returns true if this map contains a mapping for the specified + * Returns {@code true} if this map contains a mapping for the specified * key. * * @param key key whose presence in this map is to be tested - * @return true if this map contains a mapping for the + * @return {@code true} if this map contains a mapping for the * specified key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map @@ -227,16 +228,16 @@ public class TreeMap } /** - * Returns true if this map maps one or more keys to the - * specified value. More formally, returns true if and only if - * this map contains at least one mapping to a value v such - * that (value==null ? v==null : value.equals(v)). This + * Returns {@code true} if this map maps one or more keys to the + * specified value. More formally, returns {@code true} if and only if + * this map contains at least one mapping to a value {@code v} such + * that {@code (value==null ? v==null : value.equals(v))}. This * operation will probably require time linear in the map size for * most implementations. * * @param value value whose presence in this map is to be tested - * @return true if a mapping to value exists; - * false otherwise + * @return {@code true} if a mapping to {@code value} exists; + * {@code false} otherwise * @since 1.2 */ public boolean containsValue(Object value) { @@ -256,7 +257,7 @@ public class TreeMap * method returns {@code v}; otherwise it returns {@code null}. * (There can be at most one such mapping.) * - *

A return value of {@code null} does not necessarily + *

A return value of {@code null} does not necessarily * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to @@ -322,10 +323,10 @@ public class TreeMap } /** - * Returns this map's entry for the given key, or null if the map + * Returns this map's entry for the given key, or {@code null} if the map * does not contain an entry for the key. * - * @return this map's entry for the given key, or null if the map + * @return this map's entry for the given key, or {@code null} if the map * does not contain an entry for the key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map @@ -381,7 +382,7 @@ public class TreeMap * Gets the entry corresponding to the specified key; if no such entry * exists, returns the entry for the least key greater than the specified * key; if no such entry exists (i.e., the greatest key in the Tree is less - * than the specified key), returns null. + * than the specified key), returns {@code null}. */ final Entry getCeilingEntry(K key) { Entry p = root; @@ -413,7 +414,7 @@ public class TreeMap /** * Gets the entry corresponding to the specified key; if no such entry * exists, returns the entry for the greatest key less than the specified - * key; if no such entry exists, returns null. + * key; if no such entry exists, returns {@code null}. */ final Entry getFloorEntry(K key) { Entry p = root; @@ -447,7 +448,7 @@ public class TreeMap * Gets the entry for the least key greater than the specified * key; if no such entry exists, returns the entry for the least * key greater than the specified key; if no such entry exists - * returns null. + * returns {@code null}. */ final Entry getHigherEntry(K key) { Entry p = root; @@ -478,7 +479,7 @@ public class TreeMap /** * Returns the entry for the greatest key less than the specified key; if * no such entry exists (i.e., the least key in the Tree is greater than - * the specified key), returns null. + * the specified key), returns {@code null}. */ final Entry getLowerEntry(K key) { Entry p = root; @@ -514,10 +515,10 @@ public class TreeMap * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * - * @return the previous value associated with key, or - * null if there was no mapping for key. - * (A null return can also indicate that the map - * previously associated null with key.) + * @return the previous value associated with {@code key}, or + * {@code null} if there was no mapping for {@code key}. + * (A {@code null} return can also indicate that the map + * previously associated {@code null} with {@code key}.) * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null @@ -583,10 +584,10 @@ public class TreeMap * Removes the mapping for this key from this TreeMap if present. * * @param key key for which mapping should be removed - * @return the previous value associated with key, or - * null if there was no mapping for key. - * (A null return can also indicate that the map - * previously associated null with key.) + * @return the previous value associated with {@code key}, or + * {@code null} if there was no mapping for {@code key}. + * (A {@code null} return can also indicate that the map + * previously associated {@code null} with {@code key}.) * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null @@ -614,7 +615,7 @@ public class TreeMap } /** - * Returns a shallow copy of this TreeMap instance. (The keys and + * Returns a shallow copy of this {@code TreeMap} instance. (The keys and * values themselves are not cloned.) * * @return a shallow copy of this map @@ -788,12 +789,12 @@ public class TreeMap * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through - * the iterator's own remove operation), the results of + * the iterator's own {@code remove} operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the - * Iterator.remove, Set.remove, - * removeAll, retainAll, and clear - * operations. It does not support the add or addAll + * {@code Iterator.remove}, {@code Set.remove}, + * {@code removeAll}, {@code retainAll}, and {@code clear} + * operations. It does not support the {@code add} or {@code addAll} * operations. */ public Set keySet() { @@ -822,13 +823,13 @@ public class TreeMap * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. If the map is * modified while an iteration over the collection is in progress - * (except through the iterator's own remove operation), + * (except through the iterator's own {@code remove} operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding - * mapping from the map, via the Iterator.remove, - * Collection.remove, removeAll, - * retainAll and clear operations. It does not - * support the add or addAll operations. + * mapping from the map, via the {@code Iterator.remove}, + * {@code Collection.remove}, {@code removeAll}, + * {@code retainAll} and {@code clear} operations. It does not + * support the {@code add} or {@code addAll} operations. */ public Collection values() { Collection vs = values; @@ -841,14 +842,14 @@ public class TreeMap * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through - * the iterator's own remove operation, or through the - * setValue operation on a map entry returned by the + * the iterator's own {@code remove} operation, or through the + * {@code setValue} operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding - * mapping from the map, via the Iterator.remove, - * Set.remove, removeAll, retainAll and - * clear operations. It does not support the - * add or addAll operations. + * mapping from the map, via the {@code Iterator.remove}, + * {@code Set.remove}, {@code removeAll}, {@code retainAll} and + * {@code clear} operations. It does not support the + * {@code add} or {@code addAll} operations. */ public Set> entrySet() { EntrySet es = entrySet; @@ -868,7 +869,7 @@ public class TreeMap /** * @throws ClassCastException {@inheritDoc} - * @throws NullPointerException if fromKey or toKey is + * @throws NullPointerException if {@code fromKey} or {@code toKey} is * null and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} @@ -883,7 +884,7 @@ public class TreeMap /** * @throws ClassCastException {@inheritDoc} - * @throws NullPointerException if toKey is null + * @throws NullPointerException if {@code toKey} is null * and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} @@ -897,7 +898,7 @@ public class TreeMap /** * @throws ClassCastException {@inheritDoc} - * @throws NullPointerException if fromKey is null + * @throws NullPointerException if {@code fromKey} is null * and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} @@ -911,7 +912,7 @@ public class TreeMap /** * @throws ClassCastException {@inheritDoc} - * @throws NullPointerException if fromKey or toKey is + * @throws NullPointerException if {@code fromKey} or {@code toKey} is * null and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} @@ -922,7 +923,7 @@ public class TreeMap /** * @throws ClassCastException {@inheritDoc} - * @throws NullPointerException if toKey is null + * @throws NullPointerException if {@code toKey} is null * and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} @@ -933,7 +934,7 @@ public class TreeMap /** * @throws ClassCastException {@inheritDoc} - * @throws NullPointerException if fromKey is null + * @throws NullPointerException if {@code fromKey} is null * and this map uses natural ordering, or its comparator * does not permit null keys * @throws IllegalArgumentException {@inheritDoc} @@ -1193,7 +1194,7 @@ public class TreeMap /** * Test two values for equality. Differs from o1.equals(o2) only in - * that it copes with null o1 properly. + * that it copes with {@code null} o1 properly. */ final static boolean valEquals(Object o1, Object o2) { return (o1==null ? o2==null : o1.equals(o2)); @@ -1897,7 +1898,7 @@ public class TreeMap /** * Make a new cell with given key, value, and parent, and with - * null child links, and BLACK color. + * {@code null} child links, and BLACK color. */ Entry(K key, V value, Entry parent) { this.key = key; @@ -2249,10 +2250,10 @@ public class TreeMap private static final long serialVersionUID = 919286545866124006L; /** - * Save the state of the TreeMap instance to a stream (i.e., + * Save the state of the {@code TreeMap} instance to a stream (i.e., * serialize it). * - * @serialData The size of the TreeMap (the number of key-value + * @serialData The size of the TreeMap (the number of key-value * mappings) is emitted (int), followed by the key (Object) * and value (Object) for each key-value mapping represented * by the TreeMap. The key-value mappings are emitted in @@ -2277,7 +2278,7 @@ public class TreeMap } /** - * Reconstitute the TreeMap instance from a stream (i.e., + * Reconstitute the {@code TreeMap} instance from a stream (i.e., * deserialize it). */ private void readObject(final java.io.ObjectInputStream s) diff --git a/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java b/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java index 2a07216f4ad0434dfebb8c3986e3b71a38405d0d..13901e842f72a910e1d4c42aab9770741e6b9e36 100644 --- a/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java +++ b/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java @@ -126,10 +126,8 @@ public class LinkedBlockingDeque */ Node next; - Node(E x, Node p, Node n) { + Node(E x) { item = x; - prev = p; - next = n; } } @@ -199,7 +197,7 @@ public class LinkedBlockingDeque for (E e : c) { if (e == null) throw new NullPointerException(); - if (!linkLast(e)) + if (!linkLast(new Node(e))) throw new IllegalStateException("Deque full"); } } finally { @@ -211,38 +209,38 @@ public class LinkedBlockingDeque // Basic linking and unlinking operations, called only while holding lock /** - * Links e as first element, or returns false if full. + * Links node as first element, or returns false if full. */ - private boolean linkFirst(E e) { + private boolean linkFirst(Node node) { // assert lock.isHeldByCurrentThread(); if (count >= capacity) return false; Node f = first; - Node x = new Node(e, null, f); - first = x; + node.next = f; + first = node; if (last == null) - last = x; + last = node; else - f.prev = x; + f.prev = node; ++count; notEmpty.signal(); return true; } /** - * Links e as last element, or returns false if full. + * Links node as last element, or returns false if full. */ - private boolean linkLast(E e) { + private boolean linkLast(Node node) { // assert lock.isHeldByCurrentThread(); if (count >= capacity) return false; Node l = last; - Node x = new Node(e, l, null); - last = x; + node.prev = l; + last = node; if (first == null) - first = x; + first = node; else - l.next = x; + l.next = node; ++count; notEmpty.signal(); return true; @@ -339,10 +337,11 @@ public class LinkedBlockingDeque */ public boolean offerFirst(E e) { if (e == null) throw new NullPointerException(); + Node node = new Node(e); final ReentrantLock lock = this.lock; lock.lock(); try { - return linkFirst(e); + return linkFirst(node); } finally { lock.unlock(); } @@ -353,10 +352,11 @@ public class LinkedBlockingDeque */ public boolean offerLast(E e) { if (e == null) throw new NullPointerException(); + Node node = new Node(e); final ReentrantLock lock = this.lock; lock.lock(); try { - return linkLast(e); + return linkLast(node); } finally { lock.unlock(); } @@ -368,10 +368,11 @@ public class LinkedBlockingDeque */ public void putFirst(E e) throws InterruptedException { if (e == null) throw new NullPointerException(); + Node node = new Node(e); final ReentrantLock lock = this.lock; lock.lock(); try { - while (!linkFirst(e)) + while (!linkFirst(node)) notFull.await(); } finally { lock.unlock(); @@ -384,10 +385,11 @@ public class LinkedBlockingDeque */ public void putLast(E e) throws InterruptedException { if (e == null) throw new NullPointerException(); + Node node = new Node(e); final ReentrantLock lock = this.lock; lock.lock(); try { - while (!linkLast(e)) + while (!linkLast(node)) notFull.await(); } finally { lock.unlock(); @@ -401,11 +403,12 @@ public class LinkedBlockingDeque public boolean offerFirst(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) throw new NullPointerException(); + Node node = new Node(e); long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { - while (!linkFirst(e)) { + while (!linkFirst(node)) { if (nanos <= 0) return false; nanos = notFull.awaitNanos(nanos); @@ -423,11 +426,12 @@ public class LinkedBlockingDeque public boolean offerLast(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) throw new NullPointerException(); + Node node = new Node(e); long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { - while (!linkLast(e)) { + while (!linkLast(node)) { if (nanos <= 0) return false; nanos = notFull.awaitNanos(nanos); @@ -955,7 +959,20 @@ public class LinkedBlockingDeque final ReentrantLock lock = this.lock; lock.lock(); try { - return super.toString(); + Node p = first; + if (p == null) + return "[]"; + + StringBuilder sb = new StringBuilder(); + sb.append('['); + for (;;) { + E e = p.item; + sb.append(e == this ? "(this Collection)" : e); + p = p.next; + if (p == null) + return sb.append(']').toString(); + sb.append(',').append(' '); + } } finally { lock.unlock(); } @@ -1053,6 +1070,26 @@ public class LinkedBlockingDeque } } + /** + * Returns the successor node of the given non-null, but + * possibly previously deleted, node. + */ + private Node succ(Node n) { + // Chains of deleted nodes ending in null or self-links + // are possible if multiple interior nodes are removed. + for (;;) { + Node s = nextNode(n); + if (s == null) + return null; + else if (s.item != null) + return s; + else if (s == n) + return firstNode(); + else + n = s; + } + } + /** * Advances next. */ @@ -1061,16 +1098,7 @@ public class LinkedBlockingDeque lock.lock(); try { // assert next != null; - Node s = nextNode(next); - if (s == next) { - next = firstNode(); - } else { - // Skip over removed nodes. - // May be necessary if multiple interior Nodes are removed. - while (s != null && s.item == null) - s = nextNode(s); - next = s; - } + next = succ(next); nextItem = (next == null) ? null : next.item; } finally { lock.unlock(); diff --git a/src/share/classes/java/util/jar/JarInputStream.java b/src/share/classes/java/util/jar/JarInputStream.java index a22c9372bc8f15537c3508d532b2d8b7ef7bc546..15818c932a6841653c722db34696959c43dd323f 100644 --- a/src/share/classes/java/util/jar/JarInputStream.java +++ b/src/share/classes/java/util/jar/JarInputStream.java @@ -28,6 +28,7 @@ package java.util.jar; import java.util.zip.*; import java.io.*; import sun.security.util.ManifestEntryVerifier; +import sun.misc.JarIndex; /** * The JarInputStream class is used to read the contents of @@ -47,7 +48,8 @@ class JarInputStream extends ZipInputStream { private JarEntry first; private JarVerifier jv; private ManifestEntryVerifier mev; - + private final boolean doVerify; + private boolean tryManifest; /** * Creates a new JarInputStream and reads the optional @@ -72,25 +74,33 @@ class JarInputStream extends ZipInputStream { */ public JarInputStream(InputStream in, boolean verify) throws IOException { super(in); - JarEntry e = (JarEntry)super.getNextEntry(); + this.doVerify = verify; + // This implementation assumes the META-INF/MANIFEST.MF entry + // should be either the first or the second entry (when preceded + // by the dir META-INF/). It skips the META-INF/ and then + // "consumes" the MANIFEST.MF to initialize the Manifest object. + JarEntry e = (JarEntry)super.getNextEntry(); if (e != null && e.getName().equalsIgnoreCase("META-INF/")) e = (JarEntry)super.getNextEntry(); + first = checkManifest(e); + } + private JarEntry checkManifest(JarEntry e) + throws IOException + { if (e != null && JarFile.MANIFEST_NAME.equalsIgnoreCase(e.getName())) { man = new Manifest(); byte bytes[] = getBytes(new BufferedInputStream(this)); man.read(new ByteArrayInputStream(bytes)); - //man.read(new BufferedInputStream(this)); closeEntry(); - if (verify) { + if (doVerify) { jv = new JarVerifier(bytes); mev = new ManifestEntryVerifier(man); } - first = getNextJarEntry(); - } else { - first = e; + return (JarEntry)super.getNextEntry(); } + return e; } private byte[] getBytes(InputStream is) @@ -98,10 +108,7 @@ class JarInputStream extends ZipInputStream { { byte[] buffer = new byte[8192]; ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); - int n; - - baos.reset(); while ((n = is.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, n); } @@ -133,8 +140,14 @@ class JarInputStream extends ZipInputStream { JarEntry e; if (first == null) { e = (JarEntry)super.getNextEntry(); + if (tryManifest) { + e = checkManifest(e); + tryManifest = false; + } } else { e = first; + if (first.getName().equalsIgnoreCase(JarIndex.INDEX_NAME)) + tryManifest = true; first = null; } if (jv != null && e != null) { diff --git a/src/share/classes/java/util/jar/Pack200.java b/src/share/classes/java/util/jar/Pack200.java index 41dec9180921630c0d97354a3e5fa09289bbf40f..8bf0f4ea947652d9dfa25895fc23b26db01bd2d4 100644 --- a/src/share/classes/java/util/jar/Pack200.java +++ b/src/share/classes/java/util/jar/Pack200.java @@ -30,9 +30,6 @@ import java.io.OutputStream; import java.io.File; import java.io.IOException; import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeEvent; -import java.security.AccessController; -import java.security.PrivilegedAction; @@ -225,6 +222,10 @@ public abstract class Pack200 { * If the input JAR-files contains a 1.6 class file, then the pack file * version will be set to 1.6. *

+ * Note: Unless otherwise noted, passing a null argument to a + * constructor or method in this class will cause a {@link NullPointerException} + * to be thrown. + *

* @since 1.5 */ public interface Packer { @@ -599,6 +600,10 @@ public abstract class Pack200 { * "PACK200" as a zip file comment. * This allows a deployer to detect if a JAR archive was packed and unpacked. *

+ * Note: Unless otherwise noted, passing a null argument to a + * constructor or method in this class will cause a {@link NullPointerException} + * to be thrown. + *

* This version of the unpacker is compatible with all previous versions. * @since 1.5 */ diff --git a/src/share/classes/javax/management/remote/rmi/RMIConnector.java b/src/share/classes/javax/management/remote/rmi/RMIConnector.java index afc319edf26ce92a8c6a1856894cf84452821a52..f5359f9b12c7e2d505eb177a2fc43d5ee49c2b7b 100644 --- a/src/share/classes/javax/management/remote/rmi/RMIConnector.java +++ b/src/share/classes/javax/management/remote/rmi/RMIConnector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -291,7 +291,24 @@ public class RMIConnector implements JMXConnector, Serializable, JMXAddressable if (tracing) logger.trace("connect",idstr + " getting connection..."); Object credentials = usemap.get(CREDENTIALS); - connection = getConnection(stub, credentials, checkStub); + + try { + connection = getConnection(stub, credentials, checkStub); + } catch (java.rmi.RemoteException re) { + if (jmxServiceURL != null) { + final String pro = jmxServiceURL.getProtocol(); + final String path = jmxServiceURL.getURLPath(); + + if ("rmi".equals(pro) && + path.startsWith("/jndi/iiop:")) { + MalformedURLException mfe = new MalformedURLException( + "Protocol is rmi but JNDI scheme is iiop: " + jmxServiceURL); + mfe.initCause(re); + throw mfe; + } + } + throw re; + } // Always use one of: // ClassLoader provided in Map at connect time, diff --git a/src/share/classes/javax/security/auth/Policy.java b/src/share/classes/javax/security/auth/Policy.java index 4b2560a86206e4d96374aaf494b137e3182deab8..6c508b2ce95eb5cd68ae57ee9e21c0250893796d 100644 --- a/src/share/classes/javax/security/auth/Policy.java +++ b/src/share/classes/javax/security/auth/Policy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -237,7 +237,7 @@ public abstract class Policy { } catch (Exception e) { throw new SecurityException (sun.security.util.ResourcesMgr.getString - ("unable to instantiate Subject-based policy")); + ("unable.to.instantiate.Subject.based.policy")); } } } diff --git a/src/share/classes/javax/security/auth/PrivateCredentialPermission.java b/src/share/classes/javax/security/auth/PrivateCredentialPermission.java index fd25008dc90ce38f1889d64dbfa3cb3e78b9b844..e78df3fdb5b8a577c9598edda971193c2dc930b7 100644 --- a/src/share/classes/javax/security/auth/PrivateCredentialPermission.java +++ b/src/share/classes/javax/security/auth/PrivateCredentialPermission.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -172,7 +172,7 @@ public final class PrivateCredentialPermission extends Permission { if (!"read".equalsIgnoreCase(actions)) throw new IllegalArgumentException - (ResourcesMgr.getString("actions can only be 'read'")); + (ResourcesMgr.getString("actions.can.only.be.read.")); init(name); } @@ -344,12 +344,11 @@ public final class PrivateCredentialPermission extends Permission { if (tokenizer.hasMoreTokens() == false) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("permission name [name] syntax invalid: ")); + ("permission.name.name.syntax.invalid.")); Object[] source = {name}; throw new IllegalArgumentException (form.format(source) + ResourcesMgr.getString - ("Credential Class not followed by a " + - "Principal Class and Name")); + ("Credential.Class.not.followed.by.a.Principal.Class.and.Name")); } while (tokenizer.hasMoreTokens()) { @@ -364,11 +363,11 @@ public final class PrivateCredentialPermission extends Permission { if (tokenizer.hasMoreTokens() == false) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("permission name [name] syntax invalid: ")); + ("permission.name.name.syntax.invalid.")); Object[] source = {name}; throw new IllegalArgumentException (form.format(source) + ResourcesMgr.getString - ("Principal Class not followed by a Principal Name")); + ("Principal.Class.not.followed.by.a.Principal.Name")); } // skip delimiter @@ -379,11 +378,11 @@ public final class PrivateCredentialPermission extends Permission { if (!principalName.startsWith("\"")) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("permission name [name] syntax invalid: ")); + ("permission.name.name.syntax.invalid.")); Object[] source = {name}; throw new IllegalArgumentException (form.format(source) + ResourcesMgr.getString - ("Principal Name must be surrounded by quotes")); + ("Principal.Name.must.be.surrounded.by.quotes")); } if (!principalName.endsWith("\"")) { @@ -401,11 +400,11 @@ public final class PrivateCredentialPermission extends Permission { if (!principalName.endsWith("\"")) { MessageFormat form = new MessageFormat (ResourcesMgr.getString - ("permission name [name] syntax invalid: ")); + ("permission.name.name.syntax.invalid.")); Object[] source = {name}; throw new IllegalArgumentException (form.format(source) + ResourcesMgr.getString - ("Principal Name missing end quote")); + ("Principal.Name.missing.end.quote")); } } @@ -418,9 +417,7 @@ public final class PrivateCredentialPermission extends Permission { if (principalClass.equals("*") && !principalName.equals("*")) { throw new IllegalArgumentException(ResourcesMgr.getString - ("PrivateCredentialPermission Principal Class " + - "can not be a wildcard (*) value if Principal Name " + - "is not a wildcard (*) value")); + ("PrivateCredentialPermission.Principal.Class.can.not.be.a.wildcard.value.if.Principal.Name.is.not.a.wildcard.value")); } if (testing) @@ -556,8 +553,7 @@ public final class PrivateCredentialPermission extends Permission { public String toString() { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("CredOwner:\n\tPrincipal Class = class\n\t" + - "Principal Name = name")); + ("CredOwner.Principal.Class.class.Principal.Name.name")); Object[] source = {principalClass, principalName}; return (form.format(source)); } diff --git a/src/share/classes/javax/security/auth/Subject.java b/src/share/classes/javax/security/auth/Subject.java index a5d56e75a25265735f26df7ac155c69b43245446..56e864c491cd3eba1dad09b831de237ca6fcdf4e 100644 --- a/src/share/classes/javax/security/auth/Subject.java +++ b/src/share/classes/javax/security/auth/Subject.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -204,7 +204,7 @@ public final class Subject implements java.io.Serializable { pubCredentials == null || privCredentials == null) throw new NullPointerException - (ResourcesMgr.getString("invalid null input(s)")); + (ResourcesMgr.getString("invalid.null.input.s.")); this.principals = Collections.synchronizedSet(new SecureSet (this, PRINCIPAL_SET, principals)); @@ -289,7 +289,7 @@ public final class Subject implements java.io.Serializable { if (acc == null) { throw new NullPointerException(ResourcesMgr.getString - ("invalid null AccessControlContext provided")); + ("invalid.null.AccessControlContext.provided")); } // return the Subject from the DomainCombiner of the provided context @@ -346,7 +346,7 @@ public final class Subject implements java.io.Serializable { } if (action == null) throw new NullPointerException - (ResourcesMgr.getString("invalid null action provided")); + (ResourcesMgr.getString("invalid.null.action.provided")); // set up the new Subject-based AccessControlContext // for doPrivileged @@ -406,7 +406,7 @@ public final class Subject implements java.io.Serializable { if (action == null) throw new NullPointerException - (ResourcesMgr.getString("invalid null action provided")); + (ResourcesMgr.getString("invalid.null.action.provided")); // set up the new Subject-based AccessControlContext for doPrivileged final AccessControlContext currentAcc = AccessController.getContext(); @@ -460,7 +460,7 @@ public final class Subject implements java.io.Serializable { if (action == null) throw new NullPointerException - (ResourcesMgr.getString("invalid null action provided")); + (ResourcesMgr.getString("invalid.null.action.provided")); // set up the new Subject-based AccessControlContext // for doPrivileged @@ -524,7 +524,7 @@ public final class Subject implements java.io.Serializable { if (action == null) throw new NullPointerException - (ResourcesMgr.getString("invalid null action provided")); + (ResourcesMgr.getString("invalid.null.action.provided")); // set up the new Subject-based AccessControlContext for doPrivileged final AccessControlContext callerAcc = @@ -603,7 +603,7 @@ public final class Subject implements java.io.Serializable { if (c == null) throw new NullPointerException - (ResourcesMgr.getString("invalid null Class provided")); + (ResourcesMgr.getString("invalid.null.Class.provided")); // always return an empty Set instead of null // so LoginModules can add to the Set if necessary @@ -697,7 +697,7 @@ public final class Subject implements java.io.Serializable { if (c == null) throw new NullPointerException - (ResourcesMgr.getString("invalid null Class provided")); + (ResourcesMgr.getString("invalid.null.Class.provided")); // always return an empty Set instead of null // so LoginModules can add to the Set if necessary @@ -742,7 +742,7 @@ public final class Subject implements java.io.Serializable { if (c == null) throw new NullPointerException - (ResourcesMgr.getString("invalid null Class provided")); + (ResourcesMgr.getString("invalid.null.Class.provided")); // always return an empty Set instead of null // so LoginModules can add to the Set if necessary @@ -832,15 +832,15 @@ public final class Subject implements java.io.Serializable { */ String toString(boolean includePrivateCredentials) { - String s = ResourcesMgr.getString("Subject:\n"); + String s = ResourcesMgr.getString("Subject."); String suffix = ""; synchronized(principals) { Iterator pI = principals.iterator(); while (pI.hasNext()) { Principal p = pI.next(); - suffix = suffix + ResourcesMgr.getString("\tPrincipal: ") + - p.toString() + ResourcesMgr.getString("\n"); + suffix = suffix + ResourcesMgr.getString(".Principal.") + + p.toString() + ResourcesMgr.getString("NEWLINE"); } } @@ -849,8 +849,8 @@ public final class Subject implements java.io.Serializable { while (pI.hasNext()) { Object o = pI.next(); suffix = suffix + - ResourcesMgr.getString("\tPublic Credential: ") + - o.toString() + ResourcesMgr.getString("\n"); + ResourcesMgr.getString(".Public.Credential.") + + o.toString() + ResourcesMgr.getString("NEWLINE"); } } @@ -861,12 +861,12 @@ public final class Subject implements java.io.Serializable { try { Object o = pI.next(); suffix += ResourcesMgr.getString - ("\tPrivate Credential: ") + + (".Private.Credential.") + o.toString() + - ResourcesMgr.getString("\n"); + ResourcesMgr.getString("NEWLINE"); } catch (SecurityException se) { suffix += ResourcesMgr.getString - ("\tPrivate Credential inaccessible\n"); + (".Private.Credential.inaccessible."); break; } } @@ -1036,7 +1036,7 @@ public final class Subject implements java.io.Serializable { if (subject.isReadOnly()) { throw new IllegalStateException(ResourcesMgr.getString - ("Subject is read-only")); + ("Subject.is.read.only")); } java.lang.SecurityManager sm = System.getSecurityManager(); @@ -1062,7 +1062,7 @@ public final class Subject implements java.io.Serializable { if (subject.isReadOnly()) { throw new IllegalStateException - (ResourcesMgr.getString("Subject is read-only")); + (ResourcesMgr.getString("Subject.is.read.only")); } java.lang.SecurityManager sm = System.getSecurityManager(); @@ -1084,9 +1084,7 @@ public final class Subject implements java.io.Serializable { case Subject.PRINCIPAL_SET: if (!(o instanceof Principal)) { throw new SecurityException(ResourcesMgr.getString - ("attempting to add an object which is not an " + - "instance of java.security.Principal to a " + - "Subject's Principal Set")); + ("attempting.to.add.an.object.which.is.not.an.instance.of.java.security.Principal.to.a.Subject.s.Principal.Set")); } break; default: @@ -1389,8 +1387,7 @@ public final class Subject implements java.io.Serializable { if (!o.getClass().isAssignableFrom(c)) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("attempting to add an object which is not an " + - "instance of class")); + ("attempting.to.add.an.object.which.is.not.an.instance.of.class")); Object[] source = {c.toString()}; throw new SecurityException(form.format(source)); } diff --git a/src/share/classes/javax/security/auth/login/AppConfigurationEntry.java b/src/share/classes/javax/security/auth/login/AppConfigurationEntry.java index 0b02cd7e5bdb09ae2a7aab14bfe068f19ace0910..7c70d580cb9ea7828b917327896a01362b50fec8 100644 --- a/src/share/classes/javax/security/auth/login/AppConfigurationEntry.java +++ b/src/share/classes/javax/security/auth/login/AppConfigurationEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -167,7 +167,7 @@ public class AppConfigurationEntry { */ public String toString() { return (sun.security.util.ResourcesMgr.getString - ("LoginModuleControlFlag: ") + controlFlag); + ("LoginModuleControlFlag.") + controlFlag); } } } diff --git a/src/share/classes/javax/security/auth/login/LoginContext.java b/src/share/classes/javax/security/auth/login/LoginContext.java index ee46616d6a4b7981b96017f222a841be2211ce86..6fb484aa094d148f9646b03d344209c984c24ef1 100644 --- a/src/share/classes/javax/security/auth/login/LoginContext.java +++ b/src/share/classes/javax/security/auth/login/LoginContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -244,7 +244,7 @@ public class LoginContext { if (name == null) throw new LoginException - (ResourcesMgr.getString("Invalid null input: name")); + (ResourcesMgr.getString("Invalid.null.input.name")); // get the Configuration if (config == null) { @@ -268,7 +268,7 @@ public class LoginContext { entries = config.getAppConfigurationEntry(OTHER); if (entries == null) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("No LoginModules configured for name")); + ("No.LoginModules.configured.for.name")); Object[] source = {name}; throw new LoginException(form.format(source)); } @@ -382,7 +382,7 @@ public class LoginContext { init(name); if (subject == null) throw new LoginException - (ResourcesMgr.getString("invalid null Subject provided")); + (ResourcesMgr.getString("invalid.null.Subject.provided")); this.subject = subject; subjectProvided = true; loadDefaultCallbackHandler(); @@ -418,7 +418,7 @@ public class LoginContext { init(name); if (callbackHandler == null) throw new LoginException(ResourcesMgr.getString - ("invalid null CallbackHandler provided")); + ("invalid.null.CallbackHandler.provided")); this.callbackHandler = new SecureCallbackHandler (java.security.AccessController.getContext(), callbackHandler); @@ -459,7 +459,7 @@ public class LoginContext { this(name, subject); if (callbackHandler == null) throw new LoginException(ResourcesMgr.getString - ("invalid null CallbackHandler provided")); + ("invalid.null.CallbackHandler.provided")); this.callbackHandler = new SecureCallbackHandler (java.security.AccessController.getContext(), callbackHandler); @@ -633,7 +633,7 @@ public class LoginContext { public void logout() throws LoginException { if (subject == null) { throw new LoginException(ResourcesMgr.getString - ("null subject - logout called before login")); + ("null.subject.logout.called.before.login")); } if (configProvided) { @@ -811,21 +811,20 @@ public class LoginContext { } catch (NoSuchMethodException nsme) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("unable to instantiate LoginModule, module, because " + - "it does not provide a no-argument constructor")); + ("unable.to.instantiate.LoginModule.module.because.it.does.not.provide.a.no.argument.constructor")); Object[] source = {moduleStack[i].entry.getLoginModuleName()}; throwException(null, new LoginException(form.format(source))); } catch (InstantiationException ie) { throwException(null, new LoginException(ResourcesMgr.getString - ("unable to instantiate LoginModule: ") + + ("unable.to.instantiate.LoginModule.") + ie.getMessage())); } catch (ClassNotFoundException cnfe) { throwException(null, new LoginException(ResourcesMgr.getString - ("unable to find LoginModule class: ") + + ("unable.to.find.LoginModule.class.") + cnfe.getMessage())); } catch (IllegalAccessException iae) { throwException(null, new LoginException(ResourcesMgr.getString - ("unable to access LoginModule: ") + + ("unable.to.access.LoginModule.") + iae.getMessage())); } catch (InvocationTargetException ite) { @@ -934,7 +933,7 @@ public class LoginContext { } else if (success == false) { // no module succeeded -- all modules were IGNORED throwException(new LoginException - (ResourcesMgr.getString("Login Failure: all modules ignored")), + (ResourcesMgr.getString("Login.Failure.all.modules.ignored")), null); } else { // success diff --git a/src/share/classes/javax/security/auth/x500/X500Principal.java b/src/share/classes/javax/security/auth/x500/X500Principal.java index d296684675206865d9a8fcb055f8069edc688246..5636856313c4273a891a7a8c99f2593db098a039 100644 --- a/src/share/classes/javax/security/auth/x500/X500Principal.java +++ b/src/share/classes/javax/security/auth/x500/X500Principal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -155,12 +155,12 @@ public final class X500Principal implements Principal, java.io.Serializable { if (name == null) { throw new NullPointerException (sun.security.util.ResourcesMgr.getString - ("provided null name")); + ("provided.null.name")); } if (keywordMap == null) { throw new NullPointerException (sun.security.util.ResourcesMgr.getString - ("provided null keyword map")); + ("provided.null.keyword.map")); } try { @@ -391,7 +391,7 @@ public final class X500Principal implements Principal, java.io.Serializable { if (oidMap == null) { throw new NullPointerException (sun.security.util.ResourcesMgr.getString - ("provided null OID map")); + ("provided.null.OID.map")); } if (format != null) { if (format.equalsIgnoreCase(RFC1779)) { diff --git a/src/share/classes/javax/sql/rowset/spi/SyncFactory.java b/src/share/classes/javax/sql/rowset/spi/SyncFactory.java index 4c8d6b48e0a1cc6689651d5ff6e7fa0f403d9833..f3358e0fb12b43805526fb3135c563a722484f5b 100644 --- a/src/share/classes/javax/sql/rowset/spi/SyncFactory.java +++ b/src/share/classes/javax/sql/rowset/spi/SyncFactory.java @@ -197,12 +197,6 @@ import javax.naming.*; */ public class SyncFactory { - /* - * The variable that represents the singleton instance - * of the SyncFactory class. - */ - private static SyncFactory syncFactory = null; - /** * Creates a new SyncFactory object, which is the singleton * instance. @@ -252,7 +246,7 @@ public class SyncFactory { /** * The Logger object to be used by the SyncFactory. */ - private static Logger rsLogger; + private static volatile Logger rsLogger; /** * */ @@ -315,27 +309,12 @@ public class SyncFactory { * @return the SyncFactory instance */ public static SyncFactory getSyncFactory() { - - // This method uses the Singleton Design Pattern - // with Double-Checked Locking Pattern for - // 1. Creating single instance of the SyncFactory - // 2. Make the class thread safe, so that at one time - // only one thread enters the synchronized block - // to instantiate. - - // if syncFactory object is already there - // don't go into synchronized block and return - // that object. - // else go into synchronized block - - if (syncFactory == null) { - synchronized (SyncFactory.class) { - if (syncFactory == null) { - syncFactory = new SyncFactory(); - } //end if - } //end synchronized block - } //end if - return syncFactory; + /* + * Using Initialization on Demand Holder idiom as + * Effective Java 2nd Edition,ITEM 71, indicates it is more performant + * than the Double-Check Locking idiom. + */ + return SyncFactoryHolder.factory; } /** @@ -435,11 +414,7 @@ public class SyncFactory { } } } - /** - * The internal boolean switch that indicates whether a JNDI - * context has been established or not. - */ - private static boolean jndiCtxEstablished = false; + /** * The internal debug switch. */ @@ -621,6 +596,7 @@ public class SyncFactory { * @param logger A Logger object instance * @throws java.lang.SecurityException if a security manager exists and its * {@code checkPermission} method denies calling {@code setLogger} + * @throws NullPointerException if the logger is null * @see SecurityManager#checkPermission */ public static void setLogger(Logger logger) { @@ -629,6 +605,10 @@ public class SyncFactory { if (sec != null) { sec.checkPermission(SET_SYNCFACTORY_PERMISSION); } + + if(logger == null){ + throw new NullPointerException("You must provide a Logger"); + } rsLogger = logger; } @@ -654,6 +634,7 @@ public class SyncFactory { * {@code checkPermission} method denies calling {@code setLogger} * @throws java.util.logging.LoggingPermission if a security manager exists and its * {@code checkPermission} method denies calling {@code setLevel} + * @throws NullPointerException if the logger is null * @see SecurityManager#checkPermission * @see LoggingPermission */ @@ -663,8 +644,12 @@ public class SyncFactory { if (sec != null) { sec.checkPermission(SET_SYNCFACTORY_PERMISSION); } + + if(logger == null){ + throw new NullPointerException("You must provide a Logger"); + } + logger.setLevel(level); rsLogger = logger; - rsLogger.setLevel(level); } /** @@ -674,11 +659,14 @@ public class SyncFactory { * @throws SyncFactoryException if no logging object has been set. */ public static Logger getLogger() throws SyncFactoryException { + + Logger result = rsLogger; // only one logger per session - if (rsLogger == null) { + if (result == null) { throw new SyncFactoryException("(SyncFactory) : No logger has been set"); } - return rsLogger; + + return result; } /** @@ -699,7 +687,7 @@ public class SyncFactory { * {@code checkPermission} method denies calling {@code setJNDIContext} * @see SecurityManager#checkPermission */ - public static void setJNDIContext(javax.naming.Context ctx) + public static synchronized void setJNDIContext(javax.naming.Context ctx) throws SyncFactoryException { SecurityManager sec = System.getSecurityManager(); if (sec != null) { @@ -709,17 +697,16 @@ public class SyncFactory { throw new SyncFactoryException("Invalid JNDI context supplied"); } ic = ctx; - jndiCtxEstablished = true; } /** - * Controls JNDI context intialization. + * Controls JNDI context initialization. * * @throws SyncFactoryException if an error occurs parsing the JNDI context */ - private static void initJNDIContext() throws SyncFactoryException { + private static synchronized void initJNDIContext() throws SyncFactoryException { - if (jndiCtxEstablished && (ic != null) && (lazyJNDICtxRefresh == false)) { + if ((ic != null) && (lazyJNDICtxRefresh == false)) { try { parseProperties(parseJNDIContext()); lazyJNDICtxRefresh = true; // touch JNDI namespace once. @@ -793,6 +780,13 @@ public class SyncFactory { enumerateBindings(bindings, properties); } } + + /** + * Lazy initialization Holder class used by {@code getSyncFactory} + */ + private static class SyncFactoryHolder { + static final SyncFactory factory = new SyncFactory(); + } } /** diff --git a/src/share/classes/javax/swing/GroupLayout.java b/src/share/classes/javax/swing/GroupLayout.java index 7628076a99473e2a368b816f09d82aea90967220..9219932776ed301462aa613e838a81df0d352019 100644 --- a/src/share/classes/javax/swing/GroupLayout.java +++ b/src/share/classes/javax/swing/GroupLayout.java @@ -653,6 +653,10 @@ public class GroupLayout implements LayoutManager2 { */ public ParallelGroup createParallelGroup(Alignment alignment, boolean resizable){ + if (alignment == null) { + throw new IllegalArgumentException("alignment must be non null"); + } + if (alignment == Alignment.BASELINE) { return new BaselineGroup(resizable); } diff --git a/src/share/classes/javax/swing/JComponent.java b/src/share/classes/javax/swing/JComponent.java index 6f017402ec7e01e9d8f6b1bc480a35ae7c38e0e8..78fddfcb11bb877c93da708b0fb05fa7d65ca947 100644 --- a/src/share/classes/javax/swing/JComponent.java +++ b/src/share/classes/javax/swing/JComponent.java @@ -4734,6 +4734,8 @@ public abstract class JComponent extends Container implements Serializable, * Notifies this component that it now has a parent component. * When this method is invoked, the chain of parent components is * set up with KeyboardAction event listeners. + * This method is called by the toolkit internally and should + * not be called directly by programs. * * @see #registerKeyboardAction */ @@ -4750,6 +4752,8 @@ public abstract class JComponent extends Container implements Serializable, * Notifies this component that it no longer has a parent component. * When this method is invoked, any KeyboardActions * set up in the the chain of parent components are removed. + * This method is called by the toolkit internally and should + * not be called directly by programs. * * @see #registerKeyboardAction */ diff --git a/src/share/classes/javax/swing/Popup.java b/src/share/classes/javax/swing/Popup.java index a77d574d72ecb4d45d77603ecad34d236913ee20..83cd7d6d789c6e9462fc241799e783f86a57adb4 100644 --- a/src/share/classes/javax/swing/Popup.java +++ b/src/share/classes/javax/swing/Popup.java @@ -156,7 +156,8 @@ public class Popup { component.setLocation(ownerX, ownerY); component.getContentPane().add(contents, BorderLayout.CENTER); - contents.invalidate(); + component.invalidate(); + component.validate(); if(component.isVisible()) { // Do not call pack() if window is not visible to // avoid early native peer creation diff --git a/src/share/classes/javax/swing/text/DefaultHighlighter.java b/src/share/classes/javax/swing/text/DefaultHighlighter.java index d90128b82ac17f81f6503b5334405eba9d8a5dde..dc68ae474fd60305ae2e796cc0ad6ef44b1a93ae 100644 --- a/src/share/classes/javax/swing/text/DefaultHighlighter.java +++ b/src/share/classes/javax/swing/text/DefaultHighlighter.java @@ -113,6 +113,14 @@ public class DefaultHighlighter extends LayeredHighlighter { * @exception BadLocationException if the specified location is invalid */ public Object addHighlight(int p0, int p1, Highlighter.HighlightPainter p) throws BadLocationException { + if (p0 < 0) { + throw new BadLocationException("Invalid start offset", p0); + } + + if (p1 < p0) { + throw new BadLocationException("Invalid end offset", p1); + } + Document doc = component.getDocument(); HighlightInfo i = (getDrawsLayeredHighlights() && (p instanceof LayeredHighlighter.LayerPainter)) ? @@ -217,6 +225,14 @@ public class DefaultHighlighter extends LayeredHighlighter { * @exception BadLocationException if the specified location is invalid */ public void changeHighlight(Object tag, int p0, int p1) throws BadLocationException { + if (p0 < 0) { + throw new BadLocationException("Invalid beginning of the range", p0); + } + + if (p1 < p0) { + throw new BadLocationException("Invalid end of the range", p1); + } + Document doc = component.getDocument(); if (tag instanceof LayeredHighlightInfo) { LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag; diff --git a/src/share/classes/sun/awt/UngrabEvent.java b/src/share/classes/sun/awt/UngrabEvent.java index e27e04068304e6aabdaebbd2be39de5a8ab1911a..7c1b8ecf9f515092238f9c7841c4dcf982bec1dd 100644 --- a/src/share/classes/sun/awt/UngrabEvent.java +++ b/src/share/classes/sun/awt/UngrabEvent.java @@ -40,8 +40,10 @@ import java.awt.Component; *

To listen for this event, install AWTEventListener with {@value sun.awt.SunToolkit#GRAB_EVENT_MASK} */ public class UngrabEvent extends AWTEvent { + private final static int UNGRAB_EVENT_ID = 1998; + public UngrabEvent(Component source) { - super(source, 0xffff); + super(source, UNGRAB_EVENT_ID); } public String toString() { diff --git a/src/share/classes/sun/nio/ch/FileChannelImpl.java b/src/share/classes/sun/nio/ch/FileChannelImpl.java index 6d1bed731ee3de01145b147a31254e82fcda5792..e37fe799d84b3c8f5dc0d610becc0f1ea6503be0 100644 --- a/src/share/classes/sun/nio/ch/FileChannelImpl.java +++ b/src/share/classes/sun/nio/ch/FileChannelImpl.java @@ -460,6 +460,16 @@ public class FileChannelImpl } finally { unmap(dbb); } + } catch (ClosedByInterruptException e) { + // target closed by interrupt as ClosedByInterruptException needs + // to be thrown after closing this channel. + assert !target.isOpen(); + try { + close(); + } catch (IOException ignore) { + // nothing we can do + } + throw e; } catch (IOException ioe) { // Only throw exception if no bytes have been written if (remaining == count) diff --git a/src/share/classes/sun/nio/ch/Interruptible.java b/src/share/classes/sun/nio/ch/Interruptible.java index e8d3824473ef270abacbf19991f0684b5a633829..8ca1cb959ce36fe7387bfe493346b1921b5613ec 100644 --- a/src/share/classes/sun/nio/ch/Interruptible.java +++ b/src/share/classes/sun/nio/ch/Interruptible.java @@ -23,14 +23,14 @@ * questions. */ -/* +/** + * An object that interrupts a thread blocked in an I/O operation. */ package sun.nio.ch; - public interface Interruptible { - public void interrupt(); + public void interrupt(Thread t); } diff --git a/src/share/classes/sun/security/krb5/Config.java b/src/share/classes/sun/security/krb5/Config.java index 21fb4cea7f5b001bc2248b38b1cf497f8c762338..272c3b1e6ca66f626ea91935a2980594ec92f3f6 100644 --- a/src/share/classes/sun/security/krb5/Config.java +++ b/src/share/classes/sun/security/krb5/Config.java @@ -111,7 +111,7 @@ public class Config { public static synchronized void refresh() throws KrbException { singleton = new Config(); KeyTab.refresh(); - KrbKdcReq.initStatic(); + KdcComm.initStatic(); } diff --git a/src/share/classes/sun/security/krb5/Credentials.java b/src/share/classes/sun/security/krb5/Credentials.java index 6896aa18e95fdc49a17cb625ffee61399dd61c8a..86dc3a01668a02151abb6091ebb8702ac266db60 100644 --- a/src/share/classes/sun/security/krb5/Credentials.java +++ b/src/share/classes/sun/security/krb5/Credentials.java @@ -347,94 +347,6 @@ public class Credentials { } } - /** - * Returns a TGT for the given client principal via an AS-Exchange. - * This method causes pre-authentication data to be sent in the - * AS-REQ. - * - * @param princ the client principal. This value cannot be null. - * @param secretKey the secret key of the client principal.This value - * cannot be null. - * @returns the TGT credentials - */ - public static Credentials acquireTGT(PrincipalName princ, - EncryptionKey[] secretKeys, - char[] password) - throws KrbException, IOException { - - if (princ == null) - throw new IllegalArgumentException( - "Cannot have null principal to do AS-Exchange"); - - if (secretKeys == null) - throw new IllegalArgumentException( - "Cannot have null secretKey to do AS-Exchange"); - - KrbAsRep asRep = null; - try { - asRep = sendASRequest(princ, secretKeys, null); - } catch (KrbException ke) { - if ((ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) || - (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED)) { - // process pre-auth info - if (DEBUG) { - System.out.println("AcquireTGT: PREAUTH FAILED/REQUIRED," + - " re-send AS-REQ"); - } - - KRBError error = ke.getError(); - // update salt in PrincipalName - String newSalt = error.getSalt(); - if (newSalt != null && newSalt.length() > 0) { - princ.setSalt(newSalt); - } - - // refresh keys - if (password != null) { - secretKeys = EncryptionKey.acquireSecretKeys(password, - princ.getSalt(), true, - error.getEType(), error.getParams()); - } - asRep = sendASRequest(princ, secretKeys, ke.getError()); - } else { - throw ke; - } - } - return asRep.getCreds(); - } - - /** - * Sends the AS-REQ - */ - private static KrbAsRep sendASRequest(PrincipalName princ, - EncryptionKey[] secretKeys, KRBError error) - throws KrbException, IOException { - - // %%% - KrbAsReq asReq = null; - if (error == null) { - asReq = new KrbAsReq(princ, secretKeys); - } else { - asReq = new KrbAsReq(princ, secretKeys, true, - error.getEType(), error.getSalt(), error.getParams()); - } - - String kdc = null; - KrbAsRep asRep = null; - try { - kdc = asReq.send(); - asRep = asReq.getReply(secretKeys); - } catch (KrbException ke) { - if (ke.returnCode() == Krb5.KRB_ERR_RESPONSE_TOO_BIG) { - asReq.send(princ.getRealmString(), kdc, true); - asRep = asReq.getReply(secretKeys); - } else { - throw ke; - } - } - return asRep; - } - /** * Acquires default credentials. *
The possible locations for default credentials cache is searched in @@ -529,29 +441,6 @@ public class Credentials { return CredentialsUtil.acquireServiceCreds(service, ccreds); } - - /* - * This method does the real job to request the service credential. - */ - - private static Credentials serviceCreds(ServiceName service, - Credentials ccreds) - throws KrbException, IOException { - return new KrbTgsReq( - new KDCOptions(), - ccreds, - service, - null, // KerberosTime from - null, // KerberosTime till - null, // KerberosTime rtime - null, // int[] eTypes - null, // HostAddresses addresses - null, // AuthorizationData - null, // Ticket[] additionalTickets - null // EncryptionKey subSessionKey - ).sendAndGetCreds(); - } - public CredentialsCache getCache() { return cache; } diff --git a/src/share/classes/sun/security/krb5/EncryptionKey.java b/src/share/classes/sun/security/krb5/EncryptionKey.java index ff920af8e9927d8012f1d059beb520a0d8f91f97..8ce51c0c659f7fbffc63443d5b680226adb81a74 100644 --- a/src/share/classes/sun/security/krb5/EncryptionKey.java +++ b/src/share/classes/sun/security/krb5/EncryptionKey.java @@ -156,6 +156,22 @@ public class EncryptionKey return ktab.readServiceKeys(princ); } + /** + * Obtains a key for a given etype with salt and optional s2kparams + * @param password NOT null + * @param salt NOT null + * @param etype + * @param s2kparams can be NULL + */ + public static EncryptionKey acquireSecretKey(char[] password, + String salt, int etype, byte[] s2kparams) + throws KrbException { + + return new EncryptionKey( + stringToKey(password, salt, s2kparams, etype), + etype, null); + } + /** * Generate a list of keys using the given principal and password. * Construct a key for each configured etype. @@ -169,19 +185,8 @@ public class EncryptionKey * as the default in that case. If default_tkt_enctypes was set in * the libdefaults of krb5.conf, then use that sequence. */ - // Used in Krb5LoginModule public static EncryptionKey[] acquireSecretKeys(char[] password, - String salt) throws KrbException { - return (acquireSecretKeys(password, salt, false, 0, null)); - } - - /** - * Generates a list of keys using the given principal, password, - * and the pre-authentication values. - */ - public static EncryptionKey[] acquireSecretKeys(char[] password, - String salt, boolean pa_exists, int pa_etype, byte[] pa_s2kparams) - throws KrbException { + String salt) throws KrbException { int[] etypes = EType.getDefaults("default_tkt_enctypes"); if (etypes == null) { @@ -191,10 +196,8 @@ public class EncryptionKey EncryptionKey[] encKeys = new EncryptionKey[etypes.length]; for (int i = 0; i < etypes.length; i++) { if (EType.isSupported(etypes[i])) { - byte[] s2kparams = (pa_exists && etypes[i] == pa_etype) - ? pa_s2kparams : null; encKeys[i] = new EncryptionKey( - stringToKey(password, salt, s2kparams, etypes[i]), + stringToKey(password, salt, null, etypes[i]), etypes[i], null); } else { if (DEBUG) { diff --git a/src/share/classes/sun/security/krb5/KrbKdcReq.java b/src/share/classes/sun/security/krb5/KdcComm.java similarity index 84% rename from src/share/classes/sun/security/krb5/KrbKdcReq.java rename to src/share/classes/sun/security/krb5/KdcComm.java index 9f968014ea17d182415a8397ac6ee8c51f337d25..22e54afe5e86aeaf30200df1aed85f11ee31ded0 100644 --- a/src/share/classes/sun/security/krb5/KrbKdcReq.java +++ b/src/share/classes/sun/security/krb5/KdcComm.java @@ -31,13 +31,11 @@ package sun.security.krb5; -import java.security.AccessController; import java.security.PrivilegedAction; import java.security.Security; import java.util.Locale; import sun.security.krb5.internal.Krb5; -import sun.security.krb5.internal.UDPClient; -import sun.security.krb5.internal.TCPClient; +import sun.security.krb5.internal.NetClient; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.StringTokenizer; @@ -48,8 +46,13 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; +import sun.security.krb5.internal.KRBError; -public abstract class KrbKdcReq { +/** + * KDC-REQ/KDC-REP communication. No more base class for KrbAsReq and + * KrbTgsReq. This class is now communication only. + */ +public final class KdcComm { // The following settings can be configured in [libdefaults] // section of krb5.conf, which are global for all realms. Each of @@ -161,20 +164,23 @@ public abstract class KrbKdcReq { KdcAccessibility.reset(); } - protected byte[] obuf; - protected byte[] ibuf; - /** - * Sends the provided data to the KDC of the specified realm. - * Returns the response from the KDC. - * Default realm/KDC is used if realm is null. - * @param realm the realm of the KDC where data is to be sent. - * @returns the kdc to which the AS request was sent to - * @exception InterruptedIOException if timeout expires - * @exception KrbException + * The instance fields */ + private String realm; + + public KdcComm(String realm) throws KrbException { + if (realm == null) { + realm = Config.getInstance().getDefaultRealm(); + if (realm == null) { + throw new KrbException(Krb5.KRB_ERR_GENERIC, + "Cannot find default realm"); + } + } + this.realm = realm; + } - public String send(String realm) + public byte[] send(byte[] obuf) throws IOException, KrbException { int udpPrefLimit = getRealmSpecificValue( realm, "udp_preference_limit", defaultUdpPrefLimit); @@ -182,10 +188,10 @@ public abstract class KrbKdcReq { boolean useTCP = (udpPrefLimit > 0 && (obuf != null && obuf.length > udpPrefLimit)); - return (send(realm, useTCP)); + return send(obuf, useTCP); } - public String send(String realm, boolean useTCP) + private byte[] send(byte[] obuf, boolean useTCP) throws IOException, KrbException { if (obuf == null) @@ -206,10 +212,21 @@ public abstract class KrbKdcReq { throw new KrbException("Cannot get kdc for realm " + realm); } String tempKdc = null; // may include the port number also + byte[] ibuf = null; for (String tmp: KdcAccessibility.list(kdcList)) { tempKdc = tmp; try { - send(realm,tempKdc,useTCP); + ibuf = send(obuf,tempKdc,useTCP); + KRBError ke = null; + try { + ke = new KRBError(ibuf); + } catch (Exception e) { + // OK + } + if (ke != null && ke.getErrorCode() == + Krb5.KRB_ERR_RESPONSE_TOO_BIG) { + ibuf = send(obuf, tempKdc, true); + } KdcAccessibility.removeBad(tempKdc); break; } catch (Exception e) { @@ -229,16 +246,16 @@ public abstract class KrbKdcReq { throw (KrbException) savedException; } } - return tempKdc; + return ibuf; } // send the AS Request to the specified KDC - public void send(String realm, String tempKdc, boolean useTCP) + private byte[] send(byte[] obuf, String tempKdc, boolean useTCP) throws IOException, KrbException { if (obuf == null) - return; + return null; int port = Krb5.KDC_INET_DEFAULT_PORT; int retries = getRealmSpecificValue( @@ -303,11 +320,12 @@ public abstract class KrbKdcReq { KdcCommunication kdcCommunication = new KdcCommunication(kdc, port, useTCP, timeout, retries, obuf); try { - ibuf = AccessController.doPrivileged(kdcCommunication); + byte[] ibuf = AccessController.doPrivileged(kdcCommunication); if (DEBUG) { System.out.println(">>> KrbKdcReq send: #bytes read=" + (ibuf != null ? ibuf.length : 0)); } + return ibuf; } catch (PrivilegedActionException e) { Exception wrappedException = e.getException(); if (wrappedException instanceof IOException) { @@ -316,10 +334,6 @@ public abstract class KrbKdcReq { throw (KrbException) wrappedException; } } - if (DEBUG) { - System.out.println(">>> KrbKdcReq send: #bytes read=" - + (ibuf != null ? ibuf.length : 0)); - } } private static class KdcCommunication @@ -349,12 +363,16 @@ public abstract class KrbKdcReq { byte[] ibuf = null; - if (useTCP) { - TCPClient kdcClient = new TCPClient(kdc, port); + for (int i=1; i <= retries; i++) { + String proto = useTCP?"TCP":"UDP"; + NetClient kdcClient = NetClient.getInstance( + proto, kdc, port, timeout); if (DEBUG) { System.out.println(">>> KDCCommunication: kdc=" + kdc - + " TCP:" - + port + + " " + proto + ":" + + port + ", timeout=" + + timeout + + ",Attempt =" + i + ", #bytes=" + obuf.length); } try { @@ -366,50 +384,18 @@ public abstract class KrbKdcReq { * And get a response. */ ibuf = kdcClient.receive(); - } finally { - kdcClient.close(); - } - - } else { - // For each KDC we try defaultKdcRetryLimit times to - // get the response - for (int i=1; i <= retries; i++) { - UDPClient kdcClient = new UDPClient(kdc, port, timeout); - + break; + } catch (SocketTimeoutException se) { if (DEBUG) { - System.out.println(">>> KDCCommunication: kdc=" + kdc - + (useTCP ? " TCP:":" UDP:") - + port + ", timeout=" - + timeout - + ",Attempt =" + i - + ", #bytes=" + obuf.length); + System.out.println ("SocketTimeOutException with " + + "attempt: " + i); } - try { - /* - * Send the data to the kdc. - */ - - kdcClient.send(obuf); - - /* - * And get a response. - */ - try { - ibuf = kdcClient.receive(); - break; - } catch (SocketTimeoutException se) { - if (DEBUG) { - System.out.println ("SocketTimeOutException with " + - "attempt: " + i); - } - if (i == retries) { - ibuf = null; - throw se; - } - } - } finally { - kdcClient.close(); + if (i == retries) { + ibuf = null; + throw se; } + } finally { + kdcClient.close(); } } return ibuf; diff --git a/src/share/classes/sun/security/krb5/KrbAsRep.java b/src/share/classes/sun/security/krb5/KrbAsRep.java index 709e4410a0acda90233e1a44c01c57cbf94a8129..c05d8bd08bfbde4cf9d2b3caaadbf3519fc8af9b 100644 --- a/src/share/classes/sun/security/krb5/KrbAsRep.java +++ b/src/share/classes/sun/security/krb5/KrbAsRep.java @@ -36,25 +36,24 @@ import sun.security.krb5.internal.crypto.KeyUsage; import sun.security.krb5.internal.crypto.EType; import sun.security.util.*; import java.io.IOException; +import java.util.Objects; /** * This class encapsulates a AS-REP message that the KDC sends to the * client. */ -public class KrbAsRep extends KrbKdcRep { +class KrbAsRep extends KrbKdcRep { - private ASRep rep; - private Credentials creds; + private ASRep rep; // The AS-REP message + private Credentials creds; // The Credentials provide by the AS-REP + // message, created by initiator after calling + // the decrypt() method private boolean DEBUG = Krb5.DEBUG; - KrbAsRep(byte[] ibuf, EncryptionKey[] keys, KrbAsReq asReq) throws - KrbException, Asn1Exception, IOException { - if (keys == null) - throw new KrbException(Krb5.API_INVALID_ARG); + KrbAsRep(byte[] ibuf) throws + KrbException, Asn1Exception, IOException { DerValue encoding = new DerValue(ibuf); - ASReq req = asReq.getMessage(); - ASRep rep = null; try { rep = new ASRep(encoding); } catch (Asn1Exception e) { @@ -83,25 +82,77 @@ public class KrbAsRep extends KrbKdcRep { ke.initCause(e); throw ke; } + } - int encPartKeyType = rep.encPart.getEType(); - EncryptionKey dkey = EncryptionKey.findKey(encPartKeyType, keys); + // KrbAsReqBuilder need to read back the PA for key generation + PAData[] getPA() { + return rep.pAData; + } + /** + * Called by KrbAsReqBuilder to resolve a AS-REP message using keys. + * @param keys user provided keys, not null + * @param asReq the original AS-REQ sent, used to validate AS-REP + */ + void decryptUsingKeys(EncryptionKey[] keys, KrbAsReq asReq) + throws KrbException, Asn1Exception, IOException { + EncryptionKey dkey = null; + int encPartKeyType = rep.encPart.getEType(); + Integer encPartKvno = rep.encPart.kvno; + try { + dkey = EncryptionKey.findKey(encPartKeyType, encPartKvno, keys); + } catch (KrbException ke) { + if (ke.returnCode() == Krb5.KRB_AP_ERR_BADKEYVER) { + // Fallback to no kvno. In some cases, keytab is generated + // not by sysadmin but Java's ktab command + dkey = EncryptionKey.findKey(encPartKeyType, keys); + } + } if (dkey == null) { throw new KrbException(Krb5.API_INVALID_ARG, - "Cannot find key of appropriate type to decrypt AS REP - " + - EType.toString(encPartKeyType)); + "Cannot find key for type/kvno to decrypt AS REP - " + + EType.toString(encPartKeyType) + "/" + encPartKvno); } + decrypt(dkey, asReq); + } + /** + * Called by KrbAsReqBuilder to resolve a AS-REP message using a password. + * @param password user provided password. not null + * @param asReq the original AS-REQ sent, used to validate AS-REP + * @param cname the user principal name, used to provide salt + */ + void decryptUsingPassword(char[] password, + KrbAsReq asReq, PrincipalName cname) + throws KrbException, Asn1Exception, IOException { + int encPartKeyType = rep.encPart.getEType(); + PAData.SaltAndParams snp = + PAData.getSaltAndParams(encPartKeyType, rep.pAData); + EncryptionKey dkey = null; + dkey = EncryptionKey.acquireSecretKey(password, + snp.salt == null ? cname.getSalt() : snp.salt, + encPartKeyType, + snp.params); + decrypt(dkey, asReq); + } + + /** + * Decrypts encrypted content inside AS-REP. Called by initiator. + * @param dkey the decryption key to use + * @param asReq the original AS-REQ sent, used to validate AS-REP + */ + private void decrypt(EncryptionKey dkey, KrbAsReq asReq) + throws KrbException, Asn1Exception, IOException { byte[] enc_as_rep_bytes = rep.encPart.decrypt(dkey, KeyUsage.KU_ENC_AS_REP_PART); byte[] enc_as_rep_part = rep.encPart.reset(enc_as_rep_bytes); - encoding = new DerValue(enc_as_rep_part); + DerValue encoding = new DerValue(enc_as_rep_part); EncASRepPart enc_part = new EncASRepPart(encoding); rep.ticket.sname.setRealm(rep.ticket.realm); rep.encKDCRepPart = enc_part; + ASReq req = asReq.getMessage(); check(req, rep); creds = new Credentials( @@ -119,17 +170,13 @@ public class KrbAsRep extends KrbKdcRep { System.out.println(">>> KrbAsRep cons in KrbAsReq.getReply " + req.reqBody.cname.getNameString()); } - - this.rep = rep; - this.creds = creds; } - public Credentials getCreds() { - return creds; + Credentials getCreds() { + return Objects.nonNull(creds, "Creds not available yet."); } - // made public for Kinit - public sun.security.krb5.internal.ccache.Credentials setCredentials() { + sun.security.krb5.internal.ccache.Credentials getCCreds() { return new sun.security.krb5.internal.ccache.Credentials(rep); } } diff --git a/src/share/classes/sun/security/krb5/KrbAsReq.java b/src/share/classes/sun/security/krb5/KrbAsReq.java index 77f3798332fb5312d735ac7f629140466fdffdcd..1c2dfdf94db51a92cd74086507d68f2213e5764a 100644 --- a/src/share/classes/sun/security/krb5/KrbAsReq.java +++ b/src/share/classes/sun/security/krb5/KrbAsReq.java @@ -32,291 +32,39 @@ package sun.security.krb5; import sun.security.krb5.internal.*; -import sun.security.krb5.internal.crypto.EType; import sun.security.krb5.internal.crypto.Nonce; import sun.security.krb5.internal.crypto.KeyUsage; -import sun.security.util.*; import java.io.IOException; -import java.io.ByteArrayInputStream; -import java.net.UnknownHostException; -import java.util.StringTokenizer; /** * This class encapsulates the KRB-AS-REQ message that the client * sends to the KDC. */ -public class KrbAsReq extends KrbKdcReq { - private PrincipalName princName; +public class KrbAsReq { private ASReq asReqMessg; private boolean DEBUG = Krb5.DEBUG; - private static KDCOptions defaultKDCOptions = new KDCOptions(); - - // pre-auth info - private boolean PA_ENC_TIMESTAMP_REQUIRED = false; - private boolean pa_exists = false; - private int pa_etype = 0; - private String pa_salt = null; - private byte[] pa_s2kparams = null; - - // default is address-less tickets - private boolean KDC_EMPTY_ADDRESSES_ALLOWED = true; /** - * Creates a KRB-AS-REQ to send to the default KDC - * @throws KrbException - * @throws IOException + * Constructs an AS-REQ message. */ - // Called by Credentials - KrbAsReq(PrincipalName principal, EncryptionKey[] keys) - throws KrbException, IOException { - this(keys, // for pre-authentication - false, 0, null, null, // pre-auth values - defaultKDCOptions, - principal, - null, // PrincipalName sname - null, // KerberosTime from - null, // KerberosTime till - null, // KerberosTime rtime - null, // int[] eTypes - null, // HostAddresses addresses - null); // Ticket[] additionalTickets - } - - /** - * Creates a KRB-AS-REQ to send to the default KDC - * with pre-authentication values - */ - KrbAsReq(PrincipalName principal, EncryptionKey[] keys, - boolean pa_exists, int etype, String salt, byte[] s2kparams) - throws KrbException, IOException { - this(keys, // for pre-authentication - pa_exists, etype, salt, s2kparams, // pre-auth values - defaultKDCOptions, - principal, - null, // PrincipalName sname - null, // KerberosTime from - null, // KerberosTime till - null, // KerberosTime rtime - null, // int[] eTypes - null, // HostAddresses addresses - null); // Ticket[] additionalTickets - } - - private static int[] getETypesFromKeys(EncryptionKey[] keys) { - int[] types = new int[keys.length]; - for (int i = 0; i < keys.length; i++) { - types[i] = keys[i].getEType(); - } - return types; - } - - // update with pre-auth info - public void updatePA(int etype, String salt, byte[] params, PrincipalName name) { - // set the pre-auth values - pa_exists = true; - pa_etype = etype; - pa_salt = salt; - pa_s2kparams = params; - - // update salt in PrincipalName - if (salt != null && salt.length() > 0) { - name.setSalt(salt); - if (DEBUG) { - System.out.println("Updated salt from pre-auth = " + name.getSalt()); - } - } - PA_ENC_TIMESTAMP_REQUIRED = true; - } - - // Used by Kinit - public KrbAsReq( - char[] password, - KDCOptions options, - PrincipalName cname, - PrincipalName sname, - KerberosTime from, - KerberosTime till, - KerberosTime rtime, - int[] eTypes, - HostAddresses addresses, - Ticket[] additionalTickets) - throws KrbException, IOException { - this(password, - false, 0, null, null, // pre-auth values - options, - cname, - sname, // PrincipalName sname - from, // KerberosTime from - till, // KerberosTime till - rtime, // KerberosTime rtime - eTypes, // int[] eTypes - addresses, // HostAddresses addresses - additionalTickets); // Ticket[] additionalTickets - } - - // Used by Kinit - public KrbAsReq( - char[] password, - boolean pa_exists, - int etype, - String salt, - byte[] s2kparams, - KDCOptions options, - PrincipalName cname, - PrincipalName sname, - KerberosTime from, - KerberosTime till, - KerberosTime rtime, - int[] eTypes, - HostAddresses addresses, - Ticket[] additionalTickets) - throws KrbException, IOException { - - EncryptionKey[] keys = null; - - // update with preauth info - if (pa_exists) { - updatePA(etype, salt, s2kparams, cname); + // Can be null? has default? + public KrbAsReq(EncryptionKey pakey, // ok + KDCOptions options, // ok, new KDCOptions() + PrincipalName cname, // NO and must have realm + PrincipalName sname, // ok, krgtgt@CREALM + KerberosTime from, // ok + KerberosTime till, // ok, will use + KerberosTime rtime, // ok + int[] eTypes, // NO + HostAddresses addresses // ok + ) + throws KrbException, IOException { + + if (options == null) { + options = new KDCOptions(); } - if (password != null) { - keys = EncryptionKey.acquireSecretKeys(password, cname.getSalt(), pa_exists, - pa_etype, pa_s2kparams); - } - if (DEBUG) { - System.out.println(">>>KrbAsReq salt is " + cname.getSalt()); - } - - try { - init( - keys, - options, - cname, - sname, - from, - till, - rtime, - eTypes, - addresses, - additionalTickets); - } - finally { - /* - * Its ok to destroy the key here because we created it and are - * now done with it. - */ - if (keys != null) { - for (int i = 0; i < keys.length; i++) { - keys[i].destroy(); - } - } - } - } - - // Used in Kinit - public KrbAsReq( - EncryptionKey[] keys, - KDCOptions options, - PrincipalName cname, - PrincipalName sname, - KerberosTime from, - KerberosTime till, - KerberosTime rtime, - int[] eTypes, - HostAddresses addresses, - Ticket[] additionalTickets) - throws KrbException, IOException { - this(keys, - false, 0, null, null, // pre-auth values - options, - cname, - sname, // PrincipalName sname - from, // KerberosTime from - till, // KerberosTime till - rtime, // KerberosTime rtime - eTypes, // int[] eTypes - addresses, // HostAddresses addresses - additionalTickets); // Ticket[] additionalTickets - } - - // Used by Kinit - public KrbAsReq( - EncryptionKey[] keys, - boolean pa_exists, - int etype, - String salt, - byte[] s2kparams, - KDCOptions options, - PrincipalName cname, - PrincipalName sname, - KerberosTime from, - KerberosTime till, - KerberosTime rtime, - int[] eTypes, - HostAddresses addresses, - Ticket[] additionalTickets) - throws KrbException, IOException { - - // update with preauth info - if (pa_exists) { - // update pre-auth info - updatePA(etype, salt, s2kparams, cname); - - if (DEBUG) { - System.out.println(">>>KrbAsReq salt is " + cname.getSalt()); - } - } - - init( - keys, - options, - cname, - sname, - from, - till, - rtime, - eTypes, - addresses, - additionalTickets); - } - - /* - private KrbAsReq(KDCOptions options, - PrincipalName cname, - PrincipalName sname, - KerberosTime from, - KerberosTime till, - KerberosTime rtime, - int[] eTypes, - HostAddresses addresses, - Ticket[] additionalTickets) - throws KrbException, IOException { - init(null, - options, - cname, - sname, - from, - till, - rtime, - eTypes, - addresses, - additionalTickets); - } -*/ - - private void init(EncryptionKey[] keys, - KDCOptions options, - PrincipalName cname, - PrincipalName sname, - KerberosTime from, - KerberosTime till, - KerberosTime rtime, - int[] eTypes, - HostAddresses addresses, - Ticket[] additionalTickets ) - throws KrbException, IOException { - // check if they are valid arguments. The optional fields should be // consistent with settings in KDCOptions. Mar 17 2000 if (options.get(KDCOptions.FORWARDED) || @@ -341,189 +89,66 @@ public class KrbAsReq extends KrbKdcReq { if (rtime != null) rtime = null; } - princName = cname; - int[] tktETypes = EType.getDefaults("default_tkt_enctypes", keys); PAData[] paData = null; - if (PA_ENC_TIMESTAMP_REQUIRED) { - EncryptionKey key = null; - if (pa_etype != EncryptedData.ETYPE_NULL) { - if (DEBUG) { - System.out.println("Pre-Authenticaton: find key for etype = " + pa_etype); - } - key = EncryptionKey.findKey(pa_etype, keys); - } else { - if (tktETypes.length > 0) { - key = EncryptionKey.findKey(tktETypes[0], keys); - } - } - if (DEBUG) { - System.out.println("AS-REQ: Add PA_ENC_TIMESTAMP now"); - } + if (pakey != null) { PAEncTSEnc ts = new PAEncTSEnc(); byte[] temp = ts.asn1Encode(); - if (key != null) { - // Use first key in list - EncryptedData encTs = new EncryptedData(key, temp, - KeyUsage.KU_PA_ENC_TS); - paData = new PAData[1]; - paData[0] = new PAData( Krb5.PA_ENC_TIMESTAMP, - encTs.asn1Encode()); - } + EncryptedData encTs = new EncryptedData(pakey, temp, + KeyUsage.KU_PA_ENC_TS); + paData = new PAData[1]; + paData[0] = new PAData( Krb5.PA_ENC_TIMESTAMP, + encTs.asn1Encode()); } - if (DEBUG) { - System.out.println(">>> KrbAsReq calling createMessage"); + if (cname.getRealm() == null) { + throw new RealmException(Krb5.REALM_NULL, + "default realm not specified "); } - if (eTypes == null) { - eTypes = tktETypes; + if (DEBUG) { + System.out.println(">>> KrbAsReq creating message"); } // check to use addresses in tickets - if (Config.getInstance().useAddresses()) { - KDC_EMPTY_ADDRESSES_ALLOWED = false; - } - // get the local InetAddress if required - if (addresses == null && !KDC_EMPTY_ADDRESSES_ALLOWED) { + if (addresses == null && Config.getInstance().useAddresses()) { addresses = HostAddresses.getLocalAddresses(); } - asReqMessg = createMessage( - paData, - options, - cname, - cname.getRealm(), - sname, - from, - till, - rtime, - eTypes, - addresses, - additionalTickets); - obuf = asReqMessg.asn1Encode(); - } - - /** - * Returns an AS-REP message corresponding to the AS-REQ that - * was sent. - * @param password The password that will be used to derive the - * secret key that will decrypt the AS-REP from the KDC. - * @exception KrbException if an error occurs while reading the data. - * @exception IOException if an I/O error occurs while reading encoded data. - */ - public KrbAsRep getReply(char[] password) - throws KrbException, IOException { - - if (password == null) - throw new KrbException(Krb5.API_INVALID_ARG); - KrbAsRep temp = null; - EncryptionKey[] keys = null; - try { - keys = EncryptionKey.acquireSecretKeys(password, - princName.getSalt(), pa_exists, pa_etype, pa_s2kparams); - temp = getReply(keys); - } finally { - /* - * Its ok to destroy the key here because we created it and are - * now done with it. - */ - if (keys != null) { - for (int i = 0; i < keys.length; i++) { - keys[i].destroy(); - } - } - } - return temp; - } - - /** - * Sends an AS request to the realm of the client. - * returns the KDC hostname that the request was sent to - */ - - public String send() - throws IOException, KrbException - { - String realmStr = null; - if (princName != null) - realmStr = princName.getRealmString(); - - return (send(realmStr)); - } - - /** - * Returns an AS-REP message corresponding to the AS-REQ that - * was sent. - * @param keys The secret keys that will decrypt the AS-REP from - * the KDC; key selected depends on etype used to encrypt data. - * @exception KrbException if an error occurs while reading the data. - * @exception IOException if an I/O error occurs while reading encoded - * data. - * - */ - public KrbAsRep getReply(EncryptionKey[] keys) - throws KrbException,IOException { - return new KrbAsRep(ibuf, keys, this); - } - - private ASReq createMessage( - PAData[] paData, - KDCOptions kdc_options, - PrincipalName cname, - Realm crealm, - PrincipalName sname, - KerberosTime from, - KerberosTime till, - KerberosTime rtime, - int[] eTypes, - HostAddresses addresses, - Ticket[] additionalTickets - ) throws Asn1Exception, KrbApErrException, - RealmException, UnknownHostException, IOException { - - if (DEBUG) { - System.out.println(">>> KrbAsReq in createMessage"); - } - - PrincipalName req_sname = null; if (sname == null) { - if (crealm == null) { - throw new RealmException(Krb5.REALM_NULL, - "default realm not specified "); - } - req_sname = new PrincipalName( - "krbtgt" + - PrincipalName.NAME_COMPONENT_SEPARATOR + - crealm.toString(), - PrincipalName.KRB_NT_SRV_INST); - } else - req_sname = sname; + sname = new PrincipalName("krbtgt" + + PrincipalName.NAME_COMPONENT_SEPARATOR + + cname.getRealmAsString(), + PrincipalName.KRB_NT_SRV_INST); + } - KerberosTime req_till = null; if (till == null) { - req_till = new KerberosTime(); - } else { - req_till = till; + till = new KerberosTime(0); // Choose KDC maximum allowed } - KDCReqBody kdc_req_body = new KDCReqBody(kdc_options, + // enc-authorization-data and additional-tickets never in AS-REQ + KDCReqBody kdc_req_body = new KDCReqBody(options, cname, - crealm, - req_sname, + cname.getRealm(), + sname, from, - req_till, + till, rtime, Nonce.value(), eTypes, addresses, null, - additionalTickets); + null); - return new ASReq( + asReqMessg = new ASReq( paData, kdc_req_body); } + byte[] encoding() throws IOException, Asn1Exception { + return asReqMessg.asn1Encode(); + } + + // Used by KrbAsRep to validate AS-REP ASReq getMessage() { return asReqMessg; } diff --git a/src/share/classes/sun/security/krb5/KrbAsReqBuilder.java b/src/share/classes/sun/security/krb5/KrbAsReqBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..940d31107e500438442ca67fec7adacca20a694f --- /dev/null +++ b/src/share/classes/sun/security/krb5/KrbAsReqBuilder.java @@ -0,0 +1,395 @@ +/* + * 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 sun.security.krb5; + +import java.io.IOException; +import java.util.Arrays; +import sun.security.krb5.internal.HostAddresses; +import sun.security.krb5.internal.KDCOptions; +import sun.security.krb5.internal.KRBError; +import sun.security.krb5.internal.KerberosTime; +import sun.security.krb5.internal.Krb5; +import sun.security.krb5.internal.PAData; +import sun.security.krb5.internal.crypto.EType; + +/** + * A manager class for AS-REQ communications. + * + * This class does: + * 1. Gather information to create AS-REQ + * 2. Create and send AS-REQ + * 3. Receive AS-REP and KRB-ERROR (-KRB_ERR_RESPONSE_TOO_BIG) and parse them + * 4. Emit credentials and secret keys (for JAAS storeKey=true) + * + * This class does not: + * 1. Deal with real communications (KdcComm does it, and TGS-REQ) + * a. Name of KDCs for a realm + * b. Server availability, timeout, UDP or TCP + * d. KRB_ERR_RESPONSE_TOO_BIG + * + * With this class: + * 1. KrbAsReq has only one constructor + * 2. Krb5LoginModule and Kinit call a single builder + * 3. Better handling of sensitive info + * + * @since 1.7 + */ + +public final class KrbAsReqBuilder { + + // Common data for AS-REQ fields + private KDCOptions options; + private PrincipalName cname; + private PrincipalName sname; + private KerberosTime from; + private KerberosTime till; + private KerberosTime rtime; + private HostAddresses addresses; + + // Secret source: can't be changed once assigned, only one (of the two + // sources) can be set and should be non-null + private EncryptionKey[] keys; + private char[] password; + + // Used to create a ENC-TIMESTAMP in the 2nd AS-REQ + private EncryptionKey pakey; + private PAData[] paList; // PA-DATA from both KRB-ERROR and AS-REP. + // Used by getKeys() only. + // Only AS-REP should be enough per RFC, + // combined in case etypes are different. + + // The generated and received: + int[] eTypes; + private KrbAsReq req; + private KrbAsRep rep; + + private static enum State { + INIT, // Initialized, can still add more initialization info + REQ_OK, // AS-REQ performed + DESTROYED, // Destroyed, not usable anymore + } + private State state; + + // Called by other constructors + private KrbAsReqBuilder(PrincipalName cname) + throws KrbException { + if (cname.getRealm() == null) { + cname.setRealm(Config.getInstance().getDefaultRealm()); + } + this.cname = cname; + state = State.INIT; + } + + /** + * Creates a builder to be used by {@code cname} with existing keys. + * + * @param cname the client of the AS-REQ. Must not be null. Might have no + * realm, where default realm will be used. This realm will be the target + * realm for AS-REQ. I believe a client should only get initial TGT from + * its own realm. + * @param keys must not be null. if empty, might be quite useless. + * This argument will neither be modified nor stored by the method. + * @throws KrbException + */ + public KrbAsReqBuilder(PrincipalName cname, EncryptionKey[] keys) + throws KrbException { + this(cname); + this.keys = new EncryptionKey[keys.length]; + for (int i=0; i 0) { + int oldLen = paList.length; + paList = Arrays.copyOf(paList, paList.length + extraLen); + System.arraycopy(rep.getPA(), 0, paList, oldLen, extraLen); + } + } + } + return this; + } + + /** + * Communication until AS-REP or non preauth-related KRB-ERROR received + * @throws KrbException + * @throws IOException + */ + private KrbAsReqBuilder send() throws KrbException, IOException { + boolean preAuthFailedOnce = false; + KdcComm comm = new KdcComm(cname.getRealmAsString()); + while (true) { + try { + req = build(); + rep = new KrbAsRep(comm.send(req.encoding())); + return this; + } catch (KrbException ke) { + if (!preAuthFailedOnce && ( + ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED || + ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED)) { + if (Krb5.DEBUG) { + System.out.println("KrbAsReqBuilder: " + + "PREAUTH FAILED/REQ, re-send AS-REQ"); + } + preAuthFailedOnce = true; + KRBError kerr = ke.getError(); + if (password == null) { + pakey = EncryptionKey.findKey(kerr.getEType(), keys); + } else { + PAData.SaltAndParams snp = PAData.getSaltAndParams( + kerr.getEType(), kerr.getPA()); + if (kerr.getEType() == 0) { + // Possible if PA-PW-SALT is in KRB-ERROR. RFC + // does not recommend this + pakey = EncryptionKey.acquireSecretKey(password, + snp.salt == null ? cname.getSalt() : snp.salt, + eTypes[0], + null); + } else { + pakey = EncryptionKey.acquireSecretKey(password, + snp.salt == null ? cname.getSalt() : snp.salt, + kerr.getEType(), + snp.params); + } + } + paList = kerr.getPA(); // Update current paList + } else { + throw ke; + } + } + } + } + + /** + * Performs AS-REQ send and AS-REP receive. + * Maybe a state is needed here, to divide prepare process and getCreds. + * @throws KrbException + * @throws Asn1Exception + * @throws IOException + */ + public KrbAsReqBuilder action() + throws KrbException, Asn1Exception, IOException { + checkState(State.INIT, "Cannot call action"); + state = State.REQ_OK; + return send().resolve(); + } + + /** + * Gets Credentials object after action + */ + public Credentials getCreds() { + checkState(State.REQ_OK, "Cannot retrieve creds"); + return rep.getCreds(); + } + + /** + * Gets another type of Credentials after action + */ + public sun.security.krb5.internal.ccache.Credentials getCCreds() { + checkState(State.REQ_OK, "Cannot retrieve CCreds"); + return rep.getCCreds(); + } + + /** + * Destroys the object and clears keys and password info. + */ + public void destroy() { + state = State.DESTROYED; + if (keys != null) { + for (EncryptionKey k: keys) { + k.destroy(); + } + keys = null; + } + if (password != null) { + Arrays.fill(password, (char)0); + password = null; + } + } + + /** + * Checks if the current state is the specified one. + * @param st the expected state + * @param msg error message if state is not correct + * @throws IllegalStateException if state is not correct + */ + private void checkState(State st, String msg) { + if (state != st) { + throw new IllegalStateException(msg + " at " + st + " state"); + } + } +} diff --git a/src/share/classes/sun/security/krb5/KrbTgsReq.java b/src/share/classes/sun/security/krb5/KrbTgsReq.java index 286018ce3284ee72147bd0d1edee2913e3d5c359..1021a7b10bde099b35109e2a06930ab0808db26f 100644 --- a/src/share/classes/sun/security/krb5/KrbTgsReq.java +++ b/src/share/classes/sun/security/krb5/KrbTgsReq.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -31,20 +31,16 @@ package sun.security.krb5; -import sun.security.util.*; -import sun.security.krb5.EncryptionKey; import sun.security.krb5.internal.*; import sun.security.krb5.internal.crypto.*; import java.io.IOException; import java.net.UnknownHostException; -import java.util.StringTokenizer; -import java.io.InterruptedIOException; /** * This class encapsulates a Kerberos TGS-REQ that is sent from the * client to the KDC. */ -public class KrbTgsReq extends KrbKdcReq { +public class KrbTgsReq { private PrincipalName princName; private PrincipalName servName; @@ -56,7 +52,8 @@ public class KrbTgsReq extends KrbKdcReq { private static final boolean DEBUG = Krb5.DEBUG; - private int defaultTimeout = 30*1000; // 30 seconds + private byte[] obuf; + private byte[] ibuf; // Used in CredentialsUtil public KrbTgsReq(Credentials asCreds, @@ -182,11 +179,12 @@ public class KrbTgsReq extends KrbKdcReq { * @throws KrbException * @throws IOException */ - public String send() throws IOException, KrbException { + public void send() throws IOException, KrbException { String realmStr = null; if (servName != null) realmStr = servName.getRealmString(); - return (send(realmStr)); + KdcComm comm = new KdcComm(realmStr); + ibuf = comm.send(obuf); } public KrbTgsRep getReply() @@ -201,18 +199,8 @@ public class KrbTgsReq extends KrbKdcReq { public Credentials sendAndGetCreds() throws IOException, KrbException { KrbTgsRep tgs_rep = null; String kdc = null; - try { - kdc = send(); - tgs_rep = getReply(); - } catch (KrbException ke) { - if (ke.returnCode() == Krb5.KRB_ERR_RESPONSE_TOO_BIG) { - // set useTCP and retry - send(servName.getRealmString(), kdc, true); - tgs_rep = getReply(); - } else { - throw ke; - } - } + send(); + tgs_rep = getReply(); return tgs_rep.getCreds(); } @@ -240,7 +228,7 @@ public class KrbTgsReq extends KrbKdcReq { UnknownHostException, KrbCryptoException { KerberosTime req_till = null; if (till == null) { - req_till = new KerberosTime(); + req_till = new KerberosTime(0); } else { req_till = till; } diff --git a/src/share/classes/sun/security/krb5/PrincipalName.java b/src/share/classes/sun/security/krb5/PrincipalName.java index 6e41b93d604065f6e844b053563d291c015dbf61..647f7199b3fd6b5f8d84ad1e58329a9285e3e2ce 100644 --- a/src/share/classes/sun/security/krb5/PrincipalName.java +++ b/src/share/classes/sun/security/krb5/PrincipalName.java @@ -511,10 +511,6 @@ public class PrincipalName return salt; } - public void setSalt(String salt) { - this.salt = salt; - } - public String toString() { StringBuffer str = new StringBuffer(); for (int i = 0; i < nameStrings.length; i++) { diff --git a/src/share/classes/sun/security/krb5/internal/KDCRep.java b/src/share/classes/sun/security/krb5/internal/KDCRep.java index fad96c8c4149468e86f3245d027581682b5aaf53..5ff8da2e3aae697e05ea9b1cac4170eb1cdc8d5a 100644 --- a/src/share/classes/sun/security/krb5/internal/KDCRep.java +++ b/src/share/classes/sun/security/krb5/internal/KDCRep.java @@ -32,7 +32,6 @@ package sun.security.krb5.internal; import sun.security.krb5.*; import sun.security.util.*; -import java.util.Vector; import java.io.IOException; import java.math.BigInteger; @@ -69,7 +68,7 @@ public class KDCRep { public EncKDCRepPart encKDCRepPart; //not part of ASN.1 encoding private int pvno; private int msgType; - private PAData[] pAData = null; //optional + public PAData[] pAData = null; //optional private boolean DEBUG = Krb5.DEBUG; public KDCRep( diff --git a/src/share/classes/sun/security/krb5/internal/KRBError.java b/src/share/classes/sun/security/krb5/internal/KRBError.java index 4bf1de79e94bfac9abbf9df4a0d46314e25345b5..ac8667f0686b3f48ae168de65e499e5e0887caff 100644 --- a/src/share/classes/sun/security/krb5/internal/KRBError.java +++ b/src/share/classes/sun/security/krb5/internal/KRBError.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -41,7 +41,9 @@ import sun.security.util.*; import java.io.IOException; import java.io.ObjectInputStream; import java.math.BigInteger; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import sun.security.krb5.internal.util.KerberosString; /** * Implements the ASN.1 KRBError type. @@ -96,10 +98,8 @@ public class KRBError implements java.io.Serializable { private byte[] eData; //optional private Checksum eCksum; //optional - // pre-auth info - private int etype = 0; - private String salt = null; - private byte[] s2kparams = null; + private PAData[] pa; // PA-DATA in eData + private int pa_eType; // The 1st etype appeared in salt-related PAData private static boolean DEBUG = Krb5.DEBUG; @@ -260,10 +260,12 @@ public class KRBError implements java.io.Serializable { private void parsePAData(byte[] data) throws IOException, Asn1Exception { DerValue derPA = new DerValue(data); + List paList = new ArrayList(); while (derPA.data.available() > 0) { // read the PA-DATA DerValue tmp = derPA.data.getDerValue(); PAData pa_data = new PAData(tmp); + paList.add(pa_data); int pa_type = pa_data.getType(); byte[] pa_value = pa_data.getValue(); if (DEBUG) { @@ -280,24 +282,13 @@ public class KRBError implements java.io.Serializable { case Krb5.PA_ETYPE_INFO: if (pa_value != null) { DerValue der = new DerValue(pa_value); - DerValue value = der.data.getDerValue(); - ETypeInfo info = new ETypeInfo(value); - etype = info.getEType(); - salt = info.getSalt(); - if (DEBUG) { - System.out.println("\t PA-ETYPE-INFO etype = " + etype); - System.out.println("\t PA-ETYPE-INFO salt = " + salt); - } while (der.data.available() > 0) { - value = der.data.getDerValue(); - info = new ETypeInfo(value); + DerValue value = der.data.getDerValue(); + ETypeInfo info = new ETypeInfo(value); + if (pa_eType == 0) pa_eType = info.getEType(); if (DEBUG) { - etype = info.getEType(); - System.out.println("\t salt for " + etype - + " is " + info.getSalt()); - } - if (salt == null || salt.isEmpty()) { - salt = info.getSalt(); + System.out.println("\t PA-ETYPE-INFO etype = " + info.getEType()); + System.out.println("\t PA-ETYPE-INFO salt = " + info.getSalt()); } } } @@ -305,25 +296,13 @@ public class KRBError implements java.io.Serializable { case Krb5.PA_ETYPE_INFO2: if (pa_value != null) { DerValue der = new DerValue(pa_value); - DerValue value = der.data.getDerValue(); - ETypeInfo2 info2 = new ETypeInfo2(value); - etype = info2.getEType(); - salt = info2.getSalt(); - s2kparams = info2.getParams(); - if (DEBUG) { - System.out.println("\t PA-ETYPE-INFO2 etype = " + etype); - System.out.println("\t PA-ETYPE-INFO salt = " + salt); - } while (der.data.available() > 0) { - value = der.data.getDerValue(); - info2 = new ETypeInfo2(value); + DerValue value = der.data.getDerValue(); + ETypeInfo2 info2 = new ETypeInfo2(value); + if (pa_eType == 0) pa_eType = info2.getEType(); if (DEBUG) { - etype = info2.getEType(); - System.out.println("\t salt for " + etype - + " is " + info2.getSalt()); - } - if (salt == null || salt.isEmpty()) { - salt = info2.getSalt(); + System.out.println("\t PA-ETYPE-INFO2 etype = " + info2.getEType()); + System.out.println("\t PA-ETYPE-INFO2 salt = " + info2.getSalt()); } } } @@ -333,6 +312,7 @@ public class KRBError implements java.io.Serializable { break; } } + pa = paList.toArray(new PAData[paList.size()]); } public final KerberosTime getServerTime() { @@ -356,18 +336,12 @@ public class KRBError implements java.io.Serializable { } // access pre-auth info - public final int getEType() { - return etype; - } - - // access pre-auth info - public final String getSalt() { - return salt; + public final PAData[] getPA() { + return pa; } - // access pre-auth info - public final byte[] getParams() { - return ((s2kparams == null) ? null : s2kparams.clone()); + public final int getEType() { + return pa_eType; } public final String getErrorString() { diff --git a/src/share/classes/sun/security/krb5/internal/KerberosTime.java b/src/share/classes/sun/security/krb5/internal/KerberosTime.java index 1e0cbeccb2deb8b931a26cc410abd6999c1a88ab..eae48e173ed6b295f07b32903341490719f19b97 100644 --- a/src/share/classes/sun/security/krb5/internal/KerberosTime.java +++ b/src/share/classes/sun/security/krb5/internal/KerberosTime.java @@ -77,11 +77,6 @@ public class KerberosTime implements Cloneable { public static final boolean NOW = true; public static final boolean UNADJUSTED_NOW = false; - //defaults to zero instead of now; use setNow() for current time - public KerberosTime() { - kerberosTime = 0; - } - public KerberosTime(long time) { kerberosTime = time; } diff --git a/src/share/classes/sun/security/krb5/internal/TCPClient.java b/src/share/classes/sun/security/krb5/internal/NetClient.java similarity index 66% rename from src/share/classes/sun/security/krb5/internal/TCPClient.java rename to src/share/classes/sun/security/krb5/internal/NetClient.java index 770871e7b6b2db97dd74d67c15395bf942963995..36e9a5c59c1b2767f60d724b068b78265d35b88e 100644 --- a/src/share/classes/sun/security/krb5/internal/TCPClient.java +++ b/src/share/classes/sun/security/krb5/internal/NetClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -34,18 +34,38 @@ package sun.security.krb5.internal; import java.io.*; import java.net.*; -public class TCPClient { +public abstract class NetClient { + public static NetClient getInstance(String protocol, String hostname, int port, + int timeout) throws IOException { + if (protocol.equals("TCP")) { + return new TCPClient(hostname, port, timeout); + } else { + return new UDPClient(hostname, port, timeout); + } + } + + abstract public void send(byte[] data) throws IOException; + + abstract public byte[] receive() throws IOException; + + abstract public void close() throws IOException; +} + +class TCPClient extends NetClient { private Socket tcpSocket; private BufferedOutputStream out; private BufferedInputStream in; - public TCPClient(String hostname, int port) throws IOException { + TCPClient(String hostname, int port, int timeout) + throws IOException { tcpSocket = new Socket(hostname, port); out = new BufferedOutputStream(tcpSocket.getOutputStream()); in = new BufferedInputStream(tcpSocket.getInputStream()); + tcpSocket.setSoTimeout(timeout); } + @Override public void send(byte[] data) throws IOException { byte[] lenField = new byte[4]; intToNetworkByteOrder(data.length, lenField, 0, 4); @@ -55,6 +75,7 @@ public class TCPClient { out.flush(); } + @Override public byte[] receive() throws IOException { byte[] lenField = new byte[4]; int count = readFully(lenField, 4); @@ -94,6 +115,7 @@ public class TCPClient { } } + @Override public void close() throws IOException { tcpSocket.close(); } @@ -120,7 +142,7 @@ public class TCPClient { /** * Returns the integer represented by 4 bytes in network byte order. */ - private static final int networkByteOrderToInt(byte[] buf, int start, + private static int networkByteOrderToInt(byte[] buf, int start, int count) { if (count > 4) { throw new IllegalArgumentException( @@ -140,7 +162,7 @@ public class TCPClient { * Encodes an integer into 4 bytes in network byte order in the buffer * supplied. */ - private static final void intToNetworkByteOrder(int num, byte[] buf, + private static void intToNetworkByteOrder(int num, byte[] buf, int start, int count) { if (count > 4) { throw new IllegalArgumentException( @@ -153,3 +175,47 @@ public class TCPClient { } } } + +class UDPClient extends NetClient { + InetAddress iaddr; + int iport; + int bufSize = 65507; + DatagramSocket dgSocket; + DatagramPacket dgPacketIn; + + UDPClient(String hostname, int port, int timeout) + throws UnknownHostException, SocketException { + iaddr = InetAddress.getByName(hostname); + iport = port; + dgSocket = new DatagramSocket(); + dgSocket.setSoTimeout(timeout); + } + + @Override + public void send(byte[] data) throws IOException { + DatagramPacket dgPacketOut = new DatagramPacket(data, data.length, + iaddr, iport); + dgSocket.send(dgPacketOut); + } + + @Override + public byte[] receive() throws IOException { + byte ibuf[] = new byte[bufSize]; + dgPacketIn = new DatagramPacket(ibuf, ibuf.length); + try { + dgSocket.receive(dgPacketIn); + } + catch (SocketException e) { + dgSocket.receive(dgPacketIn); + } + byte[] data = new byte[dgPacketIn.getLength()]; + System.arraycopy(dgPacketIn.getData(), 0, data, 0, + dgPacketIn.getLength()); + return data; + } + + @Override + public void close() { + dgSocket.close(); + } +} diff --git a/src/share/classes/sun/security/krb5/internal/PAData.java b/src/share/classes/sun/security/krb5/internal/PAData.java index b5f95f1ceeaf745a17b9df7c69bc10eca795c426..d32bbc47ee5b834f894ecce4cd37064dc9976971 100644 --- a/src/share/classes/sun/security/krb5/internal/PAData.java +++ b/src/share/classes/sun/security/krb5/internal/PAData.java @@ -30,9 +30,11 @@ package sun.security.krb5.internal; +import sun.security.krb5.KrbException; import sun.security.util.*; import sun.security.krb5.Asn1Exception; import java.io.IOException; +import sun.security.krb5.internal.util.KerberosString; /** * Implements the ASN.1 PA-DATA type. @@ -135,4 +137,75 @@ public class PAData { public byte[] getValue() { return ((pADataValue == null) ? null : pADataValue.clone()); } + + /** + * A place to store a pair of salt and s2kparams. + * An empty salt is changed to null, to be interopable + * with Windows 2000 server. + */ + public static class SaltAndParams { + public final String salt; + public final byte[] params; + public SaltAndParams(String s, byte[] p) { + if (s != null && s.isEmpty()) s = null; + this.salt = s; + this.params = p; + } + } + + /** + * Fetches salt and s2kparams value for eType in a series of PA-DATAs. + * The preference order is PA-ETYPE-INFO2 > PA-ETYPE-INFO > PA-PW-SALT. + * If multiple PA-DATA for the same etype appears, use the last one. + * (This is useful when PA-DATAs from KRB-ERROR and AS-REP are combined). + * @return salt and s2kparams. never null, its field might be null. + */ + public static SaltAndParams getSaltAndParams(int eType, PAData[] pas) + throws Asn1Exception, KrbException { + + if (pas == null || pas.length == 0) { + return new SaltAndParams(null, null); + } + + String paPwSalt = null; + ETypeInfo2 info2 = null; + ETypeInfo info = null; + + for (PAData p: pas) { + if (p.getValue() != null) { + try { + switch (p.getType()) { + case Krb5.PA_PW_SALT: + paPwSalt = new String(p.getValue(), + KerberosString.MSNAME?"UTF8":"8859_1"); + break; + case Krb5.PA_ETYPE_INFO: + DerValue der = new DerValue(p.getValue()); + while (der.data.available() > 0) { + DerValue value = der.data.getDerValue(); + ETypeInfo tmp = new ETypeInfo(value); + if (tmp.getEType() == eType) info = tmp; + } + break; + case Krb5.PA_ETYPE_INFO2: + der = new DerValue(p.getValue()); + while (der.data.available() > 0) { + DerValue value = der.data.getDerValue(); + ETypeInfo2 tmp = new ETypeInfo2(value); + if (tmp.getEType() == eType) info2 = tmp; + } + break; + } + } catch (IOException ioe) { + // Ignored + } + } + } + if (info2 != null) { + return new SaltAndParams(info2.getSalt(), info2.getParams()); + } else if (info != null) { + return new SaltAndParams(info.getSalt(), null); + } + return new SaltAndParams(paPwSalt, null); + } } diff --git a/src/share/classes/sun/security/krb5/internal/UDPClient.java b/src/share/classes/sun/security/krb5/internal/UDPClient.java deleted file mode 100644 index 59b53edfcd9cecc6129a81de1716ad95c67f2a84..0000000000000000000000000000000000000000 --- a/src/share/classes/sun/security/krb5/internal/UDPClient.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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. - */ - -/* - * - * (C) Copyright IBM Corp. 1999 All Rights Reserved. - * Copyright 1997 The Open Group Research Institute. All rights reserved. - */ - -package sun.security.krb5.internal; - -import java.io.*; -import java.net.*; - -public class UDPClient { - InetAddress iaddr; - int iport; - int bufSize = 65507; - DatagramSocket dgSocket; - DatagramPacket dgPacketIn; - - public UDPClient(InetAddress newIAddr, int port) - throws SocketException { - iaddr = newIAddr; - iport = port; - dgSocket = new DatagramSocket(); - } - - public UDPClient(String hostname, int port) - throws UnknownHostException, SocketException { - iaddr = InetAddress.getByName(hostname); - iport = port; - dgSocket = new DatagramSocket(); - } - - public UDPClient(String hostname, int port, int timeout) - throws UnknownHostException, SocketException { - iaddr = InetAddress.getByName(hostname); - iport = port; - dgSocket = new DatagramSocket(); - dgSocket.setSoTimeout(timeout); - } - - public void setBufSize(int newBufSize) { - bufSize = newBufSize; - } - - public InetAddress getInetAddress() { - if (dgPacketIn != null) - return dgPacketIn.getAddress(); - return null; - } - - public void send(byte[] data) throws IOException { - DatagramPacket dgPacketOut = new DatagramPacket(data, data.length, - iaddr, iport); - dgSocket.send(dgPacketOut); - } - - public byte[] receive() throws IOException { - byte ibuf[] = new byte[bufSize]; - dgPacketIn = new DatagramPacket(ibuf, ibuf.length); - try { - dgSocket.receive(dgPacketIn); - } - catch (SocketException e) { - dgSocket.receive(dgPacketIn); - } - byte[] data = new byte[dgPacketIn.getLength()]; - System.arraycopy(dgPacketIn.getData(), 0, data, 0, - dgPacketIn.getLength()); - return data; - } - - public void close() { - dgSocket.close(); - } -} diff --git a/src/share/classes/sun/security/pkcs11/SunPKCS11.java b/src/share/classes/sun/security/pkcs11/SunPKCS11.java index 33691f87ef725f7c5a20788af6fc8b82f0d2e135..55843b95c583b319cebf8c3fafe4a00dcf451a3d 100644 --- a/src/share/classes/sun/security/pkcs11/SunPKCS11.java +++ b/src/share/classes/sun/security/pkcs11/SunPKCS11.java @@ -1123,7 +1123,7 @@ public final class SunPKCS11 extends AuthProvider { java.text.MessageFormat form = new java.text.MessageFormat (ResourcesMgr.getString - ("PKCS11 Token [providerName] Password: ")); + ("PKCS11.Token.providerName.Password.")); Object[] source = { getName() }; PasswordCallback pcall = new PasswordCallback(form.format(source), diff --git a/src/share/classes/sun/security/provider/PolicyFile.java b/src/share/classes/sun/security/provider/PolicyFile.java index 5e5598bde33002efdcbb838dd7d20d9cc343b2cf..739c375796f5cbb8b67c6b1f0027501959d82c4d 100644 --- a/src/share/classes/sun/security/provider/PolicyFile.java +++ b/src/share/classes/sun/security/provider/PolicyFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -653,7 +653,7 @@ public class PolicyFile extends java.security.Policy { } } catch (PolicyParser.ParsingException pe) { MessageFormat form = new MessageFormat(ResourcesMgr.getString - (POLICY + ": error parsing policy:\n\tmessage")); + (POLICY + ".error.parsing.policy.message")); Object[] source = {policy, pe.getLocalizedMessage()}; System.err.println(form.format(source)); if (debug != null) @@ -895,7 +895,7 @@ public class PolicyFile extends java.security.Policy { MessageFormat form = new MessageFormat (ResourcesMgr.getString (POLICY + - ": error adding Permission, perm:\n\tmessage")); + ".error.adding.Permission.perm.message")); Object[] source = {pe.permission, ite.getTargetException().toString()}; System.err.println(form.format(source)); @@ -903,7 +903,7 @@ public class PolicyFile extends java.security.Policy { MessageFormat form = new MessageFormat (ResourcesMgr.getString (POLICY + - ": error adding Permission, perm:\n\tmessage")); + ".error.adding.Permission.perm.message")); Object[] source = {pe.permission, e.toString()}; System.err.println(form.format(source)); @@ -915,7 +915,7 @@ public class PolicyFile extends java.security.Policy { } catch (Exception e) { MessageFormat form = new MessageFormat(ResourcesMgr.getString (POLICY - + ": error adding Entry:\n\tmessage")); + + ".error.adding.Entry.message")); Object[] source = {e.toString()}; System.err.println(form.format(source)); } @@ -1950,7 +1950,7 @@ public class PolicyFile extends java.security.Policy { if (colonIndex == -1) { MessageFormat form = new MessageFormat (ResourcesMgr.getString - ("alias name not provided (pe.name)")); + ("alias.name.not.provided.pe.name.")); Object[] source = {pe.name}; throw new Exception(form.format(source)); } @@ -1958,7 +1958,7 @@ public class PolicyFile extends java.security.Policy { if ((suffix = getDN(suffix, keystore)) == null) { MessageFormat form = new MessageFormat (ResourcesMgr.getString - ("unable to perform substitution on alias, suffix")); + ("unable.to.perform.substitution.on.alias.suffix")); Object[] source = {value.substring(colonIndex+1)}; throw new Exception(form.format(source)); } @@ -1968,7 +1968,7 @@ public class PolicyFile extends java.security.Policy { } else { MessageFormat form = new MessageFormat (ResourcesMgr.getString - ("substitution value, prefix, unsupported")); + ("substitution.value.prefix.unsupported")); Object[] source = {prefix}; throw new Exception(form.format(source)); } @@ -2127,18 +2127,18 @@ public class PolicyFile extends java.security.Policy { @Override public String toString(){ StringBuilder sb = new StringBuilder(); - sb.append(ResourcesMgr.getString("(")); + sb.append(ResourcesMgr.getString("LPARAM")); sb.append(getCodeSource()); sb.append("\n"); for (int j = 0; j < permissions.size(); j++) { Permission p = permissions.get(j); - sb.append(ResourcesMgr.getString(" ")); - sb.append(ResourcesMgr.getString(" ")); + sb.append(ResourcesMgr.getString("SPACE")); + sb.append(ResourcesMgr.getString("SPACE")); sb.append(p); - sb.append(ResourcesMgr.getString("\n")); + sb.append(ResourcesMgr.getString("NEWLINE")); } - sb.append(ResourcesMgr.getString(")")); - sb.append(ResourcesMgr.getString("\n")); + sb.append(ResourcesMgr.getString("RPARAM")); + sb.append(ResourcesMgr.getString("NEWLINE")); return sb.toString(); } } @@ -2195,7 +2195,7 @@ public class PolicyFile extends java.security.Policy { super(type); if (type == null) { throw new NullPointerException - (ResourcesMgr.getString("type can't be null")); + (ResourcesMgr.getString("type.can.t.be.null")); } this.type = type; this.name = name; diff --git a/src/share/classes/sun/security/provider/PolicyParser.java b/src/share/classes/sun/security/provider/PolicyParser.java index aae3f103d7a3dbeee3af33dac8a34bfa12920915..07956f4e33e14840d7e3c2d06d00209a0a962d2e 100644 --- a/src/share/classes/sun/security/provider/PolicyParser.java +++ b/src/share/classes/sun/security/provider/PolicyParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -219,8 +219,7 @@ public class PolicyParser { if (keyStoreUrlString == null && storePassURL != null) { throw new ParsingException(ResourcesMgr.getString - ("keystorePasswordURL can not be specified without also " + - "specifying keystore")); + ("keystorePasswordURL.can.not.be.specified.without.also.specifying.keystore")); } } @@ -357,7 +356,7 @@ public class PolicyParser { keyStoreType = match("quoted string"); } else { throw new ParsingException(st.lineno(), - ResourcesMgr.getString("expected keystore type")); + ResourcesMgr.getString("expected.keystore.type")); } // parse keystore provider @@ -370,7 +369,7 @@ public class PolicyParser { keyStoreProvider = match("quoted string"); } else { throw new ParsingException(st.lineno(), - ResourcesMgr.getString("expected keystore provider")); + ResourcesMgr.getString("expected.keystore.provider")); } } @@ -421,7 +420,7 @@ public class PolicyParser { throw new ParsingException( st.lineno(), ResourcesMgr.getString - ("multiple Codebase expressions")); + ("multiple.Codebase.expressions")); e.codeBase = match("quoted string"); peekAndMatch(","); } else if (peekAndMatch("SignedBy")) { @@ -429,7 +428,7 @@ public class PolicyParser { throw new ParsingException( st.lineno(), ResourcesMgr.getString( - "multiple SignedBy expressions")); + "multiple.SignedBy.expressions")); e.signedBy = match("quoted string"); // verify syntax of the aliases @@ -448,7 +447,7 @@ public class PolicyParser { throw new ParsingException( st.lineno(), ResourcesMgr.getString( - "SignedBy has empty alias")); + "SignedBy.has.empty.alias")); peekAndMatch(","); } else if (peekAndMatch("Principal")) { @@ -491,8 +490,7 @@ public class PolicyParser { throw new ParsingException (st.lineno(), ResourcesMgr.getString - ("can not specify Principal with a " + - "wildcard class without a wildcard name")); + ("can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name")); } } @@ -529,8 +527,7 @@ public class PolicyParser { } else { throw new ParsingException(st.lineno(), ResourcesMgr.getString( - "expected codeBase or SignedBy or " + - "Principal")); + "expected.codeBase.or.SignedBy.or.Principal")); } } @@ -554,7 +551,7 @@ public class PolicyParser { throw new ParsingException(st.lineno(), ResourcesMgr.getString( - "expected permission entry")); + "expected.permission.entry")); } } match("}"); @@ -727,12 +724,12 @@ public class PolicyParser { switch (lookahead) { case StreamTokenizer.TT_NUMBER: throw new ParsingException(st.lineno(), expect, - ResourcesMgr.getString("number ") + + ResourcesMgr.getString("number.") + String.valueOf(st.nval)); case StreamTokenizer.TT_EOF: MessageFormat form = new MessageFormat( ResourcesMgr.getString - ("expected [expect], read [end of file]")); + ("expected.expect.read.end.of.file.")); Object[] source = {expect}; throw new ParsingException(form.format(source)); case StreamTokenizer.TT_WORD: @@ -809,11 +806,11 @@ public class PolicyParser { switch (lookahead) { case StreamTokenizer.TT_NUMBER: throw new ParsingException(st.lineno(), ";", - ResourcesMgr.getString("number ") + + ResourcesMgr.getString("number.") + String.valueOf(st.nval)); case StreamTokenizer.TT_EOF: throw new ParsingException(ResourcesMgr.getString - ("expected [;], read [end of file]")); + ("expected.read.end.of.file.")); default: lookahead = st.nextToken(); } @@ -973,7 +970,7 @@ public class PolicyParser { public PrincipalEntry(String principalClass, String principalName) { if (principalClass == null || principalName == null) throw new NullPointerException(ResourcesMgr.getString( - "null principalClass or principalName")); + "null.principalClass.or.principalName")); this.principalClass = principalClass; this.principalName = principalName; } @@ -1199,7 +1196,7 @@ public class PolicyParser { public ParsingException(int line, String msg) { super("line " + line + ": " + msg); MessageFormat form = new MessageFormat - (ResourcesMgr.getString("line number: msg")); + (ResourcesMgr.getString("line.number.msg")); Object[] source = {new Integer(line), msg}; i18nMessage = form.format(source); } @@ -1208,7 +1205,7 @@ public class PolicyParser { super("line " + line + ": expected [" + expect + "], found [" + actual + "]"); MessageFormat form = new MessageFormat(ResourcesMgr.getString - ("line number: expected [expect], found [actual]")); + ("line.number.expected.expect.found.actual.")); Object[] source = {new Integer(line), expect, actual}; i18nMessage = form.format(source); } diff --git a/src/share/classes/sun/security/tools/JarSigner.java b/src/share/classes/sun/security/tools/JarSigner.java index 981b7fd531aa4e411827707d8d82cc03ac55d4d1..89b9c7e75d739af18b5393a5b892cc239032acd2 100644 --- a/src/share/classes/sun/security/tools/JarSigner.java +++ b/src/share/classes/sun/security/tools/JarSigner.java @@ -205,7 +205,7 @@ public class JarSigner { if (!(obj instanceof Provider)) { MessageFormat form = new MessageFormat(rb.getString - ("provName not a provider")); + ("provName.not.a.provider")); Object[] source = {provName}; throw new Exception(form.format(source)); } @@ -218,7 +218,7 @@ public class JarSigner { loadKeyStore(keystore, false); } catch (Exception e) { if ((keystore != null) || (storepass != null)) { - System.out.println(rb.getString("jarsigner error: ") + + System.out.println(rb.getString("jarsigner.error.") + e.getMessage()); System.exit(1); } @@ -264,7 +264,7 @@ public class JarSigner { signJar(jarfile, alias, args); } } catch (Exception e) { - System.out.println(rb.getString("jarsigner error: ") + e); + System.out.println(rb.getString("jarsigner.error.") + e); if (debug) { e.printStackTrace(); } @@ -420,7 +420,7 @@ public class JarSigner { } } else { System.err.println( - rb.getString("Illegal option: ") + flags); + rb.getString("Illegal.option.") + flags); usage(); } } @@ -430,15 +430,15 @@ public class JarSigner { if (verbose == null) showcerts = false; if (jarfile == null) { - System.err.println(rb.getString("Please specify jarfile name")); + System.err.println(rb.getString("Please.specify.jarfile.name")); usage(); } if (!verify && alias == null) { - System.err.println(rb.getString("Please specify alias name")); + System.err.println(rb.getString("Please.specify.alias.name")); usage(); } if (!verify && ckaliases.size() > 1) { - System.err.println(rb.getString("Only one alias can be specified")); + System.err.println(rb.getString("Only.one.alias.can.be.specified")); usage(); } @@ -471,30 +471,27 @@ public class JarSigner { if (token && !nullStream) { System.err.println(MessageFormat.format(rb.getString - ("-keystore must be NONE if -storetype is {0}"), storetype)); + (".keystore.must.be.NONE.if.storetype.is.{0}"), storetype)); usage(); } if (token && keypass != null) { System.err.println(MessageFormat.format(rb.getString - ("-keypass can not be specified " + - "if -storetype is {0}"), storetype)); + (".keypass.can.not.be.specified.if.storetype.is.{0}"), storetype)); usage(); } if (protectedPath) { if (storepass != null || keypass != null) { System.err.println(rb.getString - ("If -protected is specified, " + - "then -storepass and -keypass must not be specified")); + ("If.protected.is.specified.then.storepass.and.keypass.must.not.be.specified")); usage(); } } if (KeyStoreUtil.isWindowsKeyStore(storetype)) { if (storepass != null || keypass != null) { System.err.println(rb.getString - ("If keystore is not password protected, " + - "then -storepass and -keypass must not be specified")); + ("If.keystore.is.not.password.protected.then.storepass.and.keypass.must.not.be.specified")); usage(); } } @@ -508,94 +505,94 @@ public class JarSigner { } static void usageNoArg() { - System.out.println(rb.getString("Option lacks argument")); + System.out.println(rb.getString("Option.lacks.argument")); usage(); } static void usage() { System.out.println(); - System.out.println(rb.getString("Please type jarsigner -help for usage")); + System.out.println(rb.getString("Please.type.jarsigner.help.for.usage")); System.exit(1); } static void fullusage() { System.out.println(rb.getString - ("Usage: jarsigner [options] jar-file alias")); + ("Usage.jarsigner.options.jar.file.alias")); System.out.println(rb.getString - (" jarsigner -verify [options] jar-file [alias...]")); + (".jarsigner.verify.options.jar.file.alias.")); System.out.println(); System.out.println(rb.getString - ("[-keystore ] keystore location")); + (".keystore.url.keystore.location")); System.out.println(); System.out.println(rb.getString - ("[-storepass ] password for keystore integrity")); + (".storepass.password.password.for.keystore.integrity")); System.out.println(); System.out.println(rb.getString - ("[-storetype ] keystore type")); + (".storetype.type.keystore.type")); System.out.println(); System.out.println(rb.getString - ("[-keypass ] password for private key (if different)")); + (".keypass.password.password.for.private.key.if.different.")); System.out.println(); System.out.println(rb.getString - ("[-certchain ] name of alternative certchain file")); + (".certchain.file.name.of.alternative.certchain.file")); System.out.println(); System.out.println(rb.getString - ("[-sigfile ] name of .SF/.DSA file")); + (".sigfile.file.name.of.SF.DSA.file")); System.out.println(); System.out.println(rb.getString - ("[-signedjar ] name of signed JAR file")); + (".signedjar.file.name.of.signed.JAR.file")); System.out.println(); System.out.println(rb.getString - ("[-digestalg ] name of digest algorithm")); + (".digestalg.algorithm.name.of.digest.algorithm")); System.out.println(); System.out.println(rb.getString - ("[-sigalg ] name of signature algorithm")); + (".sigalg.algorithm.name.of.signature.algorithm")); System.out.println(); System.out.println(rb.getString - ("[-crl[:auto| ] include CRL in signed jar")); + (".crl.auto.file.include.CRL.in.signed.jar")); System.out.println(); System.out.println(rb.getString - ("[-verify] verify a signed JAR file")); + (".verify.verify.a.signed.JAR.file")); System.out.println(); System.out.println(rb.getString - ("[-verbose[:suboptions]] verbose output when signing/verifying.")); + (".verbose.suboptions.verbose.output.when.signing.verifying.")); System.out.println(rb.getString - (" suboptions can be all, grouped or summary")); + (".suboptions.can.be.all.grouped.or.summary")); System.out.println(); System.out.println(rb.getString - ("[-certs] display certificates when verbose and verifying")); + (".certs.display.certificates.when.verbose.and.verifying")); System.out.println(); System.out.println(rb.getString - ("[-tsa ] location of the Timestamping Authority")); + (".tsa.url.location.of.the.Timestamping.Authority")); System.out.println(); System.out.println(rb.getString - ("[-tsacert ] public key certificate for Timestamping Authority")); + (".tsacert.alias.public.key.certificate.for.Timestamping.Authority")); System.out.println(); System.out.println(rb.getString - ("[-altsigner ] class name of an alternative signing mechanism")); + (".altsigner.class.class.name.of.an.alternative.signing.mechanism")); System.out.println(); System.out.println(rb.getString - ("[-altsignerpath ] location of an alternative signing mechanism")); + (".altsignerpath.pathlist.location.of.an.alternative.signing.mechanism")); System.out.println(); System.out.println(rb.getString - ("[-internalsf] include the .SF file inside the signature block")); + (".internalsf.include.the.SF.file.inside.the.signature.block")); System.out.println(); System.out.println(rb.getString - ("[-sectionsonly] don't compute hash of entire manifest")); + (".sectionsonly.don.t.compute.hash.of.entire.manifest")); System.out.println(); System.out.println(rb.getString - ("[-protected] keystore has protected authentication path")); + (".protected.keystore.has.protected.authentication.path")); System.out.println(); System.out.println(rb.getString - ("[-providerName ] provider name")); + (".providerName.name.provider.name")); System.out.println(); System.out.println(rb.getString - ("[-providerClass name of cryptographic service provider's")); + (".providerClass.class.name.of.cryptographic.service.provider.s")); System.out.println(rb.getString - (" [-providerArg ]] ... master class file and constructor argument")); + (".providerArg.arg.master.class.file.and.constructor.argument")); System.out.println(); System.out.println(rb.getString - ("[-strict] treat warnings as errors")); + (".strict.treat.warnings.as.errors")); System.out.println(); System.exit(0); @@ -644,7 +641,7 @@ public class JarSigner { Enumeration e = entriesVec.elements(); long now = System.currentTimeMillis(); - String tab = rb.getString(" "); + String tab = rb.getString("6SPACE"); while (e.hasMoreElements()) { JarEntry je = e.nextElement(); @@ -672,12 +669,12 @@ public class JarSigner { (man.getAttributes("./"+name) != null) || (man.getAttributes("/"+name) != null)); sb.append( - (isSigned ? rb.getString("s") : rb.getString(" ")) + - (inManifest ? rb.getString("m") : rb.getString(" ")) + - (inStore ? rb.getString("k") : rb.getString(" ")) + - (inScope ? rb.getString("i") : rb.getString(" ")) + + (isSigned ? rb.getString("s") : rb.getString("SPACE")) + + (inManifest ? rb.getString("m") : rb.getString("SPACE")) + + (inStore ? rb.getString("k") : rb.getString("SPACE")) + + (inScope ? rb.getString("i") : rb.getString("SPACE")) + ((inStoreOrScope & NOT_ALIAS) != 0 ?"X":" ") + - rb.getString(" ")); + rb.getString("SPACE")); sb.append("|"); } @@ -701,7 +698,7 @@ public class JarSigner { if (crl instanceof X509CRLImpl) { sb.append(tab).append("["); sb.append(String.format( - rb.getString("with a CRL including %d entries"), + rb.getString("with.a.CRL.including.d.entries"), ((X509CRLImpl)crl).getRevokedCertificates().size())) .append("]\n"); } @@ -714,10 +711,10 @@ public class JarSigner { // to be consistent with old behavior. if (signatureRelated(name)) { sb.append("\n" + tab + rb.getString( - "(Signature related entries)") + "\n\n"); + ".Signature.related.entries.") + "\n\n"); } else { sb.append("\n" + tab + rb.getString( - "(Unsigned entries)") + "\n\n"); + ".Unsigned.entries.") + "\n\n"); } } @@ -773,7 +770,7 @@ public class JarSigner { if (files.size() > 1) { System.out.println(files.get(0) + " " + String.format(rb.getString( - "(and %d more)"), files.size()-1)); + ".and.d.more."), files.size()-1)); } else { System.out.println(files.get(0)); } @@ -783,89 +780,89 @@ public class JarSigner { } System.out.println(); System.out.println(rb.getString( - " s = signature was verified ")); + ".s.signature.was.verified.")); System.out.println(rb.getString( - " m = entry is listed in manifest")); + ".m.entry.is.listed.in.manifest")); System.out.println(rb.getString( - " k = at least one certificate was found in keystore")); + ".k.at.least.one.certificate.was.found.in.keystore")); System.out.println(rb.getString( - " i = at least one certificate was found in identity scope")); + ".i.at.least.one.certificate.was.found.in.identity.scope")); if (ckaliases.size() > 0) { - System.out.println(( - " X = not signed by specified alias(es)")); + System.out.println(rb.getString( + ".X.not.signed.by.specified.alias.es.")); } System.out.println(); } if (man == null) - System.out.println(rb.getString("no manifest.")); + System.out.println(rb.getString("no.manifest.")); if (!anySigned) { System.out.println(rb.getString( - "jar is unsigned. (signatures missing or not parsable)")); + "jar.is.unsigned.signatures.missing.or.not.parsable.")); } else { - System.out.println(rb.getString("jar verified.")); + System.out.println(rb.getString("jar.verified.")); if (hasUnsignedEntry || hasExpiredCert || hasExpiringCert || badKeyUsage || badExtendedKeyUsage || badNetscapeCertType || notYetValidCert || chainNotValidated || aliasNotInStore || notSignedByAlias) { System.out.println(); - System.out.println(rb.getString("Warning: ")); + System.out.println(rb.getString("Warning.")); if (badKeyUsage) { System.out.println( - rb.getString("This jar contains entries whose signer certificate's KeyUsage extension doesn't allow code signing.")); + rb.getString("This.jar.contains.entries.whose.signer.certificate.s.KeyUsage.extension.doesn.t.allow.code.signing.")); } if (badExtendedKeyUsage) { System.out.println( - rb.getString("This jar contains entries whose signer certificate's ExtendedKeyUsage extension doesn't allow code signing.")); + rb.getString("This.jar.contains.entries.whose.signer.certificate.s.ExtendedKeyUsage.extension.doesn.t.allow.code.signing.")); } if (badNetscapeCertType) { System.out.println( - rb.getString("This jar contains entries whose signer certificate's NetscapeCertType extension doesn't allow code signing.")); + rb.getString("This.jar.contains.entries.whose.signer.certificate.s.NetscapeCertType.extension.doesn.t.allow.code.signing.")); } if (hasUnsignedEntry) { System.out.println(rb.getString( - "This jar contains unsigned entries which have not been integrity-checked. ")); + "This.jar.contains.unsigned.entries.which.have.not.been.integrity.checked.")); } if (hasExpiredCert) { System.out.println(rb.getString( - "This jar contains entries whose signer certificate has expired. ")); + "This.jar.contains.entries.whose.signer.certificate.has.expired.")); } if (hasExpiringCert) { System.out.println(rb.getString( - "This jar contains entries whose signer certificate will expire within six months. ")); + "This.jar.contains.entries.whose.signer.certificate.will.expire.within.six.months.")); } if (notYetValidCert) { System.out.println(rb.getString( - "This jar contains entries whose signer certificate is not yet valid. ")); + "This.jar.contains.entries.whose.signer.certificate.is.not.yet.valid.")); } if (chainNotValidated) { System.out.println( - rb.getString("This jar contains entries whose certificate chain is not validated.")); + rb.getString("This.jar.contains.entries.whose.certificate.chain.is.not.validated.")); } if (notSignedByAlias) { System.out.println( - rb.getString("This jar contains signed entries which is not signed by the specified alias(es).")); + rb.getString("This.jar.contains.signed.entries.which.is.not.signed.by.the.specified.alias.es.")); } if (aliasNotInStore) { - System.out.println(rb.getString("This jar contains signed entries that's not signed by alias in this keystore.")); + System.out.println(rb.getString("This.jar.contains.signed.entries.that.s.not.signed.by.alias.in.this.keystore.")); } if (! (verbose != null && showcerts)) { System.out.println(); System.out.println(rb.getString( - "Re-run with the -verbose and -certs options for more details.")); + "Re.run.with.the.verbose.and.certs.options.for.more.details.")); } } } return; } catch (Exception e) { - System.out.println(rb.getString("jarsigner: ") + e); + System.out.println(rb.getString("jarsigner.") + e); if (debug) { e.printStackTrace(); } @@ -895,13 +892,13 @@ public class JarSigner { long now) { StringBuilder certStr = new StringBuilder(); - String space = rb.getString(" "); + String space = rb.getString("SPACE"); X509Certificate x509Cert = null; if (c instanceof X509Certificate) { x509Cert = (X509Certificate) c; certStr.append(tab).append(x509Cert.getType()) - .append(rb.getString(", ")) + .append(rb.getString("COMMA")) .append(x509Cert.getSubjectDN().getName()); } else { certStr.append(tab).append(c.getType()); @@ -927,7 +924,7 @@ public class JarSigner { if (expiringTimeForm == null) { expiringTimeForm = new MessageFormat( - rb.getString("certificate will expire on")); + rb.getString("certificate.will.expire.on")); } Object[] source = { notAfter }; certStr.append(expiringTimeForm.format(source)); @@ -935,7 +932,7 @@ public class JarSigner { } else { if (validityTimeForm == null) { validityTimeForm = new MessageFormat( - rb.getString("certificate is valid from")); + rb.getString("certificate.is.valid.from")); } Object[] source = { x509Cert.getNotBefore(), notAfter }; certStr.append(validityTimeForm.format(source)); @@ -945,7 +942,7 @@ public class JarSigner { if (expiredTimeForm == null) { expiredTimeForm = new MessageFormat( - rb.getString("certificate expired on")); + rb.getString("certificate.expired.on")); } Object[] source = { notAfter }; certStr.append(expiredTimeForm.format(source)); @@ -955,7 +952,7 @@ public class JarSigner { if (notYetTimeForm == null) { notYetTimeForm = new MessageFormat( - rb.getString("certificate is not valid until")); + rb.getString("certificate.is.not.valid.until")); } Object[] source = { x509Cert.getNotBefore() }; certStr.append(notYetTimeForm.format(source)); @@ -979,7 +976,7 @@ public class JarSigner { } certStr.append("\n").append(tab) .append(MessageFormat.format(rb.getString( - "[{0} extension does not support code signing]"), x)); + ".{0}.extension.does.not.support.code.signing."), x)); } } return certStr.toString(); @@ -991,7 +988,7 @@ public class JarSigner { if (signTimeForm == null) { signTimeForm = - new MessageFormat(rb.getString("entry was signed on")); + new MessageFormat(rb.getString("entry.was.signed.on")); } Object[] source = { timestamp.getTimestamp() }; @@ -1093,7 +1090,7 @@ public class JarSigner { } else { throw new RuntimeException(rb.getString - ("signature filename must consist of the following characters: A-Z, 0-9, _ or -")); + ("signature.filename.must.consist.of.the.following.characters.A.Z.0.9.or.")); } } tmpSigFile.append(c); @@ -1112,14 +1109,14 @@ public class JarSigner { try { zipFile = new ZipFile(jarName); } catch (IOException ioe) { - error(rb.getString("unable to open jar file: ")+jarName, ioe); + error(rb.getString("unable.to.open.jar.file.")+jarName, ioe); } FileOutputStream fos = null; try { fos = new FileOutputStream(signedJarFile); } catch (IOException ioe) { - error(rb.getString("unable to create: ")+tmpJarName, ioe); + error(rb.getString("unable.to.create.")+tmpJarName, ioe); } PrintStream ps = new PrintStream(fos); @@ -1263,10 +1260,10 @@ public class JarSigner { } if (verbose != null) { if (mfCreated) { - System.out.println(rb.getString(" adding: ") + + System.out.println(rb.getString(".adding.") + mfFile.getName()); } else if (mfModified) { - System.out.println(rb.getString(" updating: ") + + System.out.println(rb.getString(".updating.") + mfFile.getName()); } } @@ -1291,10 +1288,10 @@ public class JarSigner { zipFile); } catch (SocketTimeoutException e) { // Provide a helpful message when TSA is beyond a firewall - error(rb.getString("unable to sign jar: ") + - rb.getString("no response from the Timestamping Authority. ") + - rb.getString("When connecting from behind a firewall then an HTTP proxy may need to be specified. ") + - rb.getString("Supply the following options to jarsigner: ") + + error(rb.getString("unable.to.sign.jar.") + + rb.getString("no.response.from.the.Timestamping.Authority.") + + rb.getString("When.connecting.from.behind.a.firewall.then.an.HTTP.proxy.may.need.to.be.specified.") + + rb.getString("Supply.the.following.options.to.jarsigner.") + "\n -J-Dhttp.proxyHost= " + "\n -J-Dhttp.proxyPort= ", e); } @@ -1314,10 +1311,10 @@ public class JarSigner { sf.write(zos); if (verbose != null) { if (zipFile.getEntry(sfFilename) != null) { - System.out.println(rb.getString(" updating: ") + + System.out.println(rb.getString(".updating.") + sfFilename); } else { - System.out.println(rb.getString(" adding: ") + + System.out.println(rb.getString(".adding.") + sfFilename); } } @@ -1325,24 +1322,24 @@ public class JarSigner { if (verbose != null) { if (tsaUrl != null || tsaCert != null) { System.out.println( - rb.getString("requesting a signature timestamp")); + rb.getString("requesting.a.signature.timestamp")); } if (tsaUrl != null) { - System.out.println(rb.getString("TSA location: ") + tsaUrl); + System.out.println(rb.getString("TSA.location.") + tsaUrl); } if (tsaCert != null) { String certUrl = TimestampedSigner.getTimestampingUrl(tsaCert); if (certUrl != null) { - System.out.println(rb.getString("TSA location: ") + + System.out.println(rb.getString("TSA.location.") + certUrl); } - System.out.println(rb.getString("TSA certificate: ") + + System.out.println(rb.getString("TSA.certificate.") + printCert("", tsaCert, false, 0)); } if (signingMechanism != null) { System.out.println( - rb.getString("using an alternative signing mechanism")); + rb.getString("using.an.alternative.signing.mechanism")); } } @@ -1351,10 +1348,10 @@ public class JarSigner { block.write(zos); if (verbose != null) { if (zipFile.getEntry(bkFilename) != null) { - System.out.println(rb.getString(" updating: ") + + System.out.println(rb.getString(".updating.") + bkFilename); } else { - System.out.println(rb.getString(" adding: ") + + System.out.println(rb.getString(".adding.") + bkFilename); } } @@ -1378,17 +1375,17 @@ public class JarSigner { if (!ze.getName().startsWith(META_INF)) { if (verbose != null) { if (manifest.getAttributes(ze.getName()) != null) - System.out.println(rb.getString(" signing: ") + + System.out.println(rb.getString(".signing.") + ze.getName()); else - System.out.println(rb.getString(" adding: ") + + System.out.println(rb.getString(".adding.") + ze.getName()); } writeEntry(zipFile, zos, ze); } } } catch(IOException ioe) { - error(rb.getString("unable to sign jar: ")+ioe, ioe); + error(rb.getString("unable.to.sign.jar.")+ioe, ioe); } finally { // close the resouces if (zipFile != null) { @@ -1416,13 +1413,13 @@ public class JarSigner { origJar.delete(); } else { MessageFormat form = new MessageFormat(rb.getString - ("attempt to rename signedJarFile to jarFile failed")); + ("attempt.to.rename.signedJarFile.to.jarFile.failed")); Object[] source = {signedJarFile, jarFile}; error(form.format(source)); } } else { MessageFormat form = new MessageFormat(rb.getString - ("attempt to rename jarFile to origJar failed")); + ("attempt.to.rename.jarFile.to.origJar.failed")); Object[] source = {jarFile, origJar}; error(form.format(source)); } @@ -1434,43 +1431,43 @@ public class JarSigner { || badNetscapeCertType || chainNotValidated) { System.out.println(); - System.out.println(rb.getString("Warning: ")); + System.out.println(rb.getString("Warning.")); if (badKeyUsage) { System.out.println( - rb.getString("The signer certificate's KeyUsage extension doesn't allow code signing.")); + rb.getString("The.signer.certificate.s.KeyUsage.extension.doesn.t.allow.code.signing.")); } if (badExtendedKeyUsage) { System.out.println( - rb.getString("The signer certificate's ExtendedKeyUsage extension doesn't allow code signing.")); + rb.getString("The.signer.certificate.s.ExtendedKeyUsage.extension.doesn.t.allow.code.signing.")); } if (badNetscapeCertType) { System.out.println( - rb.getString("The signer certificate's NetscapeCertType extension doesn't allow code signing.")); + rb.getString("The.signer.certificate.s.NetscapeCertType.extension.doesn.t.allow.code.signing.")); } if (hasExpiredCert) { System.out.println( - rb.getString("The signer certificate has expired.")); + rb.getString("The.signer.certificate.has.expired.")); } else if (hasExpiringCert) { System.out.println( - rb.getString("The signer certificate will expire within six months.")); + rb.getString("The.signer.certificate.will.expire.within.six.months.")); } else if (notYetValidCert) { System.out.println( - rb.getString("The signer certificate is not yet valid.")); + rb.getString("The.signer.certificate.is.not.yet.valid.")); } if (chainNotValidated) { System.out.println( - rb.getString("The signer's certificate chain is not validated.")); + rb.getString("The.signer.s.certificate.chain.is.not.validated.")); } } // no IOException thrown in the above try clause, so disable // the catch clause. // } catch(IOException ioe) { - // error(rb.getString("unable to sign jar: ")+ioe, ioe); + // error(rb.getString("unable.to.sign.jar.")+ioe, ioe); // } } @@ -1557,7 +1554,7 @@ public class JarSigner { validator.validate(cp, pkixParameters); } catch (Exception e) { chainNotValidated = true; - s.append(tab + rb.getString("[CertPath not validated: ") + + s.append(tab + rb.getString(".CertPath.not.validated.") + e.getLocalizedMessage() + "]\n"); // TODO } String result = s.toString(); @@ -1624,10 +1621,10 @@ public class JarSigner { if (token && storepass == null && !protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype)) { storepass = getPass - (rb.getString("Enter Passphrase for keystore: ")); + (rb.getString("Enter.Passphrase.for.keystore.")); } else if (!token && storepass == null && prompt) { storepass = getPass - (rb.getString("Enter Passphrase for keystore: ")); + (rb.getString("Enter.Passphrase.for.keystore.")); } if (nullStream) { @@ -1694,20 +1691,20 @@ public class JarSigner { // Only if tas is empty } } catch (IOException ioe) { - throw new RuntimeException(rb.getString("keystore load: ") + + throw new RuntimeException(rb.getString("keystore.load.") + ioe.getMessage()); } catch (java.security.cert.CertificateException ce) { - throw new RuntimeException(rb.getString("certificate exception: ") + + throw new RuntimeException(rb.getString("certificate.exception.") + ce.getMessage()); } catch (NoSuchProviderException pe) { - throw new RuntimeException(rb.getString("keystore load: ") + + throw new RuntimeException(rb.getString("keystore.load.") + pe.getMessage()); } catch (NoSuchAlgorithmException nsae) { - throw new RuntimeException(rb.getString("keystore load: ") + + throw new RuntimeException(rb.getString("keystore.load.") + nsae.getMessage()); } catch (KeyStoreException kse) { throw new RuntimeException - (rb.getString("unable to instantiate keystore class: ") + + (rb.getString("unable.to.instantiate.keystore.class.") + kse.getMessage()); } } @@ -1723,7 +1720,7 @@ public class JarSigner { } if (cs == null || (!(cs instanceof X509Certificate))) { MessageFormat form = new MessageFormat(rb.getString - ("Certificate not found for: alias. alias must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority.")); + ("Certificate.not.found.for.alias.alias.must.reference.a.valid.KeyStore.entry.containing.an.X.509.public.key.certificate.for.the")); Object[] source = {alias, alias}; error(form.format(source)); } @@ -1816,9 +1813,9 @@ public class JarSigner { generateCertificates(new FileInputStream(altCertChain)). toArray(new Certificate[0]); } catch (CertificateException ex) { - error(rb.getString("Cannot restore certchain from file specified")); + error(rb.getString("Cannot.restore.certchain.from.file.specified")); } catch (FileNotFoundException ex) { - error(rb.getString("File specified by -certchain does not exist")); + error(rb.getString("File.specified.by.certchain.does.not.exist")); } } else { try { @@ -1830,12 +1827,10 @@ public class JarSigner { if (cs == null || cs.length == 0) { if (altCertChain != null) { error(rb.getString - ("Certificate chain not found in the file specified.")); + ("Certificate.chain.not.found.in.the.file.specified.")); } else { MessageFormat form = new MessageFormat(rb.getString - ("Certificate chain not found for: alias. alias must" + - " reference a valid KeyStore key entry containing a" + - " private key and corresponding public key certificate chain.")); + ("Certificate.chain.not.found.for.alias.alias.must.reference.a.valid.KeyStore.key.entry.containing.a.private.key.and")); Object[] source = {alias, alias}; error(form.format(source)); } @@ -1845,7 +1840,7 @@ public class JarSigner { for (int i=0; i] keystore location", + {".keystore.url.keystore.location", "[-keystore ] keystore location"}, - {"[-storepass ] password for keystore integrity", + {".storepass.password.password.for.keystore.integrity", "[-storepass ] password for keystore integrity"}, - {"[-storetype ] keystore type", + {".storetype.type.keystore.type", "[-storetype ] keystore type"}, - {"[-keypass ] password for private key (if different)", + {".keypass.password.password.for.private.key.if.different.", "[-keypass ] password for private key (if different)"}, - {"[-certchain ] name of alternative certchain file", + {".certchain.file.name.of.alternative.certchain.file", "[-certchain ] name of alternative certchain file"}, - {"[-sigfile ] name of .SF/.DSA file", + {".sigfile.file.name.of.SF.DSA.file", "[-sigfile ] name of .SF/.DSA file"}, - {"[-signedjar ] name of signed JAR file", + {".signedjar.file.name.of.signed.JAR.file", "[-signedjar ] name of signed JAR file"}, - {"[-digestalg ] name of digest algorithm", + {".digestalg.algorithm.name.of.digest.algorithm", "[-digestalg ] name of digest algorithm"}, - {"[-sigalg ] name of signature algorithm", + {".sigalg.algorithm.name.of.signature.algorithm", "[-sigalg ] name of signature algorithm"}, - {"[-crl[:auto| ] include CRL in signed jar", + {".crl.auto.file.include.CRL.in.signed.jar", "[-crl[:auto| ] include CRL in signed jar"}, - {"[-verify] verify a signed JAR file", + {".verify.verify.a.signed.JAR.file", "[-verify] verify a signed JAR file"}, - {"[-verbose[:suboptions]] verbose output when signing/verifying.", + {".verbose.suboptions.verbose.output.when.signing.verifying.", "[-verbose[:suboptions]] verbose output when signing/verifying."}, - {" suboptions can be all, grouped or summary", + {".suboptions.can.be.all.grouped.or.summary", " suboptions can be all, grouped or summary"}, - {"[-certs] display certificates when verbose and verifying", + {".certs.display.certificates.when.verbose.and.verifying", "[-certs] display certificates when verbose and verifying"}, - {"[-tsa ] location of the Timestamping Authority", + {".tsa.url.location.of.the.Timestamping.Authority", "[-tsa ] location of the Timestamping Authority"}, - {"[-tsacert ] public key certificate for Timestamping Authority", + {".tsacert.alias.public.key.certificate.for.Timestamping.Authority", "[-tsacert ] public key certificate for Timestamping Authority"}, - {"[-altsigner ] class name of an alternative signing mechanism", + {".altsigner.class.class.name.of.an.alternative.signing.mechanism", "[-altsigner ] class name of an alternative signing mechanism"}, - {"[-altsignerpath ] location of an alternative signing mechanism", + {".altsignerpath.pathlist.location.of.an.alternative.signing.mechanism", "[-altsignerpath ] location of an alternative signing mechanism"}, - {"[-internalsf] include the .SF file inside the signature block", + {".internalsf.include.the.SF.file.inside.the.signature.block", "[-internalsf] include the .SF file inside the signature block"}, - {"[-sectionsonly] don't compute hash of entire manifest", + {".sectionsonly.don.t.compute.hash.of.entire.manifest", "[-sectionsonly] don't compute hash of entire manifest"}, - {"[-protected] keystore has protected authentication path", + {".protected.keystore.has.protected.authentication.path", "[-protected] keystore has protected authentication path"}, - {"[-providerName ] provider name", + {".providerName.name.provider.name", "[-providerName ] provider name"}, - {"[-providerClass name of cryptographic service provider's", + {".providerClass.class.name.of.cryptographic.service.provider.s", "[-providerClass name of cryptographic service provider's"}, - {" [-providerArg ]] ... master class file and constructor argument", + {".providerArg.arg.master.class.file.and.constructor.argument", " [-providerArg ]] ... master class file and constructor argument"}, - {"[-strict] treat warnings as errors", + {".strict.treat.warnings.as.errors", "[-strict] treat warnings as errors"}, - {"Option lacks argument", "Option lacks argument"}, - {"Please type jarsigner -help for usage", "Please type jarsigner -help for usage"}, - {"Please specify jarfile name", "Please specify jarfile name"}, - {"Please specify alias name", "Please specify alias name"}, - {"Only one alias can be specified", "Only one alias can be specified"}, - {"This jar contains signed entries which is not signed by the specified alias(es).", + {"Option.lacks.argument", "Option lacks argument"}, + {"Please.type.jarsigner.help.for.usage", "Please type jarsigner -help for usage"}, + {"Please.specify.jarfile.name", "Please specify jarfile name"}, + {"Please.specify.alias.name", "Please specify alias name"}, + {"Only.one.alias.can.be.specified", "Only one alias can be specified"}, + {"This.jar.contains.signed.entries.which.is.not.signed.by.the.specified.alias.es.", "This jar contains signed entries which is not signed by the specified alias(es)."}, - {"This jar contains signed entries that's not signed by alias in this keystore.", + {"This.jar.contains.signed.entries.that.s.not.signed.by.alias.in.this.keystore.", "This jar contains signed entries that's not signed by alias in this keystore."}, {"s", "s"}, {"m", "m"}, {"k", "k"}, {"i", "i"}, - {"(and %d more)", "(and %d more)"}, - {" s = signature was verified ", + {".and.d.more.", "(and %d more)"}, + {".s.signature.was.verified.", " s = signature was verified "}, - {" m = entry is listed in manifest", + {".m.entry.is.listed.in.manifest", " m = entry is listed in manifest"}, - {" k = at least one certificate was found in keystore", + {".k.at.least.one.certificate.was.found.in.keystore", " k = at least one certificate was found in keystore"}, - {" i = at least one certificate was found in identity scope", + {".i.at.least.one.certificate.was.found.in.identity.scope", " i = at least one certificate was found in identity scope"}, - {" X = not signed by specified alias(es)", + {".X.not.signed.by.specified.alias.es.", " X = not signed by specified alias(es)"}, - {"no manifest.", "no manifest."}, - {"(Signature related entries)","(Signature related entries)"}, - {"(Unsigned entries)", "(Unsigned entries)"}, - {"jar is unsigned. (signatures missing or not parsable)", + {"no.manifest.", "no manifest."}, + {".Signature.related.entries.","(Signature related entries)"}, + {".Unsigned.entries.", "(Unsigned entries)"}, + {"jar.is.unsigned.signatures.missing.or.not.parsable.", "jar is unsigned. (signatures missing or not parsable)"}, - {"jar verified.", "jar verified."}, - {"jarsigner: ", "jarsigner: "}, - {"signature filename must consist of the following characters: A-Z, 0-9, _ or -", + {"jar.verified.", "jar verified."}, + {"jarsigner.", "jarsigner: "}, + {"signature.filename.must.consist.of.the.following.characters.A.Z.0.9.or.", "signature filename must consist of the following characters: A-Z, 0-9, _ or -"}, - {"unable to open jar file: ", "unable to open jar file: "}, - {"unable to create: ", "unable to create: "}, - {" adding: ", " adding: "}, - {" updating: ", " updating: "}, - {" signing: ", " signing: "}, - {"attempt to rename signedJarFile to jarFile failed", + {"unable.to.open.jar.file.", "unable to open jar file: "}, + {"unable.to.create.", "unable to create: "}, + {".adding.", " adding: "}, + {".updating.", " updating: "}, + {".signing.", " signing: "}, + {"attempt.to.rename.signedJarFile.to.jarFile.failed", "attempt to rename {0} to {1} failed"}, - {"attempt to rename jarFile to origJar failed", + {"attempt.to.rename.jarFile.to.origJar.failed", "attempt to rename {0} to {1} failed"}, - {"unable to sign jar: ", "unable to sign jar: "}, - {"Enter Passphrase for keystore: ", "Enter Passphrase for keystore: "}, - {"keystore load: ", "keystore load: "}, - {"certificate exception: ", "certificate exception: "}, - {"unable to instantiate keystore class: ", + {"unable.to.sign.jar.", "unable to sign jar: "}, + {"Enter.Passphrase.for.keystore.", "Enter Passphrase for keystore: "}, + {"keystore.load.", "keystore load: "}, + {"certificate.exception.", "certificate exception: "}, + {"unable.to.instantiate.keystore.class.", "unable to instantiate keystore class: "}, - {"Certificate chain not found for: alias. alias must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain.", + {"Certificate.chain.not.found.for.alias.alias.must.reference.a.valid.KeyStore.key.entry.containing.a.private.key.and", "Certificate chain not found for: {0}. {1} must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain."}, - {"File specified by -certchain does not exist", + {"File.specified.by.certchain.does.not.exist", "File specified by -certchain does not exist"}, - {"Cannot restore certchain from file specified", + {"Cannot.restore.certchain.from.file.specified", "Cannot restore certchain from file specified"}, - {"Certificate chain not found in the file specified.", + {"Certificate.chain.not.found.in.the.file.specified.", "Certificate chain not found in the file specified."}, - {"found non-X.509 certificate in signer's chain", + {"found.non.X.509.certificate.in.signer.s.chain", "found non-X.509 certificate in signer's chain"}, - {"incomplete certificate chain", "incomplete certificate chain"}, - {"Enter key password for alias: ", "Enter key password for {0}: "}, - {"unable to recover key from keystore", + {"incomplete.certificate.chain", "incomplete certificate chain"}, + {"Enter.key.password.for.alias.", "Enter key password for {0}: "}, + {"unable.to.recover.key.from.keystore", "unable to recover key from keystore"}, - {"key associated with alias not a private key", + {"key.associated.with.alias.not.a.private.key", "key associated with {0} not a private key"}, - {"you must enter key password", "you must enter key password"}, - {"unable to read password: ", "unable to read password: "}, - {"certificate is valid from", "certificate is valid from {0} to {1}"}, - {"certificate expired on", "certificate expired on {0}"}, - {"certificate is not valid until", + {"you.must.enter.key.password", "you must enter key password"}, + {"unable.to.read.password.", "unable to read password: "}, + {"certificate.is.valid.from", "certificate is valid from {0} to {1}"}, + {"certificate.expired.on", "certificate expired on {0}"}, + {"certificate.is.not.valid.until", "certificate is not valid until {0}"}, - {"certificate will expire on", "certificate will expire on {0}"}, - {"[CertPath not validated: ", "[CertPath not validated: "}, - {"requesting a signature timestamp", + {"certificate.will.expire.on", "certificate will expire on {0}"}, + {".CertPath.not.validated.", "[CertPath not validated: "}, + {"requesting.a.signature.timestamp", "requesting a signature timestamp"}, - {"TSA location: ", "TSA location: "}, - {"TSA certificate: ", "TSA certificate: "}, - {"no response from the Timestamping Authority. ", + {"TSA.location.", "TSA location: "}, + {"TSA.certificate.", "TSA certificate: "}, + {"no.response.from.the.Timestamping.Authority.", "no response from the Timestamping Authority. "}, - {"When connecting from behind a firewall then an HTTP proxy may need to be specified. ", + {"When.connecting.from.behind.a.firewall.then.an.HTTP.proxy.may.need.to.be.specified.", "When connecting from behind a firewall then an HTTP proxy may need to be specified. "}, - {"Supply the following options to jarsigner: ", + {"Supply.the.following.options.to.jarsigner.", "Supply the following options to jarsigner: "}, - {"Certificate not found for: alias. alias must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority.", + {"Certificate.not.found.for.alias.alias.must.reference.a.valid.KeyStore.entry.containing.an.X.509.public.key.certificate.for.the", "Certificate not found for: {0}. {1} must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority."}, - {"using an alternative signing mechanism", + {"using.an.alternative.signing.mechanism", "using an alternative signing mechanism"}, - {"entry was signed on", "entry was signed on {0}"}, - {"with a CRL including %d entries", "with a CRL including %d entries"}, - {"Warning: ", "Warning: "}, - {"This jar contains unsigned entries which have not been integrity-checked. ", + {"entry.was.signed.on", "entry was signed on {0}"}, + {"with.a.CRL.including.d.entries", "with a CRL including %d entries"}, + {"Warning.", "Warning: "}, + {"This.jar.contains.unsigned.entries.which.have.not.been.integrity.checked.", "This jar contains unsigned entries which have not been integrity-checked. "}, - {"This jar contains entries whose signer certificate has expired. ", + {"This.jar.contains.entries.whose.signer.certificate.has.expired.", "This jar contains entries whose signer certificate has expired. "}, - {"This jar contains entries whose signer certificate will expire within six months. ", + {"This.jar.contains.entries.whose.signer.certificate.will.expire.within.six.months.", "This jar contains entries whose signer certificate will expire within six months. "}, - {"This jar contains entries whose signer certificate is not yet valid. ", + {"This.jar.contains.entries.whose.signer.certificate.is.not.yet.valid.", "This jar contains entries whose signer certificate is not yet valid. "}, - {"Re-run with the -verbose option for more details.", + {"Re.run.with.the.verbose.option.for.more.details.", "Re-run with the -verbose option for more details."}, - {"Re-run with the -verbose and -certs options for more details.", + {"Re.run.with.the.verbose.and.certs.options.for.more.details.", "Re-run with the -verbose and -certs options for more details."}, - {"The signer certificate has expired.", + {"The.signer.certificate.has.expired.", "The signer certificate has expired."}, - {"The signer certificate will expire within six months.", + {"The.signer.certificate.will.expire.within.six.months.", "The signer certificate will expire within six months."}, - {"The signer certificate is not yet valid.", + {"The.signer.certificate.is.not.yet.valid.", "The signer certificate is not yet valid."}, - {"The signer certificate's KeyUsage extension doesn't allow code signing.", + {"The.signer.certificate.s.KeyUsage.extension.doesn.t.allow.code.signing.", "The signer certificate's KeyUsage extension doesn't allow code signing."}, - {"The signer certificate's ExtendedKeyUsage extension doesn't allow code signing.", + {"The.signer.certificate.s.ExtendedKeyUsage.extension.doesn.t.allow.code.signing.", "The signer certificate's ExtendedKeyUsage extension doesn't allow code signing."}, - {"The signer certificate's NetscapeCertType extension doesn't allow code signing.", + {"The.signer.certificate.s.NetscapeCertType.extension.doesn.t.allow.code.signing.", "The signer certificate's NetscapeCertType extension doesn't allow code signing."}, - {"This jar contains entries whose signer certificate's KeyUsage extension doesn't allow code signing.", + {"This.jar.contains.entries.whose.signer.certificate.s.KeyUsage.extension.doesn.t.allow.code.signing.", "This jar contains entries whose signer certificate's KeyUsage extension doesn't allow code signing."}, - {"This jar contains entries whose signer certificate's ExtendedKeyUsage extension doesn't allow code signing.", + {"This.jar.contains.entries.whose.signer.certificate.s.ExtendedKeyUsage.extension.doesn.t.allow.code.signing.", "This jar contains entries whose signer certificate's ExtendedKeyUsage extension doesn't allow code signing."}, - {"This jar contains entries whose signer certificate's NetscapeCertType extension doesn't allow code signing.", + {"This.jar.contains.entries.whose.signer.certificate.s.NetscapeCertType.extension.doesn.t.allow.code.signing.", "This jar contains entries whose signer certificate's NetscapeCertType extension doesn't allow code signing."}, - {"[{0} extension does not support code signing]", + {".{0}.extension.does.not.support.code.signing.", "[{0} extension does not support code signing]"}, - {"The signer's certificate chain is not validated.", + {"The.signer.s.certificate.chain.is.not.validated.", "The signer's certificate chain is not validated."}, - {"This jar contains entries whose certificate chain is not validated.", + {"This.jar.contains.entries.whose.certificate.chain.is.not.validated.", "This jar contains entries whose certificate chain is not validated."}, }; diff --git a/src/share/classes/sun/security/tools/KeyTool.java b/src/share/classes/sun/security/tools/KeyTool.java index a3a102bfd47254e978952ec7eca1e7b2473dc772..5ce08316f357c22cf16ee6d26a07bb96054151f2 100644 --- a/src/share/classes/sun/security/tools/KeyTool.java +++ b/src/share/classes/sun/security/tools/KeyTool.java @@ -160,82 +160,82 @@ public final class KeyTool { private List v3ext = new ArrayList (); enum Command { - CERTREQ("Generates a certificate request", + CERTREQ("Generates.a.certificate.request", ALIAS, SIGALG, FILEOUT, KEYPASS, KEYSTORE, DNAME, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - CHANGEALIAS("Changes an entry's alias", + CHANGEALIAS("Changes.an.entry.s.alias", ALIAS, DESTALIAS, KEYPASS, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - DELETE("Deletes an entry", + DELETE("Deletes.an.entry", ALIAS, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - EXPORTCERT("Exports certificate", + EXPORTCERT("Exports.certificate", RFC, ALIAS, FILEOUT, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - GENKEYPAIR("Generates a key pair", + GENKEYPAIR("Generates.a.key.pair", ALIAS, KEYALG, KEYSIZE, SIGALG, DESTALIAS, DNAME, STARTDATE, EXT, VALIDITY, KEYPASS, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - GENSECKEY("Generates a secret key", + GENSECKEY("Generates.a.secret.key", ALIAS, KEYPASS, KEYALG, KEYSIZE, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - GENCERT("Generates certificate from a certificate request", + GENCERT("Generates.certificate.from.a.certificate.request", RFC, INFILE, OUTFILE, ALIAS, SIGALG, DNAME, STARTDATE, EXT, VALIDITY, KEYPASS, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - IMPORTCERT("Imports a certificate or a certificate chain", + IMPORTCERT("Imports.a.certificate.or.a.certificate.chain", NOPROMPT, TRUSTCACERTS, PROTECTED, ALIAS, FILEIN, KEYPASS, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V), - IMPORTKEYSTORE("Imports one or all entries from another keystore", + IMPORTKEYSTORE("Imports.one.or.all.entries.from.another.keystore", SRCKEYSTORE, DESTKEYSTORE, SRCSTORETYPE, DESTSTORETYPE, SRCSTOREPASS, DESTSTOREPASS, SRCPROTECTED, SRCPROVIDERNAME, DESTPROVIDERNAME, SRCALIAS, DESTALIAS, SRCKEYPASS, DESTKEYPASS, NOPROMPT, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V), - KEYPASSWD("Changes the key password of an entry", + KEYPASSWD("Changes.the.key.password.of.an.entry", ALIAS, KEYPASS, NEW, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V), - LIST("Lists entries in a keystore", + LIST("Lists.entries.in.a.keystore", RFC, ALIAS, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - PRINTCERT("Prints the content of a certificate", + PRINTCERT("Prints.the.content.of.a.certificate", RFC, FILEIN, SSLSERVER, JARFILE, V), - PRINTCERTREQ("Prints the content of a certificate request", + PRINTCERTREQ("Prints.the.content.of.a.certificate.request", FILEIN, V), - PRINTCRL("Prints the content of a CRL file", + PRINTCRL("Prints.the.content.of.a.CRL.file", FILEIN, V), - STOREPASSWD("Changes the store password of a keystore", + STOREPASSWD("Changes.the.store.password.of.a.keystore", NEW, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V), // Undocumented start here, KEYCLONE is used a marker in -help; - KEYCLONE("Clones a key entry", + KEYCLONE("Clones.a.key.entry", ALIAS, DESTALIAS, KEYPASS, NEW, STORETYPE, KEYSTORE, STOREPASS, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V), - SELFCERT("Generates a self-signed certificate", + SELFCERT("Generates.a.self.signed.certificate", ALIAS, SIGALG, DNAME, STARTDATE, VALIDITY, KEYPASS, STORETYPE, KEYSTORE, STOREPASS, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V), - GENCRL("Generates CRL", + GENCRL("Generates.CRL", RFC, FILEOUT, ID, ALIAS, SIGALG, EXT, KEYPASS, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V, PROTECTED), - IDENTITYDB("Imports entries from a JDK 1.1.x-style identity database", + IDENTITYDB("Imports.entries.from.a.JDK.1.1.x.style.identity.database", FILEIN, STORETYPE, KEYSTORE, STOREPASS, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V); @@ -252,49 +252,49 @@ public final class KeyTool { }; enum Option { - ALIAS("alias", "", "alias name of the entry to process"), - DESTALIAS("destalias", "", "destination alias"), - DESTKEYPASS("destkeypass", "", "destination key password"), - DESTKEYSTORE("destkeystore", "", "destination keystore name"), - DESTPROTECTED("destprotected", null, "destination keystore password protected"), - DESTPROVIDERNAME("destprovidername", "", "destination keystore provider name"), - DESTSTOREPASS("deststorepass", "", "destination keystore password"), - DESTSTORETYPE("deststoretype", "", "destination keystore type"), - DNAME("dname", "", "distinguished name"), - EXT("ext", "", "X.509 extension"), - FILEOUT("file", "", "output file name"), - FILEIN("file", "", "input file name"), - ID("id", "", "Serial ID of cert to revoke"), - INFILE("infile", "", "input file name"), - KEYALG("keyalg", "", "key algorithm name"), - KEYPASS("keypass", "", "key password"), - KEYSIZE("keysize", "", "key bit size"), - KEYSTORE("keystore", "", "keystore name"), - NEW("new", "", "new password"), - NOPROMPT("noprompt", null, "do not prompt"), - OUTFILE("outfile", "", "output file name"), - PROTECTED("protected", null, "password through protected mechanism"), - PROVIDERARG("providerarg", "", "provider argument"), - PROVIDERCLASS("providerclass", "", "provider class name"), - PROVIDERNAME("providername", "", "provider name"), - PROVIDERPATH("providerpath", "", "provider classpath"), - RFC("rfc", null, "output in RFC style"), - SIGALG("sigalg", "", "signature algorithm name"), - SRCALIAS("srcalias", "", "source alias"), - SRCKEYPASS("srckeypass", "", "source key password"), - SRCKEYSTORE("srckeystore", "", "source keystore name"), - SRCPROTECTED("srcprotected", null, "source keystore password protected"), - SRCPROVIDERNAME("srcprovidername", "", "source keystore provider name"), - SRCSTOREPASS("srcstorepass", "", "source keystore password"), - SRCSTORETYPE("srcstoretype", "", "source keystore type"), - SSLSERVER("sslserver", "", "SSL server host and port"), - JARFILE("jarfile", "", "signed jar file"), - STARTDATE("startdate", "", "certificate validity start date/time"), - STOREPASS("storepass", "", "keystore password"), - STORETYPE("storetype", "", "keystore type"), - TRUSTCACERTS("trustcacerts", null, "trust certificates from cacerts"), - V("v", null, "verbose output"), - VALIDITY("validity", "", "validity number of days"); + ALIAS("alias", "", "alias.name.of.the.entry.to.process"), + DESTALIAS("destalias", "", "destination.alias"), + DESTKEYPASS("destkeypass", "", "destination.key.password"), + DESTKEYSTORE("destkeystore", "", "destination.keystore.name"), + DESTPROTECTED("destprotected", null, "destination.keystore.password.protected"), + DESTPROVIDERNAME("destprovidername", "", "destination.keystore.provider.name"), + DESTSTOREPASS("deststorepass", "", "destination.keystore.password"), + DESTSTORETYPE("deststoretype", "", "destination.keystore.type"), + DNAME("dname", "", "distinguished.name"), + EXT("ext", "", "X.509.extension"), + FILEOUT("file", "", "output.file.name"), + FILEIN("file", "", "input.file.name"), + ID("id", "", "Serial.ID.of.cert.to.revoke"), + INFILE("infile", "", "input.file.name"), + KEYALG("keyalg", "", "key.algorithm.name"), + KEYPASS("keypass", "", "key.password"), + KEYSIZE("keysize", "", "key.bit.size"), + KEYSTORE("keystore", "", "keystore.name"), + NEW("new", "", "new.password"), + NOPROMPT("noprompt", null, "do.not.prompt"), + OUTFILE("outfile", "", "output.file.name"), + PROTECTED("protected", null, "password.through.protected.mechanism"), + PROVIDERARG("providerarg", "", "provider.argument"), + PROVIDERCLASS("providerclass", "", "provider.class.name"), + PROVIDERNAME("providername", "", "provider.name"), + PROVIDERPATH("providerpath", "", "provider.classpath"), + RFC("rfc", null, "output.in.RFC.style"), + SIGALG("sigalg", "", "signature.algorithm.name"), + SRCALIAS("srcalias", "", "source.alias"), + SRCKEYPASS("srckeypass", "", "source.key.password"), + SRCKEYSTORE("srckeystore", "", "source.keystore.name"), + SRCPROTECTED("srcprotected", null, "source.keystore.password.protected"), + SRCPROVIDERNAME("srcprovidername", "", "source.keystore.provider.name"), + SRCSTOREPASS("srcstorepass", "", "source.keystore.password"), + SRCSTORETYPE("srcstoretype", "", "source.keystore.type"), + SSLSERVER("sslserver", "", "SSL.server.host.and.port"), + JARFILE("jarfile", "", "signed.jar.file"), + STARTDATE("startdate", "", "certificate.validity.start.date.time"), + STOREPASS("storepass", "", "keystore.password"), + STORETYPE("storetype", "", "keystore.type"), + TRUSTCACERTS("trustcacerts", null, "trust.certificates.from.cacerts"), + V("v", null, "verbose.output"), + VALIDITY("validity", "", "validity.number.of.days"); final String name, arg, description; Option(String name, String arg, String description) { @@ -339,7 +339,7 @@ public final class KeyTool { doCommands(out); } } catch (Exception e) { - System.out.println(rb.getString("keytool error: ") + e); + System.out.println(rb.getString("keytool.error.") + e); if (verbose) { e.printStackTrace(System.out); } @@ -532,13 +532,13 @@ public final class KeyTool { } else if (collator.compare(flags, "-srcprotected") == 0) { srcprotectedPath = true; } else { - System.err.println(rb.getString("Illegal option: ") + flags); + System.err.println(rb.getString("Illegal.option.") + flags); tinyHelp(); } } if (i value.")); + "Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value.")); if (keyPass != null && !Arrays.equals(storePass, keyPass)) { Object[] source = {"-keypass"}; System.err.println(form.format(source)); @@ -946,10 +933,10 @@ public final class KeyTool { } if (verbose && filename != null) { MessageFormat form = new MessageFormat(rb.getString - ("Certification request stored in file ")); + ("Certification.request.stored.in.file.filename.")); Object[] source = {filename}; System.err.println(form.format(source)); - System.err.println(rb.getString("Submit this to your CA")); + System.err.println(rb.getString("Submit.this.to.your.CA")); } } else if (command == DELETE) { doDeleteEntry(alias); @@ -970,7 +957,7 @@ public final class KeyTool { } if (filename != null) { MessageFormat form = new MessageFormat(rb.getString - ("Certificate stored in file ")); + ("Certificate.stored.in.file.filename.")); Object[] source = {filename}; System.err.println(form.format(source)); } @@ -1010,10 +997,10 @@ public final class KeyTool { kssave = installReply(importAlias, inStream); if (kssave) { System.err.println(rb.getString - ("Certificate reply was installed in keystore")); + ("Certificate.reply.was.installed.in.keystore")); } else { System.err.println(rb.getString - ("Certificate reply was not installed in keystore")); + ("Certificate.reply.was.not.installed.in.keystore")); } } else if (!keyStore.containsAlias(importAlias) || keyStore.entryInstanceOf(importAlias, @@ -1021,10 +1008,10 @@ public final class KeyTool { kssave = addTrustedCert(importAlias, inStream); if (kssave) { System.err.println(rb.getString - ("Certificate was added to keystore")); + ("Certificate.was.added.to.keystore")); } else { System.err.println(rb.getString - ("Certificate was not added to keystore")); + ("Certificate.was.not.added.to.keystore")); } } } finally { @@ -1044,14 +1031,13 @@ public final class KeyTool { } if (keyStore.containsAlias(alias) == false) { MessageFormat form = new MessageFormat - (rb.getString("Alias does not exist")); + (rb.getString("Alias.alias.does.not.exist")); Object[] source = {alias}; throw new Exception(form.format(source)); } if (!keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) { MessageFormat form = new MessageFormat(rb.getString( - "Alias references an entry type that is not a private key entry. " + - "The -keyclone command only supports cloning of private key entries")); + "Alias.alias.references.an.entry.type.that.is.not.a.private.key.entry.The.keyclone.command.only.supports.cloning.of.private.key")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -1148,7 +1134,7 @@ public final class KeyTool { if (kssave) { if (verbose) { MessageFormat form = new MessageFormat - (rb.getString("[Storing ksfname]")); + (rb.getString(".Storing.ksfname.")); Object[] source = {nullStream ? "keystore" : ksfname}; System.err.println(form.format(source)); } @@ -1336,7 +1322,7 @@ public final class KeyTool { Certificate cert = keyStore.getCertificate(alias); if (cert == null) { MessageFormat form = new MessageFormat - (rb.getString("alias has no public key (certificate)")); + (rb.getString("alias.has.no.public.key.certificate.")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -1368,7 +1354,7 @@ public final class KeyTool { private void doDeleteEntry(String alias) throws Exception { if (keyStore.containsAlias(alias) == false) { MessageFormat form = new MessageFormat - (rb.getString("Alias does not exist")); + (rb.getString("Alias.alias.does.not.exist")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -1390,7 +1376,7 @@ public final class KeyTool { } if (keyStore.containsAlias(alias) == false) { MessageFormat form = new MessageFormat - (rb.getString("Alias does not exist")); + (rb.getString("Alias.alias.does.not.exist")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -1398,7 +1384,7 @@ public final class KeyTool { X509Certificate cert = (X509Certificate)keyStore.getCertificate(alias); if (cert == null) { MessageFormat form = new MessageFormat - (rb.getString("Alias has no certificate")); + (rb.getString("Alias.alias.has.no.certificate")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -1419,15 +1405,15 @@ public final class KeyTool { int count; for (count = 0; count < 3; count++) { MessageFormat form = new MessageFormat(rb.getString - ("Enter key password for ")); + ("Enter.key.password.for.alias.")); Object[] source = {alias}; System.err.println(form.format(source)); if (orig == null) { System.err.print(rb.getString - ("\t(RETURN if same as keystore password): ")); + (".RETURN.if.same.as.keystore.password.")); } else { form = new MessageFormat(rb.getString - ("\t(RETURN if same as for )")); + (".RETURN.if.same.as.for.otherAlias.")); Object[] src = {orig}; System.err.print(form.format(src)); } @@ -1437,27 +1423,27 @@ public final class KeyTool { if (entered == null) { return origPass; } else if (entered.length >= 6) { - System.err.print(rb.getString("Re-enter new password: ")); + System.err.print(rb.getString("Re.enter.new.password.")); char[] passAgain = Password.readPassword(System.in); passwords.add(passAgain); if (!Arrays.equals(entered, passAgain)) { System.err.println - (rb.getString("They don't match. Try again")); + (rb.getString("They.don.t.match.Try.again")); continue; } return entered; } else { System.err.println(rb.getString - ("Key password is too short - must be at least 6 characters")); + ("Key.password.is.too.short.must.be.at.least.6.characters")); } } if (count == 3) { if (command == KEYCLONE) { throw new Exception(rb.getString - ("Too many failures. Key entry not cloned")); + ("Too.many.failures.Key.entry.not.cloned")); } else { throw new Exception(rb.getString - ("Too many failures - key not added to keystore")); + ("Too.many.failures.key.not.added.to.keystore")); } } } @@ -1475,7 +1461,7 @@ public final class KeyTool { } if (keyStore.containsAlias(alias)) { MessageFormat form = new MessageFormat(rb.getString - ("Secret key not generated, alias already exists")); + ("Secret.key.not.generated.alias.alias.already.exists")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -1490,7 +1476,7 @@ public final class KeyTool { keygen.init(168); } else { throw new Exception(rb.getString - ("Please provide -keysize for secret key generation")); + ("Please.provide.keysize.for.secret.key.generation")); } secKey = keygen.generateKey(); @@ -1514,7 +1500,7 @@ public final class KeyTool { return "SHA256withECDSA"; } else { throw new Exception(rb.getString - ("Cannot derive signature algorithm")); + ("Cannot.derive.signature.algorithm")); } } /** @@ -1540,7 +1526,7 @@ public final class KeyTool { if (keyStore.containsAlias(alias)) { MessageFormat form = new MessageFormat(rb.getString - ("Key pair not generated, alias already exists")); + ("Key.pair.not.generated.alias.alias.already.exists")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -1569,8 +1555,7 @@ public final class KeyTool { if (verbose) { MessageFormat form = new MessageFormat(rb.getString - ("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.for")); Object[] source = {new Integer(keysize), privKey.getAlgorithm(), chain[0].getSigAlgName(), @@ -1603,7 +1588,7 @@ public final class KeyTool { if (keyStore.containsAlias(dest)) { MessageFormat form = new MessageFormat - (rb.getString("Destination alias already exists")); + (rb.getString("Destination.alias.dest.already.exists")); Object[] source = {dest}; throw new Exception(form.format(source)); } @@ -1644,7 +1629,7 @@ public final class KeyTool { if (keyPassNew == null) { MessageFormat form = new MessageFormat - (rb.getString("key password for ")); + (rb.getString("key.password.for.alias.")); Object[] source = {alias}; keyPassNew = getNewPasswd(form.format(source), keyPass); } @@ -1661,7 +1646,7 @@ public final class KeyTool { throws Exception { System.err.println(rb.getString - ("No entries from identity database added")); + ("No.entries.from.identity.database.added")); } /** @@ -1678,32 +1663,32 @@ public final class KeyTool { if (keyStore.containsAlias(alias) == false) { MessageFormat form = new MessageFormat - (rb.getString("Alias does not exist")); + (rb.getString("Alias.alias.does.not.exist")); Object[] source = {alias}; throw new Exception(form.format(source)); } if (verbose || rfc || debug) { MessageFormat form = new MessageFormat - (rb.getString("Alias name: alias")); + (rb.getString("Alias.name.alias")); Object[] source = {alias}; out.println(form.format(source)); if (!token) { form = new MessageFormat(rb.getString - ("Creation date: keyStore.getCreationDate(alias)")); + ("Creation.date.keyStore.getCreationDate.alias.")); Object[] src = {keyStore.getCreationDate(alias)}; out.println(form.format(src)); } } else { if (!token) { MessageFormat form = new MessageFormat - (rb.getString("alias, keyStore.getCreationDate(alias), ")); + (rb.getString("alias.keyStore.getCreationDate.alias.")); Object[] source = {alias, keyStore.getCreationDate(alias)}; out.print(form.format(source)); } else { MessageFormat form = new MessageFormat - (rb.getString("alias, ")); + (rb.getString("alias.")); Object[] source = {alias}; out.print(form.format(source)); } @@ -1713,7 +1698,7 @@ public final class KeyTool { if (verbose || rfc || debug) { Object[] source = {"SecretKeyEntry"}; out.println(new MessageFormat( - rb.getString("Entry type: ")).format(source)); + rb.getString("Entry.type.type.")).format(source)); } else { out.println("SecretKeyEntry, "); } @@ -1721,7 +1706,7 @@ public final class KeyTool { if (verbose || rfc || debug) { Object[] source = {"PrivateKeyEntry"}; out.println(new MessageFormat( - rb.getString("Entry type: ")).format(source)); + rb.getString("Entry.type.type.")).format(source)); } else { out.println("PrivateKeyEntry, "); } @@ -1731,10 +1716,10 @@ public final class KeyTool { if (chain != null) { if (verbose || rfc || debug) { out.println(rb.getString - ("Certificate chain length: ") + chain.length); + ("Certificate.chain.length.") + chain.length); for (int i = 0; i < chain.length; i ++) { MessageFormat form = new MessageFormat - (rb.getString("Certificate[(i + 1)]:")); + (rb.getString("Certificate.i.1.")); Object[] source = {new Integer((i + 1))}; out.println(form.format(source)); if (verbose && (chain[i] instanceof X509Certificate)) { @@ -1748,7 +1733,7 @@ public final class KeyTool { } else { // Print the digest of the user cert only out.println - (rb.getString("Certificate fingerprint (SHA1): ") + + (rb.getString("Certificate.fingerprint.SHA1.") + getCertFingerPrint("SHA1", chain[0])); } } @@ -1757,20 +1742,20 @@ public final class KeyTool { // We have a trusted certificate entry Certificate cert = keyStore.getCertificate(alias); if (verbose && (cert instanceof X509Certificate)) { - out.println(rb.getString("Entry type: trustedCertEntry\n")); + out.println(rb.getString("Entry.type.trustedCertEntry.")); printX509Cert((X509Certificate)cert, out); } else if (rfc) { - out.println(rb.getString("Entry type: trustedCertEntry\n")); + out.println(rb.getString("Entry.type.trustedCertEntry.")); dumpCert(cert, out); } else if (debug) { out.println(cert.toString()); } else { - out.println(rb.getString("trustedCertEntry,")); - out.println(rb.getString("Certificate fingerprint (SHA1): ") + out.println(rb.getString("trustedCertEntry.")); + out.println(rb.getString("Certificate.fingerprint.SHA1.") + getCertFingerPrint("SHA1", cert)); } } else { - out.println(rb.getString("Unknown Entry Type")); + out.println(rb.getString("Unknown.Entry.Type")); } } @@ -1787,7 +1772,7 @@ public final class KeyTool { KeyStoreUtil.isWindowsKeyStore(srcstoretype)) { if (!NONE.equals(srcksfname)) { System.err.println(MessageFormat.format(rb.getString - ("-keystore must be NONE if -storetype is {0}"), srcstoretype)); + (".keystore.must.be.NONE.if.storetype.is.{0}"), srcstoretype)); System.err.println(); tinyHelp(); } @@ -1797,13 +1782,13 @@ public final class KeyTool { File srcksfile = new File(srcksfname); if (srcksfile.exists() && srcksfile.length() == 0) { throw new Exception(rb.getString - ("Source keystore file exists, but is empty: ") + + ("Source.keystore.file.exists.but.is.empty.") + srcksfname); } is = new FileInputStream(srcksfile); } else { throw new Exception(rb.getString - ("Please specify -srckeystore")); + ("Please.specify.srckeystore")); } } @@ -1818,7 +1803,7 @@ public final class KeyTool { if (srcstorePass == null && !srcprotectedPath && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) { - System.err.print(rb.getString("Enter source keystore password: ")); + System.err.print(rb.getString("Enter.source.keystore.password.")); System.err.flush(); srcstorePass = Password.readPassword(System.in); passwords.add(srcstorePass); @@ -1829,8 +1814,7 @@ public final class KeyTool { if (srckeyPass != null && srcstorePass != null && !Arrays.equals(srcstorePass, srckeyPass)) { MessageFormat form = new MessageFormat(rb.getString( - "Warning: Different store and key passwords not supported " + - "for PKCS12 KeyStores. Ignoring user-specified value.")); + "Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value.")); Object[] source = {"-srckeypass"}; System.err.println(form.format(source)); srckeyPass = srcstorePass; @@ -1850,15 +1834,15 @@ public final class KeyTool { // but change 2 lines System.err.println(); System.err.println(rb.getString - ("***************** WARNING WARNING WARNING *****************")); + (".WARNING.WARNING.WARNING.")); System.err.println(rb.getString - ("* The integrity of the information stored in the srckeystore*")); + (".The.integrity.of.the.information.stored.in.the.srckeystore.")); System.err.println(rb.getString - ("* has NOT been verified! In order to verify its integrity, *")); + (".has.NOT.been.verified.In.order.to.verify.its.integrity.")); System.err.println(rb.getString - ("* you must provide the srckeystore password. *")); + (".you.must.provide.the.srckeystore.password.")); System.err.println(rb.getString - ("***************** WARNING WARNING WARNING *****************")); + (".WARNING.WARNING.WARNING.")); System.err.println(); } @@ -1877,8 +1861,7 @@ public final class KeyTool { } else { if (dest != null || srckeyPass != null || destKeyPass != null) { throw new Exception(rb.getString( - "if alias not specified, destalias, srckeypass, " + - "and destkeypass must not be specified")); + "if.alias.not.specified.destalias.srckeypass.and.destkeypass.must.not.be.specified")); } doImportKeyStoreAll(loadSourceKeyStore()); } @@ -1906,16 +1889,16 @@ public final class KeyTool { Object[] source = {alias}; if (noprompt) { System.err.println(new MessageFormat(rb.getString( - "Warning: Overwriting existing alias in destination keystore")).format(source)); + "Warning.Overwriting.existing.alias.alias.in.destination.keystore")).format(source)); } else { String reply = getYesNoReply(new MessageFormat(rb.getString( - "Existing entry alias exists, overwrite? [no]: ")).format(source)); + "Existing.entry.alias.alias.exists.overwrite.no.")).format(source)); if ("NO".equals(reply)) { newAlias = inputStringFromStdin(rb.getString - ("Enter new alias name\t(RETURN to cancel import for this entry): ")); + ("Enter.new.alias.name.RETURN.to.cancel.import.for.this.entry.")); if ("".equals(newAlias)) { System.err.println(new MessageFormat(rb.getString( - "Entry for alias not imported.")).format( + "Entry.for.alias.alias.not.imported.")).format( source)); return 0; } @@ -1944,7 +1927,7 @@ public final class KeyTool { } catch (KeyStoreException kse) { Object[] source2 = {alias, kse.toString()}; MessageFormat form = new MessageFormat(rb.getString( - "Problem importing entry for alias : .\nEntry for alias not imported.")); + "Problem.importing.entry.for.alias.alias.exception.Entry.for.alias.alias.not.imported.")); System.err.println(form.format(source2)); return 2; } @@ -1961,7 +1944,7 @@ public final class KeyTool { if (result == 1) { ok++; Object[] source = {alias}; - MessageFormat form = new MessageFormat(rb.getString("Entry for alias successfully imported.")); + MessageFormat form = new MessageFormat(rb.getString("Entry.for.alias.alias.successfully.imported.")); System.err.println(form.format(source)); } else if (result == 2) { if (!noprompt) { @@ -1974,7 +1957,7 @@ public final class KeyTool { } Object[] source = {ok, count-ok}; MessageFormat form = new MessageFormat(rb.getString( - "Import command completed: entries successfully imported, entries failed or cancelled")); + "Import.command.completed.ok.entries.successfully.imported.fail.entries.failed.or.cancelled")); System.err.println(form.format(source)); } @@ -1991,17 +1974,17 @@ public final class KeyTool { out.println(); } - out.println(rb.getString("Keystore type: ") + keyStore.getType()); - out.println(rb.getString("Keystore provider: ") + + out.println(rb.getString("Keystore.type.") + keyStore.getType()); + out.println(rb.getString("Keystore.provider.") + keyStore.getProvider().getName()); out.println(); MessageFormat form; form = (keyStore.size() == 1) ? new MessageFormat(rb.getString - ("Your keystore contains keyStore.size() entry")) : + ("Your.keystore.contains.keyStore.size.entry")) : new MessageFormat(rb.getString - ("Your keystore contains keyStore.size() entries")); + ("Your.keystore.contains.keyStore.size.entries")); Object[] source = {new Integer(keyStore.size())}; out.println(form.format(source)); out.println(); @@ -2011,11 +1994,11 @@ public final class KeyTool { String alias = e.nextElement(); doPrintEntry(alias, out, false); if (verbose || rfc) { - out.println(rb.getString("\n")); + out.println(rb.getString("NEWLINE")); out.println(rb.getString - ("*******************************************")); + ("STAR")); out.println(rb.getString - ("*******************************************\n\n")); + ("STARNN")); } } } @@ -2171,10 +2154,10 @@ public final class KeyTool { } if (issuer == null) { out.println(rb.getString - ("*******************************************")); + ("STAR")); out.println("WARNING: not verified. Make sure -keystore and -alias are correct."); out.println(rb.getString - ("*******************************************\n\n")); + ("STARNN")); } } } @@ -2214,15 +2197,14 @@ public final class KeyTool { PKCS10 req = new PKCS10(new BASE64Decoder().decodeBuffer(new String(sb))); PublicKey pkey = req.getSubjectPublicKeyInfo(); - out.printf(rb.getString("PKCS #10 Certificate Request (Version 1.0)\n" + - "Subject: %s\nPublic Key: %s format %s key\n"), + out.printf(rb.getString("PKCS.10.Certificate.Request.Version.1.0.Subject.s.Public.Key.s.format.s.key."), req.getSubjectName(), pkey.getFormat(), pkey.getAlgorithm()); for (PKCS10Attribute attr: req.getAttributes().getAttributes()) { ObjectIdentifier oid = attr.getAttributeId(); if (oid.equals(PKCS9Attribute.EXTENSION_REQUEST_OID)) { CertificateExtensions exts = (CertificateExtensions)attr.getAttributeValue(); if (exts != null) { - printExtensions(rb.getString("Extension Request:"), exts, out); + printExtensions(rb.getString("Extension.Request."), exts, out); } } else { out.println(attr.getAttributeId()); @@ -2245,10 +2227,10 @@ public final class KeyTool { try { c = cf.generateCertificates(in); } catch (CertificateException ce) { - throw new Exception(rb.getString("Failed to parse input"), ce); + throw new Exception(rb.getString("Failed.to.parse.input"), ce); } if (c.isEmpty()) { - throw new Exception(rb.getString("Empty input")); + throw new Exception(rb.getString("Empty.input")); } Certificate[] certs = c.toArray(new Certificate[c.size()]); for (int i=0; i 1) { MessageFormat form = new MessageFormat - (rb.getString("Certificate[(i + 1)]:")); + (rb.getString("Certificate.i.1.")); Object[] source = {new Integer(i + 1)}; out.println(form.format(source)); } @@ -2299,15 +2281,15 @@ public final class KeyTool { for (CodeSigner signer: signers) { if (!ss.contains(signer)) { ss.add(signer); - out.printf(rb.getString("Signer #%d:"), ++pos); + out.printf(rb.getString("Signer.d."), ++pos); out.println(); out.println(); - out.println(rb.getString("Signature:")); + out.println(rb.getString("Signature.")); out.println(); for (Certificate cert: signer.getSignerCertPath().getCertificates()) { X509Certificate x = (X509Certificate)cert; if (rfc) { - out.println(rb.getString("Certificate owner: ") + x.getSubjectDN() + "\n"); + out.println(rb.getString("Certificate.owner.") + x.getSubjectDN() + "\n"); dumpCert(x, out); } else { printX509Cert(x, out); @@ -2316,12 +2298,12 @@ public final class KeyTool { } Timestamp ts = signer.getTimestamp(); if (ts != null) { - out.println(rb.getString("Timestamp:")); + out.println(rb.getString("Timestamp.")); out.println(); for (Certificate cert: ts.getSignerCertPath().getCertificates()) { X509Certificate x = (X509Certificate)cert; if (rfc) { - out.println(rb.getString("Certificate owner: ") + x.getSubjectDN() + "\n"); + out.println(rb.getString("Certificate.owner.") + x.getSubjectDN() + "\n"); dumpCert(x, out); } else { printX509Cert(x, out); @@ -2333,7 +2315,7 @@ public final class KeyTool { .getJavaSecurityCodeSignerAccess() .getCRLs(signer); if (crls != null) { - out.println(rb.getString("CRLs:")); + out.println(rb.getString("CRLs.")); out.println(); for (CRL crl: crls) { printCRL(crl, out); @@ -2345,7 +2327,7 @@ public final class KeyTool { } jf.close(); if (ss.size() == 0) { - out.println(rb.getString("Not a signed jar file")); + out.println(rb.getString("Not.a.signed.jar.file")); } } else if (sslserver != null) { SSLContext sc = SSLContext.getInstance("SSL"); @@ -2410,7 +2392,7 @@ public final class KeyTool { // if the URL connection is successful. if (!certPrinted[0]) { Exception e = new Exception( - rb.getString("No certificate from the SSL server")); + rb.getString("No.certificate.from.the.SSL.server")); if (ex != null) { e.initCause(ex); } @@ -2455,13 +2437,13 @@ public final class KeyTool { Certificate oldCert = keyStore.getCertificate(alias); if (oldCert == null) { MessageFormat form = new MessageFormat - (rb.getString("alias has no public key")); + (rb.getString("alias.has.no.public.key")); Object[] source = {alias}; throw new Exception(form.format(source)); } if (!(oldCert instanceof X509Certificate)) { MessageFormat form = new MessageFormat - (rb.getString("alias has no X.509 certificate")); + (rb.getString("alias.has.no.X.509.certificate")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -2532,7 +2514,7 @@ public final class KeyTool { new Certificate[] { newCert } ); if (verbose) { - System.err.println(rb.getString("New certificate (self-signed):")); + System.err.println(rb.getString("New.certificate.self.signed.")); System.err.print(newCert.toString()); System.err.println(); } @@ -2568,7 +2550,7 @@ public final class KeyTool { Certificate userCert = keyStore.getCertificate(alias); if (userCert == null) { MessageFormat form = new MessageFormat - (rb.getString("alias has no public key (certificate)")); + (rb.getString("alias.has.no.public.key.certificate.")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -2576,7 +2558,7 @@ public final class KeyTool { // Read the certificates in the reply Collection c = cf.generateCertificates(in); if (c.isEmpty()) { - throw new Exception(rb.getString("Reply has no certificates")); + throw new Exception(rb.getString("Reply.has.no.certificates")); } Certificate[] replyCerts = c.toArray(new Certificate[c.size()]); Certificate[] newChain; @@ -2609,11 +2591,11 @@ public final class KeyTool { throws Exception { if (alias == null) { - throw new Exception(rb.getString("Must specify alias")); + throw new Exception(rb.getString("Must.specify.alias")); } if (keyStore.containsAlias(alias)) { MessageFormat form = new MessageFormat(rb.getString - ("Certificate not imported, alias already exists")); + ("Certificate.not.imported.alias.alias.already.exists")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -2623,9 +2605,9 @@ public final class KeyTool { try { cert = (X509Certificate)cf.generateCertificate(in); } catch (ClassCastException cce) { - throw new Exception(rb.getString("Input not an X.509 certificate")); + throw new Exception(rb.getString("Input.not.an.X.509.certificate")); } catch (CertificateException ce) { - throw new Exception(rb.getString("Input not an X.509 certificate")); + throw new Exception(rb.getString("Input.not.an.X.509.certificate")); } // if certificate is self-signed, make sure it verifies @@ -2645,27 +2627,27 @@ public final class KeyTool { String trustalias = keyStore.getCertificateAlias(cert); if (trustalias != null) { MessageFormat form = new MessageFormat(rb.getString - ("Certificate already exists in keystore under alias ")); + ("Certificate.already.exists.in.keystore.under.alias.trustalias.")); Object[] source = {trustalias}; System.err.println(form.format(source)); reply = getYesNoReply - (rb.getString("Do you still want to add it? [no]: ")); + (rb.getString("Do.you.still.want.to.add.it.no.")); } else if (selfSigned) { if (trustcacerts && (caks != null) && ((trustalias=caks.getCertificateAlias(cert)) != null)) { MessageFormat form = new MessageFormat(rb.getString - ("Certificate already exists in system-wide CA keystore under alias ")); + ("Certificate.already.exists.in.system.wide.CA.keystore.under.alias.trustalias.")); Object[] source = {trustalias}; System.err.println(form.format(source)); reply = getYesNoReply - (rb.getString("Do you still want to add it to your own keystore? [no]: ")); + (rb.getString("Do.you.still.want.to.add.it.to.your.own.keystore.no.")); } if (trustalias == null) { // Print the cert and ask user if they really want to add // it to their keystore printX509Cert(cert, System.out); reply = getYesNoReply - (rb.getString("Trust this certificate? [no]: ")); + (rb.getString("Trust.this.certificate.no.")); } } if (reply != null) { @@ -2689,7 +2671,7 @@ public final class KeyTool { // their keystore printX509Cert(cert, System.out); reply = getYesNoReply - (rb.getString("Trust this certificate? [no]: ")); + (rb.getString("Trust.this.certificate.no.")); if ("YES".equals(reply)) { keyStore.setCertificateEntry(alias, cert); return true; @@ -2716,26 +2698,26 @@ public final class KeyTool { for (int count = 0; count < 3; count++) { MessageFormat form = new MessageFormat - (rb.getString("New prompt: ")); + (rb.getString("New.prompt.")); Object[] source = {prompt}; System.err.print(form.format(source)); entered = Password.readPassword(System.in); passwords.add(entered); if (entered == null || entered.length < 6) { System.err.println(rb.getString - ("Password is too short - must be at least 6 characters")); + ("Password.is.too.short.must.be.at.least.6.characters")); } else if (Arrays.equals(entered, oldPasswd)) { - System.err.println(rb.getString("Passwords must differ")); + System.err.println(rb.getString("Passwords.must.differ")); } else { form = new MessageFormat - (rb.getString("Re-enter new prompt: ")); + (rb.getString("Re.enter.new.prompt.")); Object[] src = {prompt}; System.err.print(form.format(src)); reentered = Password.readPassword(System.in); passwords.add(reentered); if (!Arrays.equals(entered, reentered)) { System.err.println - (rb.getString("They don't match. Try again")); + (rb.getString("They.don.t.match.Try.again")); } else { Arrays.fill(reentered, ' '); return entered; @@ -2750,7 +2732,7 @@ public final class KeyTool { reentered = null; } } - throw new Exception(rb.getString("Too many failures - try later")); + throw new Exception(rb.getString("Too.many.failures.try.later")); } /** @@ -2761,11 +2743,11 @@ public final class KeyTool { private String getAlias(String prompt) throws Exception { if (prompt != null) { MessageFormat form = new MessageFormat - (rb.getString("Enter prompt alias name: ")); + (rb.getString("Enter.prompt.alias.name.")); Object[] source = {prompt}; System.err.print(form.format(source)); } else { - System.err.print(rb.getString("Enter alias name: ")); + System.err.print(rb.getString("Enter.alias.name.")); } return (new BufferedReader(new InputStreamReader( System.in))).readLine(); @@ -2796,17 +2778,17 @@ public final class KeyTool { do { if (otherKeyPass != null) { MessageFormat form = new MessageFormat(rb.getString - ("Enter key password for ")); + ("Enter.key.password.for.alias.")); Object[] source = {alias}; System.err.println(form.format(source)); form = new MessageFormat(rb.getString - ("\t(RETURN if same as for )")); + (".RETURN.if.same.as.for.otherAlias.")); Object[] src = {otherAlias}; System.err.print(form.format(src)); } else { MessageFormat form = new MessageFormat(rb.getString - ("Enter key password for ")); + ("Enter.key.password.for.alias.")); Object[] source = {alias}; System.err.print(form.format(source)); } @@ -2820,7 +2802,7 @@ public final class KeyTool { } while ((keyPass == null) && count < 3); if (keyPass == null) { - throw new Exception(rb.getString("Too many failures - try later")); + throw new Exception(rb.getString("Too.many.failures.try.later")); } return keyPass; @@ -2851,7 +2833,7 @@ public final class KeyTool { */ MessageFormat form = new MessageFormat - (rb.getString("*PATTERN* printX509Cert")); + (rb.getString(".PATTERN.printX509Cert")); Object[] source = {cert.getSubjectDN().toString(), cert.getIssuerDN().toString(), cert.getSerialNumber().toString(16), @@ -2873,7 +2855,7 @@ public final class KeyTool { CertificateExtensions exts = (CertificateExtensions) certInfo.get(X509CertInfo.EXTENSIONS); if (exts != null) { - printExtensions(rb.getString("Extensions: "), exts, out); + printExtensions(rb.getString("Extensions."), exts, out); } } } @@ -2894,7 +2876,7 @@ public final class KeyTool { if (ext.getClass() == Extension.class) { byte[] v = ext.getExtensionValue(); if (v.length == 0) { - out.println(rb.getString("(Empty value)")); + out.println(rb.getString(".Empty.value.")); } else { new sun.misc.HexDumpEncoder().encodeBuffer(ext.getExtensionValue(), out); out.println(); @@ -2972,32 +2954,32 @@ public final class KeyTool { do { if (maxRetry-- < 0) { throw new RuntimeException(rb.getString( - "Too many retries, program terminated")); + "Too.many.retries.program.terminated")); } commonName = inputString(in, - rb.getString("What is your first and last name?"), + rb.getString("What.is.your.first.and.last.name."), commonName); organizationalUnit = inputString(in, rb.getString - ("What is the name of your organizational unit?"), + ("What.is.the.name.of.your.organizational.unit."), organizationalUnit); organization = inputString(in, - rb.getString("What is the name of your organization?"), + rb.getString("What.is.the.name.of.your.organization."), organization); city = inputString(in, - rb.getString("What is the name of your City or Locality?"), + rb.getString("What.is.the.name.of.your.City.or.Locality."), city); state = inputString(in, - rb.getString("What is the name of your State or Province?"), + rb.getString("What.is.the.name.of.your.State.or.Province."), state); country = inputString(in, rb.getString - ("What is the two-letter country code for this unit?"), + ("What.is.the.two.letter.country.code.for.this.unit."), country); name = new X500Name(commonName, organizationalUnit, organization, city, state, country); MessageFormat form = new MessageFormat - (rb.getString("Is correct?")); + (rb.getString("Is.name.correct.")); Object[] source = {name}; userInput = inputString (in, form.format(source), rb.getString("no")); @@ -3014,7 +2996,7 @@ public final class KeyTool { { System.err.println(prompt); MessageFormat form = new MessageFormat - (rb.getString(" [defaultValue]: ")); + (rb.getString(".defaultValue.")); Object[] source = {defaultValue}; System.err.print(form.format(source)); System.err.flush(); @@ -3085,14 +3067,14 @@ public final class KeyTool { if (keyStore.containsAlias(alias) == false) { MessageFormat form = new MessageFormat - (rb.getString("Alias does not exist")); + (rb.getString("Alias.alias.does.not.exist")); Object[] source = {alias}; throw new Exception(form.format(source)); } if (!keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class) && !keyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) { MessageFormat form = new MessageFormat - (rb.getString("Alias has no key")); + (rb.getString("Alias.alias.has.no.key")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -3134,7 +3116,7 @@ public final class KeyTool { if (ks.containsAlias(alias) == false) { MessageFormat form = new MessageFormat - (rb.getString("Alias does not exist")); + (rb.getString("Alias.alias.does.not.exist")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -3212,15 +3194,15 @@ public final class KeyTool { private void printWarning() { System.err.println(); System.err.println(rb.getString - ("***************** WARNING WARNING WARNING *****************")); + (".WARNING.WARNING.WARNING.")); System.err.println(rb.getString - ("* The integrity of the information stored in your keystore *")); + (".The.integrity.of.the.information.stored.in.your.keystore.")); System.err.println(rb.getString - ("* has NOT been verified! In order to verify its integrity, *")); + (".has.NOT.been.verified.In.order.to.verify.its.integrity.")); System.err.println(rb.getString - ("* you must provide your keystore password. *")); + (".you.must.provide.your.keystore.password.")); System.err.println(rb.getString - ("***************** WARNING WARNING WARNING *****************")); + (".WARNING.WARNING.WARNING.")); System.err.println(); } @@ -3250,7 +3232,7 @@ public final class KeyTool { } if (i == replyCerts.length) { MessageFormat form = new MessageFormat(rb.getString - ("Certificate reply does not contain public key for ")); + ("Certificate.reply.does.not.contain.public.key.for.alias.")); Object[] source = {alias}; throw new Exception(form.format(source)); } @@ -3275,7 +3257,7 @@ public final class KeyTool { } if (j == replyCerts.length) { throw new Exception - (rb.getString("Incomplete certificate chain in reply")); + (rb.getString("Incomplete.certificate.chain.in.reply")); } } @@ -3292,12 +3274,12 @@ public final class KeyTool { if (root == null) { System.err.println(); System.err.println - (rb.getString("Top-level certificate in reply:\n")); + (rb.getString("Top.level.certificate.in.reply.")); printX509Cert((X509Certificate)topCert, System.out); System.err.println(); - System.err.print(rb.getString("... is not trusted. ")); + System.err.print(rb.getString(".is.not.trusted.")); String reply = getYesNoReply - (rb.getString("Install reply anyway? [no]: ")); + (rb.getString("Install.reply.anyway.no.")); if ("NO".equals(reply)) { return null; } @@ -3335,14 +3317,14 @@ public final class KeyTool { PublicKey replyPubKey = certToVerify.getPublicKey(); if (!origPubKey.equals(replyPubKey)) { throw new Exception(rb.getString - ("Public keys in reply and keystore don't match")); + ("Public.keys.in.reply.and.keystore.don.t.match")); } // If the two certs are identical, we're done: no need to import // anything if (certToVerify.equals(userCert)) { throw new Exception(rb.getString - ("Certificate reply and certificate in keystore are identical")); + ("Certificate.reply.and.certificate.in.keystore.are.identical")); } } @@ -3379,7 +3361,7 @@ public final class KeyTool { return newChain; } else { throw new Exception - (rb.getString("Failed to establish chain from reply")); + (rb.getString("Failed.to.establish.chain.from.reply")); } } @@ -3443,7 +3425,7 @@ public final class KeyTool { do { if (maxRetry-- < 0) { throw new RuntimeException(rb.getString( - "Too many retries, program terminated")); + "Too.many.retries.program.terminated")); } System.err.print(prompt); System.err.flush(); @@ -3457,7 +3439,7 @@ public final class KeyTool { collator.compare(reply, rb.getString("yes")) == 0) { reply = "YES"; } else { - System.err.println(rb.getString("Wrong answer, try again")); + System.err.println(rb.getString("Wrong.answer.try.again")); reply = null; } } while (reply == null); @@ -3528,7 +3510,7 @@ public final class KeyTool { Calendar c = new GregorianCalendar(); if (s != null) { IOException ioe = new IOException( - rb.getString("Illegal startdate value")); + rb.getString("Illegal.startdate.value")); int len = s.length(); if (len == 0) { throw ioe; @@ -3654,7 +3636,7 @@ public final class KeyTool { } StringBuffer sb = new StringBuffer(); MessageFormat form = new MessageFormat(rb.getString - ("command {0} is ambiguous:")); + ("command.{0}.is.ambiguous.")); Object[] source = {s}; sb.append(form.format(source)); sb.append("\n "); @@ -3678,7 +3660,7 @@ public final class KeyTool { int p = oneOf(t, "EMAIL", "URI", "DNS", "IP", "OID"); if (p < 0) { throw new Exception(rb.getString( - "Unrecognized GeneralName type: ") + t); + "Unrecognized.GeneralName.type.") + t); } switch (p) { case 0: gn = new RFC822Name(v); break; @@ -3773,7 +3755,7 @@ public final class KeyTool { "critical", "non-critical"); if (action == -1) { throw new Exception(rb.getString - ("Illegal value: ") + item); + ("Illegal.value.") + item); } } } @@ -3837,7 +3819,7 @@ public final class KeyTool { String[] nv = part.split(":"); if (nv.length != 2) { throw new Exception(rb.getString - ("Illegal value: ") + extstr); + ("Illegal.value.") + extstr); } else { if (nv[0].equalsIgnoreCase("ca")) { isCA = Boolean.parseBoolean(nv[1]); @@ -3845,7 +3827,7 @@ public final class KeyTool { pathLen = Integer.parseInt(nv[1]); } else { throw new Exception(rb.getString - ("Illegal value: ") + extstr); + ("Illegal.value.") + extstr); } } } @@ -3872,7 +3854,7 @@ public final class KeyTool { "contentCommitment" // also (1) ); if (p < 0) { - throw new Exception(rb.getString("Unknown keyUsage type: ") + s); + throw new Exception(rb.getString("Unknown.keyUsage.type.") + s); } if (p == 9) p = 1; ok[p] = true; @@ -3886,7 +3868,7 @@ public final class KeyTool { kue.getExtensionValue())); } else { throw new Exception(rb.getString - ("Illegal value: ") + extstr); + ("Illegal.value.") + extstr); } break; case 2: // EKU @@ -3911,7 +3893,7 @@ public final class KeyTool { v.add(new ObjectIdentifier(s)); } catch (Exception e) { throw new Exception(rb.getString( - "Unknown extendedkeyUsage type: ") + s); + "Unknown.extendedkeyUsage.type.") + s); } } else if (p == 0) { v.add(new ObjectIdentifier("2.5.29.37.0")); @@ -3923,7 +3905,7 @@ public final class KeyTool { new ExtendedKeyUsageExtension(isCritical, v)); } else { throw new Exception(rb.getString - ("Illegal value: ") + extstr); + ("Illegal.value.") + extstr); } break; case 3: // SAN @@ -3951,14 +3933,14 @@ public final class KeyTool { } } else { throw new Exception(rb.getString - ("Illegal value: ") + extstr); + ("Illegal.value.") + extstr); } break; case 5: // SIA, always non-critical case 6: // AIA, always non-critical if (isCritical) { throw new Exception(rb.getString( - "This extension cannot be marked as critical. ") + extstr); + "This.extension.cannot.be.marked.as.critical.") + extstr); } if(value != null) { List accessDescriptions = @@ -3969,7 +3951,7 @@ public final class KeyTool { int colonpos2 = item.indexOf(':', colonpos+1); if (colonpos < 0 || colonpos2 < 0) { throw new Exception(rb.getString - ("Illegal value: ") + extstr); + ("Illegal.value.") + extstr); } String m = item.substring(0, colonpos); String t = item.substring(colonpos+1, colonpos2); @@ -3988,7 +3970,7 @@ public final class KeyTool { oid = new ObjectIdentifier(m); } catch (Exception e) { throw new Exception(rb.getString( - "Unknown AccessDescription type: ") + m); + "Unknown.AccessDescription.type.") + m); } } else { oid = new ObjectIdentifier("1.3.6.1.5.5.7.48." + p); @@ -4005,7 +3987,7 @@ public final class KeyTool { } } else { throw new Exception(rb.getString - ("Illegal value: ") + extstr); + ("Illegal.value.") + extstr); } break; case 8: // CRL, experimental, only support 1 distributionpoint @@ -4027,7 +4009,7 @@ public final class KeyTool { new DistributionPoint(gnames, null, null)))); } else { throw new Exception(rb.getString - ("Illegal value: ") + extstr); + ("Illegal.value.") + extstr); } break; case -1: @@ -4056,7 +4038,7 @@ public final class KeyTool { } if (pos % 2 != 0) { throw new Exception(rb.getString( - "Odd number of hex digits found: ") + extstr); + "Odd.number.of.hex.digits.found.") + extstr); } data = Arrays.copyOf(data, pos/2); } else { @@ -4068,7 +4050,7 @@ public final class KeyTool { break; default: throw new Exception(rb.getString( - "Unknown extension type: ") + extstr); + "Unknown.extension.type.") + extstr); } } // always non-critical @@ -4092,11 +4074,11 @@ public final class KeyTool { private void usage() { if (command != null) { System.err.println("keytool " + command + - rb.getString(" [OPTION]...")); + rb.getString(".OPTION.")); System.err.println(); System.err.println(rb.getString(command.description)); System.err.println(); - System.err.println(rb.getString("Options:")); + System.err.println(rb.getString("Options.")); System.err.println(); // Left and right sides of the options list @@ -4123,12 +4105,12 @@ public final class KeyTool { } System.err.println(); System.err.println(rb.getString( - "Use \"keytool -help\" for all available commands")); + "Use.keytool.help.for.all.available.commands")); } else { System.err.println(rb.getString( - "Key and Certificate Management Tool")); + "Key.and.Certificate.Management.Tool")); System.err.println(); - System.err.println(rb.getString("Commands:")); + System.err.println(rb.getString("Commands.")); System.err.println(); for (Command c: Command.values()) { if (c == KEYCLONE) break; @@ -4136,7 +4118,7 @@ public final class KeyTool { } System.err.println(); System.err.println(rb.getString( - "Use \"keytool -command_name -help\" for usage of command_name")); + "Use.keytool.command.name.help.for.usage.of.command.name")); } } @@ -4152,7 +4134,7 @@ public final class KeyTool { private void errorNeedArgument(String flag) { Object[] source = {flag}; System.err.println(new MessageFormat( - rb.getString("Command option needs an argument.")).format(source)); + rb.getString("Command.option.flag.needs.an.argument.")).format(source)); tinyHelp(); } @@ -4171,7 +4153,7 @@ public final class KeyTool { String value = System.getenv(arg); if (value == null) { System.err.println(rb.getString( - "Cannot find environment variable: ") + arg); + "Cannot.find.environment.variable.") + arg); return null; } else { return value.toCharArray(); @@ -4187,7 +4169,7 @@ public final class KeyTool { url = f.toURI().toURL(); } else { System.err.println(rb.getString( - "Cannot find file: ") + arg); + "Cannot.find.file.") + arg); return null; } } @@ -4205,7 +4187,7 @@ public final class KeyTool { return null; } } else { - System.err.println(rb.getString("Unknown password type: ") + + System.err.println(rb.getString("Unknown.password.type.") + modifier); return null; } diff --git a/src/share/classes/sun/security/tools/policytool/PolicyTool.java b/src/share/classes/sun/security/tools/policytool/PolicyTool.java index 8791e731aebd4cfd42024d9f1d583227db17c2e7..e04316317a880e7daa6d9302b7659678d22dc613 100644 --- a/src/share/classes/sun/security/tools/policytool/PolicyTool.java +++ b/src/share/classes/sun/security/tools/policytool/PolicyTool.java @@ -228,9 +228,7 @@ public class PolicyTool { if (pubKey == null) { newWarning = true; MessageFormat form = new MessageFormat(rb.getString - ("Warning: A public key for alias " + - "'signers[i]' does not exist. " + - "Make sure a KeyStore is properly configured.")); + ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured.")); Object[] source = {signers[i]}; warnings.addElement(form.format(source)); } @@ -248,7 +246,7 @@ public class PolicyTool { } catch (ClassNotFoundException fnfe) { newWarning = true; MessageFormat form = new MessageFormat(rb.getString - ("Warning: Class not found: class")); + ("Warning.Class.not.found.class")); Object[] source = {pe.getPrincipalClass()}; warnings.addElement(form.format(source)); } @@ -264,13 +262,13 @@ public class PolicyTool { } catch (ClassNotFoundException fnfe) { newWarning = true; MessageFormat form = new MessageFormat(rb.getString - ("Warning: Class not found: class")); + ("Warning.Class.not.found.class")); Object[] source = {pe.permission}; warnings.addElement(form.format(source)); } catch (InvocationTargetException ite) { newWarning = true; MessageFormat form = new MessageFormat(rb.getString - ("Warning: Invalid argument(s) for constructor: arg")); + ("Warning.Invalid.argument.s.for.constructor.arg")); Object[] source = {pe.permission}; warnings.addElement(form.format(source)); } @@ -285,9 +283,7 @@ public class PolicyTool { if (pubKey == null) { newWarning = true; MessageFormat form = new MessageFormat(rb.getString - ("Warning: A public key for alias " + - "'signers[i]' does not exist. " + - "Make sure a KeyStore is properly configured.")); + ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured.")); Object[] source = {signers[i]}; warnings.addElement(form.format(source)); } @@ -615,7 +611,7 @@ public class PolicyTool { Thread.currentThread().getContextClassLoader()); if (!PRIN.isAssignableFrom(pc)) { MessageFormat form = new MessageFormat(rb.getString - ("Illegal Principal Type: type")); + ("Illegal.Principal.Type.type")); Object[] source = {type}; throw new InstantiationException(form.format(source)); } @@ -691,7 +687,7 @@ public class PolicyTool { policyFileName = args[n]; } else { MessageFormat form = new MessageFormat(rb.getString - ("Illegal option: option")); + ("Illegal.option.option")); Object[] source = { flags }; System.err.println(form.format(source)); usage(); @@ -700,10 +696,10 @@ public class PolicyTool { } static void usage() { - System.out.println(rb.getString("Usage: policytool [options]")); + System.out.println(rb.getString("Usage.policytool.options.")); System.out.println(); System.out.println(rb.getString - (" [-file ] policy file location")); + (".file.file.policy.file.location")); System.out.println(); System.exit(1); @@ -903,23 +899,23 @@ class ToolWindow extends Frame { public static final String SAVE_POLICY_FILE = PolicyTool.rb.getString("Save"); public static final String SAVE_AS_POLICY_FILE = - PolicyTool.rb.getString("Save As"); + PolicyTool.rb.getString("Save.As"); public static final String VIEW_WARNINGS = - PolicyTool.rb.getString("View Warning Log"); + PolicyTool.rb.getString("View.Warning.Log"); public static final String QUIT = PolicyTool.rb.getString("Exit"); public static final String ADD_POLICY_ENTRY = - PolicyTool.rb.getString("Add Policy Entry"); + PolicyTool.rb.getString("Add.Policy.Entry"); public static final String EDIT_POLICY_ENTRY = - PolicyTool.rb.getString("Edit Policy Entry"); + PolicyTool.rb.getString("Edit.Policy.Entry"); public static final String REMOVE_POLICY_ENTRY = - PolicyTool.rb.getString("Remove Policy Entry"); + PolicyTool.rb.getString("Remove.Policy.Entry"); public static final String EDIT_KEYSTORE = PolicyTool.rb.getString("Edit"); public static final String ADD_PUBKEY_ALIAS = - PolicyTool.rb.getString("Add Public Key Alias"); + PolicyTool.rb.getString("Add.Public.Key.Alias"); public static final String REMOVE_PUBKEY_ALIAS = - PolicyTool.rb.getString("Remove Public Key Alias"); + PolicyTool.rb.getString("Remove.Public.Key.Alias"); /* gridbag index for components in the main window (MW) */ public static final int MW_FILENAME_LABEL = 0; @@ -968,13 +964,13 @@ class ToolWindow extends Frame { // policy entry listing - Label label = new Label(PolicyTool.rb.getString("Policy File:")); + Label label = new Label(PolicyTool.rb.getString("Policy.File.")); addNewComponent(this, label, MW_FILENAME_LABEL, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, TOP_BOTTOM_PADDING); TextField tf = new TextField(50); tf.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("Policy File:")); + PolicyTool.rb.getString("Policy.File.")); tf.setEditable(false); addNewComponent(this, tf, MW_FILENAME_TEXTFIELD, 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, @@ -1056,7 +1052,7 @@ class ToolWindow extends Frame { // display the error MessageFormat form = new MessageFormat(PolicyTool.rb.getString - ("Could not open policy file: policyFile: e.toString()")); + ("Could.not.open.policy.file.policyFile.e.toString.")); Object[] source = {policyFile, e.toString()}; displayErrorDialog(null, form.format(source)); } @@ -1133,7 +1129,7 @@ class ToolWindow extends Frame { */ void displayToolWindow(String args[]) { - setTitle(PolicyTool.rb.getString("Policy Tool")); + setTitle(PolicyTool.rb.getString("Policy.Tool")); setResizable(true); addWindowListener(new ToolWindowListener(this)); setBounds(135, 80, 500, 500); @@ -1146,9 +1142,7 @@ class ToolWindow extends Frame { if (tool.newWarning == true) { displayStatusDialog(this, PolicyTool.rb.getString - ("Errors have occurred while opening the " + - "policy configuration. View the Warning Log " + - "for more information.")); + ("Errors.have.occurred.while.opening.the.policy.configuration.View.the.Warning.Log.for.more.information.")); } } @@ -1231,7 +1225,7 @@ class ToolWindow extends Frame { ta.setEditable(false); for (int i = 0; i < tool.warnings.size(); i++) { ta.append(tool.warnings.elementAt(i)); - ta.append(PolicyTool.rb.getString("\n")); + ta.append(PolicyTool.rb.getString("NEWLINE")); } addNewComponent(wd, ta, 0, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, @@ -1332,22 +1326,22 @@ class ToolDialog extends Dialog { /* popup menus */ public static final String PERM = PolicyTool.rb.getString - ("Permission: "); + ("Permission."); public static final String PRIN_TYPE = - PolicyTool.rb.getString("Principal Type:"); + PolicyTool.rb.getString("Principal.Type."); public static final String PRIN_NAME = - PolicyTool.rb.getString("Principal Name:"); + PolicyTool.rb.getString("Principal.Name."); /* more popu menus */ public static final String PERM_NAME = PolicyTool.rb.getString - ("Target Name: "); + ("Target.Name."); /* and more popup menus */ public static final String PERM_ACTIONS = PolicyTool.rb.getString - ("Actions: "); + ("Actions."); /* gridbag index for display OverWriteFile (OW) components */ public static final int OW_LABEL = 0; @@ -1540,7 +1534,7 @@ class ToolDialog extends Dialog { // ask the user if they want to over write the existing file MessageFormat form = new MessageFormat(PolicyTool.rb.getString - ("OK to overwrite existing file filename?")); + ("OK.to.overwrite.existing.file.filename.")); Object[] source = {filename}; Label label = new Label(form.format(source)); tw.addNewComponent(this, label, OW_LABEL, @@ -1584,12 +1578,12 @@ class ToolDialog extends Dialog { PolicyEntry entries[] = null; TaggedList prinList = new TaggedList(3, false); prinList.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("Principal List")); + PolicyTool.rb.getString("Principal.List")); prinList.addActionListener (new EditPrinButtonListener(tool, tw, this, edit)); TaggedList permList = new TaggedList(10, false); permList.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("Permission List")); + PolicyTool.rb.getString("Permission.List")); permList.addActionListener (new EditPermButtonListener(tool, tw, this, edit)); @@ -1627,7 +1621,7 @@ class ToolDialog extends Dialog { } // codebase label and textfield - Label label = new Label(PolicyTool.rb.getString("CodeBase:")); + Label label = new Label(PolicyTool.rb.getString("CodeBase.")); tw.addNewComponent(this, label, PE_CODEBASE_LABEL, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH); TextField tf; @@ -1635,19 +1629,19 @@ class ToolDialog extends Dialog { new TextField(entries[listIndex].getGrantEntry().codeBase, 60) : new TextField(60)); tf.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("Code Base")); + PolicyTool.rb.getString("Code.Base")); tw.addNewComponent(this, tf, PE_CODEBASE_TEXTFIELD, 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH); // signedby label and textfield - label = new Label(PolicyTool.rb.getString("SignedBy:")); + label = new Label(PolicyTool.rb.getString("SignedBy.")); tw.addNewComponent(this, label, PE_SIGNEDBY_LABEL, 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH); tf = (edit ? new TextField(entries[listIndex].getGrantEntry().signedBy, 60) : new TextField(60)); tf.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("Signed By:")); + PolicyTool.rb.getString("Signed.By.")); tw.addNewComponent(this, tf, PE_SIGNEDBY_TEXTFIELD, 1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH); @@ -1655,19 +1649,19 @@ class ToolDialog extends Dialog { Panel panel = new Panel(); panel.setLayout(new GridBagLayout()); - Button button = new Button(PolicyTool.rb.getString("Add Principal")); + Button button = new Button(PolicyTool.rb.getString("Add.Principal")); button.addActionListener (new AddPrinButtonListener(tool, tw, this, edit)); tw.addNewComponent(panel, button, PE_ADD_PRIN_BUTTON, 0, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL); - button = new Button(PolicyTool.rb.getString("Edit Principal")); + button = new Button(PolicyTool.rb.getString("Edit.Principal")); button.addActionListener(new EditPrinButtonListener (tool, tw, this, edit)); tw.addNewComponent(panel, button, PE_EDIT_PRIN_BUTTON, 1, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL); - button = new Button(PolicyTool.rb.getString("Remove Principal")); + button = new Button(PolicyTool.rb.getString("Remove.Principal")); button.addActionListener(new RemovePrinButtonListener (tool, tw, this, edit)); tw.addNewComponent(panel, button, PE_REMOVE_PRIN_BUTTON, @@ -1677,7 +1671,7 @@ class ToolDialog extends Dialog { 1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.HORIZONTAL); // principal label and list - label = new Label(PolicyTool.rb.getString("Principals:")); + label = new Label(PolicyTool.rb.getString("Principals.")); tw.addNewComponent(this, label, PE_PRIN_LABEL, 0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); @@ -1689,20 +1683,20 @@ class ToolDialog extends Dialog { panel = new Panel(); panel.setLayout(new GridBagLayout()); - button = new Button(PolicyTool.rb.getString(" Add Permission")); + button = new Button(PolicyTool.rb.getString(".Add.Permission")); button.addActionListener(new AddPermButtonListener (tool, tw, this, edit)); tw.addNewComponent(panel, button, PE_ADD_PERM_BUTTON, 0, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL); - button = new Button(PolicyTool.rb.getString(" Edit Permission")); + button = new Button(PolicyTool.rb.getString(".Edit.Permission")); button.addActionListener(new EditPermButtonListener (tool, tw, this, edit)); tw.addNewComponent(panel, button, PE_EDIT_PERM_BUTTON, 1, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL); - button = new Button(PolicyTool.rb.getString("Remove Permission")); + button = new Button(PolicyTool.rb.getString("Remove.Permission")); button.addActionListener(new RemovePermButtonListener (tool, tw, this, edit)); tw.addNewComponent(panel, button, PE_REMOVE_PERM_BUTTON, @@ -1808,7 +1802,7 @@ class ToolDialog extends Dialog { // KeyStore label and textfield Label label = new Label - (PolicyTool.rb.getString("KeyStore URL:")); + (PolicyTool.rb.getString("KeyStore.URL.")); tw.addNewComponent(this, label, KSD_NAME_LABEL, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); @@ -1816,45 +1810,45 @@ class ToolDialog extends Dialog { // URL to U R L, so that accessibility reader will pronounce well tf.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("KeyStore U R L:")); + PolicyTool.rb.getString("KeyStore.U.R.L.")); tw.addNewComponent(this, tf, KSD_NAME_TEXTFIELD, 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); // KeyStore type and textfield - label = new Label(PolicyTool.rb.getString("KeyStore Type:")); + label = new Label(PolicyTool.rb.getString("KeyStore.Type.")); tw.addNewComponent(this, label, KSD_TYPE_LABEL, 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); tf = new TextField(tool.getKeyStoreType(), 30); tf.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("KeyStore Type:")); + PolicyTool.rb.getString("KeyStore.Type.")); tw.addNewComponent(this, tf, KSD_TYPE_TEXTFIELD, 1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); // KeyStore provider and textfield label = new Label(PolicyTool.rb.getString - ("KeyStore Provider:")); + ("KeyStore.Provider.")); tw.addNewComponent(this, label, KSD_PROVIDER_LABEL, 0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); tf = new TextField(tool.getKeyStoreProvider(), 30); tf.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("KeyStore Provider:")); + PolicyTool.rb.getString("KeyStore.Provider.")); tw.addNewComponent(this, tf, KSD_PROVIDER_TEXTFIELD, 1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); // KeyStore password URL and textfield label = new Label(PolicyTool.rb.getString - ("KeyStore Password URL:")); + ("KeyStore.Password.URL.")); tw.addNewComponent(this, label, KSD_PWD_URL_LABEL, 0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); tf = new TextField(tool.getKeyStorePwdURL(), 30); tf.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("KeyStore Password U R L:")); + PolicyTool.rb.getString("KeyStore.Password.U.R.L.")); tw.addNewComponent(this, tf, KSD_PWD_URL_TEXTFIELD, 1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); @@ -1909,8 +1903,8 @@ class ToolDialog extends Dialog { // description label Label label = (edit ? - new Label(PolicyTool.rb.getString(" Edit Principal:")) : - new Label(PolicyTool.rb.getString(" Add New Principal:"))); + new Label(PolicyTool.rb.getString(".Edit.Principal.")) : + new Label(PolicyTool.rb.getString(".Add.New.Principal."))); tw.addNewComponent(newTD, label, PRD_DESC_LABEL, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.TOP_BOTTOM_PADDING); @@ -2016,8 +2010,8 @@ class ToolDialog extends Dialog { // description label Label label = (edit ? - new Label(PolicyTool.rb.getString(" Edit Permission:")) : - new Label(PolicyTool.rb.getString(" Add New Permission:"))); + new Label(PolicyTool.rb.getString(".Edit.Permission.")) : + new Label(PolicyTool.rb.getString(".Add.New.Permission."))); tw.addNewComponent(newTD, label, PD_DESC_LABEL, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.TOP_BOTTOM_PADDING); @@ -2084,13 +2078,13 @@ class ToolDialog extends Dialog { tw.LR_PADDING); // signedby label and textfield - label = new Label(PolicyTool.rb.getString("Signed By:")); + label = new Label(PolicyTool.rb.getString("Signed.By.")); tw.addNewComponent(newTD, label, PD_SIGNEDBY_LABEL, 0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.LR_PADDING); tf = (edit ? new TextField(editMe.signedBy, 40) : new TextField(40)); tf.getAccessibleContext().setAccessibleName( - PolicyTool.rb.getString("Signed By:")); + PolicyTool.rb.getString("Signed.By.")); tw.addNewComponent(newTD, tf, PD_SIGNEDBY_TEXTFIELD, 1, 4, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.LR_PADDING); @@ -2135,12 +2129,10 @@ class ToolDialog extends Dialog { if ((pclass.equals(PolicyParser.PrincipalEntry.WILDCARD_CLASS)) && (!pname.equals(PolicyParser.PrincipalEntry.WILDCARD_NAME))) { throw new Exception - (PolicyTool.rb.getString("Cannot Specify Principal " + - "with a Wildcard Class without a Wildcard Name")); + (PolicyTool.rb.getString("Cannot.Specify.Principal.with.a.Wildcard.Class.without.a.Wildcard.Name")); } else if (pname.equals("")) { throw new Exception - (PolicyTool.rb.getString("Cannot Specify Principal " + - "without a Name")); + (PolicyTool.rb.getString("Cannot.Specify.Principal.without.a.Name")); } else if (pclass.equals("")) { // make this consistent with what PolicyParser does // when it sees an empty principal class @@ -2188,7 +2180,7 @@ class ToolDialog extends Dialog { if (permission.equals("") || (!permission.equals(ALL_PERM_CLASS) && name == null)) { throw new InvalidParameterException(PolicyTool.rb.getString - ("Permission and Target Name must have a value")); + ("Permission.and.Target.Name.must.have.a.value")); } // When the permission is FilePermission, we need to check the name @@ -2205,12 +2197,7 @@ class ToolDialog extends Dialog { char result = tw.displayYesNoDialog(this, PolicyTool.rb.getString("Warning"), PolicyTool.rb.getString( - "Warning: File name may include escaped backslash characters. " + - "It is not necessary to escape backslash characters " + - "(the tool escapes characters as necessary when writing " + - "the policy contents to the persistent store).\n\n" + - "Click on Retain to retain the entered name, or click on " + - "Edit to edit the name."), + "Warning.File.name.may.include.escaped.backslash.characters.It.is.not.necessary.to.escape.backslash.characters.the.tool.escapes"), PolicyTool.rb.getString("Retain"), PolicyTool.rb.getString("Edit") ); @@ -2244,9 +2231,7 @@ class ToolDialog extends Dialog { if (pubKey == null) { MessageFormat form = new MessageFormat (PolicyTool.rb.getString - ("Warning: A public key for alias " + - "'signers[i]' does not exist. " + - "Make sure a KeyStore is properly configured.")); + ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured.")); Object[] source = {signers[i]}; tool.warnings.addElement(form.format(source)); tw.displayStatusDialog(this, form.format(source)); @@ -2276,7 +2261,7 @@ class ToolDialog extends Dialog { // ask the user do they really want to do this? Label label = new Label - (PolicyTool.rb.getString("Remove this Policy Entry?")); + (PolicyTool.rb.getString("Remove.this.Policy.Entry.")); tw.addNewComponent(this, label, CRPE_LABEL1, 0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.BOTTOM_PADDING); @@ -2340,7 +2325,7 @@ class ToolDialog extends Dialog { // pop up a dialog box for the user to enter a filename. FileDialog fd = new FileDialog - (tw, PolicyTool.rb.getString("Save As"), FileDialog.SAVE); + (tw, PolicyTool.rb.getString("Save.As"), FileDialog.SAVE); fd.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().setVisible(false); @@ -2362,7 +2347,7 @@ class ToolDialog extends Dialog { if (saveAsFile.exists()) { // display a dialog box for the user to enter policy info ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Overwrite File"), tool, tw, true); + (PolicyTool.rb.getString("Overwrite.File"), tool, tw, true); td.displayOverWriteFileDialog(filename, nextEvent); } else { try { @@ -2371,7 +2356,7 @@ class ToolDialog extends Dialog { // display status MessageFormat form = new MessageFormat(PolicyTool.rb.getString - ("Policy successfully written to filename")); + ("Policy.successfully.written.to.filename")); Object[] source = {filename}; tw.displayStatusDialog(null, form.format(source)); @@ -2388,7 +2373,7 @@ class ToolDialog extends Dialog { } catch (FileNotFoundException fnfe) { if (filename == null || filename.equals("")) { tw.displayErrorDialog(null, new FileNotFoundException - (PolicyTool.rb.getString("null filename"))); + (PolicyTool.rb.getString("null.filename"))); } else { tw.displayErrorDialog(null, fnfe); } @@ -2411,7 +2396,7 @@ class ToolDialog extends Dialog { setLayout(new GridBagLayout()); Label label = new Label - (PolicyTool.rb.getString("Save changes?")); + (PolicyTool.rb.getString("Save.changes.")); tw.addNewComponent(this, label, USC_LABEL, 0, 0, 3, 1, 0.0, 0.0, GridBagConstraints.BOTH, tw.L_TOP_BOTTOM_PADDING); @@ -2535,9 +2520,7 @@ class ToolDialog extends Dialog { // inform user of warnings if (tool.newWarning == true) { tw.displayStatusDialog(null, PolicyTool.rb.getString - ("Errors have occurred while opening the " + - "policy configuration. View the Warning Log " + - "for more information.")); + ("Errors.have.occurred.while.opening.the.policy.configuration.View.the.Warning.Log.for.more.information.")); } } catch (Exception e) { @@ -2556,7 +2539,7 @@ class ToolDialog extends Dialog { // display the error MessageFormat form = new MessageFormat(PolicyTool.rb.getString - ("Could not open policy file: policyFile: e.toString()")); + ("Could.not.open.policy.file.policyFile.e.toString.")); Object[] source = {policyFile, e.toString()}; tw.displayErrorDialog(null, form.format(source)); } @@ -2708,7 +2691,7 @@ class PolicyListListener implements ActionListener { // display the permission list for a policy entry ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Policy Entry"), tool, tw, true); + (PolicyTool.rb.getString("Policy.Entry"), tool, tw, true); td.displayPolicyEntryDialog(true); } } @@ -2732,7 +2715,7 @@ class FileMenuListener implements ActionListener { // ask user if they want to save changes ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Save Changes"), tool, tw, true); + (PolicyTool.rb.getString("Save.Changes"), tool, tw, true); td.displayUserSave(td.QUIT); // the above method will perform the QUIT as long as the @@ -2743,7 +2726,7 @@ class FileMenuListener implements ActionListener { // ask user if they want to save changes ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Save Changes"), tool, tw, true); + (PolicyTool.rb.getString("Save.Changes"), tool, tw, true); td.displayUserSave(td.NEW); // the above method will perform the NEW as long as the @@ -2754,7 +2737,7 @@ class FileMenuListener implements ActionListener { // ask user if they want to save changes ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Save Changes"), tool, tw, true); + (PolicyTool.rb.getString("Save.Changes"), tool, tw, true); td.displayUserSave(td.OPEN); // the above method will perform the OPEN as long as the @@ -2771,7 +2754,7 @@ class FileMenuListener implements ActionListener { if (filename == null || filename.length() == 0) { // user wants to SAVE AS ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Save As"), tool, tw, true); + (PolicyTool.rb.getString("Save.As"), tool, tw, true); td.displaySaveAsDialog(td.NOACTION); } else { try { @@ -2781,13 +2764,13 @@ class FileMenuListener implements ActionListener { // display status MessageFormat form = new MessageFormat (PolicyTool.rb.getString - ("Policy successfully written to filename")); + ("Policy.successfully.written.to.filename")); Object[] source = {filename}; tw.displayStatusDialog(null, form.format(source)); } catch (FileNotFoundException fnfe) { if (filename == null || filename.equals("")) { tw.displayErrorDialog(null, new FileNotFoundException - (PolicyTool.rb.getString("null filename"))); + (PolicyTool.rb.getString("null.filename"))); } else { tw.displayErrorDialog(null, fnfe); } @@ -2800,7 +2783,7 @@ class FileMenuListener implements ActionListener { // user wants to SAVE AS ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Save As"), tool, tw, true); + (PolicyTool.rb.getString("Save.As"), tool, tw, true); td.displaySaveAsDialog(td.NOACTION); } else if (PolicyTool.collator.compare(e.getActionCommand(), @@ -2830,7 +2813,7 @@ class MainWindowListener implements ActionListener { // display a dialog box for the user to enter policy info ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Policy Entry"), tool, tw, true); + (PolicyTool.rb.getString("Policy.Entry"), tool, tw, true); td.displayPolicyEntryDialog(false); } else if (PolicyTool.collator.compare(e.getActionCommand(), @@ -2841,13 +2824,13 @@ class MainWindowListener implements ActionListener { int index = list.getSelectedIndex(); if (index < 0) { tw.displayErrorDialog(null, new Exception - (PolicyTool.rb.getString("No Policy Entry selected"))); + (PolicyTool.rb.getString("No.Policy.Entry.selected"))); return; } // ask the user if they really want to remove the policy entry ToolDialog td = new ToolDialog(PolicyTool.rb.getString - ("Remove Policy Entry"), tool, tw, true); + ("Remove.Policy.Entry"), tool, tw, true); td.displayConfirmRemovePolicyEntry(); } else if (PolicyTool.collator.compare(e.getActionCommand(), @@ -2858,13 +2841,13 @@ class MainWindowListener implements ActionListener { int index = list.getSelectedIndex(); if (index < 0) { tw.displayErrorDialog(null, new Exception - (PolicyTool.rb.getString("No Policy Entry selected"))); + (PolicyTool.rb.getString("No.Policy.Entry.selected"))); return; } // display the permission list for a policy entry ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Policy Entry"), tool, tw, true); + (PolicyTool.rb.getString("Policy.Entry"), tool, tw, true); td.displayPolicyEntryDialog(true); } else if (PolicyTool.collator.compare(e.getActionCommand(), @@ -2906,7 +2889,7 @@ class OverWriteFileOKButtonListener implements ActionListener { // display status MessageFormat form = new MessageFormat (PolicyTool.rb.getString - ("Policy successfully written to filename")); + ("Policy.successfully.written.to.filename")); Object[] source = {filename}; tw.displayStatusDialog(null, form.format(source)); @@ -2925,7 +2908,7 @@ class OverWriteFileOKButtonListener implements ActionListener { } catch (FileNotFoundException fnfe) { if (filename == null || filename.equals("")) { tw.displayErrorDialog(null, new FileNotFoundException - (PolicyTool.rb.getString("null filename"))); + (PolicyTool.rb.getString("null.filename"))); } else { tw.displayErrorDialog(null, fnfe); } @@ -2977,9 +2960,7 @@ class AddEntryDoneButtonListener implements ActionListener { if (pubKey == null) { MessageFormat form = new MessageFormat (PolicyTool.rb.getString - ("Warning: A public key for alias " + - "'signers[i]' does not exist. " + - "Make sure a KeyStore is properly configured.")); + ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured.")); Object[] source = {signers[i]}; tool.warnings.addElement(form.format(source)); tw.displayStatusDialog(td, form.format(source)); @@ -3047,7 +3028,7 @@ class ChangeKeyStoreOKButtonListener implements ActionListener { tool.modified = true; } catch (Exception ex) { MessageFormat form = new MessageFormat(PolicyTool.rb.getString - ("Unable to open KeyStore: ex.toString()")); + ("Unable.to.open.KeyStore.ex.toString.")); Object[] source = {ex.toString()}; tw.displayErrorDialog(td, form.format(source)); return; @@ -3143,7 +3124,7 @@ class NewPolicyPrinOKButtonListener implements ActionListener { } catch (ClassNotFoundException cnfe) { MessageFormat form = new MessageFormat (PolicyTool.rb.getString - ("Warning: Class not found: class")); + ("Warning.Class.not.found.class")); Object[] source = {pppe.getPrincipalClass()}; tool.warnings.addElement(form.format(source)); tw.displayStatusDialog(infoDialog, form.format(source)); @@ -3204,7 +3185,7 @@ class NewPolicyPermOKButtonListener implements ActionListener { tool.verifyPermission(pppe.permission, pppe.name, pppe.action); } catch (ClassNotFoundException cnfe) { MessageFormat form = new MessageFormat(PolicyTool.rb.getString - ("Warning: Class not found: class")); + ("Warning.Class.not.found.class")); Object[] source = {pppe.permission}; tool.warnings.addElement(form.format(source)); tw.displayStatusDialog(infoDialog, form.format(source)); @@ -3259,7 +3240,7 @@ class RemovePrinButtonListener implements ActionListener { if (prinIndex < 0) { tw.displayErrorDialog(td, new Exception - (PolicyTool.rb.getString("No principal selected"))); + (PolicyTool.rb.getString("No.principal.selected"))); return; } // remove the principal from the display @@ -3293,7 +3274,7 @@ class RemovePermButtonListener implements ActionListener { if (permIndex < 0) { tw.displayErrorDialog(td, new Exception - (PolicyTool.rb.getString("No permission selected"))); + (PolicyTool.rb.getString("No.permission.selected"))); return; } // remove the permission from the display @@ -3334,7 +3315,7 @@ class EditPrinButtonListener implements ActionListener { if (prinIndex < 0) { tw.displayErrorDialog(td, new Exception - (PolicyTool.rb.getString("No principal selected"))); + (PolicyTool.rb.getString("No.principal.selected"))); return; } td.displayPrincipalDialog(editPolicyEntry, true); @@ -3373,7 +3354,7 @@ class EditPermButtonListener implements ActionListener { if (permIndex < 0) { tw.displayErrorDialog(td, new Exception - (PolicyTool.rb.getString("No permission selected"))); + (PolicyTool.rb.getString("No.permission.selected"))); return; } td.displayPermissionDialog(editPolicyEntry, true); @@ -3668,7 +3649,7 @@ class UserSaveYesButtonListener implements ActionListener { // display status MessageFormat form = new MessageFormat (PolicyTool.rb.getString - ("Policy successfully written to filename")); + ("Policy.successfully.written.to.filename")); Object[] source = {filename}; tw.displayStatusDialog(null, form.format(source)); @@ -3900,7 +3881,7 @@ class AuthPerm extends Perm { "getLoginConfiguration", "setLoginConfiguration", "createLoginConfiguration.<" + - PolicyTool.rb.getString("configuration type") + ">", + PolicyTool.rb.getString("configuration.type") + ">", "refreshLoginConfiguration" }, null); @@ -4117,7 +4098,7 @@ class RuntimePerm extends Perm { "setSecurityManager", "createSecurityManager", "getenv.<" + - PolicyTool.rb.getString("environment variable name") + ">", + PolicyTool.rb.getString("environment.variable.name") + ">", "exitVM", "shutdownHooks", "setFactory", @@ -4129,11 +4110,11 @@ class RuntimePerm extends Perm { "readFileDescriptor", "writeFileDescriptor", "loadLibrary.<" + - PolicyTool.rb.getString("library name") + ">", + PolicyTool.rb.getString("library.name") + ">", "accessClassInPackage.<" + - PolicyTool.rb.getString("package name")+">", + PolicyTool.rb.getString("package.name")+">", "defineClassInPackage.<" + - PolicyTool.rb.getString("package name")+">", + PolicyTool.rb.getString("package.name")+">", "accessDeclaredMembers", "queuePrintJob", "getStackTrace", @@ -4156,15 +4137,15 @@ class SecurityPerm extends Perm { "getPolicy", "setPolicy", "createPolicy.<" + - PolicyTool.rb.getString("policy type") + ">", + PolicyTool.rb.getString("policy.type") + ">", "getProperty.<" + - PolicyTool.rb.getString("property name") + ">", + PolicyTool.rb.getString("property.name") + ">", "setProperty.<" + - PolicyTool.rb.getString("property name") + ">", + PolicyTool.rb.getString("property.name") + ">", "insertProvider.<" + - PolicyTool.rb.getString("provider name") + ">", + PolicyTool.rb.getString("provider.name") + ">", "removeProvider.<" + - PolicyTool.rb.getString("provider name") + ">", + PolicyTool.rb.getString("provider.name") + ">", //"setSystemScope", //"setIdentityPublicKey", //"setIdentityInfo", @@ -4172,11 +4153,11 @@ class SecurityPerm extends Perm { //"removeIdentityCertificate", //"printIdentity", "clearProviderProperties.<" + - PolicyTool.rb.getString("provider name") + ">", + PolicyTool.rb.getString("provider.name") + ">", "putProviderProperty.<" + - PolicyTool.rb.getString("provider name") + ">", + PolicyTool.rb.getString("provider.name") + ">", "removeProviderProperty.<" + - PolicyTool.rb.getString("provider name") + ">", + PolicyTool.rb.getString("provider.name") + ">", //"getSignerPrivateKey", //"setSignerKeyPair" }, diff --git a/src/share/classes/sun/security/util/AuthResources.java b/src/share/classes/sun/security/util/AuthResources.java index 7633ed072e9fa676955032366d7dacd7ceaa47f9..68d8d9edbe247d3bb95c363797803e951c3c9260 100644 --- a/src/share/classes/sun/security/util/AuthResources.java +++ b/src/share/classes/sun/security/util/AuthResources.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -40,103 +40,103 @@ public class AuthResources extends java.util.ListResourceBundle { private static final Object[][] contents = { // NT principals - {"invalid null input: value", "invalid null input: {0}"}, - {"NTDomainPrincipal: name", "NTDomainPrincipal: {0}"}, - {"NTNumericCredential: name", "NTNumericCredential: {0}"}, - {"Invalid NTSid value", "Invalid NTSid value"}, - {"NTSid: name", "NTSid: {0}"}, - {"NTSidDomainPrincipal: name", "NTSidDomainPrincipal: {0}"}, - {"NTSidGroupPrincipal: name", "NTSidGroupPrincipal: {0}"}, - {"NTSidPrimaryGroupPrincipal: name", "NTSidPrimaryGroupPrincipal: {0}"}, - {"NTSidUserPrincipal: name", "NTSidUserPrincipal: {0}"}, - {"NTUserPrincipal: name", "NTUserPrincipal: {0}"}, + {"invalid.null.input.value", "invalid null input: {0}"}, + {"NTDomainPrincipal.name", "NTDomainPrincipal: {0}"}, + {"NTNumericCredential.name", "NTNumericCredential: {0}"}, + {"Invalid.NTSid.value", "Invalid NTSid value"}, + {"NTSid.name", "NTSid: {0}"}, + {"NTSidDomainPrincipal.name", "NTSidDomainPrincipal: {0}"}, + {"NTSidGroupPrincipal.name", "NTSidGroupPrincipal: {0}"}, + {"NTSidPrimaryGroupPrincipal.name", "NTSidPrimaryGroupPrincipal: {0}"}, + {"NTSidUserPrincipal.name", "NTSidUserPrincipal: {0}"}, + {"NTUserPrincipal.name", "NTUserPrincipal: {0}"}, // UnixPrincipals - {"UnixNumericGroupPrincipal [Primary Group]: name", + {"UnixNumericGroupPrincipal.Primary.Group.name", "UnixNumericGroupPrincipal [Primary Group]: {0}"}, - {"UnixNumericGroupPrincipal [Supplementary Group]: name", + {"UnixNumericGroupPrincipal.Supplementary.Group.name", "UnixNumericGroupPrincipal [Supplementary Group]: {0}"}, - {"UnixNumericUserPrincipal: name", "UnixNumericUserPrincipal: {0}"}, - {"UnixPrincipal: name", "UnixPrincipal: {0}"}, + {"UnixNumericUserPrincipal.name", "UnixNumericUserPrincipal: {0}"}, + {"UnixPrincipal.name", "UnixPrincipal: {0}"}, // com.sun.security.auth.login.ConfigFile - {"Unable to properly expand config", "Unable to properly expand {0}"}, - {"extra_config (No such file or directory)", + {"Unable.to.properly.expand.config", "Unable to properly expand {0}"}, + {"extra.config.No.such.file.or.directory.", "{0} (No such file or directory)"}, - {"Configuration Error:\n\tNo such file or directory", + {"Configuration.Error.No.such.file.or.directory", "Configuration Error:\n\tNo such file or directory"}, - {"Configuration Error:\n\tInvalid control flag, flag", + {"Configuration.Error.Invalid.control.flag.flag", "Configuration Error:\n\tInvalid control flag, {0}"}, - {"Configuration Error:\n\tCan not specify multiple entries for appName", + {"Configuration.Error.Can.not.specify.multiple.entries.for.appName", "Configuration Error:\n\tCan not specify multiple entries for {0}"}, - {"Configuration Error:\n\texpected [expect], read [end of file]", + {"Configuration.Error.expected.expect.read.end.of.file.", "Configuration Error:\n\texpected [{0}], read [end of file]"}, - {"Configuration Error:\n\tLine line: expected [expect], found [value]", + {"Configuration.Error.Line.line.expected.expect.found.value.", "Configuration Error:\n\tLine {0}: expected [{1}], found [{2}]"}, - {"Configuration Error:\n\tLine line: expected [expect]", + {"Configuration.Error.Line.line.expected.expect.", "Configuration Error:\n\tLine {0}: expected [{1}]"}, - {"Configuration Error:\n\tLine line: system property [value] expanded to empty value", + {"Configuration.Error.Line.line.system.property.value.expanded.to.empty.value", "Configuration Error:\n\tLine {0}: system property [{1}] expanded to empty value"}, // com.sun.security.auth.module.JndiLoginModule - {"username: ","username: "}, - {"password: ","password: "}, + {"username.","username: "}, + {"password.","password: "}, // com.sun.security.auth.module.KeyStoreLoginModule - {"Please enter keystore information", + {"Please.enter.keystore.information", "Please enter keystore information"}, - {"Keystore alias: ","Keystore alias: "}, - {"Keystore password: ","Keystore password: "}, - {"Private key password (optional): ", + {"Keystore.alias.","Keystore alias: "}, + {"Keystore.password.","Keystore password: "}, + {"Private.key.password.optional.", "Private key password (optional): "}, // com.sun.security.auth.module.Krb5LoginModule - {"Kerberos username [[defUsername]]: ", + {"Kerberos.username.defUsername.", "Kerberos username [{0}]: "}, - {"Kerberos password for [username]: ", + {"Kerberos.password.for.username.", "Kerberos password for {0}: "}, /*** EVERYTHING BELOW IS DEPRECATED ***/ // com.sun.security.auth.PolicyFile - {": error parsing ", ": error parsing "}, - {": ", ": "}, - {": error adding Permission ", ": error adding Permission "}, - {" ", " "}, - {": error adding Entry ", ": error adding Entry "}, - {"(", "("}, - {")", ")"}, - {"attempt to add a Permission to a readonly PermissionCollection", + {".error.parsing.", ": error parsing "}, + {"COLON", ": "}, + {".error.adding.Permission.", ": error adding Permission "}, + {"SPACE", " "}, + {".error.adding.Entry.", ": error adding Entry "}, + {"LPARAM", "("}, + {"RPARAM", ")"}, + {"attempt.to.add.a.Permission.to.a.readonly.PermissionCollection", "attempt to add a Permission to a readonly PermissionCollection"}, // com.sun.security.auth.PolicyParser - {"expected keystore type", "expected keystore type"}, - {"can not specify Principal with a ", + {"expected.keystore.type", "expected keystore type"}, + {"can.not.specify.Principal.with.a.", "can not specify Principal with a "}, - {"wildcard class without a wildcard name", + {"wildcard.class.without.a.wildcard.name", "wildcard class without a wildcard name"}, - {"expected codeBase or SignedBy", "expected codeBase or SignedBy"}, - {"only Principal-based grant entries permitted", + {"expected.codeBase.or.SignedBy", "expected codeBase or SignedBy"}, + {"only.Principal.based.grant.entries.permitted", "only Principal-based grant entries permitted"}, - {"expected permission entry", "expected permission entry"}, - {"number ", "number "}, - {"expected ", "expected "}, - {", read end of file", ", read end of file"}, - {"expected ';', read end of file", "expected ';', read end of file"}, - {"line ", "line "}, - {": expected '", ": expected '"}, - {"', found '", "', found '"}, - {"'", "'"}, + {"expected.permission.entry", "expected permission entry"}, + {"number.", "number "}, + {"expected.", "expected "}, + {".read.end.of.file", ", read end of file"}, + {"expected.read.end.of.file", "expected ';', read end of file"}, + {"line.", "line "}, + {".expected.", ": expected '"}, + {".found.", "', found '"}, + {"QUOTE", "'"}, // SolarisPrincipals - {"SolarisNumericGroupPrincipal [Primary Group]: ", + {"SolarisNumericGroupPrincipal.Primary.Group.", "SolarisNumericGroupPrincipal [Primary Group]: "}, - {"SolarisNumericGroupPrincipal [Supplementary Group]: ", + {"SolarisNumericGroupPrincipal.Supplementary.Group.", "SolarisNumericGroupPrincipal [Supplementary Group]: "}, - {"SolarisNumericUserPrincipal: ", + {"SolarisNumericUserPrincipal.", "SolarisNumericUserPrincipal: "}, - {"SolarisPrincipal: ", "SolarisPrincipal: "}, - {"provided null name", "provided null name"} + {"SolarisPrincipal.", "SolarisPrincipal: "}, + {"provided.null.name", "provided null name"} }; diff --git a/src/share/classes/sun/security/util/Resources.java b/src/share/classes/sun/security/util/Resources.java index 1186c2980543465aa4c14d3b816f8acbcbebe9c1..5489c3d9eaa86e3a4ea1239a6577cc2027e6a3a8 100644 --- a/src/share/classes/sun/security/util/Resources.java +++ b/src/share/classes/sun/security/util/Resources.java @@ -35,434 +35,428 @@ public class Resources extends java.util.ListResourceBundle { private static final Object[][] contents = { // shared (from jarsigner) - {" ", " "}, - {" ", " "}, - {" ", " "}, - {", ", ", "}, + {"SPACE", " "}, + {"2SPACE", " "}, + {"6SPACE", " "}, + {"COMMA", ", "}, // shared (from keytool) - {"\n", "\n"}, - {"*******************************************", + {"NEWLINE", "\n"}, + {"STAR", "*******************************************"}, - {"*******************************************\n\n", + {"STARNN", "*******************************************\n\n"}, // keytool: Help part - {" [OPTION]...", " [OPTION]..."}, - {"Options:", "Options:"}, - {"Use \"keytool -help\" for all available commands", + {".OPTION.", " [OPTION]..."}, + {"Options.", "Options:"}, + {"Use.keytool.help.for.all.available.commands", "Use \"keytool -help\" for all available commands"}, - {"Key and Certificate Management Tool", + {"Key.and.Certificate.Management.Tool", "Key and Certificate Management Tool"}, - {"Commands:", "Commands:"}, - {"Use \"keytool -command_name -help\" for usage of command_name", + {"Commands.", "Commands:"}, + {"Use.keytool.command.name.help.for.usage.of.command.name", "Use \"keytool -command_name -help\" for usage of command_name"}, // keytool: help: commands - {"Generates a certificate request", + {"Generates.a.certificate.request", "Generates a certificate request"}, //-certreq - {"Changes an entry's alias", + {"Changes.an.entry.s.alias", "Changes an entry's alias"}, //-changealias - {"Deletes an entry", + {"Deletes.an.entry", "Deletes an entry"}, //-delete - {"Exports certificate", + {"Exports.certificate", "Exports certificate"}, //-exportcert - {"Generates a key pair", + {"Generates.a.key.pair", "Generates a key pair"}, //-genkeypair - {"Generates a secret key", + {"Generates.a.secret.key", "Generates a secret key"}, //-genseckey - {"Generates certificate from a certificate request", + {"Generates.certificate.from.a.certificate.request", "Generates certificate from a certificate request"}, //-gencert - {"Generates CRL", "Generates CRL"}, //-gencrl - {"Imports entries from a JDK 1.1.x-style identity database", + {"Generates.CRL", "Generates CRL"}, //-gencrl + {"Imports.entries.from.a.JDK.1.1.x.style.identity.database", "Imports entries from a JDK 1.1.x-style identity database"}, //-identitydb - {"Imports a certificate or a certificate chain", + {"Imports.a.certificate.or.a.certificate.chain", "Imports a certificate or a certificate chain"}, //-importcert - {"Imports one or all entries from another keystore", + {"Imports.one.or.all.entries.from.another.keystore", "Imports one or all entries from another keystore"}, //-importkeystore - {"Clones a key entry", + {"Clones.a.key.entry", "Clones a key entry"}, //-keyclone - {"Changes the key password of an entry", + {"Changes.the.key.password.of.an.entry", "Changes the key password of an entry"}, //-keypasswd - {"Lists entries in a keystore", + {"Lists.entries.in.a.keystore", "Lists entries in a keystore"}, //-list - {"Prints the content of a certificate", + {"Prints.the.content.of.a.certificate", "Prints the content of a certificate"}, //-printcert - {"Prints the content of a certificate request", + {"Prints.the.content.of.a.certificate.request", "Prints the content of a certificate request"}, //-printcertreq - {"Prints the content of a CRL file", + {"Prints.the.content.of.a.CRL.file", "Prints the content of a CRL file"}, //-printcrl - {"Generates a self-signed certificate", + {"Generates.a.self.signed.certificate", "Generates a self-signed certificate"}, //-selfcert - {"Changes the store password of a keystore", + {"Changes.the.store.password.of.a.keystore", "Changes the store password of a keystore"}, //-storepasswd // keytool: help: options - {"alias name of the entry to process", + {"alias.name.of.the.entry.to.process", "alias name of the entry to process"}, //-alias - {"destination alias", + {"destination.alias", "destination alias"}, //-destalias - {"destination key password", + {"destination.key.password", "destination key password"}, //-destkeypass - {"destination keystore name", + {"destination.keystore.name", "destination keystore name"}, //-destkeystore - {"destination keystore password protected", + {"destination.keystore.password.protected", "destination keystore password protected"}, //-destprotected - {"destination keystore provider name", + {"destination.keystore.provider.name", "destination keystore provider name"}, //-destprovidername - {"destination keystore password", + {"destination.keystore.password", "destination keystore password"}, //-deststorepass - {"destination keystore type", + {"destination.keystore.type", "destination keystore type"}, //-deststoretype - {"distinguished name", + {"distinguished.name", "distinguished name"}, //-dname - {"X.509 extension", + {"X.509.extension", "X.509 extension"}, //-ext - {"output file name", + {"output.file.name", "output file name"}, //-file and -outfile - {"input file name", + {"input.file.name", "input file name"}, //-file and -infile - {"key algorithm name", + {"key.algorithm.name", "key algorithm name"}, //-keyalg - {"key password", + {"key.password", "key password"}, //-keypass - {"key bit size", + {"key.bit.size", "key bit size"}, //-keysize - {"keystore name", + {"keystore.name", "keystore name"}, //-keystore - {"new password", + {"new.password", "new password"}, //-new - {"do not prompt", + {"do.not.prompt", "do not prompt"}, //-noprompt - {"password through protected mechanism", + {"password.through.protected.mechanism", "password through protected mechanism"}, //-protected - {"provider argument", + {"provider.argument", "provider argument"}, //-providerarg - {"provider class name", + {"provider.class.name", "provider class name"}, //-providerclass - {"provider name", + {"provider.name", "provider name"}, //-providername - {"provider classpath", + {"provider.classpath", "provider classpath"}, //-providerpath - {"output in RFC style", + {"output.in.RFC.style", "output in RFC style"}, //-rfc - {"signature algorithm name", + {"signature.algorithm.name", "signature algorithm name"}, //-sigalg - {"source alias", + {"source.alias", "source alias"}, //-srcalias - {"source key password", + {"source.key.password", "source key password"}, //-srckeypass - {"source keystore name", + {"source.keystore.name", "source keystore name"}, //-srckeystore - {"source keystore password protected", + {"source.keystore.password.protected", "source keystore password protected"}, //-srcprotected - {"source keystore provider name", + {"source.keystore.provider.name", "source keystore provider name"}, //-srcprovidername - {"source keystore password", + {"source.keystore.password", "source keystore password"}, //-srcstorepass - {"source keystore type", + {"source.keystore.type", "source keystore type"}, //-srcstoretype - {"SSL server host and port", + {"SSL.server.host.and.port", "SSL server host and port"}, //-sslserver - {"signed jar file", + {"signed.jar.file", "signed jar file"}, //=jarfile - {"certificate validity start date/time", + {"certificate.validity.start.date.time", "certificate validity start date/time"}, //-startdate - {"keystore password", + {"keystore.password", "keystore password"}, //-storepass - {"keystore type", + {"keystore.type", "keystore type"}, //-storetype - {"trust certificates from cacerts", + {"trust.certificates.from.cacerts", "trust certificates from cacerts"}, //-trustcacerts - {"verbose output", + {"verbose.output", "verbose output"}, //-v - {"validity number of days", + {"validity.number.of.days", "validity number of days"}, //-validity - {"Serial ID of cert to revoke", + {"Serial.ID.of.cert.to.revoke", "Serial ID of cert to revoke"}, //-id // keytool: Running part - {"keytool error: ", "keytool error: "}, - {"Illegal option: ", "Illegal option: "}, - {"Illegal value: ", "Illegal value: "}, - {"Unknown password type: ", "Unknown password type: "}, - {"Cannot find environment variable: ", + {"keytool.error.", "keytool error: "}, + {"Illegal.option.", "Illegal option: "}, + {"Illegal.value.", "Illegal value: "}, + {"Unknown.password.type.", "Unknown password type: "}, + {"Cannot.find.environment.variable.", "Cannot find environment variable: "}, - {"Cannot find file: ", "Cannot find file: "}, - {"Command option needs an argument.", "Command option {0} needs an argument."}, - {"Warning: Different store and key passwords not supported for PKCS12 KeyStores. Ignoring user-specified value.", + {"Cannot.find.file.", "Cannot find file: "}, + {"Command.option.flag.needs.an.argument.", "Command option {0} needs an argument."}, + {"Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value.", "Warning: Different store and key passwords not supported for PKCS12 KeyStores. Ignoring user-specified {0} value."}, - {"-keystore must be NONE if -storetype is {0}", + {".keystore.must.be.NONE.if.storetype.is.{0}", "-keystore must be NONE if -storetype is {0}"}, - {"Too many retries, program terminated", + {"Too.many.retries.program.terminated", "Too many retries, program terminated"}, - {"-storepasswd and -keypasswd commands not supported if -storetype is {0}", + {".storepasswd.and.keypasswd.commands.not.supported.if.storetype.is.{0}", "-storepasswd and -keypasswd commands not supported if -storetype is {0}"}, - {"-keypasswd commands not supported if -storetype is PKCS12", + {".keypasswd.commands.not.supported.if.storetype.is.PKCS12", "-keypasswd commands not supported if -storetype is PKCS12"}, - {"-keypass and -new can not be specified if -storetype is {0}", + {".keypass.and.new.can.not.be.specified.if.storetype.is.{0}", "-keypass and -new can not be specified if -storetype is {0}"}, - {"if -protected is specified, then -storepass, -keypass, and -new must not be specified", + {"if.protected.is.specified.then.storepass.keypass.and.new.must.not.be.specified", "if -protected is specified, then -storepass, -keypass, and -new must not be specified"}, - {"if -srcprotected is specified, then -srcstorepass and -srckeypass must not be specified", + {"if.srcprotected.is.specified.then.srcstorepass.and.srckeypass.must.not.be.specified", "if -srcprotected is specified, then -srcstorepass and -srckeypass must not be specified"}, - {"if keystore is not password protected, then -storepass, -keypass, and -new must not be specified", + {"if.keystore.is.not.password.protected.then.storepass.keypass.and.new.must.not.be.specified", "if keystore is not password protected, then -storepass, -keypass, and -new must not be specified"}, - {"if source keystore is not password protected, then -srcstorepass and -srckeypass must not be specified", + {"if.source.keystore.is.not.password.protected.then.srcstorepass.and.srckeypass.must.not.be.specified", "if source keystore is not password protected, then -srcstorepass and -srckeypass must not be specified"}, - {"Illegal startdate value", "Illegal startdate value"}, - {"Validity must be greater than zero", + {"Illegal.startdate.value", "Illegal startdate value"}, + {"Validity.must.be.greater.than.zero", "Validity must be greater than zero"}, - {"provName not a provider", "{0} not a provider"}, - {"Usage error: no command provided", "Usage error: no command provided"}, - {"Source keystore file exists, but is empty: ", "Source keystore file exists, but is empty: "}, - {"Please specify -srckeystore", "Please specify -srckeystore"}, - {"Must not specify both -v and -rfc with 'list' command", + {"provName.not.a.provider", "{0} not a provider"}, + {"Usage.error.no.command.provided", "Usage error: no command provided"}, + {"Source.keystore.file.exists.but.is.empty.", "Source keystore file exists, but is empty: "}, + {"Please.specify.srckeystore", "Please specify -srckeystore"}, + {"Must.not.specify.both.v.and.rfc.with.list.command", "Must not specify both -v and -rfc with 'list' command"}, - {"Key password must be at least 6 characters", + {"Key.password.must.be.at.least.6.characters", "Key password must be at least 6 characters"}, - {"New password must be at least 6 characters", + {"New.password.must.be.at.least.6.characters", "New password must be at least 6 characters"}, - {"Keystore file exists, but is empty: ", + {"Keystore.file.exists.but.is.empty.", "Keystore file exists, but is empty: "}, - {"Keystore file does not exist: ", + {"Keystore.file.does.not.exist.", "Keystore file does not exist: "}, - {"Must specify destination alias", "Must specify destination alias"}, - {"Must specify alias", "Must specify alias"}, - {"Keystore password must be at least 6 characters", + {"Must.specify.destination.alias", "Must specify destination alias"}, + {"Must.specify.alias", "Must specify alias"}, + {"Keystore.password.must.be.at.least.6.characters", "Keystore password must be at least 6 characters"}, - {"Enter keystore password: ", "Enter keystore password: "}, - {"Enter source keystore password: ", "Enter source keystore password: "}, - {"Enter destination keystore password: ", "Enter destination keystore password: "}, - {"Keystore password is too short - must be at least 6 characters", + {"Enter.keystore.password.", "Enter keystore password: "}, + {"Enter.source.keystore.password.", "Enter source keystore password: "}, + {"Enter.destination.keystore.password.", "Enter destination keystore password: "}, + {"Keystore.password.is.too.short.must.be.at.least.6.characters", "Keystore password is too short - must be at least 6 characters"}, - {"Unknown Entry Type", "Unknown Entry Type"}, - {"Too many failures. Alias not changed", "Too many failures. Alias not changed"}, - {"Entry for alias successfully imported.", + {"Unknown.Entry.Type", "Unknown Entry Type"}, + {"Too.many.failures.Alias.not.changed", "Too many failures. Alias not changed"}, + {"Entry.for.alias.alias.successfully.imported.", "Entry for alias {0} successfully imported."}, - {"Entry for alias not imported.", "Entry for alias {0} not imported."}, - {"Problem importing entry for alias : .\nEntry for alias not imported.", + {"Entry.for.alias.alias.not.imported.", "Entry for alias {0} not imported."}, + {"Problem.importing.entry.for.alias.alias.exception.Entry.for.alias.alias.not.imported.", "Problem importing entry for alias {0}: {1}.\nEntry for alias {0} not imported."}, - {"Import command completed: entries successfully imported, entries failed or cancelled", + {"Import.command.completed.ok.entries.successfully.imported.fail.entries.failed.or.cancelled", "Import command completed: {0} entries successfully imported, {1} entries failed or cancelled"}, - {"Warning: Overwriting existing alias in destination keystore", + {"Warning.Overwriting.existing.alias.alias.in.destination.keystore", "Warning: Overwriting existing alias {0} in destination keystore"}, - {"Existing entry alias exists, overwrite? [no]: ", + {"Existing.entry.alias.alias.exists.overwrite.no.", "Existing entry alias {0} exists, overwrite? [no]: "}, - {"Too many failures - try later", "Too many failures - try later"}, - {"Certification request stored in file ", + {"Too.many.failures.try.later", "Too many failures - try later"}, + {"Certification.request.stored.in.file.filename.", "Certification request stored in file <{0}>"}, - {"Submit this to your CA", "Submit this to your CA"}, - {"if alias not specified, destalias, srckeypass, and destkeypass must not be specified", + {"Submit.this.to.your.CA", "Submit this to your CA"}, + {"if.alias.not.specified.destalias.srckeypass.and.destkeypass.must.not.be.specified", "if alias not specified, destalias, srckeypass, and destkeypass must not be specified"}, - {"Certificate stored in file ", + {"Certificate.stored.in.file.filename.", "Certificate stored in file <{0}>"}, - {"Certificate reply was installed in keystore", + {"Certificate.reply.was.installed.in.keystore", "Certificate reply was installed in keystore"}, - {"Certificate reply was not installed in keystore", + {"Certificate.reply.was.not.installed.in.keystore", "Certificate reply was not installed in keystore"}, - {"Certificate was added to keystore", + {"Certificate.was.added.to.keystore", "Certificate was added to keystore"}, - {"Certificate was not added to keystore", + {"Certificate.was.not.added.to.keystore", "Certificate was not added to keystore"}, - {"[Storing ksfname]", "[Storing {0}]"}, - {"alias has no public key (certificate)", + {".Storing.ksfname.", "[Storing {0}]"}, + {"alias.has.no.public.key.certificate.", "{0} has no public key (certificate)"}, - {"Cannot derive signature algorithm", + {"Cannot.derive.signature.algorithm", "Cannot derive signature algorithm"}, - {"Alias does not exist", + {"Alias.alias.does.not.exist", "Alias <{0}> does not exist"}, - {"Alias has no certificate", + {"Alias.alias.has.no.certificate", "Alias <{0}> has no certificate"}, - {"Key pair not generated, alias already exists", + {"Key.pair.not.generated.alias.alias.already.exists", "Key pair not generated, alias <{0}> already exists"}, - {"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.for", "Generating {0} bit {1} key pair and self-signed certificate ({2}) with a validity of {3} days\n\tfor: {4}"}, - {"Enter key password for ", "Enter key password for <{0}>"}, - {"\t(RETURN if same as keystore password): ", + {"Enter.key.password.for.alias.", "Enter key password for <{0}>"}, + {".RETURN.if.same.as.keystore.password.", "\t(RETURN if same as keystore password): "}, - {"Key password is too short - must be at least 6 characters", + {"Key.password.is.too.short.must.be.at.least.6.characters", "Key password is too short - must be at least 6 characters"}, - {"Too many failures - key not added to keystore", + {"Too.many.failures.key.not.added.to.keystore", "Too many failures - key not added to keystore"}, - {"Destination alias already exists", + {"Destination.alias.dest.already.exists", "Destination alias <{0}> already exists"}, - {"Password is too short - must be at least 6 characters", + {"Password.is.too.short.must.be.at.least.6.characters", "Password is too short - must be at least 6 characters"}, - {"Too many failures. Key entry not cloned", + {"Too.many.failures.Key.entry.not.cloned", "Too many failures. Key entry not cloned"}, - {"key password for ", "key password for <{0}>"}, - {"Keystore entry for already exists", + {"key.password.for.alias.", "key password for <{0}>"}, + {"Keystore.entry.for.id.getName.already.exists", "Keystore entry for <{0}> already exists"}, - {"Creating keystore entry for ...", + {"Creating.keystore.entry.for.id.getName.", "Creating keystore entry for <{0}> ..."}, - {"No entries from identity database added", + {"No.entries.from.identity.database.added", "No entries from identity database added"}, - {"Alias name: alias", "Alias name: {0}"}, - {"Creation date: keyStore.getCreationDate(alias)", + {"Alias.name.alias", "Alias name: {0}"}, + {"Creation.date.keyStore.getCreationDate.alias.", "Creation date: {0,date}"}, - {"alias, keyStore.getCreationDate(alias), ", + {"alias.keyStore.getCreationDate.alias.", "{0}, {1,date}, "}, - {"alias, ", "{0}, "}, - {"Entry type: ", "Entry type: {0}"}, - {"Certificate chain length: ", "Certificate chain length: "}, - {"Certificate[(i + 1)]:", "Certificate[{0,number,integer}]:"}, - {"Certificate fingerprint (SHA1): ", "Certificate fingerprint (SHA1): "}, - {"Entry type: trustedCertEntry\n", "Entry type: trustedCertEntry\n"}, - {"trustedCertEntry,", "trustedCertEntry,"}, - {"Keystore type: ", "Keystore type: "}, - {"Keystore provider: ", "Keystore provider: "}, - {"Your keystore contains keyStore.size() entry", + {"alias.", "{0}, "}, + {"Entry.type.type.", "Entry type: {0}"}, + {"Certificate.chain.length.", "Certificate chain length: "}, + {"Certificate.i.1.", "Certificate[{0,number,integer}]:"}, + {"Certificate.fingerprint.SHA1.", "Certificate fingerprint (SHA1): "}, + {"Entry.type.trustedCertEntry.", "Entry type: trustedCertEntry\n"}, + {"trustedCertEntry.", "trustedCertEntry,"}, + {"Keystore.type.", "Keystore type: "}, + {"Keystore.provider.", "Keystore provider: "}, + {"Your.keystore.contains.keyStore.size.entry", "Your keystore contains {0,number,integer} entry"}, - {"Your keystore contains keyStore.size() entries", + {"Your.keystore.contains.keyStore.size.entries", "Your keystore contains {0,number,integer} entries"}, - {"Failed to parse input", "Failed to parse input"}, - {"Empty input", "Empty input"}, - {"Not X.509 certificate", "Not X.509 certificate"}, - {"alias has no public key", "{0} has no public key"}, - {"alias has no X.509 certificate", "{0} has no X.509 certificate"}, - {"New certificate (self-signed):", "New certificate (self-signed):"}, - {"Reply has no certificates", "Reply has no certificates"}, - {"Certificate not imported, alias already exists", + {"Failed.to.parse.input", "Failed to parse input"}, + {"Empty.input", "Empty input"}, + {"Not.X.509.certificate", "Not X.509 certificate"}, + {"alias.has.no.public.key", "{0} has no public key"}, + {"alias.has.no.X.509.certificate", "{0} has no X.509 certificate"}, + {"New.certificate.self.signed.", "New certificate (self-signed):"}, + {"Reply.has.no.certificates", "Reply has no certificates"}, + {"Certificate.not.imported.alias.alias.already.exists", "Certificate not imported, alias <{0}> already exists"}, - {"Input not an X.509 certificate", "Input not an X.509 certificate"}, - {"Certificate already exists in keystore under alias ", + {"Input.not.an.X.509.certificate", "Input not an X.509 certificate"}, + {"Certificate.already.exists.in.keystore.under.alias.trustalias.", "Certificate already exists in keystore under alias <{0}>"}, - {"Do you still want to add it? [no]: ", + {"Do.you.still.want.to.add.it.no.", "Do you still want to add it? [no]: "}, - {"Certificate already exists in system-wide CA keystore under alias ", + {"Certificate.already.exists.in.system.wide.CA.keystore.under.alias.trustalias.", "Certificate already exists in system-wide CA keystore under alias <{0}>"}, - {"Do you still want to add it to your own keystore? [no]: ", + {"Do.you.still.want.to.add.it.to.your.own.keystore.no.", "Do you still want to add it to your own keystore? [no]: "}, - {"Trust this certificate? [no]: ", "Trust this certificate? [no]: "}, + {"Trust.this.certificate.no.", "Trust this certificate? [no]: "}, {"YES", "YES"}, - {"New prompt: ", "New {0}: "}, - {"Passwords must differ", "Passwords must differ"}, - {"Re-enter new prompt: ", "Re-enter new {0}: "}, - {"Re-enter new password: ", "Re-enter new password: "}, - {"They don't match. Try again", "They don't match. Try again"}, - {"Enter prompt alias name: ", "Enter {0} alias name: "}, - {"Enter new alias name\t(RETURN to cancel import for this entry): ", + {"New.prompt.", "New {0}: "}, + {"Passwords.must.differ", "Passwords must differ"}, + {"Re.enter.new.prompt.", "Re-enter new {0}: "}, + {"Re.enter.new.password.", "Re-enter new password: "}, + {"They.don.t.match.Try.again", "They don't match. Try again"}, + {"Enter.prompt.alias.name.", "Enter {0} alias name: "}, + {"Enter.new.alias.name.RETURN.to.cancel.import.for.this.entry.", "Enter new alias name\t(RETURN to cancel import for this entry): "}, - {"Enter alias name: ", "Enter alias name: "}, - {"\t(RETURN if same as for )", + {"Enter.alias.name.", "Enter alias name: "}, + {".RETURN.if.same.as.for.otherAlias.", "\t(RETURN if same as for <{0}>)"}, - {"*PATTERN* printX509Cert", + {".PATTERN.printX509Cert", "Owner: {0}\nIssuer: {1}\nSerial number: {2}\nValid from: {3} until: {4}\nCertificate fingerprints:\n\t MD5: {5}\n\t SHA1: {6}\n\t SHA256: {7}\n\t Signature algorithm name: {8}\n\t Version: {9}"}, - {"What is your first and last name?", + {"What.is.your.first.and.last.name.", "What is your first and last name?"}, - {"What is the name of your organizational unit?", + {"What.is.the.name.of.your.organizational.unit.", "What is the name of your organizational unit?"}, - {"What is the name of your organization?", + {"What.is.the.name.of.your.organization.", "What is the name of your organization?"}, - {"What is the name of your City or Locality?", + {"What.is.the.name.of.your.City.or.Locality.", "What is the name of your City or Locality?"}, - {"What is the name of your State or Province?", + {"What.is.the.name.of.your.State.or.Province.", "What is the name of your State or Province?"}, - {"What is the two-letter country code for this unit?", + {"What.is.the.two.letter.country.code.for.this.unit.", "What is the two-letter country code for this unit?"}, - {"Is correct?", "Is {0} correct?"}, + {"Is.name.correct.", "Is {0} correct?"}, {"no", "no"}, {"yes", "yes"}, {"y", "y"}, - {" [defaultValue]: ", " [{0}]: "}, - {"Alias has no key", + {".defaultValue.", " [{0}]: "}, + {"Alias.alias.has.no.key", "Alias <{0}> has no key"}, - {"Alias references an entry type that is not a private key entry. The -keyclone command only supports cloning of private key entries", + {"Alias.alias.references.an.entry.type.that.is.not.a.private.key.entry.The.keyclone.command.only.supports.cloning.of.private.key", "Alias <{0}> references an entry type that is not a private key entry. The -keyclone command only supports cloning of private key entries"}, - {"***************** WARNING WARNING WARNING *****************", + {".WARNING.WARNING.WARNING.", "***************** WARNING WARNING WARNING *****************"}, - {"Signer #%d:", "Signer #%d:"}, - {"Timestamp:", "Timestamp:"}, - {"Signature:", "Signature:"}, - {"CRLs:", "CRLs:"}, - {"Certificate owner: ", "Certificate owner: "}, - {"Not a signed jar file", "Not a signed jar file"}, - {"No certificate from the SSL server", + {"Signer.d.", "Signer #%d:"}, + {"Timestamp.", "Timestamp:"}, + {"Signature.", "Signature:"}, + {"CRLs.", "CRLs:"}, + {"Certificate.owner.", "Certificate owner: "}, + {"Not.a.signed.jar.file", "Not a signed jar file"}, + {"No.certificate.from.the.SSL.server", "No certificate from the SSL server"}, // Translators of the following 5 pairs, ATTENTION: // the next 5 string pairs are meant to be combined into 2 paragraphs, // 1+3+4 and 2+3+5. make sure your translation also does. - {"* The integrity of the information stored in your keystore *", + {".The.integrity.of.the.information.stored.in.your.keystore.", "* The integrity of the information stored in your keystore *"}, - {"* The integrity of the information stored in the srckeystore*", + {".The.integrity.of.the.information.stored.in.the.srckeystore.", "* The integrity of the information stored in the srckeystore*"}, - {"* has NOT been verified! In order to verify its integrity, *", + {".has.NOT.been.verified.In.order.to.verify.its.integrity.", "* has NOT been verified! In order to verify its integrity, *"}, - {"* you must provide your keystore password. *", + {".you.must.provide.your.keystore.password.", "* you must provide your keystore password. *"}, - {"* you must provide the srckeystore password. *", + {".you.must.provide.the.srckeystore.password.", "* you must provide the srckeystore password. *"}, - {"Certificate reply does not contain public key for ", + {"Certificate.reply.does.not.contain.public.key.for.alias.", "Certificate reply does not contain public key for <{0}>"}, - {"Incomplete certificate chain in reply", + {"Incomplete.certificate.chain.in.reply", "Incomplete certificate chain in reply"}, - {"Certificate chain in reply does not verify: ", + {"Certificate.chain.in.reply.does.not.verify.", "Certificate chain in reply does not verify: "}, - {"Top-level certificate in reply:\n", + {"Top.level.certificate.in.reply.", "Top-level certificate in reply:\n"}, - {"... is not trusted. ", "... is not trusted. "}, - {"Install reply anyway? [no]: ", "Install reply anyway? [no]: "}, + {".is.not.trusted.", "... is not trusted. "}, + {"Install.reply.anyway.no.", "Install reply anyway? [no]: "}, {"NO", "NO"}, - {"Public keys in reply and keystore don't match", + {"Public.keys.in.reply.and.keystore.don.t.match", "Public keys in reply and keystore don't match"}, - {"Certificate reply and certificate in keystore are identical", + {"Certificate.reply.and.certificate.in.keystore.are.identical", "Certificate reply and certificate in keystore are identical"}, - {"Failed to establish chain from reply", + {"Failed.to.establish.chain.from.reply", "Failed to establish chain from reply"}, {"n", "n"}, - {"Wrong answer, try again", "Wrong answer, try again"}, - {"Secret key not generated, alias already exists", + {"Wrong.answer.try.again", "Wrong answer, try again"}, + {"Secret.key.not.generated.alias.alias.already.exists", "Secret Key not generated, alias <{0}> already exists"}, - {"Please provide -keysize for secret key generation", + {"Please.provide.keysize.for.secret.key.generation", "Please provide -keysize for secret key generation"}, - {"Extensions: ", "Extensions: "}, - {"(Empty value)", "(Empty value)"}, - {"Extension Request:", "Extension Request:"}, - {"PKCS #10 Certificate Request (Version 1.0)\n" + - "Subject: %s\nPublic Key: %s format %s key\n", + {"Extensions.", "Extensions: "}, + {".Empty.value.", "(Empty value)"}, + {"Extension.Request.", "Extension Request:"}, + {"PKCS.10.Certificate.Request.Version.1.0.Subject.s.Public.Key.s.format.s.key.", "PKCS #10 Certificate Request (Version 1.0)\n" + "Subject: %s\nPublic Key: %s format %s key\n"}, - {"Unknown keyUsage type: ", "Unknown keyUsage type: "}, - {"Unknown extendedkeyUsage type: ", "Unknown extendedkeyUsage type: "}, - {"Unknown AccessDescription type: ", "Unknown AccessDescription type: "}, - {"Unrecognized GeneralName type: ", "Unrecognized GeneralName type: "}, - {"This extension cannot be marked as critical. ", + {"Unknown.keyUsage.type.", "Unknown keyUsage type: "}, + {"Unknown.extendedkeyUsage.type.", "Unknown extendedkeyUsage type: "}, + {"Unknown.AccessDescription.type.", "Unknown AccessDescription type: "}, + {"Unrecognized.GeneralName.type.", "Unrecognized GeneralName type: "}, + {"This.extension.cannot.be.marked.as.critical.", "This extension cannot be marked as critical. "}, - {"Odd number of hex digits found: ", "Odd number of hex digits found: "}, - {"Unknown extension type: ", "Unknown extension type: "}, - {"command {0} is ambiguous:", "command {0} is ambiguous:"}, + {"Odd.number.of.hex.digits.found.", "Odd number of hex digits found: "}, + {"Unknown.extension.type.", "Unknown extension type: "}, + {"command.{0}.is.ambiguous.", "command {0} is ambiguous:"}, // policytool - {"Warning: A public key for alias 'signers[i]' does not exist. Make sure a KeyStore is properly configured.", + {"Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured.", "Warning: A public key for alias {0} does not exist. Make sure a KeyStore is properly configured."}, - {"Warning: Class not found: class", "Warning: Class not found: {0}"}, - {"Warning: Invalid argument(s) for constructor: arg", + {"Warning.Class.not.found.class", "Warning: Class not found: {0}"}, + {"Warning.Invalid.argument.s.for.constructor.arg", "Warning: Invalid argument(s) for constructor: {0}"}, - {"Illegal Principal Type: type", "Illegal Principal Type: {0}"}, - {"Illegal option: option", "Illegal option: {0}"}, - {"Usage: policytool [options]", "Usage: policytool [options]"}, - {" [-file ] policy file location", + {"Illegal.Principal.Type.type", "Illegal Principal Type: {0}"}, + {"Illegal.option.option", "Illegal option: {0}"}, + {"Usage.policytool.options.", "Usage: policytool [options]"}, + {".file.file.policy.file.location", " [-file ] policy file location"}, {"New", "New"}, {"Open", "Open"}, {"Save", "Save"}, - {"Save As", "Save As"}, - {"View Warning Log", "View Warning Log"}, + {"Save.As", "Save As"}, + {"View.Warning.Log", "View Warning Log"}, {"Exit", "Exit"}, - {"Add Policy Entry", "Add Policy Entry"}, - {"Edit Policy Entry", "Edit Policy Entry"}, - {"Remove Policy Entry", "Remove Policy Entry"}, + {"Add.Policy.Entry", "Add Policy Entry"}, + {"Edit.Policy.Entry", "Edit Policy Entry"}, + {"Remove.Policy.Entry", "Remove Policy Entry"}, {"Edit", "Edit"}, {"Retain", "Retain"}, - {"Warning: File name may include escaped backslash characters. " + - "It is not necessary to escape backslash characters " + - "(the tool escapes characters as necessary when writing " + - "the policy contents to the persistent store).\n\n" + - "Click on Retain to retain the entered name, or click on " + - "Edit to edit the name.", + {"Warning.File.name.may.include.escaped.backslash.characters.It.is.not.necessary.to.escape.backslash.characters.the.tool.escapes", "Warning: File name may include escaped backslash characters. " + "It is not necessary to escape backslash characters " + "(the tool escapes characters as necessary when writing " + @@ -470,203 +464,203 @@ public class Resources extends java.util.ListResourceBundle { "Click on Retain to retain the entered name, or click on " + "Edit to edit the name."}, - {"Add Public Key Alias", "Add Public Key Alias"}, - {"Remove Public Key Alias", "Remove Public Key Alias"}, + {"Add.Public.Key.Alias", "Add Public Key Alias"}, + {"Remove.Public.Key.Alias", "Remove Public Key Alias"}, {"File", "File"}, {"KeyStore", "KeyStore"}, - {"Policy File:", "Policy File:"}, - {"Could not open policy file: policyFile: e.toString()", + {"Policy.File.", "Policy File:"}, + {"Could.not.open.policy.file.policyFile.e.toString.", "Could not open policy file: {0}: {1}"}, - {"Policy Tool", "Policy Tool"}, - {"Errors have occurred while opening the policy configuration. View the Warning Log for more information.", + {"Policy.Tool", "Policy Tool"}, + {"Errors.have.occurred.while.opening.the.policy.configuration.View.the.Warning.Log.for.more.information.", "Errors have occurred while opening the policy configuration. View the Warning Log for more information."}, {"Error", "Error"}, {"OK", "OK"}, {"Status", "Status"}, {"Warning", "Warning"}, - {"Permission: ", + {"Permission.", "Permission: "}, - {"Principal Type:", "Principal Type:"}, - {"Principal Name:", "Principal Name:"}, - {"Target Name: ", + {"Principal.Type.", "Principal Type:"}, + {"Principal.Name.", "Principal Name:"}, + {"Target.Name.", "Target Name: "}, - {"Actions: ", + {"Actions.", "Actions: "}, - {"OK to overwrite existing file filename?", + {"OK.to.overwrite.existing.file.filename.", "OK to overwrite existing file {0}?"}, {"Cancel", "Cancel"}, - {"CodeBase:", "CodeBase:"}, - {"SignedBy:", "SignedBy:"}, - {"Add Principal", "Add Principal"}, - {"Edit Principal", "Edit Principal"}, - {"Remove Principal", "Remove Principal"}, - {"Principals:", "Principals:"}, - {" Add Permission", " Add Permission"}, - {" Edit Permission", " Edit Permission"}, - {"Remove Permission", "Remove Permission"}, + {"CodeBase.", "CodeBase:"}, + {"SignedBy.", "SignedBy:"}, + {"Add.Principal", "Add Principal"}, + {"Edit.Principal", "Edit Principal"}, + {"Remove.Principal", "Remove Principal"}, + {"Principals.", "Principals:"}, + {".Add.Permission", " Add Permission"}, + {".Edit.Permission", " Edit Permission"}, + {"Remove.Permission", "Remove Permission"}, {"Done", "Done"}, - {"KeyStore URL:", "KeyStore URL:"}, - {"KeyStore Type:", "KeyStore Type:"}, - {"KeyStore Provider:", "KeyStore Provider:"}, - {"KeyStore Password URL:", "KeyStore Password URL:"}, + {"KeyStore.URL.", "KeyStore URL:"}, + {"KeyStore.Type.", "KeyStore Type:"}, + {"KeyStore.Provider.", "KeyStore Provider:"}, + {"KeyStore.Password.URL.", "KeyStore Password URL:"}, {"Principals", "Principals"}, - {" Edit Principal:", " Edit Principal:"}, - {" Add New Principal:", " Add New Principal:"}, + {".Edit.Principal.", " Edit Principal:"}, + {".Add.New.Principal.", " Add New Principal:"}, {"Permissions", "Permissions"}, - {" Edit Permission:", " Edit Permission:"}, - {" Add New Permission:", " Add New Permission:"}, - {"Signed By:", "Signed By:"}, - {"Cannot Specify Principal with a Wildcard Class without a Wildcard Name", + {".Edit.Permission.", " Edit Permission:"}, + {".Add.New.Permission.", " Add New Permission:"}, + {"Signed.By.", "Signed By:"}, + {"Cannot.Specify.Principal.with.a.Wildcard.Class.without.a.Wildcard.Name", "Cannot Specify Principal with a Wildcard Class without a Wildcard Name"}, - {"Cannot Specify Principal without a Name", + {"Cannot.Specify.Principal.without.a.Name", "Cannot Specify Principal without a Name"}, - {"Permission and Target Name must have a value", + {"Permission.and.Target.Name.must.have.a.value", "Permission and Target Name must have a value"}, - {"Remove this Policy Entry?", "Remove this Policy Entry?"}, - {"Overwrite File", "Overwrite File"}, - {"Policy successfully written to filename", + {"Remove.this.Policy.Entry.", "Remove this Policy Entry?"}, + {"Overwrite.File", "Overwrite File"}, + {"Policy.successfully.written.to.filename", "Policy successfully written to {0}"}, - {"null filename", "null filename"}, - {"Save changes?", "Save changes?"}, + {"null.filename", "null filename"}, + {"Save.changes.", "Save changes?"}, {"Yes", "Yes"}, {"No", "No"}, - {"Policy Entry", "Policy Entry"}, - {"Save Changes", "Save Changes"}, - {"No Policy Entry selected", "No Policy Entry selected"}, - {"Unable to open KeyStore: ex.toString()", + {"Policy.Entry", "Policy Entry"}, + {"Save.Changes", "Save Changes"}, + {"No.Policy.Entry.selected", "No Policy Entry selected"}, + {"Unable.to.open.KeyStore.ex.toString.", "Unable to open KeyStore: {0}"}, - {"No principal selected", "No principal selected"}, - {"No permission selected", "No permission selected"}, + {"No.principal.selected", "No principal selected"}, + {"No.permission.selected", "No permission selected"}, {"name", "name"}, - {"configuration type", "configuration type"}, - {"environment variable name", "environment variable name"}, - {"library name", "library name"}, - {"package name", "package name"}, - {"policy type", "policy type"}, - {"property name", "property name"}, - {"Principal List", "Principal List"}, - {"Permission List", "Permission List"}, - {"Code Base", "Code Base"}, - {"KeyStore U R L:", "KeyStore U R L:"}, - {"KeyStore Password U R L:", "KeyStore Password U R L:"}, + {"configuration.type", "configuration type"}, + {"environment.variable.name", "environment variable name"}, + {"library.name", "library name"}, + {"package.name", "package name"}, + {"policy.type", "policy type"}, + {"property.name", "property name"}, + {"Principal.List", "Principal List"}, + {"Permission.List", "Permission List"}, + {"Code.Base", "Code Base"}, + {"KeyStore.U.R.L.", "KeyStore U R L:"}, + {"KeyStore.Password.U.R.L.", "KeyStore Password U R L:"}, // javax.security.auth.PrivateCredentialPermission - {"invalid null input(s)", "invalid null input(s)"}, - {"actions can only be 'read'", "actions can only be 'read'"}, - {"permission name [name] syntax invalid: ", + {"invalid.null.input.s.", "invalid null input(s)"}, + {"actions.can.only.be.read.", "actions can only be 'read'"}, + {"permission.name.name.syntax.invalid.", "permission name [{0}] syntax invalid: "}, - {"Credential Class not followed by a Principal Class and Name", + {"Credential.Class.not.followed.by.a.Principal.Class.and.Name", "Credential Class not followed by a Principal Class and Name"}, - {"Principal Class not followed by a Principal Name", + {"Principal.Class.not.followed.by.a.Principal.Name", "Principal Class not followed by a Principal Name"}, - {"Principal Name must be surrounded by quotes", + {"Principal.Name.must.be.surrounded.by.quotes", "Principal Name must be surrounded by quotes"}, - {"Principal Name missing end quote", + {"Principal.Name.missing.end.quote", "Principal Name missing end quote"}, - {"PrivateCredentialPermission Principal Class can not be a wildcard (*) value if Principal Name is not a wildcard (*) value", + {"PrivateCredentialPermission.Principal.Class.can.not.be.a.wildcard.value.if.Principal.Name.is.not.a.wildcard.value", "PrivateCredentialPermission Principal Class can not be a wildcard (*) value if Principal Name is not a wildcard (*) value"}, - {"CredOwner:\n\tPrincipal Class = class\n\tPrincipal Name = name", + {"CredOwner.Principal.Class.class.Principal.Name.name", "CredOwner:\n\tPrincipal Class = {0}\n\tPrincipal Name = {1}"}, // javax.security.auth.x500 - {"provided null name", "provided null name"}, - {"provided null keyword map", "provided null keyword map"}, - {"provided null OID map", "provided null OID map"}, + {"provided.null.name", "provided null name"}, + {"provided.null.keyword.map", "provided null keyword map"}, + {"provided.null.OID.map", "provided null OID map"}, // javax.security.auth.Subject - {"invalid null AccessControlContext provided", + {"invalid.null.AccessControlContext.provided", "invalid null AccessControlContext provided"}, - {"invalid null action provided", "invalid null action provided"}, - {"invalid null Class provided", "invalid null Class provided"}, - {"Subject:\n", "Subject:\n"}, - {"\tPrincipal: ", "\tPrincipal: "}, - {"\tPublic Credential: ", "\tPublic Credential: "}, - {"\tPrivate Credentials inaccessible\n", + {"invalid.null.action.provided", "invalid null action provided"}, + {"invalid.null.Class.provided", "invalid null Class provided"}, + {"Subject.", "Subject:\n"}, + {".Principal.", "\tPrincipal: "}, + {".Public.Credential.", "\tPublic Credential: "}, + {".Private.Credentials.inaccessible.", "\tPrivate Credentials inaccessible\n"}, - {"\tPrivate Credential: ", "\tPrivate Credential: "}, - {"\tPrivate Credential inaccessible\n", + {".Private.Credential.", "\tPrivate Credential: "}, + {".Private.Credential.inaccessible.", "\tPrivate Credential inaccessible\n"}, - {"Subject is read-only", "Subject is read-only"}, - {"attempting to add an object which is not an instance of java.security.Principal to a Subject's Principal Set", + {"Subject.is.read.only", "Subject is read-only"}, + {"attempting.to.add.an.object.which.is.not.an.instance.of.java.security.Principal.to.a.Subject.s.Principal.Set", "attempting to add an object which is not an instance of java.security.Principal to a Subject's Principal Set"}, - {"attempting to add an object which is not an instance of class", + {"attempting.to.add.an.object.which.is.not.an.instance.of.class", "attempting to add an object which is not an instance of {0}"}, // javax.security.auth.login.AppConfigurationEntry - {"LoginModuleControlFlag: ", "LoginModuleControlFlag: "}, + {"LoginModuleControlFlag.", "LoginModuleControlFlag: "}, // javax.security.auth.login.LoginContext - {"Invalid null input: name", "Invalid null input: name"}, - {"No LoginModules configured for name", + {"Invalid.null.input.name", "Invalid null input: name"}, + {"No.LoginModules.configured.for.name", "No LoginModules configured for {0}"}, - {"invalid null Subject provided", "invalid null Subject provided"}, - {"invalid null CallbackHandler provided", + {"invalid.null.Subject.provided", "invalid null Subject provided"}, + {"invalid.null.CallbackHandler.provided", "invalid null CallbackHandler provided"}, - {"null subject - logout called before login", + {"null.subject.logout.called.before.login", "null subject - logout called before login"}, - {"unable to instantiate LoginModule, module, because it does not provide a no-argument constructor", + {"unable.to.instantiate.LoginModule.module.because.it.does.not.provide.a.no.argument.constructor", "unable to instantiate LoginModule, {0}, because it does not provide a no-argument constructor"}, - {"unable to instantiate LoginModule", + {"unable.to.instantiate.LoginModule", "unable to instantiate LoginModule"}, - {"unable to instantiate LoginModule: ", + {"unable.to.instantiate.LoginModule.", "unable to instantiate LoginModule: "}, - {"unable to find LoginModule class: ", + {"unable.to.find.LoginModule.class.", "unable to find LoginModule class: "}, - {"unable to access LoginModule: ", + {"unable.to.access.LoginModule.", "unable to access LoginModule: "}, - {"Login Failure: all modules ignored", + {"Login.Failure.all.modules.ignored", "Login Failure: all modules ignored"}, // sun.security.provider.PolicyFile - {"java.security.policy: error parsing policy:\n\tmessage", + {"java.security.policy.error.parsing.policy.message", "java.security.policy: error parsing {0}:\n\t{1}"}, - {"java.security.policy: error adding Permission, perm:\n\tmessage", + {"java.security.policy.error.adding.Permission.perm.message", "java.security.policy: error adding Permission, {0}:\n\t{1}"}, - {"java.security.policy: error adding Entry:\n\tmessage", + {"java.security.policy.error.adding.Entry.message", "java.security.policy: error adding Entry:\n\t{0}"}, - {"alias name not provided (pe.name)", "alias name not provided ({0})"}, - {"unable to perform substitution on alias, suffix", + {"alias.name.not.provided.pe.name.", "alias name not provided ({0})"}, + {"unable.to.perform.substitution.on.alias.suffix", "unable to perform substitution on alias, {0}"}, - {"substitution value, prefix, unsupported", + {"substitution.value.prefix.unsupported", "substitution value, {0}, unsupported"}, - {"(", "("}, - {")", ")"}, - {"type can't be null","type can't be null"}, + {"LPARAM", "("}, + {"RPARAM", ")"}, + {"type.can.t.be.null","type can't be null"}, // sun.security.provider.PolicyParser - {"keystorePasswordURL can not be specified without also specifying keystore", + {"keystorePasswordURL.can.not.be.specified.without.also.specifying.keystore", "keystorePasswordURL can not be specified without also specifying keystore"}, - {"expected keystore type", "expected keystore type"}, - {"expected keystore provider", "expected keystore provider"}, - {"multiple Codebase expressions", + {"expected.keystore.type", "expected keystore type"}, + {"expected.keystore.provider", "expected keystore provider"}, + {"multiple.Codebase.expressions", "multiple Codebase expressions"}, - {"multiple SignedBy expressions","multiple SignedBy expressions"}, - {"SignedBy has empty alias","SignedBy has empty alias"}, - {"can not specify Principal with a wildcard class without a wildcard name", + {"multiple.SignedBy.expressions","multiple SignedBy expressions"}, + {"SignedBy.has.empty.alias","SignedBy has empty alias"}, + {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name", "can not specify Principal with a wildcard class without a wildcard name"}, - {"expected codeBase or SignedBy or Principal", + {"expected.codeBase.or.SignedBy.or.Principal", "expected codeBase or SignedBy or Principal"}, - {"expected permission entry", "expected permission entry"}, - {"number ", "number "}, - {"expected [expect], read [end of file]", + {"expected.permission.entry", "expected permission entry"}, + {"number.", "number "}, + {"expected.expect.read.end.of.file.", "expected [{0}], read [end of file]"}, - {"expected [;], read [end of file]", + {"expected.read.end.of.file.", "expected [;], read [end of file]"}, - {"line number: msg", "line {0}: {1}"}, - {"line number: expected [expect], found [actual]", + {"line.number.msg", "line {0}: {1}"}, + {"line.number.expected.expect.found.actual.", "line {0}: expected [{1}], found [{2}]"}, - {"null principalClass or principalName", + {"null.principalClass.or.principalName", "null principalClass or principalName"}, // sun.security.pkcs11.SunPKCS11 - {"PKCS11 Token [providerName] Password: ", + {"PKCS11.Token.providerName.Password.", "PKCS11 Token [{0}] Password: "}, /* --- DEPRECATED --- */ // javax.security.auth.Policy - {"unable to instantiate Subject-based policy", + {"unable.to.instantiate.Subject.based.policy", "unable to instantiate Subject-based policy"} }; diff --git a/src/share/demo/nio/zipfs/Demo.java b/src/share/demo/nio/zipfs/Demo.java index 3666dfd70de13bea14e233480db55805bb564bdc..99669d1fdf224dd6518f9a8553b51e376a75d1a0 100644 --- a/src/share/demo/nio/zipfs/Demo.java +++ b/src/share/demo/nio/zipfs/Demo.java @@ -75,9 +75,15 @@ public class Demo { // copy an external src file into zipfile // as entry dst + copyin_attrs, // + // copy an external src file into zipfile + // as entry dst, with attributes (timestamp) + copyout, // // copy zipfile entry src" out to file dst + copyout_attrs, // + zzmove, // // move entry path/dir from zfsrc to zfdst @@ -94,6 +100,9 @@ public class Demo { setmtime, // // set the lastModifiedTime of entry path + setatime, // + setctime, // + lsdir, // // list dir's direct child files/dirs @@ -135,12 +144,14 @@ public class Demo { attrs2, // // test different ways to print attrs + + prof, } public static void main(String[] args) throws Throwable { - Action action = Action.valueOf(args[0]);; - Map env = env = new HashMap(); + Action action = Action.valueOf(args[0]); + Map env = env = new HashMap<>(); if (action == Action.create) env.put("createNew", true); if (action == Action.tlist || action == Action.twalk) @@ -185,6 +196,16 @@ public class Demo { dst = fs.getPath(args[3]); src.copyTo(dst); break; + case copyin_attrs: + src = Paths.get(args[2]); + dst = fs.getPath(args[3]); + src.copyTo(dst, COPY_ATTRIBUTES); + break; + case copyout_attrs: + src = fs.getPath(args[2]); + dst = Paths.get(args[3]); + src.copyTo(dst, COPY_ATTRIBUTES); + break; case zzmove: fs2 = FileSystems.newFileSystem( URI.create("zip" + Paths.get(args[2]).toUri().toString().substring(4)), @@ -206,6 +227,7 @@ public class Demo { case attrs: for (int i = 2; i < args.length; i++) { path = fs.getPath(args[i]); + System.out.println(path); System.out.println( Attributes.readBasicFileAttributes(path).toString()); } @@ -221,6 +243,28 @@ public class Demo { Attributes.readBasicFileAttributes(path).toString()); } break; + case setctime: + df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss"); + newDatetime = df.parse(args[2]); + for (int i = 3; i < args.length; i++) { + path = fs.getPath(args[i]); + path.setAttribute("creationTime", + FileTime.fromMillis(newDatetime.getTime())); + System.out.println( + Attributes.readBasicFileAttributes(path).toString()); + } + break; + case setatime: + df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss"); + newDatetime = df.parse(args[2]); + for (int i = 3; i < args.length; i++) { + path = fs.getPath(args[i]); + path.setAttribute("lastAccessTime", + FileTime.fromMillis(newDatetime.getTime())); + System.out.println( + Attributes.readBasicFileAttributes(path).toString()); + } + break; case attrsspace: path = fs.getPath("/"); FileStore fstore = path.getFileStore(); @@ -293,6 +337,7 @@ public class Demo { case attrs2: for (int i = 2; i < args.length; i++) { path = fs.getPath(args[i]); + System.out.printf("%n%s%n", path); System.out.println("-------(1)---------"); System.out.println( Attributes.readBasicFileAttributes(path).toString()); @@ -308,6 +353,13 @@ public class Demo { } } break; + case prof: + list(fs.getPath("/"), false); + while (true) { + Thread.sleep(10000); + //list(fs.getPath("/"), true); + System.out.println("sleeping..."); + } } } catch (Exception x) { x.printStackTrace(); @@ -501,10 +553,11 @@ public class Demo { } 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 (!"/".equals(path.toString())) { + System.out.printf(" %s%n", path.toString()); + if (verbose) + System.out.println(Attributes.readBasicFileAttributes(path).toString()); + } if (path.notExists()) return; if (Attributes.readBasicFileAttributes(path).isDirectory()) { diff --git a/src/share/demo/nio/zipfs/README.txt b/src/share/demo/nio/zipfs/README.txt index 227a67e270e36b4a46bc0e6400a9e039da35f67e..d5517bf7baeb481e4c601863944fee63c733421e 100644 --- a/src/share/demo/nio/zipfs/README.txt +++ b/src/share/demo/nio/zipfs/README.txt @@ -2,7 +2,7 @@ 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 /demo/nio/ZipFileSystem/zipfs.jar +directory or else add /demo/nio/zipfs/zipfs.jar to your class path. The factory methods defined by the java.nio.file.FileSystems class can be @@ -10,8 +10,8 @@ used to create a FileSystem, eg: // use file type detection Map env = Collections.emptyMap(); - Path jarfile = Path.get("foo.jar"); - FileSystem fs = FileSystems.newFileSystem(jarfile, env); + Path jarfile = Paths.get("foo.jar"); + FileSystem fs = FileSystems.newFileSystem(jarfile, env, null); -or diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/JarFileSystemProvider.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/JarFileSystemProvider.java index 2fc9c83ef14d5f087ae85d289a9f152f70fc421f..dddf69e4deefd7b6edcc934fc484dbe12e44379c 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/JarFileSystemProvider.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/JarFileSystemProvider.java @@ -68,4 +68,21 @@ public class JarFileSystemProvider extends ZipFileSystemProvider throw new AssertionError(e); //never thrown } } + + @Override + public Path getPath(URI uri) { + FileSystem fs = getFileSystem(uri); + String path = uri.getFragment(); + if (path == null) { + String uristr = uri.toString(); + int off = uristr.indexOf("!/"); + if (off != -1) + path = uristr.substring(off + 2); + } + if (path != null) + return fs.getPath(path); + throw new IllegalArgumentException("URI: " + + uri + + " does not contain path fragment ex. jar:///c:/foo.zip!/BAR"); + } } diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipConstants.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipConstants.java index aa7073ac15e16d9ae71ac2647c34be0af635ca40..24c28cfe80c5477b59e761892780b0c2344de47d 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipConstants.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipConstants.java @@ -31,7 +31,6 @@ package com.sun.nio.zipfs; -import java.nio.ByteBuffer; /** * @@ -48,6 +47,7 @@ class ZipConstants { static final int METHOD_BZIP2 = 12; static final int METHOD_LZMA = 14; static final int METHOD_LZ77 = 19; + static final int METHOD_AES = 99; /* * General purpose big flag @@ -168,7 +168,8 @@ class ZipConstants { static final int EXTID_ZIP64 = 0x0001; // ZIP64 static final int EXTID_NTFS = 0x000a; // NTFS static final int EXTID_UNIX = 0x000d; // UNIX - + static final int EXTID_EFS = 0x0017; // Strong Encryption + static final int EXTID_EXTT = 0x5455; // Info-ZIP Extended Timestamp /* * fields access methods @@ -226,34 +227,23 @@ class ZipConstants { 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);} + // central directory header (CEN) fields + static final long CENSIG(byte[] b, int pos) { return LG(b, pos + 0); } + static final int CENVEM(byte[] b, int pos) { return SH(b, pos + 4); } + static final int CENVER(byte[] b, int pos) { return SH(b, pos + 6); } + static final int CENFLG(byte[] b, int pos) { return SH(b, pos + 8); } + static final int CENHOW(byte[] b, int pos) { return SH(b, pos + 10);} + static final long CENTIM(byte[] b, int pos) { return LG(b, pos + 12);} + static final long CENCRC(byte[] b, int pos) { return LG(b, pos + 16);} + static final long CENSIZ(byte[] b, int pos) { return LG(b, pos + 20);} + static final long CENLEN(byte[] b, int pos) { return LG(b, pos + 24);} + static final int CENNAM(byte[] b, int pos) { return SH(b, pos + 28);} + static final int CENEXT(byte[] b, int pos) { return SH(b, pos + 30);} + static final int CENCOM(byte[] b, int pos) { return SH(b, pos + 32);} + static final int CENDSK(byte[] b, int pos) { return SH(b, pos + 34);} + static final int CENATT(byte[] b, int pos) { return SH(b, pos + 36);} + static final long CENATX(byte[] b, int pos) { return LG(b, pos + 38);} + static final long CENOFF(byte[] 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; diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipDirectoryStream.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipDirectoryStream.java index 3052b34e59a6633edcca78d49c7bf7dbedbf8e38..10f6bd477a9d66c8aa38cc14dccbd7da25a20310 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipDirectoryStream.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipDirectoryStream.java @@ -38,7 +38,6 @@ import java.nio.file.Path; import java.util.Iterator; import java.util.NoSuchElementException; import java.io.IOException; -import static com.sun.nio.zipfs.ZipUtils.*; /** * @@ -77,7 +76,7 @@ public class ZipDirectoryStream implements DirectoryStream { } catch (IOException e) { throw new IllegalStateException(e); } - return new Iterator() { + return new Iterator<>() { private Path next; @Override public boolean hasNext() { diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributeView.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributeView.java index d4a9a67c9fc03293ba8e540a35846f0a3af326a9..5c31ebe7ba63c3975916ecd1d3c68eee590a09bd 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributeView.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributeView.java @@ -32,7 +32,6 @@ 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; @@ -113,6 +112,10 @@ public class ZipFileAttributeView implements BasicFileAttributeView try { if (AttrID.valueOf(attribute) == AttrID.lastModifiedTime) setTimes ((FileTime)value, null, null); + if (AttrID.valueOf(attribute) == AttrID.lastAccessTime) + setTimes (null, (FileTime)value, null); + if (AttrID.valueOf(attribute) == AttrID.creationTime) + setTimes (null, null, (FileTime)value); return; } catch (IllegalArgumentException x) {} throw new UnsupportedOperationException("'" + attribute + diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributes.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributes.java index 157f9eb163ad92c5743a148746c45ec0475b2e87..687f92644c4de283a4b96ba0bcefaa1793c48df4 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributes.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributes.java @@ -56,7 +56,7 @@ public class ZipFileAttributes implements BasicFileAttributes @Override public FileTime creationTime() { if (e.ctime != -1) - return FileTime.fromMillis(dosToJavaTime(e.ctime)); + return FileTime.fromMillis(e.ctime); return null; } @@ -78,13 +78,13 @@ public class ZipFileAttributes implements BasicFileAttributes @Override public FileTime lastAccessTime() { if (e.atime != -1) - return FileTime.fromMillis(dosToJavaTime(e.atime)); + return FileTime.fromMillis(e.atime); return null; } @Override public FileTime lastModifiedTime() { - return FileTime.fromMillis(dosToJavaTime(e.mtime)); + return FileTime.fromMillis(e.mtime); } @Override @@ -103,10 +103,6 @@ public class ZipFileAttributes implements BasicFileAttributes } ///////// zip entry attributes /////////// - public byte[] name() { - return Arrays.copyOf(e.name, e.name.length); - } - public long compressedSize() { return e.csize; } @@ -132,10 +128,13 @@ public class ZipFileAttributes implements BasicFileAttributes } public String toString() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(1024); Formatter fm = new Formatter(sb); - fm.format("[/%s]%n", new String(e.name)); // TBD encoding - fm.format(" creationTime : %s%n", creationTime()); + if (creationTime() != null) + fm.format(" creationTime : %tc%n", creationTime().toMillis()); + else + fm.format(" creationTime : null%n"); + if (lastAccessTime() != null) fm.format(" lastAccessTime : %tc%n", lastAccessTime().toMillis()); else diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java index 152ca957c1d3ed0788e8a8b080d2f8e5f2d765e1..eddc5ac938229cfb040d3de799f6e9e6fdf934fa 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java @@ -35,19 +35,18 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; -import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.nio.file.spi.*; -import java.net.URI; import java.util.*; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Pattern; import java.util.zip.CRC32; import java.util.zip.Inflater; @@ -76,8 +75,6 @@ public class ZipFileSystem extends FileSystem { private final Path zfpath; private final ZipCoder zc; - private final Object lock = new Object(); - // configurable by env map private final String defaultDir; // default dir for the file system private final String nameEncoding; // default encoding for name/comment @@ -85,6 +82,8 @@ public class ZipFileSystem extends FileSystem { private final boolean useTempFile; // use a temp file for newOS, default // is to use BAOS for better performance private final boolean createNew; // create a new zip if not exists + private static final boolean isWindows = + System.getProperty("os.name").startsWith("Windows"); ZipFileSystem(ZipFileSystemProvider provider, Path zfpath, @@ -92,13 +91,13 @@ public class ZipFileSystem extends FileSystem { throws IOException { // configurable env setup - this.buildDirTree = TRUE.equals(env.get("buildDirTree")); - this.useTempFile = TRUE.equals(env.get("useTempFile")); - this.createNew = TRUE.equals(env.get("createNew")); + this.buildDirTree = TRUE.equals(env.get("buildDirTreea")); + this.useTempFile = TRUE.equals(env.get("useTempFile")); + this.createNew = TRUE.equals(env.get("createNew")); this.nameEncoding = env.containsKey("nameEncoding") ? (String)env.get("nameEncoding") : "UTF-8"; - this.defaultDir = env.containsKey("default.dir") ? - (String)env.get("default.dir") : "/"; + this.defaultDir = env.containsKey("default.dir") ? + (String)env.get("default.dir") : "/"; if (this.defaultDir.charAt(0) != '/') throw new IllegalArgumentException("default dir should be absolute"); @@ -121,7 +120,8 @@ public class ZipFileSystem extends FileSystem { } this.zc = ZipCoder.get(nameEncoding); this.defaultdir = new ZipPath(this, getBytes(defaultDir)); - initZipFile(); + this.ch = zfpath.newByteChannel(READ); + this.cen = initCEN(); } @Override @@ -183,7 +183,7 @@ public class ZipFileSystem extends FileSystem { @Override public Iterable getFileStores() { - ArrayList list = new ArrayList(1); + ArrayList list = new ArrayList<>(1); list.add(new ZipFileStore(new ZipPath(this, new byte[]{'/'}))); return list; } @@ -240,19 +240,27 @@ public class ZipFileSystem extends FileSystem { @Override public void close() throws IOException { - synchronized (lock) { + beginWrite(); + try { if (!isOpen) return; - isOpen = false; - if (!streams.isEmpty()) { - synchronized(streams) { - for (InputStream is: streams) - is.close(); - } - } + isOpen = false; // set closed + } finally { + endWrite(); + } + if (!streams.isEmpty()) { // unlock and close all remaining streams + Set copy = new HashSet<>(streams); + for (InputStream is: copy) + is.close(); + } + beginWrite(); // lock and sync + try { sync(); - ch.close(); + ch.close(); // close the ch just in case no update + } finally { // and sync dose not close the ch + endWrite(); } + synchronized (inflaters) { for (Inflater inf : inflaters) inf.end(); @@ -261,97 +269,101 @@ public class ZipFileSystem extends FileSystem { for (Deflater def : deflaters) def.end(); } - for (Path p: tmppaths) { - try { - p.deleteIfExists(); - } catch (IOException x) { - x.printStackTrace(); + + synchronized (tmppaths) { + for (Path p: tmppaths) { + try { + p.deleteIfExists(); + } catch (IOException x) { + x.printStackTrace(); + } } } provider.removeFileSystem(zfpath); } - ZipFileAttributes[] getAllAttributes() throws IOException { - ensureOpen(); - int n = inodes.size(); - ZipFileAttributes[] zes = new ZipFileAttributes[n]; - Iterator itr = inodes.values().iterator(); - int i = 0; - while(itr.hasNext()) { - zes[i++] = new ZipFileAttributes(Entry.readCEN(cen, itr.next().pos)); - } - return zes; - } - - EntryName[] getEntryNames() throws IOException { - ensureOpen(); - return inodes.keySet().toArray(new EntryName[0]); - } - ZipFileAttributes getFileAttributes(byte[] path) throws IOException { - synchronized (lock) { - Entry e = getEntry0(path); - if (e == null) { - if (path.length == 0) { - e = new Entry(new byte[0]); // root - } else if (buildDirTree) { - IndexNode inode = getDirs().get(new EntryName(path)); - if (inode == null) - return null; - e = new Entry(inode.name); - } else { + Entry e; + beginRead(); + try { + ensureOpen(); + e = getEntry0(path); + } finally { + endRead(); + } + if (e == null) { + if (path.length == 0) { + e = new Entry(new byte[0]); // root + } else if (buildDirTree) { + IndexNode inode = getDirs().get(IndexNode.keyOf(path)); + if (inode == null) return null; - } - e.method = METHOD_STORED; // STORED for dir - BasicFileAttributes bfas = Attributes.readBasicFileAttributes(zfpath); - if (bfas.lastModifiedTime() != null) - e.mtime = javaToDosTime(bfas.lastModifiedTime().toMillis()); - if (bfas.lastAccessTime() != null) - e.atime = javaToDosTime(bfas.lastAccessTime().toMillis()); - if (bfas.creationTime() != null) - e.ctime = javaToDosTime(bfas.creationTime().toMillis()); + e = new Entry(inode.name); + } else { + return null; } - return new ZipFileAttributes(e); + e.method = METHOD_STORED; // STORED for dir + BasicFileAttributes bfas = Attributes.readBasicFileAttributes(zfpath); + if (bfas.lastModifiedTime() != null) + e.mtime = bfas.lastModifiedTime().toMillis(); + if (bfas.lastAccessTime() != null) + e.atime = bfas.lastAccessTime().toMillis(); + if (bfas.creationTime() != null) + e.ctime = bfas.creationTime().toMillis(); } + return new ZipFileAttributes(e); } void setTimes(byte[] path, FileTime mtime, FileTime atime, FileTime ctime) throws IOException { checkWritable(); - synchronized (lock) { + beginWrite(); + try { + ensureOpen(); Entry e = getEntry0(path); // ensureOpen checked if (e == null) throw new NoSuchFileException(getString(path)); if (e.type == Entry.CEN) e.type = Entry.COPY; // copy e if (mtime != null) - e.mtime = javaToDosTime(mtime.toMillis()); + e.mtime = mtime.toMillis(); if (atime != null) - e.atime = javaToDosTime(atime.toMillis()); + e.atime = atime.toMillis(); if (ctime != null) - e.ctime = javaToDosTime(ctime.toMillis()); + e.ctime = ctime.toMillis(); update(e); + } finally { + endWrite(); } } boolean exists(byte[] path) throws IOException { - return getEntry0(path) != null; + beginRead(); + try { + ensureOpen(); + return getEntry0(path) != null; + } finally { + endRead(); + } } boolean isDirectory(byte[] path) throws IOException { - synchronized (lock) { - if (buildDirTree) { - return getDirs().containsKey(new EntryName(path)); - } + if (buildDirTree) + return getDirs().containsKey(IndexNode.keyOf(path)); + + beginRead(); + try { Entry e = getEntry0(path); return (e != null && e.isDir()) || path.length == 0; + } finally { + endRead(); } } @@ -368,12 +380,14 @@ public class ZipFileSystem extends FileSystem { DirectoryStream.Filter filter) throws IOException { - synchronized (lock) { + beginWrite(); // iteration of inodes needs exclusive lock + try { + ensureOpen(); if (buildDirTree) { - IndexNode inode = getDirs().get(new EntryName(path)); + IndexNode inode = getDirs().get(IndexNode.keyOf(path)); if (inode == null) throw new NotDirectoryException(getString(path)); - List list = new ArrayList(); + List list = new ArrayList<>(); IndexNode child = inode.child; while (child != null) { ZipPath zp = toZipPath(child.name); @@ -386,25 +400,26 @@ public class ZipFileSystem extends FileSystem { if (!isDirectory(path)) throw new NotDirectoryException(getString(path)); - List list = new ArrayList(); - EntryName[] entries = getEntryNames(); + List list = new ArrayList<>(); path = toDirectoryPath(path); - for (EntryName en :entries) { - if (!isParentOf(path, en.name)) // is "path" the parent of "name" + for (IndexNode key : inodes.keySet()) { + if (!isParentOf(path, key.name)) // is "path" the parent of "name" continue; int off = path.length; - while (off < en.name.length) { - if (en.name[off] == '/') + while (off < key.name.length) { + if (key.name[off] == '/') break; off++; } - if (off < (en.name.length - 1)) + if (off < (key.name.length - 1)) continue; - ZipPath zp = toZipPath(en.name); + ZipPath zp = toZipPath(key.name); if (filter == null || filter.accept(zp)) list.add(zp); } return list.iterator(); + } finally { + endWrite(); } } @@ -413,16 +428,18 @@ public class ZipFileSystem extends FileSystem { { checkWritable(); dir = toDirectoryPath(dir); - synchronized (lock) { + beginWrite(); + try { ensureOpen(); - // pseudo root dir, or exiting dir - if (dir.length == 0 || exists(dir)) + if (dir.length == 0 || exists(dir)) // root dir, or exiting dir throw new FileAlreadyExistsException(getString(dir)); - checkParents(dir); + checkParents(dir); Entry e = new Entry(dir, Entry.NEW); - e.method = METHOD_STORED; // STORED for dir + e.method = METHOD_STORED; // STORED for dir update(e); + } finally { + endWrite(); } } @@ -432,7 +449,10 @@ public class ZipFileSystem extends FileSystem { checkWritable(); if (Arrays.equals(src, dst)) return; // do nothing, src and dst are the same - synchronized (lock) { + + beginWrite(); + try { + ensureOpen(); Entry eSrc = getEntry0(src); // ensureOpen checked if (eSrc == null) throw new NoSuchFileException(getString(src)); @@ -457,11 +477,6 @@ public class ZipFileSystem extends FileSystem { } Entry u = new Entry(eSrc, Entry.COPY); // copy eSrc entry u.name = dst; // change name - // don't touch the "nlen and elen" here. writeLOC() always - // re-calculate from "name" and "extra" for the correct length, - // copyLOCEntry however needs the original lengths to skip the - // loc header. - // u.nlen = dst.length; if (eSrc.type == Entry.NEW || eSrc.type == Entry.FILECH) { u.type = eSrc.type; // make it the same type @@ -475,10 +490,12 @@ public class ZipFileSystem extends FileSystem { } } if (!hasCopyAttrs) - u.mtime = u.atime= u.ctime = javaToDosTime(System.currentTimeMillis()); + u.mtime = u.atime= u.ctime = System.currentTimeMillis(); update(u); if (deletesrc) updateDelete(eSrc); + } finally { + endWrite(); } } @@ -501,7 +518,9 @@ public class ZipFileSystem extends FileSystem { if (opt == APPEND) hasAppend = true; } - synchronized (lock) { + beginRead(); // only need a readlock, the "update()" will + try { // try to obtain a writelock when the os is + ensureOpen(); // being closed. Entry e = getEntry0(path); if (e != null) { if (e.isDir() || hasCreateNew) @@ -512,27 +531,33 @@ public class ZipFileSystem extends FileSystem { copyStream(is, os); is.close(); return os; - } - return getOutputStream(new Entry(e, Entry.NEW)); + } + return getOutputStream(new Entry(e, Entry.NEW)); } else { if (!hasCreate && !hasCreateNew) throw new NoSuchFileException(getString(path)); checkParents(path); return getOutputStream(new Entry(path, Entry.NEW)); } + } finally { + endRead(); } } // Returns an input stream for reading the contents of the specified // file entry. InputStream newInputStream(byte[] path) throws IOException { - synchronized (lock) { + beginRead(); + try { + ensureOpen(); Entry e = getEntry0(path); if (e == null) throw new NoSuchFileException(getString(path)); if (e.isDir()) throw new FileSystemException(getString(path), "is a directory", null); return getInputStream(e); + } finally { + endRead(); } } @@ -559,78 +584,111 @@ public class ZipFileSystem extends FileSystem { if (options.contains(StandardOpenOption.WRITE) || options.contains(StandardOpenOption.APPEND)) { checkWritable(); - final WritableByteChannel wbc = Channels.newChannel(newOutputStream(path, - options.toArray(new OpenOption[0]))); - long leftover = 0;; - if (options.contains(StandardOpenOption.APPEND)) { - Entry e = getEntry0(path); - if (e != null && e.size >= 0) - leftover = e.size; - } - final long offset = leftover; - return new SeekableByteChannel() { - long written = offset; - public boolean isOpen() { - return wbc.isOpen(); - } - public long position() throws IOException { - return written; - } - public SeekableByteChannel position(long pos) throws IOException { - throw new UnsupportedOperationException(); - } - public int read(ByteBuffer dst) throws IOException { - throw new UnsupportedOperationException(); - } - public SeekableByteChannel truncate(long size) throws IOException { - throw new UnsupportedOperationException(); - } - public int write(ByteBuffer src) throws IOException { - int n = wbc.write(src); - written += n; - return n; - } - public long size() throws IOException { - return written; - } - public void close() throws IOException { - wbc.close(); + beginRead(); + try { + final WritableByteChannel wbc = Channels.newChannel( + newOutputStream(path, options.toArray(new OpenOption[0]))); + long leftover = 0; + if (options.contains(StandardOpenOption.APPEND)) { + Entry e = getEntry0(path); + if (e != null && e.size >= 0) + leftover = e.size; } - }; + final long offset = leftover; + return new SeekableByteChannel() { + long written = offset; + public boolean isOpen() { + return wbc.isOpen(); + } + + public long position() throws IOException { + return written; + } + + public SeekableByteChannel position(long pos) + throws IOException + { + throw new UnsupportedOperationException(); + } + + public int read(ByteBuffer dst) throws IOException { + throw new UnsupportedOperationException(); + } + + public SeekableByteChannel truncate(long size) + throws IOException + { + throw new UnsupportedOperationException(); + } + + public int write(ByteBuffer src) throws IOException { + int n = wbc.write(src); + written += n; + return n; + } + + public long size() throws IOException { + return written; + } + + public void close() throws IOException { + wbc.close(); + } + }; + } finally { + endRead(); + } } else { - Entry e = getEntry0(path); - if (e == null || e.isDir()) - throw new NoSuchFileException(getString(path)); - final ReadableByteChannel rbc = - Channels.newChannel(getInputStream(e)); - final long size = e.size; - return new SeekableByteChannel() { - long read = 0; - public boolean isOpen() { - return rbc.isOpen(); - } - public long position() throws IOException { - return read; - } - public SeekableByteChannel position(long pos) throws IOException { - throw new UnsupportedOperationException(); - } - public int read(ByteBuffer dst) throws IOException { - return rbc.read(dst); - } - public SeekableByteChannel truncate(long size) throws IOException { - throw new NonWritableChannelException(); - } - public int write (ByteBuffer src) throws IOException { - throw new NonWritableChannelException(); - } - public long size() throws IOException { - return size; - } - public void close() throws IOException { - rbc.close(); - } - }; + beginRead(); + try { + ensureOpen(); + Entry e = getEntry0(path); + if (e == null || e.isDir()) + throw new NoSuchFileException(getString(path)); + final ReadableByteChannel rbc = + Channels.newChannel(getInputStream(e)); + final long size = e.size; + return new SeekableByteChannel() { + long read = 0; + public boolean isOpen() { + return rbc.isOpen(); + } + + public long position() throws IOException { + return read; + } + + public SeekableByteChannel position(long pos) + throws IOException + { + throw new UnsupportedOperationException(); + } + + public int read(ByteBuffer dst) throws IOException { + return rbc.read(dst); + } + + public SeekableByteChannel truncate(long size) + throws IOException + { + throw new NonWritableChannelException(); + } + + public int write (ByteBuffer src) throws IOException { + throw new NonWritableChannelException(); + } + + public long size() throws IOException { + return size; + } + + public void close() throws IOException { + rbc.close(); + } + }; + } finally { + endRead(); + } } } @@ -647,125 +705,131 @@ public class ZipFileSystem extends FileSystem { checkOptions(options); final boolean forWrite = (options.contains(StandardOpenOption.WRITE) || options.contains(StandardOpenOption.APPEND)); - Entry e = getEntry0(path); - if (forWrite) { - checkWritable(); - if (e == null) { + beginRead(); + try { + ensureOpen(); + Entry e = getEntry0(path); + if (forWrite) { + checkWritable(); + if (e == null) { if (!options.contains(StandardOpenOption.CREATE_NEW)) throw new NoSuchFileException(getString(path)); - } else { - if (options.contains(StandardOpenOption.CREATE_NEW)) - throw new FileAlreadyExistsException(getString(path)); - if (e.isDir()) - throw new FileAlreadyExistsException("directory <" - + getString(path) + "> exists"); - } - options.remove(StandardOpenOption.CREATE_NEW); // for tmpfile - } else if (e == null || e.isDir()) { - throw new NoSuchFileException(getString(path)); - } - - final boolean isFCH = (e != null && e.type == Entry.FILECH); - final Path tmpfile = isFCH ? e.file : getTempPathForEntry(path); - final FileChannel fch = tmpfile.getFileSystem() - .provider() - .newFileChannel(tmpfile, options, attrs); - final Entry u = isFCH ? e : new Entry(path, tmpfile, Entry.FILECH); - if (forWrite) { - u.flag = FLAG_DATADESCR; - u.method = METHOD_DEFLATED; - } - // is there a better way to hook into the FileChannel's close method? - return new FileChannel() { - public int write(ByteBuffer src) throws IOException { - return fch.write(src); - } - public long write(ByteBuffer[] srcs, int offset, int length) - throws IOException - { - return fch.write(srcs, offset, length); - } - public long position() throws IOException { - return fch.position(); - } - public FileChannel position(long newPosition) - throws IOException - { - fch.position(newPosition); - return this; - } - public long size() throws IOException { - return fch.size(); - } - public FileChannel truncate(long size) - throws IOException - { - fch.truncate(size); - return this; - } - public void force(boolean metaData) - throws IOException - { - fch.force(metaData); - } - public long transferTo(long position, long count, - WritableByteChannel target) - throws IOException - { - return fch.transferTo(position, count, target); - } - public long transferFrom(ReadableByteChannel src, - long position, long count) - throws IOException - { - return fch.transferFrom(src, position, count); - } - public int read(ByteBuffer dst) throws IOException { - return fch.read(dst); - } - public int read(ByteBuffer dst, long position) - throws IOException - { - return fch.read(dst, position); - } - public long read(ByteBuffer[] dsts, int offset, int length) - throws IOException - { - return fch.read(dsts, offset, length); - } - public int write(ByteBuffer src, long position) - throws IOException - { - return fch.write(src, position); - } - public MappedByteBuffer map(MapMode mode, - long position, long size) - throws IOException - { - throw new UnsupportedOperationException(); - } - public FileLock lock(long position, long size, boolean shared) - throws IOException - { - return fch.lock(position, size, shared); - } - public FileLock tryLock(long position, long size, boolean shared) - throws IOException - { - return fch.tryLock(position, size, shared); - } - protected void implCloseChannel() throws IOException { - fch.close(); - if (forWrite) { - u.mtime = javaToDosTime(System.currentTimeMillis()); - u.size = Attributes.readBasicFileAttributes(u.file).size(); - update(u); } else { - if (!isFCH) // if this is a new fch for reading - removeTempPathForEntry(tmpfile); + if (options.contains(StandardOpenOption.CREATE_NEW)) + throw new FileAlreadyExistsException(getString(path)); + if (e.isDir()) + throw new FileAlreadyExistsException("directory <" + + getString(path) + "> exists"); } + options.remove(StandardOpenOption.CREATE_NEW); // for tmpfile + } else if (e == null || e.isDir()) { + throw new NoSuchFileException(getString(path)); } - }; + + final boolean isFCH = (e != null && e.type == Entry.FILECH); + final Path tmpfile = isFCH ? e.file : getTempPathForEntry(path); + final FileChannel fch = tmpfile.getFileSystem() + .provider() + .newFileChannel(tmpfile, options, attrs); + final Entry u = isFCH ? e : new Entry(path, tmpfile, Entry.FILECH); + if (forWrite) { + u.flag = FLAG_DATADESCR; + u.method = METHOD_DEFLATED; + } + // is there a better way to hook into the FileChannel's close method? + return new FileChannel() { + public int write(ByteBuffer src) throws IOException { + return fch.write(src); + } + public long write(ByteBuffer[] srcs, int offset, int length) + throws IOException + { + return fch.write(srcs, offset, length); + } + public long position() throws IOException { + return fch.position(); + } + public FileChannel position(long newPosition) + throws IOException + { + fch.position(newPosition); + return this; + } + public long size() throws IOException { + return fch.size(); + } + public FileChannel truncate(long size) + throws IOException + { + fch.truncate(size); + return this; + } + public void force(boolean metaData) + throws IOException + { + fch.force(metaData); + } + public long transferTo(long position, long count, + WritableByteChannel target) + throws IOException + { + return fch.transferTo(position, count, target); + } + public long transferFrom(ReadableByteChannel src, + long position, long count) + throws IOException + { + return fch.transferFrom(src, position, count); + } + public int read(ByteBuffer dst) throws IOException { + return fch.read(dst); + } + public int read(ByteBuffer dst, long position) + throws IOException + { + return fch.read(dst, position); + } + public long read(ByteBuffer[] dsts, int offset, int length) + throws IOException + { + return fch.read(dsts, offset, length); + } + public int write(ByteBuffer src, long position) + throws IOException + { + return fch.write(src, position); + } + public MappedByteBuffer map(MapMode mode, + long position, long size) + throws IOException + { + throw new UnsupportedOperationException(); + } + public FileLock lock(long position, long size, boolean shared) + throws IOException + { + return fch.lock(position, size, shared); + } + public FileLock tryLock(long position, long size, boolean shared) + throws IOException + { + return fch.tryLock(position, size, shared); + } + protected void implCloseChannel() throws IOException { + fch.close(); + if (forWrite) { + u.mtime = System.currentTimeMillis(); + u.size = Attributes.readBasicFileAttributes(u.file).size(); + update(u); + } else { + if (!isFCH) // if this is a new fch for reading + removeTempPathForEntry(tmpfile); + } + } + }; + } finally { + endRead(); + } } // the outstanding input streams that need to be closed @@ -776,11 +840,9 @@ public class ZipFileSystem extends FileSystem { // input streams are all closed by the obtainers. private Set exChClosers = new HashSet<>(); - private Set tmppaths = new HashSet<>(); + private Set tmppaths = Collections.synchronizedSet(new HashSet()); private Path getTempPathForEntry(byte[] path) throws IOException { Path tmpPath = createTempFileInSameDirectoryAs(zfpath); - tmppaths.add(tmpPath); - if (path != null) { Entry e = getEntry0(path); if (e != null) { @@ -805,9 +867,14 @@ public class ZipFileSystem extends FileSystem { // check if all parents really exit. ZIP spec does not require // the existence of any "parent directory". private void checkParents(byte[] path) throws IOException { - while ((path = getParent(path)) != null) { - if (!inodes.containsKey(new EntryName(path))) - throw new NoSuchFileException(getString(path)); + beginRead(); + try { + while ((path = getParent(path)) != null) { + if (!inodes.containsKey(IndexNode.keyOf(path))) + throw new NoSuchFileException(getString(path)); + } + } finally { + endRead(); } } @@ -839,25 +906,40 @@ public class ZipFileSystem extends FileSystem { return true; } - /////////////////////////////////////////////////////////////////// - private void initZipFile() throws IOException { - ch = zfpath.newByteChannel(READ); - initCEN(); + private final void beginWrite() { + rwlock.writeLock().lock(); + } + + private final void endWrite() { + rwlock.writeLock().unlock(); + } + + private final void beginRead() { + rwlock.readLock().lock(); } + private final void endRead() { + rwlock.readLock().unlock(); + } + + /////////////////////////////////////////////////////////////////// + private volatile boolean isOpen = true; - private SeekableByteChannel ch; // channel to the zipfile - ByteBuffer cen; // CEN & ENDHDR + private final SeekableByteChannel ch; // channel to the zipfile + final byte[] cen; // CEN & ENDHDR private END end; private long locpos; // position of first LOC header (usually 0) - // name -> pos (in cen), package private for ZipInfo - LinkedHashMap inodes; + private final ReadWriteLock rwlock = new ReentrantReadWriteLock(); + + // name -> pos (in cen), IndexNode itself can be used as a "key" + private LinkedHashMap inodes; - byte[] getBytes(String name) { + final byte[] getBytes(String name) { return zc.getBytes(name); } - String getString(byte[] name) { + + final String getString(byte[] name) { return zc.toString(name); } @@ -881,7 +963,7 @@ public class ZipFileSystem extends FileSystem { // Reads len bytes of data from the specified offset into buf. // Returns the total number of bytes read. // Each/every byte read from here (except the cen, which is mapped). - private long readFullyAt(byte[] buf, int off, long len, long pos) + final long readFullyAt(byte[] buf, int off, long len, long pos) throws IOException { ByteBuffer bb = ByteBuffer.wrap(buf); @@ -890,7 +972,7 @@ public class ZipFileSystem extends FileSystem { return readFullyAt(bb, pos); } - private long readFullyAt(ByteBuffer bb, long pos) + private final long readFullyAt(ByteBuffer bb, long pos) throws IOException { synchronized(ch) { @@ -971,12 +1053,12 @@ public class ZipFileSystem extends FileSystem { // CEN header, otherwise returns -1 if an error occured. If zip->msg != NULL // then the error was a zip format error and zip->msg has the error text. // Always pass in -1 for knownTotal; it's used for a recursive call. - private long initCEN() throws IOException { + private byte[] initCEN() throws IOException { end = findEND(); if (end.endpos == 0) { - inodes = new LinkedHashMap(10); + inodes = new LinkedHashMap<>(10); locpos = 0; - return 0; // only END header present + return null; // only END header present } if (end.cenlen > end.endpos) zerror("invalid END header (bad central directory size)"); @@ -989,18 +1071,14 @@ public class ZipFileSystem extends FileSystem { zerror("invalid END header (bad central directory offset)"); // read in the CEN and END - cen = ByteBuffer.allocate((int)(end.cenlen + ENDHDR)); - if (readFullyAt(cen, cenpos) != end.cenlen + ENDHDR) { + byte[] cen = new byte[(int)(end.cenlen + ENDHDR)]; + if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) { zerror("read CEN tables failed"); } - cen.order(ByteOrder.LITTLE_ENDIAN).flip(); - // Iterate through the entries in the central directory - inodes = new LinkedHashMap(end.centot + 1); + inodes = new LinkedHashMap<>(end.centot + 1); int pos = 0; - int limit = cen.remaining() - ENDHDR; - int i = 0; - byte[] bBuf = new byte[1024]; + int limit = cen.length - ENDHDR; while (pos < limit) { if (CENSIG(cen, pos) != CENSIG) zerror("invalid CEN header (bad signature)"); @@ -1011,24 +1089,19 @@ public class ZipFileSystem extends FileSystem { if ((CENFLG(cen, pos) & 1) != 0) zerror("invalid CEN header (encrypted entry)"); if (method != METHOD_STORED && method != METHOD_DEFLATED) - zerror("invalid CEN header (bad compression method: " + method + ")"); + zerror("invalid CEN header (unsupported compression method: " + method + ")"); if (pos + CENHDR + nlen > limit) zerror("invalid CEN header (bad header size)"); - if (bBuf.length < nlen) - bBuf = new byte[nlen]; - cen.position(pos + CENHDR); - byte[] name = new byte[nlen]; - cen.get(name); - inodes.put(new EntryName(name), new IndexNode(name, pos)); + byte[] name = Arrays.copyOfRange(cen, pos + CENHDR, pos + CENHDR + nlen); + IndexNode inode = new IndexNode(name, pos); + inodes.put(inode, inode); // skip ext and comment - cen.position(pos += (CENHDR + nlen + elen + clen)); - i++; + pos += (CENHDR + nlen + elen + clen); } - if (cen.remaining() != ENDHDR) { + if (pos + ENDHDR != cen.length) { zerror("invalid CEN header (bad header size)"); } - dirs = null; // clear the dir map - return cenpos; + return cen; } private void ensureOpen() throws IOException { @@ -1038,27 +1111,40 @@ public class ZipFileSystem extends FileSystem { // Creates a new empty temporary file in the same directory as the // specified file. A variant of File.createTempFile. - private static Path createTempFileInSameDirectoryAs(Path path) + private Path createTempFileInSameDirectoryAs(Path path) throws IOException { Path parent = path.toAbsolutePath().getParent(); String dir = (parent == null)? "." : parent.toString(); - return File.createTempFile("zipfstmp", null, new File(dir)).toPath(); + Path tmpPath = File.createTempFile("zipfstmp", null, new File(dir)).toPath(); + tmppaths.add(tmpPath); + return tmpPath; } ////////////////////update & sync ////////////////////////////////////// private boolean hasUpdate = false; + private void updateDelete(Entry e) { - EntryName en = new EntryName(e.name); - inodes.remove(en); - hasUpdate = true; + beginWrite(); + try { + inodes.remove(IndexNode.keyOf(e.name)); //inodes.remove(e.name); + hasUpdate = true; + dirs = null; + } finally { + endWrite(); + } } private void update(Entry e) { - EntryName en = new EntryName(e.name); - inodes.put(en, e); - hasUpdate = true; + beginWrite(); + try { + inodes.put(IndexNode.keyOf(e.name), e); //inodes.put(e, e); + hasUpdate = true; + dirs = null; + } finally { + endWrite(); + } } // copy over the whole LOC entry (header if necessary, data and ext) from @@ -1080,13 +1166,18 @@ public class ZipFileSystem extends FileSystem { else size = 16; } - if (updateHeader) { // if we need update the loc header - locoff += LOCHDR + e.nlen + e.elen; // skip header + // read loc, use the original loc.elen/nlen + if (readFullyAt(buf, 0, LOCHDR , locoff) != LOCHDR) + throw new ZipException("loc: reading failed"); + if (updateHeader) { + locoff += LOCHDR + LOCNAM(buf) + LOCEXT(buf); // skip header size += e.csize; written = e.writeLOC(os) + size; } else { - size += LOCHDR + e.nlen + e.elen + e.csize; - written = size; + os.write(buf, 0, LOCHDR); // write out the loc header + locoff += LOCHDR; + size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf); + written = LOCHDR + size; } int n; while (size > 0 && @@ -1103,7 +1194,7 @@ public class ZipFileSystem extends FileSystem { // sync the zip file system, if there is any udpate private void sync() throws IOException { - assert Thread.holdsLock(this); + //System.out.printf("->sync(%s) starting....!%n", toString()); // check ex-closer if (!exChClosers.isEmpty()) { @@ -1117,7 +1208,6 @@ public class ZipFileSystem extends FileSystem { } if (!hasUpdate) return; - Path tmpFile = createTempFileInSameDirectoryAs(zfpath); OutputStream os = tmpFile.newOutputStream(WRITE); ArrayList elist = new ArrayList<>(inodes.size()); @@ -1174,7 +1264,7 @@ public class ZipFileSystem extends FileSystem { x.printStackTrace(); // skip any in-accurate entry } } else { // unchanged inode - e = Entry.readCEN(cen, inode.pos); + e = Entry.readCEN(this, inode.pos); try { written += copyLOCEntry(e, false, os, written, buf); elist.add(e); @@ -1195,6 +1285,11 @@ public class ZipFileSystem extends FileSystem { os.close(); if (!streams.isEmpty()) { + // + // TBD: ExChannelCloser should not be necessary if we only + // sync when being closed, all streams should have been + // closed already. Keep the logic here for now. + // // There are outstanding input streams open on existing "ch", // so, don't close the "cha" and delete the "file for now, let // the "ex-channel-closer" to handle them @@ -1209,45 +1304,41 @@ public class ZipFileSystem extends FileSystem { ch.close(); zfpath.delete(); } + tmpFile.moveTo(zfpath, REPLACE_EXISTING); hasUpdate = false; // clear - + /* if (isOpen) { ch = zfpath.newByteChannel(READ); // re-fresh "ch" and "cen" - initCEN(); + cen = initCEN(); } - //System.out.println("->sync() done!"); + */ + //System.out.printf("->sync(%s) done!%n", toString()); } private Entry getEntry0(byte[] path) throws IOException { - assert Thread.holdsLock(this); - if (path == null) throw new NullPointerException("path"); if (path.length == 0) return null; - EntryName en = new EntryName(path); IndexNode inode = null; - synchronized (lock) { - ensureOpen(); - if ((inode = inodes.get(en)) == null) { - if (path[path.length -1] == '/') // already has a slash - return null; - path = Arrays.copyOf(path, path.length + 1); - path[path.length - 1] = '/'; - en.name(path); - if ((inode = inodes.get(en)) == null) - return null; - } - if (inode instanceof Entry) - return (Entry)inode; - return Entry.readCEN(cen, inode.pos); + IndexNode key = IndexNode.keyOf(path); + if ((inode = inodes.get(key)) == null) { + if (path[path.length -1] == '/') // already has a slash + return null; + path = Arrays.copyOf(path, path.length + 1); + path[path.length - 1] = '/'; + if ((inode = inodes.get(key.as(path))) == null) + return null; } + if (inode instanceof Entry) + return (Entry)inode; + return Entry.readCEN(this, inode.pos); } // Test if the "name" a parent directory of any entry (dir empty) boolean isAncestor(byte[] name) { - for (Map.Entry entry : inodes.entrySet()) { + for (Map.Entry entry : inodes.entrySet()) { byte[] ename = entry.getKey().name; if (isParentOf(name, ename)) return true; @@ -1259,18 +1350,16 @@ public class ZipFileSystem extends FileSystem { throws IOException { checkWritable(); - synchronized(lock) { - Entry e = getEntry0(path); - if (e == null) { - if (path != null && path.length == 0) - throw new ZipException("root directory can't not be delete"); - if (failIfNotExists) - throw new NoSuchFileException(getString(path)); - } else { - if (e.isDir() && isAncestor(path)) - throw new DirectoryNotEmptyException(getString(path)); - updateDelete(e); - } + Entry e = getEntry0(path); + if (e == null) { + if (path != null && path.length == 0) + throw new ZipException("root directory can't not be delete"); + if (failIfNotExists) + throw new NoSuchFileException(getString(path)); + } else { + if (e.isDir() && isAncestor(path)) + throw new DirectoryNotEmptyException(getString(path)); + updateDelete(e); } } @@ -1289,9 +1378,8 @@ public class ZipFileSystem extends FileSystem { // (2) updating/replacing the contents of the specified existing entry. private OutputStream getOutputStream(Entry e) throws IOException { - ensureOpen(); if (e.mtime == -1) - e.mtime = javaToDosTime(System.currentTimeMillis()); + e.mtime = System.currentTimeMillis(); if (e.method == -1) e.method = METHOD_DEFLATED; // TBD: use default method // store size, compressed size, and crc-32 in LOC header @@ -1334,7 +1422,7 @@ public class ZipFileSystem extends FileSystem { long bufSize = e.size + 2; // Inflater likes a bit of slack if (bufSize > 65536) bufSize = 8192; - final long size = e.size;; + final long size = e.size; eis = new InflaterInputStream(eis, getInflater(), (int)bufSize) { private boolean isClosed = false; @@ -1343,6 +1431,7 @@ public class ZipFileSystem extends FileSystem { releaseInflater(inf); this.in.close(); isClosed = true; + streams.remove(this); } } // Override fill() method to provide an extra "dummy" byte @@ -1372,7 +1461,9 @@ public class ZipFileSystem extends FileSystem { Integer.MAX_VALUE : (int) avail; } }; - } else if (e.method != METHOD_STORED) { + } else if (e.method == METHOD_STORED) { + // TBD: wrap/ it does not seem necessary + } else { throw new ZipException("invalid compression method"); } streams.add(eis); @@ -1382,11 +1473,11 @@ public class ZipFileSystem extends FileSystem { // Inner class implementing the input stream used to read // a (possibly compressed) zip file entry. private class EntryInputStream extends InputStream { - private SeekableByteChannel zfch; // local ref to zipfs's "ch". zipfs.ch might + private final SeekableByteChannel zfch; // local ref to zipfs's "ch". zipfs.ch might // point to a new channel after sync() private long pos; // current position within entry data protected long rem; // number of remaining bytes within entry - protected long size; // uncompressed size of this entry + protected final long size; // uncompressed size of this entry EntryInputStream(Entry e, SeekableByteChannel zfch) throws IOException @@ -1527,14 +1618,14 @@ public class ZipFileSystem extends FileSystem { } } - private static void zerror(String msg) { + static void zerror(String msg) { throw new ZipError(msg); } // Maxmum number of de/inflater we cache private final int MAX_FLATER = 20; // List of available Inflater objects for decompression - private List inflaters = new ArrayList<>(); + private final List inflaters = new ArrayList<>(); // Gets an inflater from the list of available inflaters or allocates // a new one. @@ -1563,7 +1654,7 @@ public class ZipFileSystem extends FileSystem { } // List of available Deflater objects for compression - private List deflaters = new ArrayList<>(); + private final List deflaters = new ArrayList<>(); // Gets an deflater from the list of available deflaters or allocates // a new one. @@ -1660,44 +1751,40 @@ public class ZipFileSystem extends FileSystem { } } - // wrapper for the byte[] name - static class EntryName { + // Internal node that links a "name" to its pos in cen table. + // The node itself can be used as a "key" to lookup itself in + // the HashMap inodes. + static class IndexNode { byte[] name; - int hashcode; // node is hashable/hashed by its name + int hashcode; // node is hashable/hashed by its name + int pos = -1; // postion in cen table, -1 menas the + // entry does not exists in zip file + IndexNode(byte[] name, int pos) { + as(name); + this.pos = pos; + } - public EntryName (byte[] name) { - name(name); + final static IndexNode keyOf(byte[] name) { // get a lookup key; + return new IndexNode(name, -1); } - void name(byte[] name) { - this.name = name; + final IndexNode as(byte[] name) { // reuse the node, mostly + this.name = name; // as a lookup "key" this.hashcode = Arrays.hashCode(name); + return this; } public boolean equals(Object other) { - if (!(other instanceof EntryName)) + if (!(other instanceof IndexNode)) return false; - return Arrays.equals(name, ((EntryName)other).name); + return Arrays.equals(name, ((IndexNode)other).name); } public int hashCode() { return hashcode; } - } - - // can simply use Integer instead, if we don't use it to - // build a internal node tree. - static class IndexNode { - byte[] name; - int pos = -1; // postion in cen table, -1 menas the - // entry does not exists in zip file - IndexNode(byte[] name, int pos) { - this.name = name; - this.pos = pos; - } IndexNode() {} - IndexNode sibling; IndexNode child; // 1st child } @@ -1723,37 +1810,25 @@ public class ZipFileSystem extends FileSystem { long crc = -1; // crc-32 of entry data long csize = -1; // compressed size of entry data long size = -1; // uncompressed size of entry data - int nlen; - int elen; byte[] extra; - // loc - long startPos; - long endPos; // exclusive - // cen int versionMade; int disk; int attrs; long attrsEx; long locoff; - - int clen; byte[] comment; - // ZIP64 flag - boolean hasZip64; - Entry() {} Entry(byte[] name) { - this.name = name; - //this.nlen = name.length; - this.mtime = javaToDosTime(System.currentTimeMillis()); - this.crc = 0; - this.size = 0; - this.csize = 0; - this.method = METHOD_DEFLATED; + this.name = name; + this.mtime = System.currentTimeMillis(); + this.crc = 0; + this.size = 0; + this.csize = 0; + this.method = METHOD_DEFLATED; } Entry(byte[] name, int type) { @@ -1761,16 +1836,9 @@ public class ZipFileSystem extends FileSystem { this.type = type; } - Entry (byte[] name, Path file, int type) { - this(name, type); - this.file = file; - this.method = METHOD_STORED; - } - - Entry(Entry e) { + Entry (Entry e, int type) { this.version = e.version; - this.name = e.name; // copyOf? - this.nlen = e.nlen; + this.name = e.name; this.ctime = e.ctime; this.atime = e.atime; this.mtime = e.mtime; @@ -1778,25 +1846,21 @@ public class ZipFileSystem extends FileSystem { this.size = e.size; this.csize = e.csize; this.method = e.method; - this.extra = (e.extra == null)? - null:Arrays.copyOf(e.extra, e.extra.length); - this.elen = e.elen; + this.extra = e.extra; this.versionMade = e.versionMade; this.disk = e.disk; this.attrs = e.attrs; this.attrsEx = e.attrsEx; this.locoff = e.locoff; - this.clen = e.clen; - this.comment = (e.comment == null)? - null:Arrays.copyOf(e.comment, e.comment.length); - this.startPos = e.startPos; - this.endPos = e.endPos; - this.hasZip64 = e.hasZip64;; + this.comment = e.comment; + + this.type = type; } - Entry (Entry e, int type) { - this(e); - this.type = type; + Entry (byte[] name, Path file, int type) { + this(name, type); + this.file = file; + this.method = METHOD_STORED; } boolean isDir() { @@ -1814,77 +1878,45 @@ public class ZipFileSystem extends FileSystem { } ///////////////////// CEN ////////////////////// - static Entry readCEN(ByteBuffer cen, int pos) throws IOException + static Entry readCEN(ZipFileSystem zipfs, int pos) + throws IOException { - return new Entry().cen(cen, pos); + return new Entry().cen(zipfs, pos); } - private Entry cen(ByteBuffer cen, int pos) throws IOException + private Entry cen(ZipFileSystem zipfs, int pos) + throws IOException { + byte[] cen = zipfs.cen; if (CENSIG(cen, pos) != CENSIG) zerror("invalid CEN header (bad signature)"); versionMade = CENVEM(cen, pos); version = CENVER(cen, pos); flag = CENFLG(cen, pos); method = CENHOW(cen, pos); - mtime = CENTIM(cen, pos); + mtime = dosToJavaTime(CENTIM(cen, pos)); crc = CENCRC(cen, pos); csize = CENSIZ(cen, pos); size = CENLEN(cen, pos); - nlen = CENNAM(cen, pos); - elen = CENEXT(cen, pos); - clen = CENCOM(cen, pos); + int nlen = CENNAM(cen, pos); + int elen = CENEXT(cen, pos); + int clen = CENCOM(cen, pos); disk = CENDSK(cen, pos); attrs = CENATT(cen, pos); attrsEx = CENATX(cen, pos); locoff = CENOFF(cen, pos); - cen.position(pos + CENHDR); - name = new byte[nlen]; - cen.get(name); + pos += CENHDR; + name = Arrays.copyOfRange(cen, pos, pos + nlen); + pos += nlen; if (elen > 0) { - extra = new byte[elen]; - cen.get(extra); - if (csize == ZIP64_MINVAL || size == ZIP64_MINVAL || - locoff == ZIP64_MINVAL) { - int off = 0; - while (off + 4 < elen) { - // extra spec: HeaderID+DataSize+Data - int sz = SH(extra, off + 2); - if (SH(extra, off) == EXTID_ZIP64) { - off += 4; - if (size == ZIP64_MINVAL) { - // if invalid zip64 extra fields, just skip - if (sz < 8 || (off + 8) > elen) - break; - size = LL(extra, off); - sz -= 8; - off += 8; - } - if (csize == ZIP64_MINVAL) { - if (sz < 8 || (off + 8) > elen) - break; - csize = LL(extra, off); - sz -= 8; - off += 8; - } - if (locoff == ZIP64_MINVAL) { - if (sz < 8 || (off + 8) > elen) - break; - locoff = LL(extra, off); - sz -= 8; - off += 8; - } - break; - } - off += (sz + 4); - } - } + extra = Arrays.copyOfRange(cen, pos, pos + elen); + pos += elen; + readExtra(zipfs); } if (clen > 0) { - comment = new byte[clen]; - cen.get(comment); + comment = Arrays.copyOfRange(cen, pos, pos + clen); } return this; } @@ -1897,31 +1929,37 @@ public class ZipFileSystem extends FileSystem { long csize0 = csize; long size0 = size; long locoff0 = locoff; - int e64len = 0; + int elen64 = 0; // extra for ZIP64 + int elenNTFS = 0; // extra for NTFS (a/c/mtime) + int elenEXTT = 0; // extra for Extended Timestamp // confirm size/length - nlen = (name != null) ? name.length : 0; - elen = (extra != null) ? extra.length : 0; - clen = (comment != null) ? comment.length : 0; - - boolean hasZip64 = false; + int nlen = (name != null) ? name.length : 0; + int elen = (extra != null) ? extra.length : 0; + int clen = (comment != null) ? comment.length : 0; if (csize >= ZIP64_MINVAL) { csize0 = ZIP64_MINVAL; - e64len += 8; // csize(8) - hasZip64 = true; + elen64 += 8; // csize(8) } if (size >= ZIP64_MINVAL) { size0 = ZIP64_MINVAL; // size(8) - e64len += 8; - hasZip64 = true; + elen64 += 8; } if (locoff >= ZIP64_MINVAL) { locoff0 = ZIP64_MINVAL; - e64len += 8; // offset(8) - hasZip64 = true; + elen64 += 8; // offset(8) + } + if (elen64 != 0) + elen64 += 4; // header and data sz 4 bytes + + if (atime != -1) { + if (isWindows) // use NTFS + elenNTFS = 36; // total 36 bytes + else // Extended Timestamp otherwise + elenEXTT = 9; // only mtime in cen } writeInt(os, CENSIG); // CEN header signature - if (hasZip64) { + if (elen64 != 0) { writeShort(os, 45); // ver 4.5 for zip64 writeShort(os, 45); } else { @@ -1930,18 +1968,14 @@ public class ZipFileSystem extends FileSystem { } writeShort(os, flag); // general purpose bit flag writeShort(os, method); // compression method - writeInt(os, mtime); // last modification time + // last modification time + writeInt(os, (int)javaToDosTime(mtime)); writeInt(os, crc); // crc-32 writeInt(os, csize0); // compressed size writeInt(os, size0); // uncompressed size writeShort(os, name.length); + writeShort(os, elen + elen64 + elenNTFS + elenEXTT); - if (hasZip64) { - // + headid(2) + datasize(2) - writeShort(os, e64len + 4 + elen); - } else { - writeShort(os, elen); - } if (comment != null) { writeShort(os, Math.min(clen, 0xffff)); } else { @@ -1952,9 +1986,9 @@ public class ZipFileSystem extends FileSystem { writeInt(os, 0); // external file attributes (unused) writeInt(os, locoff0); // relative offset of local header writeBytes(os, name); - if (hasZip64) { + if (elen64 != 0) { writeShort(os, EXTID_ZIP64);// Zip64 extra - writeShort(os, e64len); + writeShort(os, elen64); // size of "this" extra block if (size0 == ZIP64_MINVAL) writeLong(os, size); if (csize0 == ZIP64_MINVAL) @@ -1962,58 +1996,73 @@ public class ZipFileSystem extends FileSystem { if (locoff0 == ZIP64_MINVAL) writeLong(os, locoff); } - if (extra != null) { - writeBytes(os, extra); + if (elenNTFS != 0) { + // System.out.println("writing NTFS:" + elenNTFS); + writeShort(os, EXTID_NTFS); + writeShort(os, elenNTFS - 4); + writeInt(os, 0); // reserved + writeShort(os, 0x0001); // NTFS attr tag + writeShort(os, 24); + writeLong(os, javaToWinTime(mtime)); + writeLong(os, javaToWinTime(atime)); + writeLong(os, javaToWinTime(ctime)); + } + if (elenEXTT != 0) { + writeShort(os, EXTID_EXTT); + writeShort(os, elenEXTT - 4); + if (ctime == -1) + os.write(0x3); // mtime and atime + else + os.write(0x7); // mtime, atime and ctime + writeInt(os, javaToUnixTime(mtime)); } - if (comment != null) { - //TBD: 0, Math.min(commentBytes.length, 0xffff)); + if (extra != null) // whatever not recognized + writeBytes(os, extra); + if (comment != null) //TBD: 0, Math.min(commentBytes.length, 0xffff)); writeBytes(os, comment); - } - return CENHDR + nlen + elen + clen + (hasZip64?(e64len + 4):0); + return CENHDR + nlen + elen + clen + elen64 + elenNTFS + elenEXTT; } ///////////////////// LOC ////////////////////// - static Entry readLOC(ZipFileSystem zf, long pos) + static Entry readLOC(ZipFileSystem zipfs, long pos) throws IOException { - return readLOC(zf, pos, new byte[1024]); + return readLOC(zipfs, pos, new byte[1024]); } - static Entry readLOC(ZipFileSystem zf, long pos, byte[] buf) + static Entry readLOC(ZipFileSystem zipfs, long pos, byte[] buf) throws IOException { - return new Entry().loc(zf, pos, buf); + return new Entry().loc(zipfs, pos, buf); } - Entry loc(ZipFileSystem zf, long pos, byte[] buf) + Entry loc(ZipFileSystem zipfs, long pos, byte[] buf) throws IOException { assert (buf.length >= LOCHDR); - if (zf.readFullyAt(buf, 0, LOCHDR , pos) != LOCHDR) { + if (zipfs.readFullyAt(buf, 0, LOCHDR , pos) != LOCHDR) throw new ZipException("loc: reading failed"); - } - if (LOCSIG(buf) != LOCSIG) { + if (LOCSIG(buf) != LOCSIG) throw new ZipException("loc: wrong sig ->" + Long.toString(LOCSIG(buf), 16)); - } - startPos = pos; + //startPos = pos; version = LOCVER(buf); flag = LOCFLG(buf); method = LOCHOW(buf); - mtime = LOCTIM(buf); + mtime = dosToJavaTime(LOCTIM(buf)); crc = LOCCRC(buf); csize = LOCSIZ(buf); size = LOCLEN(buf); - nlen = LOCNAM(buf); - elen = LOCEXT(buf); + int nlen = LOCNAM(buf); + int elen = LOCEXT(buf); name = new byte[nlen]; - if (zf.readFullyAt(name, 0, nlen, pos + LOCHDR) != nlen) { + if (zipfs.readFullyAt(name, 0, nlen, pos + LOCHDR) != nlen) { throw new ZipException("loc: name reading failed"); } if (elen > 0) { extra = new byte[elen]; - if (zf.readFullyAt(extra, 0, elen, pos + LOCHDR + nlen) + if (zipfs.readFullyAt(extra, 0, elen, pos + LOCHDR + nlen) != elen) { throw new ZipException("loc: ext reading failed"); } @@ -2021,7 +2070,7 @@ public class ZipFileSystem extends FileSystem { pos += (LOCHDR + nlen + elen); if ((flag & FLAG_DATADESCR) != 0) { // Data Descriptor - Entry e = zf.getEntry0(name); // get the size/csize from cen + Entry e = zipfs.getEntry0(name); // get the size/csize from cen if (e == null) throw new ZipException("loc: name not found in cen"); size = e.size; @@ -2032,7 +2081,6 @@ public class ZipFileSystem extends FileSystem { else pos += 16; } else { - boolean hasZip64 = false; if (extra != null && (size == ZIP64_MINVAL || csize == ZIP64_MINVAL)) { // zip64 ext: must include both size and csize @@ -2042,7 +2090,6 @@ public class ZipFileSystem extends FileSystem { if (SH(extra, off) == EXTID_ZIP64 && sz == 16) { size = LL(extra, off + 4); csize = LL(extra, off + 12); - hasZip64 = true; break; } off += (sz + 4); @@ -2050,7 +2097,6 @@ public class ZipFileSystem extends FileSystem { } pos += (method == METHOD_STORED ? size : csize); } - endPos = pos; return this; } @@ -2058,14 +2104,18 @@ public class ZipFileSystem extends FileSystem { throws IOException { writeInt(os, LOCSIG); // LOC header signature - int version = version(); + + int nlen = (name != null) ? name.length : 0; + int elen = (extra != null) ? extra.length : 0; + int elen64 = 0; + int elenEXTT = 0; if ((flag & FLAG_DATADESCR) != 0) { writeShort(os, version()); // version needed to extract writeShort(os, flag); // general purpose bit flag writeShort(os, method); // compression method - writeInt(os, mtime); // last modification time - + // last modification time + writeInt(os, (int)javaToDosTime(mtime)); // store size, uncompressed size, and crc-32 in data descriptor // immediately following compressed entry data writeInt(os, 0); @@ -2073,7 +2123,7 @@ public class ZipFileSystem extends FileSystem { writeInt(os, 0); } else { if (csize >= ZIP64_MINVAL || size >= ZIP64_MINVAL) { - hasZip64 = true; + elen64 = 20; //headid(2) + size(2) + size(8) + csize(8) writeShort(os, 45); // ver 4.5 for zip64 } else { writeShort(os, version()); // version needed to extract @@ -2082,29 +2132,45 @@ public class ZipFileSystem extends FileSystem { writeShort(os, method); // compression method writeInt(os, mtime); // last modification time writeInt(os, crc); // crc-32 - if (hasZip64) { + if (elen64 != 0) { writeInt(os, ZIP64_MINVAL); writeInt(os, ZIP64_MINVAL); - //TBD: e.elen += 20; //headid(2) + size(2) + size(8) + csize(8) } else { writeInt(os, csize); // compressed size writeInt(os, size); // uncompressed size } } + if (atime != -1 && !isWindows) { // on unix use "ext time" + if (ctime == -1) + elenEXTT = 13; + else + elenEXTT = 17; + } writeShort(os, name.length); - writeShort(os, elen + (hasZip64 ? 20 : 0)); + writeShort(os, elen + elen64 + elenEXTT); writeBytes(os, name); - if (hasZip64) { - // TBD: should we update extra directory? + if (elen64 != 0) { writeShort(os, EXTID_ZIP64); writeShort(os, 16); writeLong(os, size); writeLong(os, csize); } + if (elenEXTT != 0) { + writeShort(os, EXTID_EXTT); + writeShort(os, elenEXTT - 4);// size for the folowing data block + if (ctime == -1) + os.write(0x3); // mtime and atime + else + os.write(0x7); // mtime, atime and ctime + writeInt(os, javaToUnixTime(mtime)); + writeInt(os, javaToUnixTime(atime)); + if (ctime != -1) + writeInt(os, javaToUnixTime(ctime)); + } if (extra != null) { writeBytes(os, extra); } - return LOCHDR + name.length + elen + (hasZip64 ? 20 : 0); + return LOCHDR + name.length + elen + elen64 + elenEXTT; } // Data Descriptior @@ -2125,17 +2191,18 @@ public class ZipFileSystem extends FileSystem { } // read NTFS, UNIX and ZIP64 data from cen.extra - void readExtra() { + void readExtra(ZipFileSystem zipfs) throws IOException { if (extra == null) return; int elen = extra.length; int off = 0; + int newOff = 0; while (off + 4 < elen) { // extra spec: HeaderID+DataSize+Data - int sz = SH(extra, off + 2); - int tag = SH(extra, off); - off += 4; int pos = off; + int tag = SH(extra, pos); + int sz = SH(extra, pos + 2); + pos += 4; if (pos + sz > elen) // invalid data break; switch (tag) { @@ -2165,18 +2232,66 @@ public class ZipFileSystem extends FileSystem { break; if (SH(extra, pos + 2) != 24) break; - mtime = LL(extra, pos + 4); - atime = LL(extra, pos + 12); - ctime = LL(extra, pos + 20); + // override the loc field, datatime here is + // more "accurate" + mtime = winToJavaTime(LL(extra, pos + 4)); + atime = winToJavaTime(LL(extra, pos + 12)); + ctime = winToJavaTime(LL(extra, pos + 20)); break; - case EXTID_UNIX: - atime = LG(extra, pos); - mtime = LG(extra, pos + 4); + case EXTID_EXTT: + // spec says the Extened timestamp in cen only has mtime + // need to read the loc to get the extra a/ctime + byte[] buf = new byte[LOCHDR]; + if (zipfs.readFullyAt(buf, 0, buf.length , locoff) + != buf.length) + throw new ZipException("loc: reading failed"); + if (LOCSIG(buf) != LOCSIG) + throw new ZipException("loc: wrong sig ->" + + Long.toString(LOCSIG(buf), 16)); + + int locElen = LOCEXT(buf); + if (locElen < 9) // EXTT is at lease 9 bytes + break; + int locNlen = LOCNAM(buf); + buf = new byte[locElen]; + if (zipfs.readFullyAt(buf, 0, buf.length , locoff + LOCHDR + locNlen) + != buf.length) + throw new ZipException("loc extra: reading failed"); + int locPos = 0; + while (locPos + 4 < buf.length) { + int locTag = SH(buf, locPos); + int locSZ = SH(buf, locPos + 2); + locPos += 4; + if (locTag != EXTID_EXTT) { + locPos += locSZ; + continue; + } + int flag = CH(buf, locPos++); + if ((flag & 0x1) != 0) { + mtime = unixToJavaTime(LG(buf, locPos)); + locPos += 4; + } + if ((flag & 0x2) != 0) { + atime = unixToJavaTime(LG(buf, locPos)); + locPos += 4; + } + if ((flag & 0x4) != 0) { + ctime = unixToJavaTime(LG(buf, locPos)); + locPos += 4; + } + break; + } break; - default: // unknow + default: // unknown tag + System.arraycopy(extra, off, extra, newOff, sz + 4); + newOff += (sz + 4); } - off += sz; + off += (sz + 4); } + if (newOff != 0 && newOff != extra.length) + extra = Arrays.copyOf(extra, newOff); + else + extra = null; } } @@ -2201,9 +2316,9 @@ public class ZipFileSystem extends FileSystem { // structure. // A possible solution is to build the node tree ourself as // implemented below. - private HashMap dirs; + private HashMap dirs; private IndexNode root; - private IndexNode addToDir(EntryName child) { + private IndexNode addToDir(IndexNode child) { IndexNode cinode = dirs.get(child); if (cinode != null) return cinode; @@ -2213,7 +2328,7 @@ public class ZipFileSystem extends FileSystem { IndexNode pinode; if (pname != null) - pinode = addToDir(new EntryName(pname)); + pinode = addToDir(IndexNode.keyOf(pname)); else pinode = root; cinode = inodes.get(child); @@ -2222,8 +2337,8 @@ public class ZipFileSystem extends FileSystem { pinode.child = cinode; return null; } - cinode = dirs.get(child); - if (cinode == null) // pseudo directry entry + //cinode = dirs.get(child); + if (cinode == null) // pseudo directry entry cinode = new IndexNode(cname, -1); cinode.sibling = pinode.child; pinode.child = cinode; @@ -2232,26 +2347,21 @@ public class ZipFileSystem extends FileSystem { return cinode; } - private HashMap getDirs() + private HashMap getDirs() throws IOException { - if (hasUpdate) - sync(); - if (dirs != null) + beginWrite(); + try { + if (dirs != null) + return dirs; + dirs = new HashMap<>(); + root = new IndexNode(new byte[0], -1); + dirs.put(root, root); + for (IndexNode node : inodes.keySet()) + addToDir(node); return dirs; - dirs = new HashMap(); - byte[] empty = new byte[0]; - root = new IndexNode(empty, -1); - dirs.put(new EntryName(empty), root); - - EntryName[] names = inodes.keySet().toArray(new EntryName[0]); - int i = names.length; - while (--i >= 0) { - addToDir(names[i]); - } - // for (int i EntryName en : inodes.keySet()) { - // addToDir(en); - // } - return dirs; + } finally { + endWrite(); + } } } diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java index a43b2cf7de34ef19439151cde7c5f426b70b9666..08c3a17648c2f0e3e2e72d8b678b940968be6923 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java @@ -55,6 +55,8 @@ import java.util.Set; */ public class ZipFileSystemProvider extends FileSystemProvider { + + private final Map filesystems = new HashMap<>(); public ZipFileSystemProvider() {} @@ -101,10 +103,16 @@ public class ZipFileSystemProvider extends FileSystemProvider { throws IOException { synchronized(filesystems) { - if (filesystems.containsKey(path)) - throw new FileSystemAlreadyExistsException(); + Path realPath = null; + if (path.exists()) { + realPath = path.toRealPath(true); + if (filesystems.containsKey(realPath)) + throw new FileSystemAlreadyExistsException(); + } ZipFileSystem zipfs = new ZipFileSystem(this, path, env); - filesystems.put(path, zipfs); + if (realPath == null) + realPath = path.toRealPath(true); + filesystems.put(realPath, zipfs); return zipfs; } } @@ -137,16 +145,21 @@ public class ZipFileSystemProvider extends FileSystemProvider { @Override public FileSystem getFileSystem(URI uri) { synchronized (filesystems) { - ZipFileSystem zipfs = filesystems.get(uriToPath(uri)); + ZipFileSystem zipfs = null; + try { + zipfs = filesystems.get(uriToPath(uri).toRealPath(true)); + } catch (IOException x) { + // ignore the ioe from toRealPath(), return FSNFE + } if (zipfs == null) throw new FileSystemNotFoundException(); return zipfs; } } - void removeFileSystem(Path zfpath) { + void removeFileSystem(Path zfpath) throws IOException { synchronized (filesystems) { - filesystems.remove(zfpath); + filesystems.remove(zfpath.toRealPath(true)); } } } diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java index 741376daf0d4c62971cf25030097f7648fcaf330..dd18cc9f4440044337b006ae815da5a29d9e709e 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java @@ -31,7 +31,6 @@ package com.sun.nio.zipfs; -import java.io.PrintStream; import java.nio.file.Paths; import java.util.Collections; import java.util.Iterator; @@ -41,7 +40,7 @@ import static com.sun.nio.zipfs.ZipConstants.*; import static com.sun.nio.zipfs.ZipUtils.*; /** - * Print the loc and cen tables of the ZIP file + * Print all loc and cen headers of the ZIP file * * @author Xueming Shen */ @@ -49,34 +48,38 @@ import static com.sun.nio.zipfs.ZipUtils.*; public class ZipInfo { public static void main(String[] args) throws Throwable { - if (args.length < 2) { - print("Usage: java ZipInfo [cen|loc] zfname"); + if (args.length < 1) { + print("Usage: java ZipInfo zfname"); } else { Map env = Collections.emptyMap(); ZipFileSystem zfs = (ZipFileSystem)(new ZipFileSystemProvider() - .newFileSystem(Paths.get(args[1]), env)); - - long pos = 0; + .newFileSystem(Paths.get(args[0]), env)); + byte[] cen = zfs.cen; + if (cen == null) { + print("zip file is empty%n"); + return; + } + int pos = 0; + byte[] buf = new byte[1024]; + int no = 1; + while (pos + CENHDR < cen.length) { + print("----------------#%d--------------------%n", no++); + printCEN(cen, pos); - if ("loc".equals(args[0])) { - print("[Local File Header]%n"); - byte[] buf = new byte[1024]; - for (int i = 0; i < zfs.getEntryNames().length; i++) { - Entry loc = Entry.readLOC(zfs, pos, buf); - print("--------loc[%x]--------%n", pos); - printLOC(loc); - pos = loc.endPos; - } - } if ("cen".equals(args[0])) { - int i = 0; - Iterator itr = zfs.inodes.values().iterator(); - print("[Central Directory Header]%n"); - while (itr.hasNext()) { - Entry cen = Entry.readCEN(zfs.cen, itr.next().pos); - print("--------cen[%d]--------%n", i); - printCEN(cen); - i++; + // use size CENHDR as the extra bytes to read, just in case the + // loc.extra is bigger than the cen.extra, try to avoid to read + // twice + long len = LOCHDR + CENNAM(cen, pos) + CENEXT(cen, pos) + CENHDR; + if (zfs.readFullyAt(buf, 0, len, locoff(cen, pos)) != len) + zfs.zerror("read loc header failed"); + if (LOCEXT(buf) > CENEXT(cen, pos) + CENHDR) { + // have to read the second time; + len = LOCHDR + LOCNAM(buf) + LOCEXT(buf); + if (zfs.readFullyAt(buf, 0, len, locoff(cen, pos)) != len) + zfs.zerror("read loc header failed"); } + printLOC(buf); + pos += CENHDR + CENNAM(cen, pos) + CENEXT(cen, pos) + CENCOM(cen, pos); } zfs.close(); } @@ -86,47 +89,135 @@ public class ZipInfo { System.out.printf(fmt, objs); } - static void printLOC(Entry loc) { - print(" [%x, %x]%n", loc.startPos, loc.endPos); - print(" Signature : %8x%n", LOCSIG); - print(" Version : %4x [%d.%d]%n", - loc.version, loc. version/10, loc. version%10); - print(" Flag : %4x%n", loc.flag); - print(" Method : %4x%n", loc. method); - print(" LastMTime : %8x [%tc]%n", - loc.mtime, dosToJavaTime(loc.mtime)); - print(" CRC : %8x%n", loc.crc); - print(" CSize : %8x%n", loc.csize); - print(" Size : %8x%n", loc.size); - print(" NameLength : %4x [%s]%n", - loc.nlen, new String(loc.name)); - print(" ExtraLength : %4x%n", loc.elen); - if (loc.hasZip64) - print(" *ZIP64*%n"); + static void printLOC(byte[] loc) { + print("%n"); + print("[Local File Header]%n"); + print(" Signature : %#010x%n", LOCSIG(loc)); + if (LOCSIG(loc) != LOCSIG) { + print(" Wrong signature!"); + return; + } + print(" Version : %#6x [%d.%d]%n", + LOCVER(loc), LOCVER(loc) / 10, LOCVER(loc) % 10); + print(" Flag : %#6x%n", LOCFLG(loc)); + print(" Method : %#6x%n", LOCHOW(loc)); + print(" LastMTime : %#10x [%tc]%n", + LOCTIM(loc), dosToJavaTime(LOCTIM(loc))); + print(" CRC : %#10x%n", LOCCRC(loc)); + print(" CSize : %#10x%n", LOCSIZ(loc)); + print(" Size : %#10x%n", LOCLEN(loc)); + print(" NameLength : %#6x [%s]%n", + LOCNAM(loc), new String(loc, LOCHDR, LOCNAM(loc))); + print(" ExtraLength : %#6x%n", LOCEXT(loc)); + if (LOCEXT(loc) != 0) + printExtra(loc, LOCHDR + LOCNAM(loc), LOCEXT(loc)); + } + + static void printCEN(byte[] cen, int off) { + print("[Central Directory Header]%n"); + print(" Signature : %#010x%n", CENSIG(cen, off)); + if (CENSIG(cen, off) != CENSIG) { + print(" Wrong signature!"); + return; + } + print(" VerMadeby : %#6x [%d, %d.%d]%n", + CENVEM(cen, off), (CENVEM(cen, off) >> 8), + (CENVEM(cen, off) & 0xff) / 10, + (CENVEM(cen, off) & 0xff) % 10); + print(" VerExtract : %#6x [%d.%d]%n", + CENVER(cen, off), CENVER(cen, off) / 10, CENVER(cen, off) % 10); + print(" Flag : %#6x%n", CENFLG(cen, off)); + print(" Method : %#6x%n", CENHOW(cen, off)); + print(" LastMTime : %#10x [%tc]%n", + CENTIM(cen, off), dosToJavaTime(CENTIM(cen, off))); + print(" CRC : %#10x%n", CENCRC(cen, off)); + print(" CSize : %#10x%n", CENSIZ(cen, off)); + print(" Size : %#10x%n", CENLEN(cen, off)); + print(" NameLen : %#6x [%s]%n", + CENNAM(cen, off), new String(cen, off + CENHDR, CENNAM(cen, off))); + print(" ExtraLen : %#6x%n", CENEXT(cen, off)); + if (CENEXT(cen, off) != 0) + printExtra(cen, off + CENHDR + CENNAM(cen, off), CENEXT(cen, off)); + print(" CommentLen : %#6x%n", CENCOM(cen, off)); + print(" DiskStart : %#6x%n", CENDSK(cen, off)); + print(" Attrs : %#6x%n", CENATT(cen, off)); + print(" AttrsEx : %#10x%n", CENATX(cen, off)); + print(" LocOff : %#10x%n", CENOFF(cen, off)); + + } + + static long locoff(byte[] cen, int pos) { + long locoff = CENOFF(cen, pos); + if (locoff == ZIP64_MINVAL) { //ZIP64 + int off = pos + CENHDR + CENNAM(cen, pos); + int end = off + CENEXT(cen, pos); + while (off + 4 < end) { + int tag = SH(cen, off); + int sz = SH(cen, off + 2); + if (tag != EXTID_ZIP64) { + off += 4 + sz; + continue; + } + off += 4; + if (CENLEN(cen, pos) == ZIP64_MINVAL) + off += 8; + if (CENSIZ(cen, pos) == ZIP64_MINVAL) + off += 8; + return LL(cen, off); + } + // should never be here + } + return locoff; } - static void printCEN(Entry cen) { - print(" Signature : %08x%n", CENSIG); - print(" VerMadeby : %4x [%d.%d]%n", - cen.versionMade, cen.versionMade/10, cen.versionMade%10); - print(" VerExtract : %4x [%d.%d]%n", - cen.version, cen.version/10, cen.version%10); - print(" Flag : %4x%n", cen.flag); - print(" Method : %4x%n", cen.method); - print(" LastMTime : %8x [%tc]%n", - cen.mtime, dosToJavaTime(cen.mtime)); - print(" CRC : %8x%n", cen.crc); - print(" CSize : %8x%n", cen.csize); - print(" Size : %8x%n", cen.size); - print(" NameLen : %4x [%s]%n", - cen.nlen, new String(cen.name)); - print(" ExtraLen : %4x%n", cen.elen); - print(" CommentLen : %4x%n", cen.clen); - print(" DiskStart : %4x%n", cen.disk); - print(" Attrs : %4x%n", cen.attrs); - print(" AttrsEx : %8x%n", cen.attrsEx); - print(" LocOff : %8x%n", cen.locoff); - if (cen.hasZip64) - print(" *ZIP64*%n"); + static void printExtra(byte[] extra, int off, int len) { + int end = off + len; + while (off + 4 < end) { + int tag = SH(extra, off); + int sz = SH(extra, off + 2); + print(" [tag=0x%04x, sz=%d, data= ", tag, sz); + if (off + sz > end) { + print(" Error: Invalid extra data, beyond extra length"); + break; + } + off += 4; + for (int i = 0; i < sz; i++) + print("%02x ", extra[off + i]); + print("]%n"); + switch (tag) { + case EXTID_ZIP64 : + print(" ->ZIP64: "); + int pos = off; + while (pos + 8 <= off + sz) { + print(" *0x%x ", LL(extra, pos)); + pos += 8; + } + print("%n"); + break; + case EXTID_NTFS: + print(" ->PKWare NTFS%n"); + // 4 bytes reserved + if (SH(extra, off + 4) != 0x0001 || SH(extra, off + 6) != 24) + print(" Error: Invalid NTFS sub-tag or subsz"); + print(" mtime:%tc%n", + winToJavaTime(LL(extra, off + 8))); + print(" atime:%tc%n", + winToJavaTime(LL(extra, off + 16))); + print(" ctime:%tc%n", + winToJavaTime(LL(extra, off + 24))); + break; + case EXTID_EXTT: + print(" ->Inof-ZIP Extended Timestamp: flag=%x%n",extra[off]); + pos = off + 1 ; + while (pos + 4 <= off + sz) { + print(" *%tc%n", + unixToJavaTime(LG(extra, pos))); + pos += 4; + } + break; + default: + } + off += sz; + } } } diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java index 1ceab8fc81ad95dba5e21e91c06e3f89f4c95609..5fba2fafa9aef2c022b056e3418bd66153328b4c 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java @@ -32,24 +32,19 @@ package com.sun.nio.zipfs; import java.io.File; -import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; -import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.file.*; import java.nio.file.DirectoryStream.Filter; -import java.nio.file.spi.FileSystemProvider; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileTime; import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import static java.nio.file.StandardOpenOption.*; import static java.nio.file.StandardCopyOption.*; @@ -599,7 +594,7 @@ public class ZipPath extends Path { } private static final DirectoryStream.Filter acceptAllFilter = - new DirectoryStream.Filter() { + new DirectoryStream.Filter<>() { @Override public boolean accept(Path entry) { return true; } }; @@ -625,7 +620,7 @@ public class ZipPath extends Path { // create a matcher and return a filter that uses it. final PathMatcher matcher = getFileSystem().getPathMatcher("glob:" + glob); - DirectoryStream.Filter filter = new DirectoryStream.Filter() { + DirectoryStream.Filter filter = new DirectoryStream.Filter<>() { @Override public boolean accept(Path entry) { return matcher.matches(entry.getName()); @@ -758,7 +753,7 @@ public class ZipPath extends Path { @Override public Iterator iterator() { - return new Iterator() { + return new Iterator<>() { private int i = 0; @Override @@ -803,7 +798,7 @@ public class ZipPath extends Path { @Override public SeekableByteChannel newByteChannel(OpenOption... options) throws IOException { - Set set = new HashSet(options.length); + Set set = new HashSet<>(options.length); Collections.addAll(set, options); return newByteChannel(set); } @@ -908,7 +903,7 @@ public class ZipPath extends Path { if (opt == REPLACE_EXISTING) replaceExisting = true; else if (opt == COPY_ATTRIBUTES) - copyAttrs = false; + copyAttrs = true; } // attributes of source file ZipFileAttributes zfas = getAttributes(); @@ -951,7 +946,9 @@ public class ZipPath extends Path { BasicFileAttributeView view = target.getFileAttributeView(BasicFileAttributeView.class); try { - view.setTimes(zfas.lastModifiedTime(), null, null); + view.setTimes(zfas.lastModifiedTime(), + zfas.lastAccessTime(), + zfas.creationTime()); } catch (IOException x) { // rollback? try { diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipUtils.java b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipUtils.java index b3106e09fa3dbebdeada37ee9111c9141df4425d..cddec6f9bef62d808a863e22ef914f03f678c9da 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipUtils.java +++ b/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipUtils.java @@ -36,6 +36,7 @@ import java.io.OutputStream; import java.util.Arrays; import java.util.Date; import java.util.regex.PatternSyntaxException; +import java.util.concurrent.TimeUnit; /** * @@ -48,7 +49,7 @@ class ZipUtils { * Writes a 16-bit short to the output stream in little-endian byte order. */ public static void writeShort(OutputStream os, int v) throws IOException { - os.write((v >>> 0) & 0xff); + os.write(v & 0xff); os.write((v >>> 8) & 0xff); } @@ -56,7 +57,7 @@ class ZipUtils { * Writes a 32-bit int to the output stream in little-endian byte order. */ public static void writeInt(OutputStream os, long v) throws IOException { - os.write((int)((v >>> 0) & 0xff)); + os.write((int)(v & 0xff)); os.write((int)((v >>> 8) & 0xff)); os.write((int)((v >>> 16) & 0xff)); os.write((int)((v >>> 24) & 0xff)); @@ -66,7 +67,7 @@ class ZipUtils { * Writes a 64-bit int to the output stream in little-endian byte order. */ public static void writeLong(OutputStream os, long v) throws IOException { - os.write((int)((v >>> 0) & 0xff)); + os.write((int)(v & 0xff)); os.write((int)((v >>> 8) & 0xff)); os.write((int)((v >>> 16) & 0xff)); os.write((int)((v >>> 24) & 0xff)); @@ -132,6 +133,27 @@ class ZipUtils { d.getSeconds() >> 1; } + + // used to adjust values between Windows and java epoch + private static final long WINDOWS_EPOCH_IN_MICROSECONDS = -11644473600000000L; + public static final long winToJavaTime(long wtime) { + return TimeUnit.MILLISECONDS.convert( + wtime / 10 + WINDOWS_EPOCH_IN_MICROSECONDS, TimeUnit.MICROSECONDS); + } + + public static final long javaToWinTime(long time) { + return (TimeUnit.MICROSECONDS.convert(time, TimeUnit.MILLISECONDS) + - WINDOWS_EPOCH_IN_MICROSECONDS) * 10; + } + + public static final long unixToJavaTime(long utime) { + return TimeUnit.MILLISECONDS.convert(utime, TimeUnit.SECONDS); + } + + public static final long javaToUnixTime(long time) { + return TimeUnit.SECONDS.convert(time, TimeUnit.MILLISECONDS); + } + private static final String regexMetaChars = ".^$+{[]|()"; private static final String globMetaChars = "\\*?[{"; private static boolean isRegexMeta(char c) { diff --git a/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java b/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java index 57a0492ddee0fc045174645bad2c478d07f82de1..f67efb57fb687b6982e343dd0f4f4c3082099827 100644 --- a/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java +++ b/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java @@ -42,11 +42,19 @@ class GtkFileDialogPeer extends XDialogPeer implements FileDialogPeer { private FileDialog fd; + // A pointer to the native GTK FileChooser widget + private volatile long widget = 0L; + public GtkFileDialogPeer(FileDialog fd) { super((Dialog) fd); this.fd = fd; } + private static native void initIDs(); + static { + initIDs(); + } + private native void run(String title, int mode, String dir, String file, FilenameFilter filter, boolean isMultipleMode); diff --git a/src/solaris/classes/sun/net/www/protocol/http/NTLMAuthentication.java b/src/solaris/classes/sun/net/www/protocol/http/NTLMAuthentication.java deleted file mode 100644 index 4bc5a88748499abab3f59c4d093d37db14ebf6d7..0000000000000000000000000000000000000000 --- a/src/solaris/classes/sun/net/www/protocol/http/NTLMAuthentication.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. 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 sun.net.www.protocol.http; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.InetAddress; -import java.net.PasswordAuthentication; -import java.net.UnknownHostException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import javax.crypto.Cipher; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.DESKeySpec; - -import sun.net.www.HeaderParser; - -/** - * NTLMAuthentication: - * - * @author Michael McMahon - */ - -/* - * NTLM authentication is nominally based on the framework defined in RFC2617, - * but differs from the standard (Basic & Digest) schemes as follows: - * - * 1. A complete authentication requires three request/response transactions - * as shown below: - * REQ -------------------------------> - * <---- 401 (signalling NTLM) -------- - * - * REQ (with type1 NTLM msg) ---------> - * <---- 401 (with type 2 NTLM msg) --- - * - * REQ (with type3 NTLM msg) ---------> - * <---- OK --------------------------- - * - * 2. The scope of the authentication is the TCP connection (which must be kept-alive) - * after the type2 response is received. This means that NTLM does not work end-to-end - * through a proxy, rather between client and proxy, or between client and server (with no proxy) - */ - -class NTLMAuthentication extends AuthenticationInfo { - private static final long serialVersionUID = -2403849171106437142L; - - private byte[] type1; - private byte[] type3; - - private SecretKeyFactory fac; - private Cipher cipher; - private MessageDigest md4; - private String hostname; - private static String defaultDomain; /* Domain to use if not specified by user */ - - static { - defaultDomain = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("http.auth.ntlm.domain", - "domain")); - }; - - static boolean supportsTransparentAuth () { - return false; - } - - private void init0() { - type1 = new byte[256]; - type3 = new byte[256]; - System.arraycopy (new byte[] {'N','T','L','M','S','S','P',0,1}, 0, type1, 0, 9); - type1[12] = (byte) 3; - type1[13] = (byte) 0xb2; - type1[28] = (byte) 0x20; - System.arraycopy (new byte[] {'N','T','L','M','S','S','P',0,3}, 0, type3, 0, 9); - type3[12] = (byte) 0x18; - type3[14] = (byte) 0x18; - type3[20] = (byte) 0x18; - type3[22] = (byte) 0x18; - type3[32] = (byte) 0x40; - type3[60] = (byte) 1; - type3[61] = (byte) 0x82; - - try { - hostname = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public String run() { - String localhost; - try { - localhost = InetAddress.getLocalHost().getHostName().toUpperCase(); - } catch (UnknownHostException e) { - localhost = "localhost"; - } - return localhost; - } - }); - int x = hostname.indexOf ('.'); - if (x != -1) { - hostname = hostname.substring (0, x); - } - fac = SecretKeyFactory.getInstance ("DES"); - cipher = Cipher.getInstance ("DES/ECB/NoPadding"); - md4 = sun.security.provider.MD4.getInstance(); - } catch (NoSuchPaddingException e) { - assert false; - } catch (NoSuchAlgorithmException e) { - assert false; - } - }; - - PasswordAuthentication pw; - String username; - String ntdomain; - String password; - - /** - * Create a NTLMAuthentication: - * Username may be specified as domainusername in the application Authenticator. - * If this notation is not used, then the domain will be taken - * from a system property: "http.auth.ntlm.domain". - */ - public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) { - super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - AuthScheme.NTLM, - url, - ""); - init (pw); - } - - private void init (PasswordAuthentication pw) { - this.pw = pw; - String s = pw.getUserName(); - int i = s.indexOf ('\\'); - if (i == -1) { - username = s; - ntdomain = defaultDomain; - } else { - ntdomain = s.substring (0, i).toUpperCase(); - username = s.substring (i+1); - } - password = new String (pw.getPassword()); - init0(); - } - - /** - * Constructor used for proxy entries - */ - public NTLMAuthentication(boolean isProxy, String host, int port, - PasswordAuthentication pw) { - super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - AuthScheme.NTLM, - host, - port, - ""); - init (pw); - } - - /** - * @return true if this authentication supports preemptive authorization - */ - boolean supportsPreemptiveAuthorization() { - return false; - } - - /** - * @return the name of the HTTP header this authentication wants set - */ - String getHeaderName() { - if (type == SERVER_AUTHENTICATION) { - return "Authorization"; - } else { - return "Proxy-authorization"; - } - } - - /** - * Not supported. Must use the setHeaders() method - */ - String getHeaderValue(URL url, String method) { - throw new RuntimeException ("getHeaderValue not supported"); - } - - /** - * Check if the header indicates that the current auth. parameters are stale. - * If so, then replace the relevant field with the new value - * and return true. Otherwise return false. - * returning true means the request can be retried with the same userid/password - * returning false means we have to go back to the user to ask for a new - * username password. - */ - boolean isAuthorizationStale (String header) { - return false; /* should not be called for ntlm */ - } - - /** - * Set header(s) on the given connection. - * @param conn The connection to apply the header(s) to - * @param p A source of header values for this connection, not used because - * HeaderParser converts the fields to lower case, use raw instead - * @param raw The raw header field. - * @return true if all goes well, false if no headers were set. - */ - synchronized boolean setHeaders(HttpURLConnection conn, HeaderParser p, String raw) { - - try { - String response; - if (raw.length() < 6) { /* NTLM */ - response = buildType1Msg (); - } else { - String msg = raw.substring (5); /* skip NTLM */ - response = buildType3Msg (msg); - } - conn.setAuthenticationProperty(getHeaderName(), response); - return true; - } catch (IOException e) { - return false; - } catch (GeneralSecurityException e) { - return false; - } - } - - private void copybytes (byte[] dest, int destpos, String src, String enc) { - try { - byte[] x = src.getBytes(enc); - System.arraycopy (x, 0, dest, destpos, x.length); - } catch (UnsupportedEncodingException e) { - assert false; - } - } - - private String buildType1Msg () { - int dlen = ntdomain.length(); - type1[16]= (byte) (dlen % 256); - type1[17]= (byte) (dlen / 256); - type1[18] = type1[16]; - type1[19] = type1[17]; - - int hlen = hostname.length(); - type1[24]= (byte) (hlen % 256); - type1[25]= (byte) (hlen / 256); - type1[26] = type1[24]; - type1[27] = type1[25]; - - copybytes (type1, 32, hostname, "ISO8859_1"); - copybytes (type1, hlen+32, ntdomain, "ISO8859_1"); - type1[20] = (byte) ((hlen+32) % 256); - type1[21] = (byte) ((hlen+32) / 256); - - byte[] msg = new byte [32 + hlen + dlen]; - System.arraycopy (type1, 0, msg, 0, 32 + hlen + dlen); - String result = "NTLM " + (new B64Encoder()).encode (msg); - return result; - } - - - /* Convert a 7 byte array to an 8 byte array (for a des key with parity) - * input starts at offset off - */ - private byte[] makeDesKey (byte[] input, int off) { - int[] in = new int [input.length]; - for (int i=0; i> 1)); - out[2] = (byte)(((in[off+1] << 6) & 0xFF) | (in[off+2] >> 2)); - out[3] = (byte)(((in[off+2] << 5) & 0xFF) | (in[off+3] >> 3)); - out[4] = (byte)(((in[off+3] << 4) & 0xFF) | (in[off+4] >> 4)); - out[5] = (byte)(((in[off+4] << 3) & 0xFF) | (in[off+5] >> 5)); - out[6] = (byte)(((in[off+5] << 2) & 0xFF) | (in[off+6] >> 6)); - out[7] = (byte)((in[off+6] << 1) & 0xFF); - return out; - } - - private byte[] calcLMHash () throws GeneralSecurityException { - byte[] magic = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25}; - byte[] pwb = password.toUpperCase ().getBytes(); - byte[] pwb1 = new byte [14]; - int len = password.length(); - if (len > 14) - len = 14; - System.arraycopy (pwb, 0, pwb1, 0, len); /* Zero padded */ - - DESKeySpec dks1 = new DESKeySpec (makeDesKey (pwb1, 0)); - DESKeySpec dks2 = new DESKeySpec (makeDesKey (pwb1, 7)); - - SecretKey key1 = fac.generateSecret (dks1); - SecretKey key2 = fac.generateSecret (dks2); - cipher.init (Cipher.ENCRYPT_MODE, key1); - byte[] out1 = cipher.doFinal (magic, 0, 8); - cipher.init (Cipher.ENCRYPT_MODE, key2); - byte[] out2 = cipher.doFinal (magic, 0, 8); - - byte[] result = new byte [21]; - System.arraycopy (out1, 0, result, 0, 8); - System.arraycopy (out2, 0, result, 8, 8); - return result; - } - - private byte[] calcNTHash () throws GeneralSecurityException { - byte[] pw = null; - try { - pw = password.getBytes ("UnicodeLittleUnmarked"); - } catch (UnsupportedEncodingException e) { - assert false; - } - byte[] out = md4.digest (pw); - byte[] result = new byte [21]; - System.arraycopy (out, 0, result, 0, 16); - return result; - } - - /* key is a 21 byte array. Split it into 3 7 byte chunks, - * Convert each to 8 byte DES keys, encrypt the text arg with - * each key and return the three results in a sequential [] - */ - private byte[] calcResponse (byte[] key, byte[] text) - throws GeneralSecurityException { - assert key.length == 21; - DESKeySpec dks1 = new DESKeySpec (makeDesKey (key, 0)); - DESKeySpec dks2 = new DESKeySpec (makeDesKey (key, 7)); - DESKeySpec dks3 = new DESKeySpec (makeDesKey (key, 14)); - SecretKey key1 = fac.generateSecret (dks1); - SecretKey key2 = fac.generateSecret (dks2); - SecretKey key3 = fac.generateSecret (dks3); - cipher.init (Cipher.ENCRYPT_MODE, key1); - byte[] out1 = cipher.doFinal (text, 0, 8); - cipher.init (Cipher.ENCRYPT_MODE, key2); - byte[] out2 = cipher.doFinal (text, 0, 8); - cipher.init (Cipher.ENCRYPT_MODE, key3); - byte[] out3 = cipher.doFinal (text, 0, 8); - byte[] result = new byte [24]; - System.arraycopy (out1, 0, result, 0, 8); - System.arraycopy (out2, 0, result, 8, 8); - System.arraycopy (out3, 0, result, 16, 8); - return result; - } - - private String buildType3Msg (String challenge) throws GeneralSecurityException, - IOException { - /* First decode the type2 message to get the server nonce */ - /* nonce is located at type2[24] for 8 bytes */ - - byte[] type2 = (new sun.misc.BASE64Decoder()).decodeBuffer (challenge); - byte[] nonce = new byte [8]; - System.arraycopy (type2, 24, nonce, 0, 8); - - int ulen = username.length()*2; - type3[36] = type3[38] = (byte) (ulen % 256); - type3[37] = type3[39] = (byte) (ulen / 256); - int dlen = ntdomain.length()*2; - type3[28] = type3[30] = (byte) (dlen % 256); - type3[29] = type3[31] = (byte) (dlen / 256); - int hlen = hostname.length()*2; - type3[44] = type3[46] = (byte) (hlen % 256); - type3[45] = type3[47] = (byte) (hlen / 256); - - int l = 64; - copybytes (type3, l, ntdomain, "UnicodeLittleUnmarked"); - type3[32] = (byte) (l % 256); - type3[33] = (byte) (l / 256); - l += dlen; - copybytes (type3, l, username, "UnicodeLittleUnmarked"); - type3[40] = (byte) (l % 256); - type3[41] = (byte) (l / 256); - l += ulen; - copybytes (type3, l, hostname, "UnicodeLittleUnmarked"); - type3[48] = (byte) (l % 256); - type3[49] = (byte) (l / 256); - l += hlen; - - byte[] lmhash = calcLMHash(); - byte[] lmresponse = calcResponse (lmhash, nonce); - byte[] nthash = calcNTHash(); - byte[] ntresponse = calcResponse (nthash, nonce); - System.arraycopy (lmresponse, 0, type3, l, 24); - type3[16] = (byte) (l % 256); - type3[17] = (byte) (l / 256); - l += 24; - System.arraycopy (ntresponse, 0, type3, l, 24); - type3[24] = (byte) (l % 256); - type3[25] = (byte) (l / 256); - l += 24; - type3[56] = (byte) (l % 256); - type3[57] = (byte) (l / 256); - - byte[] msg = new byte [l]; - System.arraycopy (type3, 0, msg, 0, l); - String result = "NTLM " + (new B64Encoder()).encode (msg); - return result; - } - -} - - -class B64Encoder extends sun.misc.BASE64Encoder { - /* to force it to to the entire encoding in one line */ - protected int bytesPerLine () { - return 1024; - } -} diff --git a/src/solaris/native/sun/awt/awt_MToolkit.c b/src/solaris/native/sun/awt/awt_MToolkit.c index 744646cf38ff5c3a77e4fbd00f5c442b4e8f4596..3a7c117b23bd1ff9acd6b789221f357b5a4a25c6 100644 --- a/src/solaris/native/sun/awt/awt_MToolkit.c +++ b/src/solaris/native/sun/awt/awt_MToolkit.c @@ -2773,11 +2773,6 @@ Java_sun_awt_motif_MToolkit_init(JNIEnv *env, jobject this, } } - /* - scrollBugWorkAround = - (strcmp(XServerVendor(awt_display), "Sun Microsystems, Inc.") == 0 - && XVendorRelease(awt_display) == 3400); - */ scrollBugWorkAround = TRUE; /* diff --git a/src/solaris/native/sun/awt/fontpath.c b/src/solaris/native/sun/awt/fontpath.c index e7236e4a6ff3cce8e197827f82db38f09685b40e..22157d35a4e3f6bc19749f6ee581c5f59ef36771 100644 --- a/src/solaris/native/sun/awt/fontpath.c +++ b/src/solaris/native/sun/awt/fontpath.c @@ -557,7 +557,8 @@ JNIEXPORT jstring JNICALL Java_sun_awt_X11FontManager_getFontPath #ifndef HEADLESS static int isSunXServer() { #ifdef __solaris__ - return (strcmp("Sun Microsystems, Inc.", ServerVendor(awt_display)) == 0 && + return ((strncmp(ServerVendor(awt_display), "Sun Microsystems, Inc.", 22) == 0) || + (strncmp(ServerVendor(awt_display), "Oracle Corporation", 18) == 0) && VendorRelease(awt_display) >= 6410); #else return 0; diff --git a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c index 0c26096e58009cb3852cee3ed4b94865cfa40f6c..890284e570e423f7123035c75cd775f449e723ce 100644 --- a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c +++ b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c @@ -4,13 +4,29 @@ #include #include "gtk2_interface.h" #include "sun_awt_X11_GtkFileDialogPeer.h" +#include "debug_assert.h" static JavaVM *jvm; -static GtkWidget *dialog = NULL; /* To cache some method IDs */ static jmethodID filenameFilterCallbackMethodID = NULL; static jmethodID setFileInternalMethodID = NULL; +static jfieldID widgetFieldID = NULL; + +JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs +(JNIEnv *env, jclass cx) +{ + filenameFilterCallbackMethodID = (*env)->GetMethodID(env, cx, + "filenameFilterCallback", "(Ljava/lang/String;)Z"); + DASSERT(filenameFilterCallbackMethodID != NULL); + + setFileInternalMethodID = (*env)->GetMethodID(env, cx, + "setFileInternal", "(Ljava/lang/String;[Ljava/lang/String;)V"); + DASSERT(setFileInternalMethodID != NULL); + + widgetFieldID = (*env)->GetFieldID(env, cx, "widget", "J"); + DASSERT(widgetFieldID != NULL); +} static gboolean filenameFilterCallback(const GtkFileFilterInfo * filter_info, gpointer obj) { @@ -20,30 +36,17 @@ static gboolean filenameFilterCallback(const GtkFileFilterInfo * filter_info, gp env = (JNIEnv *) JNU_GetEnv(jvm, JNI_VERSION_1_2); - if (filenameFilterCallbackMethodID == NULL) { - cx = (*env)->GetObjectClass(env, (jobject) obj); - if (cx == NULL) { - JNU_ThrowInternalError(env, "Could not get file filter class"); - return 0; - } - - filenameFilterCallbackMethodID = (*env)->GetMethodID(env, cx, - "filenameFilterCallback", "(Ljava/lang/String;)Z"); - if (filenameFilterCallbackMethodID == NULL) { - JNU_ThrowInternalError(env, - "Could not get filenameFilterCallback method id"); - return 0; - } - } - filename = (*env)->NewStringUTF(env, filter_info->filename); return (*env)->CallBooleanMethod(env, obj, filenameFilterCallbackMethodID, filename); } -static void quit(gboolean isSignalHandler) +static void quit(JNIEnv * env, jobject jpeer, gboolean isSignalHandler) { + GtkWidget * dialog = (GtkWidget*)jlong_to_ptr( + (*env)->GetLongField(env, jpeer, widgetFieldID)); + if (dialog != NULL) { // Callbacks from GTK signals are made within the GTK lock @@ -57,7 +60,8 @@ static void quit(gboolean isSignalHandler) fp_gtk_widget_destroy (dialog); fp_gtk_main_quit (); - dialog = NULL; + + (*env)->SetLongField(env, jpeer, widgetFieldID, 0); if (!isSignalHandler) { fp_gdk_threads_leave(); @@ -73,7 +77,7 @@ static void quit(gboolean isSignalHandler) JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_quit (JNIEnv * env, jobject jpeer) { - quit(FALSE); + quit(env, jpeer, FALSE); } /** @@ -132,24 +136,8 @@ static void handle_response(GtkWidget* aDialog, gint responseId, gpointer obj) if (responseId == GTK_RESPONSE_ACCEPT) { current_folder = fp_gtk_file_chooser_get_current_folder( - GTK_FILE_CHOOSER(dialog)); - filenames = fp_gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog)); - } - - if (setFileInternalMethodID == NULL) { - cx = (*env)->GetObjectClass(env, (jobject) obj); - if (cx == NULL) { - JNU_ThrowInternalError(env, "Could not get GTK peer class"); - return; - } - - setFileInternalMethodID = (*env)->GetMethodID(env, cx, - "setFileInternal", "(Ljava/lang/String;[Ljava/lang/String;)V"); - if (setFileInternalMethodID == NULL) { - JNU_ThrowInternalError(env, - "Could not get setFileInternalMethodID method id"); - return; - } + GTK_FILE_CHOOSER(aDialog)); + filenames = fp_gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(aDialog)); } jcurrent_folder = (*env)->NewStringUTF(env, current_folder); @@ -159,7 +147,7 @@ static void handle_response(GtkWidget* aDialog, gint responseId, gpointer obj) jfilenames); fp_g_free(current_folder); - quit(TRUE); + quit(env, (jobject)obj, TRUE); } /* @@ -172,6 +160,7 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer, jstring jtitle, jint mode, jstring jdir, jstring jfile, jobject jfilter, jboolean multiple) { + GtkWidget *dialog = NULL; GtkFileFilter *filter; if (jvm == NULL) { @@ -233,8 +222,12 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer, fp_g_signal_connect(G_OBJECT(dialog), "response", G_CALLBACK( handle_response), jpeer); + + (*env)->SetLongField(env, jpeer, widgetFieldID, ptr_to_jlong(dialog)); + fp_gtk_widget_show(dialog); fp_gtk_main(); fp_gdk_threads_leave(); } + diff --git a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h index 91334b4ebeec3bfbe9ec58d0c8940f49297932e2..7c3c2338d10d4a85ed286520141b32db94d0962f 100644 --- a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h +++ b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h @@ -9,6 +9,14 @@ extern "C" { #endif +/* + * Class: sun_awt_X11_GtkFileDialogPeer + * Method: initIDs + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs +(JNIEnv *, jclass); + /* * Class: sun_awt_X11_GtkFileDialogPeer * Method: run diff --git a/src/solaris/native/sun/xawt/XWindow.c b/src/solaris/native/sun/xawt/XWindow.c index 4a66d4d7e6bf6c903a82271e8ac386ab9c64c9e0..d33c87f424c9393535c75fd8a758b711c6c27767 100644 --- a/src/solaris/native/sun/xawt/XWindow.c +++ b/src/solaris/native/sun/xawt/XWindow.c @@ -766,7 +766,9 @@ adjustKeySym(XEvent *event, KeySym *keysym) static Boolean isXsunServer(XEvent *event) { if( awt_ServerDetected ) return awt_IsXsun; - if( strncmp( ServerVendor( event->xkey.display ), "Sun Microsystems, Inc.", 32) ) { + if( (strncmp( ServerVendor( event->xkey.display ), "Sun Microsystems, Inc.", 22) != 0) && + (strncmp( ServerVendor( event->xkey.display ), "Oracle Corporation", 18) != 0) ) + { awt_ServerDetected = True; awt_IsXsun = False; return False; diff --git a/src/windows/classes/sun/security/krb5/internal/tools/Kinit.java b/src/windows/classes/sun/security/krb5/internal/tools/Kinit.java index 7a3ba93c60b766361e045b6b222af4ca6bcdb4ba..f6c53f81f1ebe2fb538604a116ec556fb98fe4d6 100644 --- a/src/windows/classes/sun/security/krb5/internal/tools/Kinit.java +++ b/src/windows/classes/sun/security/krb5/internal/tools/Kinit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -33,11 +33,7 @@ package sun.security.krb5.internal.tools; import sun.security.krb5.*; import sun.security.krb5.internal.*; import sun.security.krb5.internal.ccache.*; -import java.io.BufferedReader; -import java.io.InputStreamReader; import java.io.IOException; -import java.util.StringTokenizer; -import java.io.File; import java.util.Arrays; import sun.security.util.Password; @@ -152,6 +148,7 @@ public class Kinit { if (principal != null) { princName = principal.toString(); } + KrbAsReqBuilder builder; if (DEBUG) { System.out.println("Principal is " + principal); } @@ -172,6 +169,7 @@ public class Kinit { new String(psswd)); } } + builder = new KrbAsReqBuilder(principal, psswd); } else { if (DEBUG) { System.out.println(">>> Kinit using keytab"); @@ -198,11 +196,13 @@ public class Kinit { } throw new KrbException(msg); } + builder = new KrbAsReqBuilder(principal, skeys); } KDCOptions opt = new KDCOptions(); setOptions(KDCOptions.FORWARDABLE, options.forwardable, opt); setOptions(KDCOptions.PROXIABLE, options.proxiable, opt); + builder.setOptions(opt); String realm = options.getKDCRealm(); if (realm == null) { realm = Config.getInstance().getDefaultRealm(); @@ -215,62 +215,21 @@ public class Kinit { PrincipalName sname = new PrincipalName("krbtgt" + "/" + realm, PrincipalName.KRB_NT_SRV_INST); sname.setRealm(realm); + builder.setTarget(sname); if (DEBUG) { System.out.println(">>> Creating KrbAsReq"); } - KrbAsReq as_req = null; - HostAddresses addresses = null; - try { - if (options.getAddressOption()) - addresses = HostAddresses.getLocalAddresses(); + if (options.getAddressOption()) + builder.setAddresses(HostAddresses.getLocalAddresses()); - if (useKeytab) { - as_req = new KrbAsReq(skeys, opt, - principal, sname, - null, null, null, null, addresses, null); - } else { - as_req = new KrbAsReq(psswd, opt, - principal, sname, - null, null, null, null, addresses, null); - } - } catch (KrbException exc) { - throw exc; - } catch (Exception exc) { - throw new KrbException(exc.toString()); - } - - KrbAsRep as_rep = null; - try { - as_rep = sendASRequest(as_req, useKeytab, realm, psswd, skeys); - } catch (KrbException ke) { - if ((ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) || - (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED)) { - if (DEBUG) { - System.out.println("Kinit: PREAUTH FAILED/REQ, re-send AS-REQ"); - } - KRBError error = ke.getError(); - int etype = error.getEType(); - String salt = error.getSalt(); - byte[] s2kparams = error.getParams(); - if (useKeytab) { - as_req = new KrbAsReq(skeys, true, etype, salt, - s2kparams, opt, principal, sname, - null, null, null, null, addresses, null); - } else { - as_req = new KrbAsReq(psswd, true, etype, salt, - s2kparams, opt, principal, sname, - null, null, null, null, addresses, null); - } - as_rep = sendASRequest(as_req, useKeytab, realm, psswd, skeys); - } else { - throw ke; - } - } + builder.action(); sun.security.krb5.internal.ccache.Credentials credentials = - as_rep.setCredentials(); + builder.getCCreds(); + builder.destroy(); + // we always create a new cache and store the ticket we get CredentialsCache cache = CredentialsCache.create(principal, options.cachename); @@ -296,41 +255,6 @@ public class Kinit { options = null; // release reference to options } - private static KrbAsRep sendASRequest(KrbAsReq as_req, boolean useKeytab, - String realm, char[] passwd, EncryptionKey[] skeys) - throws IOException, RealmException, KrbException { - - if (DEBUG) { - System.out.println(">>> Kinit: sending as_req to realm " + realm); - } - - String kdc = as_req.send(realm); - - if (DEBUG) { - System.out.println(">>> reading response from kdc"); - } - KrbAsRep as_rep = null; - try { - if (useKeytab) { - as_rep = as_req.getReply(skeys); - } else { - as_rep = as_req.getReply(passwd); - } - } catch (KrbException ke) { - if (ke.returnCode() == Krb5.KRB_ERR_RESPONSE_TOO_BIG) { - as_req.send(realm, kdc, true); // useTCP is set - if (useKeytab) { - as_rep = as_req.getReply(skeys); - } else { - as_rep = as_req.getReply(passwd); - } - } else { - throw ke; - } - } - return as_rep; - } - private static void setOptions(int flag, int option, KDCOptions opt) { switch (option) { case 0: diff --git a/src/windows/native/sun/windows/awt_Component.cpp b/src/windows/native/sun/windows/awt_Component.cpp index 71307cb9e58b81de1eb24defea433100f8637fb7..fd75b8d52ee75fd5587764ee36e96cccf9e71676 100644 --- a/src/windows/native/sun/windows/awt_Component.cpp +++ b/src/windows/native/sun/windows/awt_Component.cpp @@ -6084,63 +6084,67 @@ void AwtComponent::SetParent(void * param) { void AwtComponent::_SetRectangularShape(void *param) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); + if (!AwtToolkit::IsMainThread()) { + AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_SetRectangularShape, param); + } else { + JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - SetRectangularShapeStruct *data = (SetRectangularShapeStruct *)param; - jobject self = data->component; - jint x1 = data->x1; - jint x2 = data->x2; - jint y1 = data->y1; - jint y2 = data->y2; - jobject region = data->region; + SetRectangularShapeStruct *data = (SetRectangularShapeStruct *)param; + jobject self = data->component; + jint x1 = data->x1; + jint x2 = data->x2; + jint y1 = data->y1; + jint y2 = data->y2; + jobject region = data->region; - AwtComponent *c = NULL; + AwtComponent *c = NULL; - PDATA pData; - JNI_CHECK_PEER_GOTO(self, ret); + PDATA pData; + JNI_CHECK_PEER_GOTO(self, ret); - c = (AwtComponent *)pData; - if (::IsWindow(c->GetHWnd())) { - HRGN hRgn = NULL; - if (region || x1 || x2 || y1 || y2) { - // If all the params are zeros, the shape must be simply reset. - // Otherwise, convert it into a region. - RGNDATA *pRgnData = NULL; - RGNDATAHEADER *pRgnHdr; - - /* reserving memory for the worst case */ - size_t worstBufferSize = size_t(((x2 - x1) / 2 + 1) * (y2 - y1)); - pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) + - sizeof(RECT_T) * worstBufferSize); - pRgnHdr = (RGNDATAHEADER *) pRgnData; - - pRgnHdr->dwSize = sizeof(RGNDATAHEADER); - pRgnHdr->iType = RDH_RECTANGLES; - pRgnHdr->nRgnSize = 0; - pRgnHdr->rcBound.top = 0; - pRgnHdr->rcBound.left = 0; - pRgnHdr->rcBound.bottom = LONG(y2 - y1); - pRgnHdr->rcBound.right = LONG(x2 - x1); - - RECT_T * pRect = (RECT_T *) (((BYTE *) pRgnData) + sizeof(RGNDATAHEADER)); - pRgnHdr->nCount = RegionToYXBandedRectangles(env, x1, y1, x2, y2, region, &pRect, worstBufferSize); - - hRgn = ::ExtCreateRegion(NULL, - sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData); - - free(pRgnData); - } + c = (AwtComponent *)pData; + if (::IsWindow(c->GetHWnd())) { + HRGN hRgn = NULL; + if (region || x1 || x2 || y1 || y2) { + // If all the params are zeros, the shape must be simply reset. + // Otherwise, convert it into a region. + RGNDATA *pRgnData = NULL; + RGNDATAHEADER *pRgnHdr; + + /* reserving memory for the worst case */ + size_t worstBufferSize = size_t(((x2 - x1) / 2 + 1) * (y2 - y1)); + pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) + + sizeof(RECT_T) * worstBufferSize); + pRgnHdr = (RGNDATAHEADER *) pRgnData; + + pRgnHdr->dwSize = sizeof(RGNDATAHEADER); + pRgnHdr->iType = RDH_RECTANGLES; + pRgnHdr->nRgnSize = 0; + pRgnHdr->rcBound.top = 0; + pRgnHdr->rcBound.left = 0; + pRgnHdr->rcBound.bottom = LONG(y2 - y1); + pRgnHdr->rcBound.right = LONG(x2 - x1); + + RECT_T * pRect = (RECT_T *) (((BYTE *) pRgnData) + sizeof(RGNDATAHEADER)); + pRgnHdr->nCount = RegionToYXBandedRectangles(env, x1, y1, x2, y2, region, &pRect, worstBufferSize); + + hRgn = ::ExtCreateRegion(NULL, + sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData); + + free(pRgnData); + } - ::SetWindowRgn(c->GetHWnd(), hRgn, TRUE); - } + ::SetWindowRgn(c->GetHWnd(), hRgn, TRUE); + } ret: - env->DeleteGlobalRef(self); - if (region) { - env->DeleteGlobalRef(region); - } + env->DeleteGlobalRef(self); + if (region) { + env->DeleteGlobalRef(region); + } - delete data; + delete data; + } } void AwtComponent::_SetZOrder(void *param) { diff --git a/src/windows/native/sun/windows/awt_Robot.cpp b/src/windows/native/sun/windows/awt_Robot.cpp index bef6f13ede5e79ffb85d3d66d5e96a437be61a67..bab9f61b8b780c7b2460eec9890dc0dbfd76e862 100644 --- a/src/windows/native/sun/windows/awt_Robot.cpp +++ b/src/windows/native/sun/windows/awt_Robot.cpp @@ -194,9 +194,9 @@ inline jint AwtRobot::WinToJavaPixel(USHORT r, USHORT g, USHORT b) jint AwtRobot::GetRGBPixel( jint x, jint y) { - HDC hdc = GetDC(NULL); + HDC hdc = ::CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL); COLORREF ref = ::GetPixel( hdc, x, y ); - ReleaseDC(NULL,hdc); + ::DeleteDC(hdc); jint value = WinToJavaPixel(GetRValue(ref), GetGValue(ref), GetBValue(ref)); return value; } diff --git a/test/demo/zipfs/ZipFSTester.java b/test/demo/zipfs/ZipFSTester.java index 54b9274db132fd0efbda2090781d6f41d9a77cf1..76a8d7aeed3f5e6e62f759c02fa26391cc9049b3 100644 --- a/test/demo/zipfs/ZipFSTester.java +++ b/test/demo/zipfs/ZipFSTester.java @@ -64,7 +64,6 @@ public class ZipFSTester { fs0.close(); // sync to file fs = newZipFileSystem(tmpfsPath, new HashMap()); - try { // prepare a src Path src = getTempPath(); @@ -146,13 +145,6 @@ public class ZipFSTester { Path fs2Path = getTempPath(); Path fs3Path = getTempPath(); - if (fs1Path.exists()) - fs1Path.delete(); - if (fs2Path.exists()) - fs2Path.delete(); - if (fs3Path.exists()) - fs3Path.delete(); - // create a new filesystem, copy everything from fs Map env = new HashMap(); env.put("createNew", true); @@ -280,7 +272,6 @@ public class ZipFSTester { walk(fs4.getPath("/")); System.out.println("closing: fs4"); fs4.close(); - System.out.printf("failed=%d%n", failed); fs1Path.delete(); @@ -426,6 +417,8 @@ public class ZipFSTester { } private static void mkdirs(Path path) throws IOException { + if (path.exists()) + return; path = path.toAbsolutePath(); Path parent = path.getParent(); if (parent != null) { diff --git a/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java b/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java new file mode 100644 index 0000000000000000000000000000000000000000..751b38e338bb5241e73ad249a8d1c539fd2f3c09 --- /dev/null +++ b/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java @@ -0,0 +1,177 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + @test + @bug 6988428 + @summary Tests whether shape is always set + @author anthony.petrov@oracle.com: area=awt.toplevel + @run main ShapeNotSetSometimes +*/ + + +import java.awt.*; +import java.awt.event.InputEvent; +import java.awt.geom.*; + + +public class ShapeNotSetSometimes { + + private Frame backgroundFrame; + private Frame window; + private static final Color BACKGROUND_COLOR = Color.BLUE; + private Shape shape; + private int[][] pointsToCheck; + + private static Robot robot; + + public ShapeNotSetSometimes() throws Exception { + EventQueue.invokeAndWait(new Runnable() { + public void run() { + initializeGUI(); + } + }); + } + + private void initializeGUI() { + backgroundFrame = new BackgroundFrame(); + backgroundFrame.setUndecorated(true); + backgroundFrame.setSize(300, 300); + backgroundFrame.setLocation(20, 400); + backgroundFrame.setVisible(true); + + shape = null; + String shape_name = null; + Area a; + GeneralPath gp; + shape_name = "Rounded-corners"; + a = new Area(); + a.add(new Area(new Rectangle2D.Float(50, 0, 100, 150))); + a.add(new Area(new Rectangle2D.Float(0, 50, 200, 50))); + a.add(new Area(new Ellipse2D.Float(0, 0, 100, 100))); + a.add(new Area(new Ellipse2D.Float(0, 50, 100, 100))); + a.add(new Area(new Ellipse2D.Float(100, 0, 100, 100))); + a.add(new Area(new Ellipse2D.Float(100, 50, 100, 100))); + shape = a; + pointsToCheck = new int[][] { + // inside shape + {106, 86}, {96, 38}, {76, 107}, {180, 25}, {24, 105}, + {196, 77}, {165, 50}, {14, 113}, {89, 132}, {167, 117}, + // outside shape + {165, 196}, {191, 163}, {146, 185}, {61, 170}, {148, 171}, + {82, 172}, {186, 11}, {199, 141}, {13, 173}, {187, 3} + }; + + window = new TestFrame(); + window.setUndecorated(true); + window.setSize(200, 200); + window.setLocation(70, 450); + window.setShape(shape); + window.setVisible(true); + + System.out.println("Checking " + window.getClass().getSuperclass().getName() + " with " + shape_name + " shape (" + window.getShape() + ")..."); + } + + class BackgroundFrame extends Frame { + + @Override + public void paint(Graphics g) { + + g.setColor(BACKGROUND_COLOR); + g.fillRect(0, 0, 300, 300); + + super.paint(g); + } + } + + class TestFrame extends Frame { + + @Override + public void paint(Graphics g) { + + g.setColor(Color.WHITE); + g.fillRect(0, 0, 200, 200); + + super.paint(g); + } + } + + public static void main(String[] args) throws Exception { + robot = new Robot(); + + for(int i = 0; i < 100; i++) { + System.out.println("Attempt " + i); + new ShapeNotSetSometimes().doTest(); + } + } + + private void doTest() throws Exception { + Point wls = backgroundFrame.getLocationOnScreen(); + + robot.mouseMove(wls.x + 5, wls.y + 5); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.delay(10); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.delay(500); + + EventQueue.invokeAndWait(new Runnable() { + public void run() { + window.requestFocus(); + } + }); + + robot.waitForIdle(); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + // ignore this one + } + + // check transparency + final int COUNT_TARGET = 10; + + // checking outside points only + for(int i = COUNT_TARGET; i < COUNT_TARGET * 2; i++) { + int x = pointsToCheck[i][0]; + int y = pointsToCheck[i][1]; + boolean inside = i < COUNT_TARGET; + Color c = robot.getPixelColor(window.getX() + x, window.getY() + y); + System.out.println("checking " + x + ", " + y + ", color = " + c); + if (inside && BACKGROUND_COLOR.equals(c) || !inside && !BACKGROUND_COLOR.equals(c)) { + System.out.println("window.getX() = " + window.getX() + ", window.getY() = " + window.getY()); + System.err.println("Checking for transparency failed: point: " + + (window.getX() + x) + ", " + (window.getY() + y) + + ", color = " + c + (inside ? " is of un" : " is not of ") + + "expected background color " + BACKGROUND_COLOR); + throw new RuntimeException("Test failed. The shape has not been applied."); + } + } + + EventQueue.invokeAndWait(new Runnable() { + public void run() { + backgroundFrame.dispose(); + window.dispose(); + } + }); + } +} diff --git a/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java b/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java new file mode 100644 index 0000000000000000000000000000000000000000..34a7b7690570f6082ba3d5615c7f393de869e7b8 --- /dev/null +++ b/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java @@ -0,0 +1,48 @@ +/* + * 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. + */ + +/* + @test + @bug 6960516 + @summary check if the ungrab event has the ID < AWTEvent.RESERVED_ID_MAX + @author Andrei Dmitriev : area=awt.event + @run main UngrabID +*/ + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; + +public class UngrabID { + public static void main(String[] args){ + Frame f = new Frame("Dummy"); + sun.awt.UngrabEvent event = new sun.awt.UngrabEvent(f); + if (event.getID() > AWTEvent.RESERVED_ID_MAX) { + System.out.println( " Event ID : "+event.getID() + " " + event.toString()); + throw new RuntimeException(" Ungrab Event ID should be less than AWTEvent.RESERVED_ID_MAX ("+AWTEvent.RESERVED_ID_MAX+"). Actual value : "+event.getID() + " Event:" + event.toString()); + } + System.out.println("Test passed. "); + } +} diff --git a/test/java/io/ByteArrayInputStream/Skip.java b/test/java/io/ByteArrayInputStream/Skip.java new file mode 100644 index 0000000000000000000000000000000000000000..9364bd7eaacf1d74a0c51d40f219042e71191fbc --- /dev/null +++ b/test/java/io/ByteArrayInputStream/Skip.java @@ -0,0 +1,79 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* @test + * @bug 6720170 + * @summary check for ByteArrayInputStream.skip + */ + +import java.io.*; + +public class Skip { + private static void dotest(InputStream in, int curpos, long total, + long toskip, long expected) + throws Exception + { + System.err.println("\nCurrently at pos = " + curpos + + "\nTotal bytes in the stream = " + total + + "\nNumber of bytes to skip = " + toskip + + "\nNumber of bytes that should be skipped = " + + expected); + + // position to curpos; EOF if negative + in.reset(); + int avail = curpos >= 0 ? curpos : in.available(); + long n = in.skip(avail); + if (n != avail) { + throw new RuntimeException("Unexpected number of bytes skipped = " + n); + } + + long skipped = in.skip(toskip); + System.err.println("actual number skipped: "+ skipped); + + if (skipped != expected) { + throw new RuntimeException("Unexpected number of bytes skipped = " + skipped); + } + } + + public static void main(String argv[]) throws Exception { + int total = 1024; + ByteArrayInputStream in = new ByteArrayInputStream(new byte[total]); + + /* test for skip */ + dotest(in, 0, total, 23, 23); + dotest(in, 10, total, 23, 23); + + /* test for negative skip */ + dotest(in, 0, total, -23, 0); + + /* check for skip after EOF */ + dotest(in, -1, total, 20, 0); + + /* check for skip beyond EOF starting from before EOF */ + dotest(in, 0, total, total+20, total); + + /* check for skip if the pos + toskip causes integer overflow */ + dotest(in, 10, total, Long.MAX_VALUE, total-10); + } +} diff --git a/test/java/lang/Throwable/StackTraceSerialization.java b/test/java/lang/Throwable/StackTraceSerialization.java index d73c5a7e4044184ec17cac4cc3db473235e272ca..2d2f4f42a232ebfc7fc330fd0530d09acc1cc44b 100644 --- a/test/java/lang/Throwable/StackTraceSerialization.java +++ b/test/java/lang/Throwable/StackTraceSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -26,13 +26,33 @@ import java.util.*; /* * @test - * @bug 4202914 4363318 + * @bug 4202914 4363318 6991528 * @summary Basic test of serialization of stack trace information * @author Josh Bloch */ public class StackTraceSerialization { public static void main(String args[]) throws Exception { + testWithSetStackTrace(); + testWithFillInStackTrace(); + } + + private static void testWithSetStackTrace() throws Exception { + Throwable t = new Throwable(); + + t.setStackTrace(new StackTraceElement[] + {new StackTraceElement("foo", "bar", "baz", -1)}); + + if (!equal(t, reconstitute(t))) + throw new Exception("Unequal Throwables with set stacktrace"); + } + + private static void assertEmptyStackTrace(Throwable t) { + if (t.getStackTrace().length != 0) + throw new AssertionError("Nonempty stacktrace."); + } + + private static void testWithFillInStackTrace() throws Exception { Throwable original = null; try { a(); @@ -40,27 +60,42 @@ public class StackTraceSerialization { original = e; } - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - ObjectOutputStream out = new ObjectOutputStream(bout); - out.writeObject(original); - out.flush(); - ByteArrayInputStream bin = - new ByteArrayInputStream(bout.toByteArray()); - ObjectInputStream in = new ObjectInputStream(bin); - Throwable clone = (Throwable) in.readObject(); - - if (!equal(original, clone)) - throw new Exception(); + if (!equal(original, reconstitute(original))) + throw new Exception("Unequal Throwables with filled-in stacktrace"); + } + + + /** + * Serialize the argument and return the deserialized result. + */ + private static Throwable reconstitute(Throwable t) throws Exception { + Throwable result = null; + + try(ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(bout)) { + out.writeObject(t); + out.flush(); + try(ByteArrayInputStream bin = + new ByteArrayInputStream(bout.toByteArray()); + ObjectInputStream in = new ObjectInputStream(bin)) { + result = (Throwable) in.readObject(); + } + } + + return result; } /** - * Returns true if e1 and e2 have equal stack traces and their causes - * are recursively equal (by the same definition). Returns false - * or throws NullPointerExeption otherwise. + * Returns true if e1 and e2 have equal stack traces and their + * causes are recursively equal (by the same definition) and their + * suppressed exception information is equals. Returns false or + * throws NullPointerExeption otherwise. */ private static boolean equal(Throwable t1, Throwable t2) { - return t1==t2 || (Arrays.equals(t1.getStackTrace(), t2.getStackTrace()) - && equal(t1.getCause(), t2.getCause())); + return t1==t2 || + (Arrays.equals(t1.getStackTrace(), t2.getStackTrace()) && + equal(t1.getCause(), t2.getCause()) && + Objects.equals(t1.getSuppressed(), t2.getSuppressed())); } static void a() throws HighLevelException { diff --git a/test/java/lang/Throwable/SuppressedExceptions.java b/test/java/lang/Throwable/SuppressedExceptions.java index 0993cd6333f99429df9a79e6e13f0629418ed4c9..f1c30b358adfc972beda6bacfb9481f3ec89b7dd 100644 --- a/test/java/lang/Throwable/SuppressedExceptions.java +++ b/test/java/lang/Throwable/SuppressedExceptions.java @@ -26,7 +26,7 @@ import java.util.*; /* * @test - * @bug 6911258 6962571 6963622 + * @bug 6911258 6962571 6963622 6991528 * @summary Basic tests of suppressed exceptions * @author Joseph D. Darcy */ @@ -39,12 +39,21 @@ public class SuppressedExceptions { basicSupressionTest(); serializationTest(); selfReference(); + noModification(); } private static void noSelfSuppression() { Throwable throwable = new Throwable(); try { - throwable.addSuppressedException(throwable); + throwable.addSuppressed(throwable); + throw new RuntimeException("IllegalArgumentException for self-suppresion not thrown."); + } catch (IllegalArgumentException iae) { + ; // Expected + } + + throwable.addSuppressed(null); // Immutable suppression list + try { + throwable.addSuppressed(throwable); throw new RuntimeException("IllegalArgumentException for self-suppresion not thrown."); } catch (IllegalArgumentException iae) { ; // Expected @@ -56,21 +65,21 @@ public class SuppressedExceptions { RuntimeException suppressed = new RuntimeException("A suppressed exception."); AssertionError repressed = new AssertionError("A repressed error."); - Throwable[] t0 = throwable.getSuppressedExceptions(); + Throwable[] t0 = throwable.getSuppressed(); if (t0.length != 0) { throw new RuntimeException(message); } throwable.printStackTrace(); - throwable.addSuppressedException(suppressed); - Throwable[] t1 = throwable.getSuppressedExceptions(); + throwable.addSuppressed(suppressed); + Throwable[] t1 = throwable.getSuppressed(); if (t1.length != 1 || t1[0] != suppressed) {throw new RuntimeException(message); } throwable.printStackTrace(); - throwable.addSuppressedException(repressed); - Throwable[] t2 = throwable.getSuppressedExceptions(); + throwable.addSuppressed(repressed); + Throwable[] t2 = throwable.getSuppressed(); if (t2.length != 2 || t2[0] != suppressed || t2[1] != repressed) { @@ -152,7 +161,7 @@ public class SuppressedExceptions { System.err.println("TESTING SERIALIZED EXCEPTION"); - Throwable[] t0 = throwable.getSuppressedExceptions(); + Throwable[] t0 = throwable.getSuppressed(); if (t0.length != 0) { // Will fail if t0 is null. throw new RuntimeException(message); } @@ -167,9 +176,25 @@ public class SuppressedExceptions { throwable1.printStackTrace(); - throwable1.addSuppressedException(throwable2); - throwable2.addSuppressedException(throwable1); + throwable1.addSuppressed(throwable2); + throwable2.addSuppressed(throwable1); throwable1.printStackTrace(); } + + private static void noModification() { + Throwable t = new Throwable(); + t.addSuppressed(null); + + Throwable[] t0 = t.getSuppressed(); + if (t0.length != 0) + throw new RuntimeException("Bad nonzero length of suppressed exceptions."); + + t.addSuppressed(new ArithmeticException()); + + // Make sure a suppressed exception did *not* get added. + t0 = t.getSuppressed(); + if (t0.length != 0) + throw new RuntimeException("Bad nonzero length of suppressed exceptions."); + } } diff --git a/test/java/lang/reflect/Generics/Probe.java b/test/java/lang/reflect/Generics/Probe.java index c65a0558b0ad4e15a5acbf11af66bce1c47d58ca..14d094a2e6cb5aaa9a696ca9ef88bb7f8f73211d 100644 --- a/test/java/lang/reflect/Generics/Probe.java +++ b/test/java/lang/reflect/Generics/Probe.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -47,9 +47,6 @@ import static java.util.Arrays.*; "java.util.WeakHashMap$EntryIterator", "java.util.WeakHashMap$KeyIterator", "java.util.WeakHashMap$ValueIterator", - "java.util.TreeMap$EntryIterator", - "java.util.TreeMap$KeyIterator", - "java.util.TreeMap$ValueIterator", "java.util.HashMap$EntryIterator", "java.util.HashMap$KeyIterator", "java.util.HashMap$ValueIterator", diff --git a/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java b/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java index a950cc6676a2097e1e554695b3ad8a675c3f69a3..1ffd02e37d5a1e901dd12735388c04d142f208b2 100644 --- a/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java +++ b/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java @@ -22,15 +22,19 @@ */ /* @test - * @bug 4607272 + * @bug 4607272 6999915 * @summary Unit test for AsynchronousSocketChannel - * @run main/othervm -XX:+DisableExplicitGC -mx64m Leaky + * @run main/othervm -XX:+DisableExplicitGC -XX:MaxDirectMemorySize=64m Leaky */ import java.nio.ByteBuffer; +import java.nio.BufferPoolMXBean; import java.nio.channels.*; import java.net.*; +import java.util.List; import java.util.concurrent.Future; +import java.util.concurrent.ThreadFactory; +import java.lang.management.ManagementFactory; /** * Heap buffers must be substituted with direct buffers when doing I/O. This @@ -49,13 +53,13 @@ public class Leaky { private final ByteBuffer dst; private Future readResult; - Connection() throws Exception { + Connection(AsynchronousChannelGroup group) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); int port = ((InetSocketAddress)(ssc.getLocalAddress())).getPort(); SocketAddress remote = new InetSocketAddress(lh, port); - client = AsynchronousSocketChannel.open(); + client = AsynchronousSocketChannel.open(group); client.connect(remote).get(); peer = ssc.accept(); ssc.close(); @@ -77,11 +81,21 @@ public class Leaky { } public static void main(String[] args) throws Exception { + ThreadFactory threadFactory = new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }; + AsynchronousChannelGroup group = + AsynchronousChannelGroup.withFixedThreadPool(4, threadFactory); final int CONNECTION_COUNT = 10; Connection[] connections = new Connection[CONNECTION_COUNT]; for (int i=0; i pools = + ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class); + for (BufferPoolMXBean pool: pools) + System.out.format(" %8s ", pool.getName()); + System.out.println(); + for (int i=0; i anchors = Collections.singleton(anchor); params = new PKIXParameters(anchors); params.setRevocationEnabled(false); + // The certificates expired on 10/22/10, so set the validity date to + // 05/01/2009 to avoid expiration failures + params.setDate(new Date(1243828800000l)); } /* diff --git a/test/java/util/NavigableMap/LockStep.java b/test/java/util/NavigableMap/LockStep.java index fbe58dedc705979e35824763725c02566716f304..64f9bdf7683bdd19d46e13aa3ad9ef9f2f7bad90 100644 --- a/test/java/util/NavigableMap/LockStep.java +++ b/test/java/util/NavigableMap/LockStep.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,6 +25,9 @@ * @test * @bug 6420753 6242436 6691185 * @summary Compare NavigableMap implementations for identical behavior + * @run main LockStep + * @run main/othervm -XX:+AggressiveOpts LockStep + * @run main/othervm -XX:+AggressiveOpts -Dthorough=true LockStep * @author Martin Buchholz */ diff --git a/test/java/util/concurrent/ConcurrentQueues/IteratorWeakConsistency.java b/test/java/util/concurrent/ConcurrentQueues/IteratorWeakConsistency.java index 36411ad369336f8e6c5c43ceac0b85b103f93dea..78ce8d71194dd9aad1690a36a4141800364d1aea 100644 --- a/test/java/util/concurrent/ConcurrentQueues/IteratorWeakConsistency.java +++ b/test/java/util/concurrent/ConcurrentQueues/IteratorWeakConsistency.java @@ -56,23 +56,44 @@ public class IteratorWeakConsistency { // test(new ArrayBlockingQueue(20)); } - void test(Queue q) throws Throwable { + void test(Queue q) { // TODO: make this more general - for (int i = 0; i < 10; i++) - q.add(i); - Iterator it = q.iterator(); - q.poll(); - q.poll(); - q.poll(); - q.remove(7); - List list = new ArrayList(); - while (it.hasNext()) - list.add(it.next()); - equal(list, Arrays.asList(0, 3, 4, 5, 6, 8, 9)); - check(! list.contains(null)); - System.out.printf("%s: %s%n", - q.getClass().getSimpleName(), - list); + try { + for (int i = 0; i < 10; i++) + q.add(i); + Iterator it = q.iterator(); + q.poll(); + q.poll(); + q.poll(); + q.remove(7); + List list = new ArrayList(); + while (it.hasNext()) + list.add(it.next()); + equal(list, Arrays.asList(0, 3, 4, 5, 6, 8, 9)); + check(! list.contains(null)); + System.out.printf("%s: %s%n", + q.getClass().getSimpleName(), + list); + } catch (Throwable t) { unexpected(t); } + + try { + q.clear(); + q.add(1); + q.add(2); + q.add(3); + q.add(4); + Iterator it = q.iterator(); + it.next(); + q.remove(2); + q.remove(1); + q.remove(3); + boolean found4 = false; + while (it.hasNext()) { + found4 |= it.next().equals(4); + } + check(found4); + } catch (Throwable t) { unexpected(t); } + } //--------------------- Infrastructure --------------------------- @@ -85,7 +106,6 @@ public class IteratorWeakConsistency { void equal(Object x, Object y) { if (x == null ? y == null : x.equals(y)) pass(); else fail(x + " not equal to " + y);} - static Class thisClass = new Object(){}.getClass().getEnclosingClass(); public static void main(String[] args) throws Throwable { new IteratorWeakConsistency().instanceMain(args);} public void instanceMain(String[] args) throws Throwable { diff --git a/test/java/util/jar/JarInputStream/BadSignedJar.jar b/test/java/util/jar/JarInputStream/BadSignedJar.jar new file mode 100644 index 0000000000000000000000000000000000000000..651c9ff3dd08818a97f506c1389a473fed1aab8b Binary files /dev/null and b/test/java/util/jar/JarInputStream/BadSignedJar.jar differ diff --git a/test/java/util/jar/JarInputStream/TestIndexedJarWithBadSignature.java b/test/java/util/jar/JarInputStream/TestIndexedJarWithBadSignature.java new file mode 100644 index 0000000000000000000000000000000000000000..977c10121dad0d19aba947a19a222e4136a1122a --- /dev/null +++ b/test/java/util/jar/JarInputStream/TestIndexedJarWithBadSignature.java @@ -0,0 +1,57 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6544278 + * @summary Confirm the JarInputStream throws the SecurityException when + * verifying an indexed jar file with corrupted signature + */ + +import java.io.IOException; +import java.io.FileInputStream; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; + +public class TestIndexedJarWithBadSignature { + + public static void main(String...args) throws Throwable { + try (JarInputStream jis = new JarInputStream( + new FileInputStream(System.getProperty("tst.src", ".") + + System.getProperty("file.separator") + + "BadSignedJar.jar"))) + { + JarEntry je1 = jis.getNextJarEntry(); + while(je1!=null){ + System.out.println("Jar Entry1==>"+je1.getName()); + je1 = jis.getNextJarEntry(); // This should throw Security Exception + } + throw new RuntimeException( + "Test Failed:Security Exception not being thrown"); + } catch (IOException ie){ + ie.printStackTrace(); + } catch (SecurityException e) { + System.out.println("Test passed: Security Exception thrown as expected"); + } + } +} diff --git a/test/javax/management/remote/mandatory/connection/RMIConnector_NPETest.java b/test/javax/management/remote/mandatory/connection/RMIConnector_NPETest.java new file mode 100644 index 0000000000000000000000000000000000000000..91ec8fa7c46b6f8e2c81c9d0875a8f34dbfd5763 --- /dev/null +++ b/test/javax/management/remote/mandatory/connection/RMIConnector_NPETest.java @@ -0,0 +1,73 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary NPE IN RMIConnector.connect + * @bug 6984520 + * @run clean RMIConnector_NPETest + * @run build RMIConnector_NPETest + * @run main RMIConnector_NPETest + */ + +import java.io.*; +import java.lang.management.*; +import java.rmi.registry.*; +import javax.management.*; +import javax.management.remote.*; +import javax.management.remote.rmi.*; + +public class RMIConnector_NPETest { + + public static void main(String argv[]) throws Exception { + boolean testFailed = false; + String rmidCmd = System.getProperty("java.home") + File.separator + + "bin" + File.separator + "rmid -port 3333"; + String stopRmidCmd = System.getProperty("java.home") + File.separator + + "bin" + File.separator + "rmid -stop -port 3333"; + try { + //start an rmid daemon and give it some time + System.out.println("Starting rmid"); + Runtime.getRuntime().exec(rmidCmd); + Thread.sleep(5000); + + MBeanServer mbs = MBeanServerFactory.createMBeanServer(); + RMIJRMPServerImpl rmiserver = new RMIJRMPServerImpl(3333, null, null, null); + rmiserver.setMBeanServer(mbs); + RMIConnector agent = new RMIConnector(rmiserver, null); + agent.connect(); + } catch(NullPointerException npe) { + npe.printStackTrace(); + testFailed = true; + } catch (Exception e) { + // OK + } finally { + System.out.println("Stopping rmid"); + Runtime.getRuntime().exec(stopRmidCmd); + } + + if(testFailed) + throw new Exception("Test failed"); + + } +} diff --git a/test/javax/management/remote/mandatory/notif/DeadListenerTest.java b/test/javax/management/remote/mandatory/notif/DeadListenerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d5fd91e527fc83466d2394c4f2da2b4f7d2c15d8 --- /dev/null +++ b/test/javax/management/remote/mandatory/notif/DeadListenerTest.java @@ -0,0 +1,208 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6957378 + * @summary Test that a listener can be removed remotely from an MBean that no longer exists. + * @author Eamonn McManus + */ + +import com.sun.jmx.remote.internal.ServerNotifForwarder; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import javax.management.ListenerNotFoundException; +import javax.management.MBeanServer; +import javax.management.MBeanServerConnection; +import javax.management.MBeanServerDelegate; +import javax.management.Notification; +import javax.management.NotificationBroadcasterSupport; +import javax.management.NotificationFilterSupport; +import javax.management.NotificationListener; +import javax.management.ObjectName; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; +import javax.management.remote.rmi.RMIConnection; +import javax.management.remote.rmi.RMIConnectionImpl; +import javax.management.remote.rmi.RMIConnectorServer; +import javax.management.remote.rmi.RMIJRMPServerImpl; +import javax.security.auth.Subject; + +public class DeadListenerTest { + public static void main(String[] args) throws Exception { + final ObjectName delegateName = MBeanServerDelegate.DELEGATE_NAME; + + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + Noddy mbean = new Noddy(); + ObjectName name = new ObjectName("d:k=v"); + mbs.registerMBean(mbean, name); + + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///"); + SnoopRMIServerImpl rmiServer = new SnoopRMIServerImpl(); + RMIConnectorServer cs = new RMIConnectorServer(url, null, rmiServer, mbs); + cs.start(); + JMXServiceURL addr = cs.getAddress(); + assertTrue("No connections in new connector server", rmiServer.connections.isEmpty()); + + JMXConnector cc = JMXConnectorFactory.connect(addr); + MBeanServerConnection mbsc = cc.getMBeanServerConnection(); + assertTrue("One connection on server after client connect", rmiServer.connections.size() == 1); + RMIConnectionImpl connection = rmiServer.connections.get(0); + Method getServerNotifFwdM = RMIConnectionImpl.class.getDeclaredMethod("getServerNotifFwd"); + getServerNotifFwdM.setAccessible(true); + ServerNotifForwarder serverNotifForwarder = (ServerNotifForwarder) getServerNotifFwdM.invoke(connection); + Field listenerMapF = ServerNotifForwarder.class.getDeclaredField("listenerMap"); + listenerMapF.setAccessible(true); + @SuppressWarnings("unchecked") + Map> listenerMap = (Map>) listenerMapF.get(serverNotifForwarder); + assertTrue("Server listenerMap initially empty", mapWithoutKey(listenerMap, delegateName).isEmpty()); + + CountListener count1 = new CountListener(); + mbsc.addNotificationListener(name, count1, null, null); + + CountListener count2 = new CountListener(); + NotificationFilterSupport dummyFilter = new NotificationFilterSupport(); + dummyFilter.enableType(""); + mbsc.addNotificationListener(name, count2, dummyFilter, "noddy"); + + assertTrue("One entry in listenerMap for two listeners on same MBean", mapWithoutKey(listenerMap, delegateName).size() == 1); + Set set = listenerMap.get(name); + assertTrue("Set in listenerMap for MBean has two elements", set != null && set.size() == 2); + + assertTrue("Initial value of count1 == 0", count1.count() == 0); + assertTrue("Initial value of count2 == 0", count2.count() == 0); + + Notification notif = new Notification("type", name, 0); + + mbean.sendNotification(notif); + + // Make sure notifs are working normally. + long deadline = System.currentTimeMillis() + 2000; + while ((count1.count() != 1 || count2.count() != 1) && System.currentTimeMillis() < deadline) { + Thread.sleep(10); + } + assertTrue("New value of count1 == 1", count1.count() == 1); + assertTrue("Initial value of count2 == 1", count2.count() == 1); + + // Make sure that removing a nonexistent listener from an existent MBean produces ListenerNotFoundException + CountListener count3 = new CountListener(); + try { + mbsc.removeNotificationListener(name, count3); + assertTrue("Remove of nonexistent listener succeeded but should not have", false); + } catch (ListenerNotFoundException e) { + // OK: expected + } + + // Make sure that removing a nonexistent listener from a nonexistent MBean produces ListenerNotFoundException + ObjectName nonexistent = new ObjectName("foo:bar=baz"); + assertTrue("Nonexistent is nonexistent", !mbs.isRegistered(nonexistent)); + try { + mbsc.removeNotificationListener(nonexistent, count3); + assertTrue("Remove of listener from nonexistent MBean succeeded but should not have", false); + } catch (ListenerNotFoundException e) { + // OK: expected + } + + // Now unregister our MBean, and check that notifs it sends no longer go anywhere. + mbs.unregisterMBean(name); + mbean.sendNotification(notif); + Thread.sleep(200); + assertTrue("New value of count1 == 1", count1.count() == 1); + assertTrue("Initial value of count2 == 1", count2.count() == 1); + + // Check that there is no trace of the listeners any more in ServerNotifForwarder.listenerMap. + // THIS DEPENDS ON JMX IMPLEMENTATION DETAILS. + // If the JMX implementation changes, the code here may have to change too. + Set setForUnreg = listenerMap.get(name); + assertTrue("No trace of unregistered MBean: " + setForUnreg, setForUnreg == null); + + // Remove attempts should fail. + try { + mbsc.removeNotificationListener(name, count1); + assertTrue("Remove of count1 listener should have failed", false); + } catch (ListenerNotFoundException e) { + // OK: expected + } + try { + mbsc.removeNotificationListener(name, count2, dummyFilter, "noddy"); + assertTrue("Remove of count2 listener should have failed", false); + } catch (ListenerNotFoundException e) { + // OK: expected + } + } + + private static Map mapWithoutKey(Map map, K key) { + Map copy = new HashMap(map); + copy.remove(key); + return copy; + } + + public static interface NoddyMBean {} + + public static class Noddy extends NotificationBroadcasterSupport implements NoddyMBean {} + + public static class CountListener implements NotificationListener { + final AtomicInteger count; + + public CountListener() { + this.count = new AtomicInteger(); + } + + int count() { + return count.get(); + } + + public void handleNotification(Notification notification, Object handback) { + count.incrementAndGet(); + } + } + + private static void assertTrue(String what, boolean cond) { + if (!cond) { + throw new AssertionError("Assertion failed: " + what); + } + } + + private static class SnoopRMIServerImpl extends RMIJRMPServerImpl { + final List connections = new ArrayList(); + SnoopRMIServerImpl() throws IOException { + super(0, null, null, null); + } + + @Override + protected RMIConnection makeClient(String id, Subject subject) throws IOException { + RMIConnectionImpl conn = (RMIConnectionImpl) super.makeClient(id, subject); + connections.add(conn); + return conn; + } + } +} diff --git a/test/javax/swing/GroupLayout/6613904/bug6613904.java b/test/javax/swing/GroupLayout/6613904/bug6613904.java new file mode 100644 index 0000000000000000000000000000000000000000..0f0626e66c926d7cfe17e5cee5545c955d7b35dc --- /dev/null +++ b/test/javax/swing/GroupLayout/6613904/bug6613904.java @@ -0,0 +1,65 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6613904 + * @summary javax.swing.GroupLayout.createParallelGroup(..) doesn't throw IllegalArgumentException for null arg + * @author Pavel Porvatov + */ + +import javax.swing.*; + +public class bug6613904 { + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + GroupLayout groupLayout = new GroupLayout(new JPanel()); + + try { + groupLayout.createParallelGroup(null); + + throw new RuntimeException("groupLayout.createParallelGroup(null) doesn't throw IAE"); + } catch (IllegalArgumentException e) { + // Ok + } + + try { + groupLayout.createParallelGroup(null, true); + + throw new RuntimeException("groupLayout.createParallelGroup(null, true) doesn't throw IAE"); + } catch (IllegalArgumentException e) { + // Ok + } + + try { + groupLayout.createParallelGroup(null, false); + + throw new RuntimeException("groupLayout.createParallelGroup(null, false) doesn't throw IAE"); + } catch (IllegalArgumentException e) { + // Ok + } + } + }); + } +} diff --git a/test/javax/swing/JPopupMenu/6987844/bug6987844.java b/test/javax/swing/JPopupMenu/6987844/bug6987844.java new file mode 100644 index 0000000000000000000000000000000000000000..d8802351bcbff4b9b1700fe79c4dcc179daa9ab5 --- /dev/null +++ b/test/javax/swing/JPopupMenu/6987844/bug6987844.java @@ -0,0 +1,94 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6987844 + * @summary Incorrect width of JComboBox drop down + * @author Alexander Potochkin + * @run main bug6987844 + */ + +import sun.awt.SunToolkit; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.InputEvent; + +public class bug6987844 { + static JMenu menu1; + static JMenu menu2; + + public static void main(String... args) throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + Robot robot = new Robot(); + robot.setAutoDelay(200); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JMenuBar bar = new JMenuBar(); + menu1 = new JMenu("Menu1"); + menu1.add(new JMenuItem("item")); + bar.add(menu1); + menu2 = new JMenu("Menu2"); + menu2.add(new JMenuItem("item")); + menu2.add(new JMenuItem("item")); + bar.add(menu2); + + frame.setJMenuBar(bar); + frame.pack(); + + frame.setVisible(true); + } + }); + toolkit.realSync(); + Point point1 = menu1.getLocationOnScreen(); + Point point2 = menu2.getLocationOnScreen(); + + robot.mouseMove(point1.x + 1, point1.y + 1); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.mouseMove(point2.x + 1, point2.y + 1); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.mouseMove(point1.x + 1, point1.y + 1); + toolkit.realSync(); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + Dimension popupSize1 = menu1.getPopupMenu().getSize(); + Dimension popupSize2 = menu2.getPopupMenu().getSize(); + if (popupSize1.equals(popupSize2)) { + throw new RuntimeException("First popup unexpedetly changed its size"); + } + } + }); + } +} diff --git a/test/javax/swing/text/DefaultHighlighter/6771184/bug6771184.java b/test/javax/swing/text/DefaultHighlighter/6771184/bug6771184.java new file mode 100644 index 0000000000000000000000000000000000000000..d63e8da0e61c204c011a94bac7a59a0bb35880bb --- /dev/null +++ b/test/javax/swing/text/DefaultHighlighter/6771184/bug6771184.java @@ -0,0 +1,86 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6771184 + * @summary Some methods in text package don't throw BadLocationException when expected + * @author Pavel Porvatov + */ + +import javax.swing.*; +import javax.swing.text.BadLocationException; +import javax.swing.text.Highlighter; +import javax.swing.text.JTextComponent; +import java.awt.*; + +public class bug6771184 { + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JTextArea textArea = new JTextArea("Tested string"); + + Highlighter highlighter = textArea.getHighlighter(); + Highlighter.HighlightPainter myPainter = new Highlighter.HighlightPainter() { + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { + } + }; + + int negativeTestedData[][] = {{50, 0}, + {-1, 1}, + {-5, -4}, + {Integer.MAX_VALUE, Integer.MIN_VALUE}, + {Integer.MIN_VALUE, Integer.MAX_VALUE}, + {Integer.MIN_VALUE, Integer.MIN_VALUE}}; + + for (int[] data : negativeTestedData) { + try { + highlighter.addHighlight(data[0], data[1], myPainter); + + throw new RuntimeException("Method addHighlight() does not throw BadLocationException for (" + + data[0] + ", " + data[1] + ") "); + } catch (BadLocationException e) { + // Ok + } + + Object objRef; + + try { + objRef = highlighter.addHighlight(0, 1, myPainter); + } catch (BadLocationException e) { + throw new RuntimeException("highlighter.addHighlight(0, 1, myPainter) throws exception", e); + } + + try { + highlighter.changeHighlight(objRef, data[0], data[1]); + + throw new RuntimeException("Method changeHighlight() does not throw BadLocationException for (" + + data[0] + ", " + data[1] + ") "); + } catch (BadLocationException e) { + // Ok + } + } + } + }); + } +} diff --git a/test/sun/security/krb5/auto/KDC.java b/test/sun/security/krb5/auto/KDC.java index 8b56ed0f341be37e9ad26daaac67b3617a5fbbba..796415bb03e3f63493bb10e45865c8c0aa127bdc 100644 --- a/test/sun/security/krb5/auto/KDC.java +++ b/test/sun/security/krb5/auto/KDC.java @@ -35,7 +35,6 @@ import sun.net.spi.nameservice.NameServiceDescriptor; import sun.security.krb5.*; import sun.security.krb5.internal.*; import sun.security.krb5.internal.ccache.CredentialsCache; -import sun.security.krb5.internal.crypto.EType; import sun.security.krb5.internal.crypto.KeyUsage; import sun.security.krb5.internal.ktab.KeyTab; import sun.security.util.DerInputStream; @@ -129,8 +128,13 @@ public class KDC { // The random generator to generate random keys (including session keys) private static SecureRandom secureRandom = new SecureRandom(); - // Principal db. principal -> pass - private Map passwords = new HashMap(); + + // Principal db. principal -> pass. A case-insensitive TreeMap is used + // so that even if the client provides a name with different case, the KDC + // can still locate the principal and give back correct salt. + private TreeMap passwords = new TreeMap + (String.CASE_INSENSITIVE_ORDER); + // Realm name private String realm; // KDC @@ -159,9 +163,13 @@ public class KDC { */ ONLY_RC4_TGT, /** - * Only use RC4 in preauth, enc-type still using eTypes[0] + * Use RC4 as the first in preauth */ - ONLY_RC4_PREAUTH, + RC4_FIRST_PREAUTH, + /** + * Use only one preauth, so that some keys are not easy to generate + */ + ONLY_ONE_PREAUTH, }; static { @@ -191,6 +199,12 @@ public class KDC { return create(realm, "kdc." + realm.toLowerCase(), 0, true); } + public static KDC existing(String realm, String kdc, int port) { + KDC k = new KDC(realm, kdc); + k.port = port; + return k; + } + /** * Creates and starts a KDC server. * @param realm the realm name @@ -471,7 +485,18 @@ public class KDC { * @return the salt */ private String getSalt(PrincipalName p) { - String[] ns = p.getNameStrings(); + String pn = p.toString(); + if (p.getRealmString() == null) { + pn = pn + "@" + getRealm(); + } + if (passwords.containsKey(pn)) { + try { + // Find the principal name with correct case. + p = new PrincipalName(passwords.ceilingEntry(pn).getKey()); + } catch (RealmException re) { + // Won't happen + } + } String s = p.getRealmString(); if (s == null) s = getRealm(); for (String n: p.getNameStrings()) { @@ -493,8 +518,6 @@ public class KDC { try { // Do not call EncryptionKey.acquireSecretKeys(), otherwise // the krb5.conf config file would be loaded. - Method stringToKey = EncryptionKey.class.getDeclaredMethod("stringToKey", char[].class, String.class, byte[].class, Integer.TYPE); - stringToKey.setAccessible(true); Integer kvno = null; // For service whose password ending with a number, use it as kvno. // Kvno must be postive. @@ -504,12 +527,9 @@ public class KDC { kvno = pass[pass.length-1] - '0'; } } - return new EncryptionKey((byte[]) stringToKey.invoke( - null, getPassword(p, server), getSalt(p), null, etype), + return new EncryptionKey(EncryptionKeyDotStringToKey( + getPassword(p, server), getSalt(p), null, etype), etype, kvno); - } catch (InvocationTargetException ex) { - KrbException ke = (KrbException)ex.getCause(); - throw ke; } catch (KrbException ke) { throw ke; } catch (Exception e) { @@ -590,12 +610,11 @@ public class KDC { " sends TGS-REQ for " + tgsReq.reqBody.sname); KDCReqBody body = tgsReq.reqBody; - int etype = 0; + int[] eTypes = KDCReqBodyDotEType(body); + int e2 = eTypes[0]; // etype for outgoing session key + int e3 = eTypes[0]; // etype for outgoing ticket - // Reflection: PAData[] pas = tgsReq.pAData; - Field f = KDCReq.class.getDeclaredField("pAData"); - f.setAccessible(true); - PAData[] pas = (PAData[])f.get(tgsReq); + PAData[] pas = kDCReqDotPAData(tgsReq); Ticket tkt = null; EncTicketPart etp = null; @@ -607,9 +626,9 @@ public class KDC { APReq apReq = new APReq(pa.getValue()); EncryptedData ed = apReq.authenticator; tkt = apReq.ticket; - etype = tkt.encPart.getEType(); + int te = tkt.encPart.getEType(); tkt.sname.setRealm(tkt.realm); - EncryptionKey kkey = keyForUser(tkt.sname, etype, true); + EncryptionKey kkey = keyForUser(tkt.sname, te, true); byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET); DerInputStream derIn = new DerInputStream(bb); DerValue der = derIn.getDerValue(); @@ -620,16 +639,12 @@ public class KDC { throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP); } } - EncryptionKey skey = keyForUser(body.sname, etype, true); - if (skey == null) { - throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO - } // Session key for original ticket, TGT EncryptionKey ckey = etp.key; // Session key for session with the service - EncryptionKey key = generateRandomKey(etype); + EncryptionKey key = generateRandomKey(e2); // Check time, TODO KerberosTime till = body.till; @@ -678,6 +693,10 @@ public class KDC { till, body.rtime, body.addresses, null); + EncryptionKey skey = keyForUser(body.sname, e3, true); + if (skey == null) { + throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO + } Ticket t = new Ticket( body.crealm, body.sname, @@ -741,17 +760,17 @@ public class KDC { private byte[] processAsReq(byte[] in) throws Exception { ASReq asReq = new ASReq(in); int[] eTypes = null; + List outPAs = new ArrayList(); + try { System.out.println(realm + "> " + asReq.reqBody.cname + " sends AS-REQ for " + asReq.reqBody.sname); KDCReqBody body = asReq.reqBody; + body.cname.setRealm(getRealm()); - // Reflection: int[] eType = body.eType; - Field f = KDCReqBody.class.getDeclaredField("eType"); - f.setAccessible(true); - eTypes = (int[])f.get(body); + eTypes = KDCReqBodyDotEType(body); int eType = eTypes[0]; EncryptionKey ckey = keyForUser(body.cname, eType, false); @@ -807,19 +826,63 @@ public class KDC { } bFlags[Krb5.TKT_OPTS_INITIAL] = true; - f = KDCReq.class.getDeclaredField("pAData"); - f.setAccessible(true); - PAData[] pas = (PAData[])f.get(asReq); - if (pas == null || pas.length == 0) { + // Creating PA-DATA + int[] epas = eTypes; + if (options.containsKey(KDC.Option.RC4_FIRST_PREAUTH)) { + for (int i=1; i ctor = EncryptedData.class.getDeclaredConstructor(DerValue.class); - ctor.setAccessible(true); - EncryptedData data = ctor.newInstance(new DerValue(pas[0].getValue())); + EncryptedData data = newEncryptedData(new DerValue(inPAs[0].getValue())); EncryptionKey pakey = keyForUser(body.cname, data.getEType(), false); data.decrypt(pakey, KeyUsage.KU_PA_ENC_TS); } catch (Exception e) { @@ -862,7 +925,8 @@ public class KDC { body.addresses ); EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_AS_REP_PART); - ASRep asRep = new ASRep(null, + ASRep asRep = new ASRep( + outPAs.toArray(new PAData[outPAs.size()]), body.crealm, body.cname, t, @@ -907,36 +971,10 @@ public class KDC { if (kerr == null) { if (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED || ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) { - PAData pa; - - int epa = eTypes[0]; - if (options.containsKey(KDC.Option.ONLY_RC4_PREAUTH)) { - epa = EncryptedData.ETYPE_ARCFOUR_HMAC; - } - ETypeInfo2 ei2 = new ETypeInfo2(epa, null, null); - DerOutputStream eid = new DerOutputStream(); - eid.write(DerValue.tag_Sequence, ei2.asn1Encode()); - - pa = new PAData(Krb5.PA_ETYPE_INFO2, eid.toByteArray()); - DerOutputStream bytes = new DerOutputStream(); bytes.write(new PAData(Krb5.PA_ENC_TIMESTAMP, new byte[0]).asn1Encode()); - bytes.write(pa.asn1Encode()); - - boolean allOld = true; - for (int i: eTypes) { - if (i == EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96 || - i == EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96) { - allOld = false; - break; - } - } - if (allOld) { - ETypeInfo ei = new ETypeInfo(epa, null); - eid = new DerOutputStream(); - eid.write(DerValue.tag_Sequence, ei.asn1Encode()); - pa = new PAData(Krb5.PA_ETYPE_INFO, eid.toByteArray()); - bytes.write(pa.asn1Encode()); + for (PAData p: outPAs) { + bytes.write(p.asn1Encode()); } DerOutputStream temp = new DerOutputStream(); temp.write(DerValue.tag_Sequence, bytes); @@ -1146,4 +1184,61 @@ public class KDC { return "ns"; } } + + // Calling private methods thru reflections + private static final Field getPADataField; + private static final Field getEType; + private static final Constructor ctorEncryptedData; + private static final Method stringToKey; + + static { + try { + ctorEncryptedData = EncryptedData.class.getDeclaredConstructor(DerValue.class); + ctorEncryptedData.setAccessible(true); + getPADataField = KDCReq.class.getDeclaredField("pAData"); + getPADataField.setAccessible(true); + getEType = KDCReqBody.class.getDeclaredField("eType"); + getEType.setAccessible(true); + stringToKey = EncryptionKey.class.getDeclaredMethod( + "stringToKey", + char[].class, String.class, byte[].class, Integer.TYPE); + stringToKey.setAccessible(true); + } catch (NoSuchFieldException nsfe) { + throw new AssertionError(nsfe); + } catch (NoSuchMethodException nsme) { + throw new AssertionError(nsme); + } + } + private EncryptedData newEncryptedData(DerValue der) { + try { + return ctorEncryptedData.newInstance(der); + } catch (Exception e) { + throw new AssertionError(e); + } + } + private static PAData[] kDCReqDotPAData(KDCReq req) { + try { + return (PAData[])getPADataField.get(req); + } catch (Exception e) { + throw new AssertionError(e); + } + } + private static int[] KDCReqBodyDotEType(KDCReqBody body) { + try { + return (int[]) getEType.get(body); + } catch (Exception e) { + throw new AssertionError(e); + } + } + private static byte[] EncryptionKeyDotStringToKey(char[] password, String salt, + byte[] s2kparams, int keyType) throws KrbCryptoException { + try { + return (byte[])stringToKey.invoke( + null, password, salt, s2kparams, keyType); + } catch (InvocationTargetException ex) { + throw (KrbCryptoException)ex.getCause(); + } catch (Exception e) { + throw new AssertionError(e); + } + } } diff --git a/test/sun/security/krb5/auto/MoreKvno.java b/test/sun/security/krb5/auto/MoreKvno.java index bf5b7e6aada5072a85ecc2c811d31724c676ebc4..84cfa362d0d8718ec0b79da6c335cd0631b5ecd1 100644 --- a/test/sun/security/krb5/auto/MoreKvno.java +++ b/test/sun/security/krb5/auto/MoreKvno.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -48,9 +48,9 @@ public class MoreKvno { KeyTab ktab = KeyTab.create(OneKDC.KTAB); p = new PrincipalName( OneKDC.SERVER+"@"+OneKDC.REALM, PrincipalName.KRB_NT_SRV_HST); - ktab.addEntry(p, "pass1".toCharArray(), 1); - ktab.addEntry(p, "pass3".toCharArray(), 3); - ktab.addEntry(p, "pass2".toCharArray(), 2); + ktab.addEntry(p, "pass1".toCharArray(), 1, true); + ktab.addEntry(p, "pass3".toCharArray(), 3, true); + ktab.addEntry(p, "pass2".toCharArray(), 2, true); ktab.save(); char[] pass = "pass2".toCharArray(); diff --git a/test/sun/security/krb5/auto/NewSalt.java b/test/sun/security/krb5/auto/NewSalt.java new file mode 100644 index 0000000000000000000000000000000000000000..54cc9562f37f77b8e2588e8078b355496fa11f4d --- /dev/null +++ b/test/sun/security/krb5/auto/NewSalt.java @@ -0,0 +1,64 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6960894 + * @summary Better AS-REQ creation and processing + * @run main NewSalt + * @run main/othervm -Dnopreauth NewSalt + * @run main/othervm -Donlyonepreauth NewSalt + */ + +import sun.security.jgss.GSSUtil; +import sun.security.krb5.Config; + +public class NewSalt { + + public static void main(String[] args) + throws Exception { + + // Create and start the KDC + KDC kdc = new OneKDC(null); + if (System.getProperty("onlyonepreauth") != null) { + KDC.saveConfig(OneKDC.KRB5_CONF, kdc, + "default_tgs_enctypes=des3-cbc-sha1"); + Config.refresh(); + kdc.setOption(KDC.Option.ONLY_ONE_PREAUTH, true); + } + if (System.getProperty("nopreauth") != null) { + kdc.setOption(KDC.Option.PREAUTH_REQUIRED, false); + } + + // Use a different case of name. KDC will return correct salt + Context c1 = Context.fromUserPass(OneKDC.USER.toUpperCase(), + OneKDC.PASS, true); + Context c2 = Context.fromUserPass(OneKDC.USER2.toUpperCase(), + OneKDC.PASS2, true); + + c1.startAsClient(OneKDC.USER2, GSSUtil.GSS_KRB5_MECH_OID); + c2.startAsServer(GSSUtil.GSS_KRB5_MECH_OID); + + Context.handshake(c1, c2); + } +} diff --git a/test/sun/security/krb5/auto/OneKDC.java b/test/sun/security/krb5/auto/OneKDC.java index 538ab3f32c8f32ece5af390667d822f37c34a98d..79a883017e3fbd3ac32d62dba67b36916a791fe9 100644 --- a/test/sun/security/krb5/auto/OneKDC.java +++ b/test/sun/security/krb5/auto/OneKDC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 @@ -46,6 +46,8 @@ public class OneKDC extends KDC { public static final String USER = "dummy"; public static final char[] PASS = "bogus".toCharArray(); + public static final String USER2 = "foo"; + public static final char[] PASS2 = "bar".toCharArray(); public static final String KRB5_CONF = "localkdc-krb5.conf"; public static final String KTAB = "localkdc.ktab"; public static final String JAAS_CONF = "localkdc-jaas.conf"; @@ -61,6 +63,7 @@ public class OneKDC extends KDC { public OneKDC(String etype) throws Exception { super(REALM, KDCHOST, 0, true); addPrincipal(USER, PASS); + addPrincipal(USER2, PASS2); addPrincipalRandKey("krbtgt/" + REALM); addPrincipalRandKey(SERVER); addPrincipalRandKey(BACKEND); diff --git a/test/sun/security/krb5/auto/SSL.java b/test/sun/security/krb5/auto/SSL.java index 08ceaca84986fee0fd93e7def469368ae60a4717..1deae8e6f16b5b30af9f883e5a1237478cb5c7c4 100644 --- a/test/sun/security/krb5/auto/SSL.java +++ b/test/sun/security/krb5/auto/SSL.java @@ -74,9 +74,9 @@ public class SSL { KeyTab ktab = KeyTab.create(OneKDC.KTAB); PrincipalName service = new PrincipalName( "host/" + server, PrincipalName.KRB_NT_SRV_HST); - ktab.addEntry(service, "pass1".toCharArray(), 1); - ktab.addEntry(service, "pass2".toCharArray(), 2); - ktab.addEntry(service, "pass3".toCharArray(), 3); + ktab.addEntry(service, "pass1".toCharArray(), 1, true); + ktab.addEntry(service, "pass2".toCharArray(), 2, true); + ktab.addEntry(service, "pass3".toCharArray(), 3, true); ktab.save(); // and use the middle one as the real key diff --git a/test/sun/security/krb5/auto/TcpTimeout.java b/test/sun/security/krb5/auto/TcpTimeout.java new file mode 100644 index 0000000000000000000000000000000000000000..9530803b5b284470c309c228791726b36770eeb1 --- /dev/null +++ b/test/sun/security/krb5/auto/TcpTimeout.java @@ -0,0 +1,138 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6952519 + * @run main/timeout=40/othervm TcpTimeout + * @summary kdc_timeout is not being honoured when using TCP + */ + +import java.io.*; +import java.net.ServerSocket; +import sun.security.krb5.Config; + +public class TcpTimeout { + public static void main(String[] args) + throws Exception { + + System.setProperty("sun.security.krb5.debug", "true"); + final int p1 = 10000 + new java.util.Random().nextInt(10000); + final int p2 = 20000 + new java.util.Random().nextInt(10000); + final int p3 = 30000 + new java.util.Random().nextInt(10000); + + KDC k = new KDC(OneKDC.REALM, OneKDC.KDCHOST, p3, true); + k.addPrincipal(OneKDC.USER, OneKDC.PASS); + k.addPrincipalRandKey("krbtgt/" + OneKDC.REALM); + + // Start two listener that does not communicate, simulate timeout + new Thread() { + public void run() { + try { + new ServerSocket(p1).accept(); + } catch (Exception e) { + }} + }.start(); + new Thread() { + public void run() { + try { + new ServerSocket(p2).accept(); + } catch (Exception e) { + }} + }.start(); + + FileWriter fw = new FileWriter("alternative-krb5.conf"); + + fw.write("[libdefaults]\n" + + "udp_preference_limit = 1\n" + + "max_retries = 2\n" + + "default_realm = " + OneKDC.REALM + "\n" + + "kdc_timeout = 5000\n"); + fw.write("[realms]\n" + OneKDC.REALM + " = {\n" + + "kdc = " + OneKDC.KDCHOST + ":" + p1 + "\n" + + "kdc = " + OneKDC.KDCHOST + ":" + p2 + "\n" + + "kdc = " + OneKDC.KDCHOST + ":" + p3 + "\n" + + "}\n"); + + fw.close(); + System.setProperty("java.security.krb5.conf", "alternative-krb5.conf"); + Config.refresh(); + + // The correct behavior should be: + // 5 sec on p1, 5 sec on p1, fail + // 5 sec on p2, 5 sec on p2, fail + // p3 ok, p3 ok again for preauth. + // The total time should be 20sec + 2x. x is processing time for AS-REQ. + int count = 6; + long start = System.nanoTime(); + + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + PrintStream oldout = System.out; + System.setOut(new PrintStream(bo)); + Context c = Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false); + System.setOut(oldout); + + String[] lines = new String(bo.toByteArray()).split("\n"); + for (String line: lines) { + if (line.startsWith(">>> KDCCommunication")) { + System.out.println(line); + count--; + } + } + if (count != 0) { + throw new Exception("Retry count is " + count + " less"); + } + + long end = System.nanoTime(); + if ((end - start)/1000000000L < 20) { + throw new Exception("Too fast? " + (end - start)/1000000000L); + } + } + + private static KDC on(int p) throws Exception { + KDC k = new KDC(OneKDC.REALM, OneKDC.KDCHOST, p, true); + k.addPrincipal(OneKDC.USER, OneKDC.PASS); + k.addPrincipalRandKey("krbtgt/" + OneKDC.REALM); + return k; + } + + private static void addFakeKDCs() + throws Exception { + BufferedReader fr = new BufferedReader(new FileReader(OneKDC.KRB5_CONF)); + FileWriter fw = new FileWriter("alternative-krb5.conf"); + while (true) { + String s = fr.readLine(); + if (s == null) { + break; + } + if (s.trim().startsWith("kdc = ")) { + fw.write(" kdc = localhost:33333\n"); + fw.write(" kdc = localhost:22222\n"); + } + fw.write(s + "\n"); + } + fr.close(); + fw.close(); + sun.security.krb5.Config.refresh(); + } +} diff --git a/test/sun/security/krb5/auto/W83.java b/test/sun/security/krb5/auto/W83.java index a0951cad2893bf879129f7f94b3368f603323e04..5c5e9af5cb3975c7baa5b50a3393340d8189a9b1 100644 --- a/test/sun/security/krb5/auto/W83.java +++ b/test/sun/security/krb5/auto/W83.java @@ -26,6 +26,8 @@ * @bug 6932525 6951366 6959292 * @summary kerberos login failure on win2008 with AD set to win2000 compat mode * and cannot login if session key and preauth does not use the same etype + * @run main/othervm -D6932525 W83 + * @run main/othervm -D6959292 W83 */ import com.sun.security.auth.module.Krb5LoginModule; import java.io.File; @@ -56,19 +58,21 @@ public class W83 { KeyTab ktab = KeyTab.getInstance(OneKDC.KTAB); for (int etype: EType.getBuiltInDefaults()) { if (etype != EncryptedData.ETYPE_ARCFOUR_HMAC) { - ktab.deleteEntry(new PrincipalName(OneKDC.USER), etype); + ktab.deleteEntries(new PrincipalName(OneKDC.USER), etype, -1); } } ktab.save(); - // For 6932525 and 6951366, make sure the etypes sent in 2nd AS-REQ - // is not restricted to that of preauth - kdc.setOption(KDC.Option.ONLY_RC4_TGT, true); - x.go(); - - // For 6959292, make sure that when etype for enc-part in 2nd AS-REQ - // is different from that of preauth, client can still decrypt it - kdc.setOption(KDC.Option.ONLY_RC4_PREAUTH, true); + if (System.getProperty("6932525") != null) { + // For 6932525 and 6951366, make sure the etypes sent in 2nd AS-REQ + // is not restricted to that of preauth + kdc.setOption(KDC.Option.ONLY_RC4_TGT, true); + } + if (System.getProperty("6959292") != null) { + // For 6959292, make sure that when etype for enc-part in 2nd AS-REQ + // is different from that of preauth, client can still decrypt it + kdc.setOption(KDC.Option.RC4_FIRST_PREAUTH, true); + } x.go(); } @@ -78,11 +82,13 @@ public class W83 { try { Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false); } catch (Exception e) { + e.printStackTrace(); error.append("Krb5LoginModule password login error\n"); } try { Context.fromUserKtab(OneKDC.USER, OneKDC.KTAB, false); } catch (Exception e) { + e.printStackTrace(); error.append("Krb5LoginModule keytab login error\n"); } try { diff --git a/test/sun/security/krb5/ktab/KeyTabIndex.java b/test/sun/security/krb5/ktab/KeyTabIndex.java index feb9566373e830c53eb4a077171f05fe99c33359..f0cd88e6a651a03c84b485b2f582311b929638e3 100644 --- a/test/sun/security/krb5/ktab/KeyTabIndex.java +++ b/test/sun/security/krb5/ktab/KeyTabIndex.java @@ -35,8 +35,8 @@ public class KeyTabIndex { // observice the abnormal change of "index" field. kt.addEntry(new PrincipalName( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@A"), - "x".toCharArray(), 1); - kt.addEntry(new PrincipalName("a@A"), "x".toCharArray(), 1); + "x".toCharArray(), 1, true); + kt.addEntry(new PrincipalName("a@A"), "x".toCharArray(), 1, true); kt.save(); Runnable t = new Runnable() { @Override diff --git a/test/sun/security/util/Resources/NewNamesFormat.java b/test/sun/security/util/Resources/NewNamesFormat.java new file mode 100644 index 0000000000000000000000000000000000000000..9c3b4521908fc6a0de4e20d60a048cbcf50794b9 --- /dev/null +++ b/test/sun/security/util/Resources/NewNamesFormat.java @@ -0,0 +1,74 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6987827 + * @summary security/util/Resources.java needs improvement + */ + + +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Set; + +/** + * This test makes sure that the keys in resources files are using the new + * format and there is no duplication. + */ +public class NewNamesFormat { + public static void main(String[] args) throws Exception { + checkRes("sun.security.util.Resources"); + checkRes("sun.security.util.AuthResources"); + checkRes("sun.security.tools.JarSignerResources"); + } + + private static void checkRes(String resName) throws Exception { + System.out.println("Checking " + resName + "..."); + Class clazz = Class.forName(resName); + Method m = clazz.getMethod("getContents"); + Object[][] contents = (Object[][])m.invoke(clazz.newInstance()); + Set keys = new HashSet(); + for (Object[] pair: contents) { + String key = (String)pair[0]; + if (keys.contains(key)) { + System.out.println("Found dup: " + key); + throw new Exception(); + } + checkKey(key); + keys.add(key); + } + } + + private static void checkKey(String key) throws Exception { + for (char c: key.toCharArray()) { + if (Character.isLetter(c) || Character.isDigit(c) || + c == '{' || c == '}' || c == '.') { + // OK + } else { + System.out.println("Illegal char [" + c + "] in key: " + key); + throw new Exception(); + } + } + } +} diff --git a/test/sun/security/util/Resources/NewResourcesNames.java b/test/sun/security/util/Resources/NewResourcesNames.java new file mode 100644 index 0000000000000000000000000000000000000000..72078b5c333cd646a5e0a2103817f3119f2e48e0 --- /dev/null +++ b/test/sun/security/util/Resources/NewResourcesNames.java @@ -0,0 +1,439 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.HashSet; +import java.util.ListResourceBundle; +import java.util.Map; +import java.util.Set; + +/** + * Prepares new key names for Resources.java. + * 6987827: security/util/Resources.java needs improvement + * + * Run inside jdk/src/share/classes: + * + * java NewResourcesNames $( + * for a in $(find com/sun/security sun/security javax/security -type f); do + * egrep -q '(ResourcesMgr.getString|rb.getString)' $a && echo $a + * done) + * + * Before running this tool, run the following two commands to make sure there + * are only these 2 types of calls into the resources: + * for a in `find com/sun/security sun/security javax/security -type f`; do + * cat $a | perl -ne 'print if /\bResourcesMgr\b/'; done | + * grep -v ResourcesMgr.getString + * for a in `find com/sun/security sun/security -type f`; do + * cat $a | perl -ne 'print if /\brb\b/'; done | + * grep -v rb.getString + */ +class NewResourcesNames { + + // Max length of normalized names + static int MAXLEN = 127; + + static String[] resources = { + "sun/security/tools/JarSignerResources.java", + "sun/security/util/Resources.java", + "sun/security/util/AuthResources.java", + }; + + public static void main(String[] args) throws Exception { + + // Load all names inside resources files + Map allnames = loadResources(); + + // Modify the callers. There are two patterns: + // 1. ResourcesMgr.getString(" + // used by most JAAS codes + // 2. rb.getString(" + // used by tools + Set allfound = new HashSet(); + for (String arg: args) { + allfound.addAll(rewriteFile(arg, "ResourcesMgr.getString(\"")); + allfound.addAll(rewriteFile(arg, "rb.getString(\"")); + } + + // Special case 1: KeyTool's enum definition of commands and options + allfound.addAll(keyToolEnums()); + + // Special case 2: PolicyFile called this 4 times + allfound.addAll(rewriteFile("sun/security/provider/PolicyFile.java", + "ResourcesMgr.getString(POLICY+\"")); + + // During the calls above, you can read sth like: + // + // Working on com/sun/security/auth/PolicyParser.java + // GOOD match is 17 + // + // This means a " exists right after getString(. Sometimes you see + // + // Working on sun/security/tools/KeyTool.java + // BAD!! pmatch != match: 212 != 209 + // Working on sun/security/provider/PolicyFile.java + // BAD!! pmatch != match: 14 != 10 + // + // which is mismatch. There are only two such special cases list above. + // For KeyTool, there are 3 calls for showing help. For PolicyTool, 3 + // for name prefixed with POLICY. They are covered in the two special + // cases above. + + // Names used but not defined. This is mostly error, except for + // special case 2 above. So it's OK to see 3 entries red here + if (!allnames.keySet().containsAll(allfound)) { + err("FATAL: Undefined names"); + for (String name: allfound) { + if (!allnames.keySet().contains(name)) { + err(" " + name); + } + } + } + + // Names defined but not used. Mostly this is old entries not removed. + // When soemone remove a line of code, he dares not remove the entry + // in case it's also used somewhere else. + if (!allfound.containsAll(allnames.keySet())) { + System.err.println("WARNING: Unused names"); + for (String name: allnames.keySet()) { + if (!allfound.contains(name)) { + System.err.println(allnames.get(name)); + System.err.println(" " + normalize(name)); + System.err.println(" [" + name + "]"); + } + } + } + } + + + /** + * Loads the three resources files. Saves names into a Map. + */ + private static Map loadResources() throws Exception { + + // Name vs Resource + Map allnames = new HashMap(); + + for (String f: resources) { + String clazz = + f.replace('/', '.').substring(0, f.length()-5); + + Set expected = loadClass(clazz); + Set found = rewriteFile(f, "{\""); + + // This is to check that word parsing is identical to Java thinks + if (!expected.equals(found)) { + throw new Exception("Expected and found do not match"); + } + + for (String name: found) { + allnames.put(name, f); + } + } + return allnames; + } + + /** + * Special case treat for enums description in KeyTool + */ + private static Set keyToolEnums() throws Exception { + + Set names = new HashSet(); + + String file = "sun/security/tools/KeyTool.java"; + System.err.println("Working on " + file); + File origFile = new File(file); + File tmpFile = new File(file + ".tmp"); + origFile.renameTo(tmpFile); + tmpFile.deleteOnExit(); + + BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(tmpFile))); + PrintWriter out = new PrintWriter(new FileOutputStream(origFile)); + + int stage = 0; // 1. commands, 2. options, 3. finished + int match = 0; + + while (true) { + String s = br.readLine(); + if (s == null) { + break; + } + if (s.indexOf("enum Command") >= 0) stage = 1; + else if (s.indexOf("enum Option") >= 0) stage = 2; + else if (s.indexOf("private static final String JKS") >= 0) stage = 3; + + if (stage == 1 || stage == 2) { + if (s.indexOf("(\"") >= 0) { + match++; + int p1, p2; + if (stage == 1) { + p1 = s.indexOf("\""); + p2 = s.indexOf("\"", p1+1); + } else { + p2 = s.lastIndexOf("\""); + p1 = s.lastIndexOf("\"", p2-1); + } + String name = s.substring(p1+1, p2); + names.add(name); + out.println(s.substring(0, p1+1) + + normalize(name) + + s.substring(p2)); + } else { + out.println(s); + } + } else { + out.println(s); + } + } + br.close(); + out.close(); + System.err.println(" GOOD match is " + match); + return names; + } + + /** + * Loads a resources using JRE and returns the names + */ + private static Set loadClass(String clazz) throws Exception { + ListResourceBundle lrb = + (ListResourceBundle)Class.forName(clazz).newInstance(); + Set keys = lrb.keySet(); + Map newold = new HashMap(); + boolean dup = false; + // Check if normalize() creates dup entries. This is crucial. + for (String k: keys) { + String key = normalize(k); + if (newold.containsKey(key)) { + err("Dup found for " + key + ":"); + err("["+newold.get(key)+"]"); + err("["+k+"]"); + dup = true; + } + newold.put(key, k); + } + if (dup) throw new Exception(); + return keys; + } + + /** + * Rewrites a file using a pattern. The name string should be right after + * the pattern. Note: pattern ignores whitespaces. Returns names found. + */ + private static Set rewriteFile(String file, String pattern) + throws Exception { + + System.err.println("Working on " + file); + Set names = new HashSet(); + + int plen = pattern.length(); + int match = 0; + + // The bare XXX.getString is also matched. Sometimes getString is + // called but does not use literal strings. This is harder to solve. + + int pmatch = 0; + int pheadlen = plen - 2; + String phead = pattern.substring(0, plen-2); + + // The non-whitespace chars read since, used to check for pattern + StringBuilder history = new StringBuilder(); + int hlen = 0; + + File origFile = new File(file); + File tmpFile = new File(file + ".tmp"); + origFile.renameTo(tmpFile); + tmpFile.deleteOnExit(); + + FileInputStream fis = new FileInputStream(tmpFile); + FileOutputStream fos = new FileOutputStream(origFile); + + while (true) { + int ch = fis.read(); + if (ch < 0) break; + if (!Character.isWhitespace(ch)) { + history.append((char)ch); + hlen++; + if (pheadlen > 0 && hlen >= pheadlen && + history.substring(hlen-pheadlen, hlen).equals(phead)) { + pmatch++; + } + } + + if (hlen >= plen && + history.substring(hlen-plen, hlen).equals(pattern)) { + match++; + history = new StringBuilder(); + hlen = 0; + + fos.write(ch); + + // Save a name + StringBuilder sb = new StringBuilder(); + // Save things after the second ". Maybe it's an end, maybe + // it's just literal string concatenation. + StringBuilder tail = new StringBuilder(); + + boolean in = true; // inside name string + while (true) { + int n = fis.read(); + if (in) { + if (n == '\\') { + int second = fis.read(); + switch (second) { + case 'n': sb.append('\n'); break; + case 'r': sb.append('\r'); break; + case 't': sb.append('\t'); break; + case '"': sb.append('"'); break; + default: throw new Exception(String.format( + "I don't know this escape: %s%c", + sb.toString(), second)); + } + } else if (n == '"') { + in = false; + // Maybe string concat? say bytes until clear + tail = new StringBuilder(); + tail.append('"'); + } else { + sb.append((char)n); + } + } else { + tail.append((char)n); + if (n == '"') { // string concat, in again + in = true; + } else if (n == ',' || n == ')') { // real end + break; + } else if (Character.isWhitespace(n) || n == '+') { + // string concat + } else { + throw new Exception("Not a correct concat"); + } + } + } + String s = sb.toString(); + names.add(s); + fos.write(normalize(s).getBytes()); + fos.write(tail.toString().getBytes()); + } else { + fos.write(ch); + } + } + + // Check pheadlen > 0. Don't want to mess with rewrite for resources + if (pheadlen > 0 && pmatch != match) { + err(" BAD!! pmatch != match: " + pmatch + " != " + match); + } else { + System.err.println(" GOOD match is " + match); + } + + fis.close(); + fos.close(); + return names; + } + + /** + * Normalize a string. Rules: + * + * 1. If all spacebar return "nSPACE", n is count + * 2. If consisting at least one alphanumeric: + * a. All alphanumeric remain + * b. All others in a row goes to a single ".", even if at head or tail + * 3. Otherwise: + * a. "****\n\n" to "STARNN", special case + * b. the English name if first char in *,.\n():'" + * + * Current observations show there's no dup, Hurray! Otherwise, add more + * special cases. + */ + private static String normalize(String s) throws Exception { + boolean needDot = false; + + // All spacebar case + int n = 0; + for (char c: s.toCharArray()) { + if (c == ' ') n++; + else n = -10000; + } + if (n == 1) return "SPACE"; + else if (n > 1) return "" + n + "SPACE"; + + StringBuilder sb = new StringBuilder(); + int dotpos = -1; + for (int i=0; i MAXLEN) { + if (dotpos < 0) throw new Exception("No dot all over? " + s); + return res.substring(0, dotpos); + } else { + return res; + } + } + + private static void err(String string) { + System.out.println("\u001b[1;37;41m" + string + "\u001b[m"); + } +} diff --git a/test/tools/pack200/TestExceptions.java b/test/tools/pack200/TestExceptions.java new file mode 100644 index 0000000000000000000000000000000000000000..0778cf5c7e17fe4a837b9acd4a91e045871cf9c9 --- /dev/null +++ b/test/tools/pack200/TestExceptions.java @@ -0,0 +1,340 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.JarFile; +import java.util.jar.JarInputStream; +import java.util.jar.JarOutputStream; +import java.util.jar.Pack200; + +/* + * @test + * @bug 6985763 + * @summary verify that proper exceptions are thrown + * @compile -XDignore.symbol.file Utils.java TestExceptions.java + * @run main TestExceptions + * @author ksrini + */ + +public class TestExceptions { + + static final File testJar = new File("test.jar"); + static final File testPackFile = new File("test.pack"); + + static void init() { + Utils.jar("cvf", testJar.getAbsolutePath(), "."); + JarFile jf = null; + try { + jf = new JarFile(testJar); + Utils.pack(jf, testPackFile); + } catch (IOException ioe) { + throw new Error("Initialization error", ioe); + } finally { + Utils.close(jf); + } + } + + // a test that closes the input jarFile. + static void pack200Test1() { + PackTestInput ti = null; + // setup the scenario + try { + ti = new PackTestInput(new JarFile(testJar), new ByteArrayOutputStream()); + } catch (Exception e) { + throw new Error("Initialization error", e); + } finally { + Utils.close(ti.getJarFile()); + } + // test the scenario + try { + System.out.println(ti); + Pack200.Packer p = Pack200.newPacker(); + p.pack(ti.getJarFile(), ti.getOutputStream()); + } catch (Exception e) { + ti.checkException(e); + } finally { + if (ti != null) { + ti.close(); + } + } + } + + // test the Pack200.pack(JarFile, OutputStream); + static void pack200Test2() { + List tlist = new ArrayList(); + try { + // setup the test scenarios + try { + tlist.add(new PackTestInput((JarFile)null, null)); + tlist.add(new PackTestInput(new JarFile(testJar), null)); + tlist.add(new PackTestInput((JarFile)null, new ByteArrayOutputStream())); + } catch (Exception e) { + throw new Error("Initialization error", e); + } + + // test the scenarios + for (PackTestInput ti : tlist) { + System.out.println(ti); + try { + Pack200.Packer p = Pack200.newPacker(); + p.pack(ti.getJarFile(), ti.getOutputStream()); + } catch (Exception e) { + ti.checkException(e); + } + } + } finally { // keep jprt happy + for (TestInput ti : tlist) { + if (ti != null) { + ti.close(); + } + } + } + } + + // test the Pack200.pack(JarInputStream, OutputStream); + static void pack200Test3() { + List tlist = new ArrayList(); + try { + // setup the test scenarios + try { + tlist.add(new PackTestJarInputStream((JarInputStream)null, null)); + tlist.add(new PackTestJarInputStream((JarInputStream)null, + new ByteArrayOutputStream())); + tlist.add(new PackTestJarInputStream( + new JarInputStream(new FileInputStream(testJar)), null)); + + } catch (Exception e) { + throw new Error("Initialization error", e); + } + for (PackTestJarInputStream ti : tlist) { + System.out.println(ti); + try { + Pack200.Packer p = Pack200.newPacker(); + p.pack(ti.getJarInputStream(), ti.getOutputStream()); + } catch (Exception e) { + ti.checkException(e); + } + } + } finally { // keep jprt happy + for (PackTestJarInputStream ti : tlist) { + if (ti != null) { + ti.close(); + } + } + } + } + + // test the Pack200.unpack(InputStream, OutputStream); + static void unpack200Test1() { + List tlist = new ArrayList(); + try { + // setup the test scenarios + try { + tlist.add(new UnpackTestInput((InputStream)null, null)); + tlist.add(new UnpackTestInput(new FileInputStream(testPackFile), + null)); + tlist.add(new UnpackTestInput((InputStream) null, + new JarOutputStream(new ByteArrayOutputStream()))); + } catch (Exception e) { + throw new Error("Initialization error", e); + } + + // test the scenarios + for (UnpackTestInput ti : tlist) { + System.out.println(ti); + try { + Pack200.Unpacker unpacker = Pack200.newUnpacker(); + unpacker.unpack(ti.getInputStream(), ti.getJarOutputStream()); + } catch (Exception e) { + ti.checkException(e); + } + } + } finally { // keep jprt happy + for (TestInput ti : tlist) { + if (ti != null) { + ti.close(); + } + } + } + } + + // test the Pack200.unpack(File, OutputStream); + static void unpack200Test2() { + List tlist = new ArrayList(); + try { + // setup the test scenarios + try { + tlist.add(new UnpackTestFileInput((File)null, null)); + tlist.add(new UnpackTestFileInput(testPackFile, null)); + tlist.add(new UnpackTestFileInput((File)null, + new JarOutputStream(new ByteArrayOutputStream()))); + } catch (Exception e) { + throw new Error("Initialization error", e); + } + + // test the scenarios + for (UnpackTestFileInput ti : tlist) { + System.out.println(ti); + try { + Pack200.Unpacker unpacker = Pack200.newUnpacker(); + unpacker.unpack(ti.getInputFile(), ti.getJarOutputStream()); + } catch (Exception e) { + ti.checkException(e); + } + } + } finally { // keep jprt happy + for (TestInput ti : tlist) { + if (ti != null) { + ti.close(); + } + } + } + } + + public static void main(String... args) { + init(); + pack200Test1(); + pack200Test2(); + pack200Test3(); + unpack200Test1(); + } + + // containers for test inputs and management + static abstract class TestInput { + + private final Object in; + private final Object out; + final boolean shouldNPE; + final String testname; + + public TestInput(String name, Object in, Object out) { + this.testname = name; + this.in = in; + this.out = out; + shouldNPE = (in == null || out == null); + } + + @Override + public String toString() { + StringBuilder outStr = new StringBuilder(testname); + outStr.append(", input:").append(in); + outStr.append(", output:").append(this.out); + outStr.append(", should NPE:").append(shouldNPE); + return outStr.toString(); + } + + void close() { + if (in != null && (in instanceof Closeable)) { + Utils.close((Closeable) in); + } + if (out != null && (out instanceof Closeable)) { + Utils.close((Closeable) out); + } + } + + void checkException(Throwable t) { + if (shouldNPE) { + if (t instanceof NullPointerException) { + System.out.println("Got expected exception"); + return; + } else { + throw new RuntimeException("Expected NPE, but got ", t); + } + } + if (t instanceof IOException) { + System.out.println("Got expected exception"); + return; + } else { + throw new RuntimeException("Expected IOException but got ", t); + } + } + } + + static class PackTestInput extends TestInput { + + public PackTestInput(JarFile jf, OutputStream out) { + super("PackTestInput", jf, out); + } + + JarFile getJarFile() { + return (JarFile) super.in; + } + + OutputStream getOutputStream() { + return (OutputStream) super.out; + } + }; + + static class PackTestJarInputStream extends TestInput { + + public PackTestJarInputStream(JarInputStream in, OutputStream out) { + super("PackTestJarInputStream", in, out); + } + + JarInputStream getJarInputStream() { + return (JarInputStream) super.in; + } + + OutputStream getOutputStream() { + return (OutputStream) super.out; + } + }; + + static class UnpackTestInput extends TestInput { + + public UnpackTestInput(InputStream in, JarOutputStream out) { + super("UnpackTestInput", in, out); + } + + InputStream getInputStream() { + return (InputStream) super.in; + } + + JarOutputStream getJarOutputStream() { + return (JarOutputStream) super.out; + } + }; + + static class UnpackTestFileInput extends TestInput { + + public UnpackTestFileInput(File in, JarOutputStream out) { + super("UnpackTestInput", in, out); + } + + File getInputFile() { + return (File) super.in; + } + + JarOutputStream getJarOutputStream() { + return (JarOutputStream) super.out; + } + }; +}

@@ -76,7 +76,7 @@ a:visited,a:visited code{color:#917E9C}
  -

Oracle 尊重您的隐私。我们会将您的个人信息用于通信和 Sun 联机帐户的管理、Sun 联机帐户访问的服务和应用程序以及用于使用 Sun 联机帐户注册的产品和系统。

+

Oracle 尊重您的隐私。我们会将您的个人信息用于通信和 Oracle.com 帐户的管理、Oracle.com 帐户访问的服务和应用程序以及用于使用 Oracle.com 帐户注册的产品和系统。

有关注册过程中收集的数据以及这些数据的管理方式的更多信息,
请访问 http://java.sun.com/javase/registration/JDKRegistrationPrivacy.html

有关 Oracle 隐私政策的更多信息,请访问 http://www.oracle.com/html/privacy.html 或与 privacy_ww@oracle.com 联系。