This commit is contained in:
Vladimir Kozlov 2015-07-02 17:49:11 -07:00
commit 34616cd876
1688 changed files with 734120 additions and 293339 deletions

View File

@ -312,3 +312,4 @@ ff3fc75f3214ad7e03595be1b0d0f38d887b6f0e jdk9-b66
56166ce66037952fa21e9f680b31bf8eb47312c0 jdk9-b67 56166ce66037952fa21e9f680b31bf8eb47312c0 jdk9-b67
5b500c93ce4822d47061cd518ff3f72d9d8cb5b5 jdk9-b68 5b500c93ce4822d47061cd518ff3f72d9d8cb5b5 jdk9-b68
d69c968463f0ae5d0b45de3fc14fe65171b23948 jdk9-b69 d69c968463f0ae5d0b45de3fc14fe65171b23948 jdk9-b69
43d0179ee9de3bfffae3417f09e07eb6d8efc963 jdk9-b70

View File

@ -312,3 +312,4 @@ dc6e8336f51bb6b67b7245766179eab5ca7720b4 jdk9-b66
f546760134eb861fcfecd4ce611b0040b0d25a6a jdk9-b67 f546760134eb861fcfecd4ce611b0040b0d25a6a jdk9-b67
70e4272790b6199e9ca89df2758ff9cb58ec4125 jdk9-b68 70e4272790b6199e9ca89df2758ff9cb58ec4125 jdk9-b68
1bcfd6b8726582cff5a42dbfc75903e36f9dd4fe jdk9-b69 1bcfd6b8726582cff5a42dbfc75903e36f9dd4fe jdk9-b69
eed77fcd77711fcdba05f18fc22f37d86efb243c jdk9-b70

View File

@ -312,3 +312,4 @@ afc1e295c4bf83f9a5dd539c29914edd4a754a3f jdk9-b65
4418697e56f1f43597f55c7cb6573549c6117868 jdk9-b67 4418697e56f1f43597f55c7cb6573549c6117868 jdk9-b67
8efad64f40eb8cd4df376c0a5275892eeb396bbd jdk9-b68 8efad64f40eb8cd4df376c0a5275892eeb396bbd jdk9-b68
de8acedcb5b5870f1dc54cba575aaa5d33897ea2 jdk9-b69 de8acedcb5b5870f1dc54cba575aaa5d33897ea2 jdk9-b69
e7cf01990ed366bd493080663259281e91ce223b jdk9-b70

View File

@ -472,3 +472,4 @@ e7ae94c4f35e940ea423fc1dd260435df34a77c0 jdk9-b65
d47dfabd16d48eb96a451edd1b61194a39ee0eb5 jdk9-b67 d47dfabd16d48eb96a451edd1b61194a39ee0eb5 jdk9-b67
11af3990d56c97b40318bc1f20608e86f051a3f7 jdk9-b68 11af3990d56c97b40318bc1f20608e86f051a3f7 jdk9-b68
ff0929a59ced0e144201aa05819ae2e47d6f2c61 jdk9-b69 ff0929a59ced0e144201aa05819ae2e47d6f2c61 jdk9-b69
8672e9264db30c21504063932dbc374eabc287a1 jdk9-b70

View File

@ -312,3 +312,4 @@ d5963ccce28d7a3e96ee3e2dc8a8676e61699b70 jdk9-b66
78c2685daabafae827c686ca2d1bb2e451faed2b jdk9-b67 78c2685daabafae827c686ca2d1bb2e451faed2b jdk9-b67
82aae947938ec9b0119fdd78a616d0b7263072ee jdk9-b68 82aae947938ec9b0119fdd78a616d0b7263072ee jdk9-b68
f844a908d3308f47d73cf64e87c98d37d5d76ce8 jdk9-b69 f844a908d3308f47d73cf64e87c98d37d5d76ce8 jdk9-b69
42180703e0a362c1de7cdbf61d2cbc6609e678c4 jdk9-b70

View File

@ -24,7 +24,6 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.io.InputStream;
import java.lang.ClassLoader; import java.lang.ClassLoader;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
@ -115,33 +114,6 @@ public final class SecuritySupport {
} }
} }
/**
* Return resource using the same classloader for the ObjectFactory by
* default or bootclassloader when Security Manager is in place
*/
public static InputStream getResourceAsStream(final String name) {
if (System.getSecurityManager() != null) {
return getResourceAsStream(null, name);
} else {
return getResourceAsStream(findClassLoader(), name);
}
}
public static InputStream getResourceAsStream(final ClassLoader cl,
final String name) {
return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = Object.class.getResourceAsStream("/" + name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
/** /**
* Gets a resource bundle using the specified base name, the default locale, * Gets a resource bundle using the specified base name, the default locale,
* and the caller's class loader. * and the caller's class loader.

View File

@ -128,29 +128,10 @@ public final class SecuritySupport {
} }
} }
/**
* Return resource using the same classloader for the ObjectFactory by
* default or bootclassloader when Security Manager is in place
*/
public static InputStream getResourceAsStream(final String name) { public static InputStream getResourceAsStream(final String name) {
if (System.getSecurityManager()!=null) {
return getResourceAsStream(null, name);
} else {
return getResourceAsStream(ObjectFactory.findClassLoader(), name);
}
}
public static InputStream getResourceAsStream(final ClassLoader cl,
final String name) {
return (InputStream) AccessController.doPrivileged(new PrivilegedAction() { return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() { public Object run() {
InputStream ris; return SecuritySupport.class.getResourceAsStream("/"+name);
if (cl == null) {
ris = Object.class.getResourceAsStream("/"+name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
} }
}); });
} }

View File

@ -343,10 +343,7 @@ public class CoreDOMImplementationImpl
*/ */
public LSSerializer createLSSerializer() { public LSSerializer createLSSerializer() {
try { try {
Class serializerClass = ObjectFactory.findProviderClass( return new com.sun.org.apache.xml.internal.serializer.dom3.LSSerializerImpl();
"com.sun.org.apache.xml.internal.serializer.dom3.LSSerializerImpl",
ObjectFactory.findClassLoader(), true);
return (LSSerializer) serializerClass.newInstance();
} }
catch (Exception e) {} catch (Exception e) {}
// Fall back to Xerces' deprecated serializer if // Fall back to Xerces' deprecated serializer if

View File

@ -118,34 +118,6 @@ public final class SecuritySupport {
throw (FileNotFoundException)e.getException(); throw (FileNotFoundException)e.getException();
} }
} }
/**
* Return resource using the same classloader for the ObjectFactory by default
* or bootclassloader when Security Manager is in place
*/
public static InputStream getResourceAsStream(final String name) {
if (System.getSecurityManager()!=null) {
return getResourceAsStream(null, name);
} else {
return getResourceAsStream(ObjectFactory.findClassLoader(), name);
}
}
public static InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = Object.class.getResourceAsStream("/"+name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
/** /**
* Gets a resource bundle using the specified base name, the default locale, and the caller's class loader. * Gets a resource bundle using the specified base name, the default locale, and the caller's class loader.

View File

@ -23,7 +23,6 @@ package com.sun.org.apache.xerces.internal.xinclude;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
@ -113,23 +112,6 @@ final class SecuritySupport {
} }
} }
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = ClassLoader.getSystemResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
boolean getFileExists(final File f) { boolean getFileExists(final File f) {
return ((Boolean) return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() { AccessController.doPrivileged(new PrivilegedAction() {

View File

@ -23,7 +23,6 @@ package com.sun.org.apache.xml.internal.serialize;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
@ -113,23 +112,6 @@ final class SecuritySupport {
} }
} }
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = ClassLoader.getSystemResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
boolean getFileExists(final File f) { boolean getFileExists(final File f) {
return ((Boolean) return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() { AccessController.doPrivileged(new PrivilegedAction() {

View File

@ -36,6 +36,7 @@ import java.util.Properties;
import com.sun.org.apache.xml.internal.serializer.DOM3Serializer; import com.sun.org.apache.xml.internal.serializer.DOM3Serializer;
import com.sun.org.apache.xml.internal.serializer.Encodings; import com.sun.org.apache.xml.internal.serializer.Encodings;
import com.sun.org.apache.xml.internal.serializer.Serializer; import com.sun.org.apache.xml.internal.serializer.Serializer;
import com.sun.org.apache.xml.internal.serializer.ToXMLStream;
import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory; import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory;
import com.sun.org.apache.xml.internal.serializer.SerializerFactory; import com.sun.org.apache.xml.internal.serializer.SerializerFactory;
import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
@ -218,7 +219,8 @@ final public class LSSerializerImpl implements DOMConfiguration, LSSerializer {
// Get a serializer that seriailizes according to the properties, // Get a serializer that seriailizes according to the properties,
// which in this case is to xml // which in this case is to xml
fXMLSerializer = SerializerFactory.getSerializer(configProps); fXMLSerializer = new ToXMLStream();
fXMLSerializer.setOutputFormat(configProps);
// Initialize Serializer // Initialize Serializer
fXMLSerializer.setOutputFormat(fDOMConfigProperties); fXMLSerializer.setOutputFormat(fDOMConfigProperties);
@ -262,9 +264,6 @@ final public class LSSerializerImpl implements DOMConfiguration, LSSerializer {
// entities // entities
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_DEFAULT_TRUE); + DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_DEFAULT_TRUE);
// preserve entities
fDOMConfigProperties.setProperty(
OutputPropertiesFactory.S_KEY_ENTITIES, DOMConstants.S_XSL_VALUE_ENTITIES);
// error-handler // error-handler
// Should we set our default ErrorHandler // Should we set our default ErrorHandler
@ -290,9 +289,6 @@ final public class LSSerializerImpl implements DOMConfiguration, LSSerializer {
+ DOMConstants.DOM_WELLFORMED, DOMConstants.DOM3_DEFAULT_TRUE); + DOMConstants.DOM_WELLFORMED, DOMConstants.DOM3_DEFAULT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_DEFAULT_FALSE); + DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_DEFAULT_FALSE);
// preserve entities
fDOMConfigProperties.setProperty(
OutputPropertiesFactory.S_KEY_ENTITIES, "");
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_CDATA_SECTIONS, + DOMConstants.DOM_CDATA_SECTIONS,
DOMConstants.DOM3_DEFAULT_FALSE); DOMConstants.DOM3_DEFAULT_FALSE);
@ -531,8 +527,6 @@ final public class LSSerializerImpl implements DOMConfiguration, LSSerializer {
if (state) { if (state) {
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_EXPLICIT_TRUE); + DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(
OutputPropertiesFactory.S_KEY_ENTITIES, DOMConstants.S_XSL_VALUE_ENTITIES);
} else { } else {
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_EXPLICIT_FALSE); + DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_EXPLICIT_FALSE);
@ -679,31 +673,29 @@ final public class LSSerializerImpl implements DOMConfiguration, LSSerializer {
fFeatures |= WELLFORMED; fFeatures |= WELLFORMED;
fFeatures |= ELEM_CONTENT_WHITESPACE; fFeatures |= ELEM_CONTENT_WHITESPACE;
fFeatures |= COMMENTS; fFeatures |= COMMENTS;
// infoset
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_NAMESPACES, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_NAMESPACE_DECLARATIONS, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_COMMENTS, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_ELEMENT_CONTENT_WHITESPACE, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_WELLFORMED, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_EXPLICIT_FALSE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_CDATA_SECTIONS, DOMConstants.DOM3_EXPLICIT_FALSE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_VALIDATE_IF_SCHEMA, DOMConstants.DOM3_EXPLICIT_FALSE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_DATATYPE_NORMALIZATION, DOMConstants.DOM3_EXPLICIT_FALSE);
} }
// infoset
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_NAMESPACES, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_NAMESPACE_DECLARATIONS, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_COMMENTS, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_ELEMENT_CONTENT_WHITESPACE, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_WELLFORMED, DOMConstants.DOM3_EXPLICIT_TRUE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_ENTITIES, DOMConstants.DOM3_EXPLICIT_FALSE);
fDOMConfigProperties.setProperty(
OutputPropertiesFactory.S_KEY_ENTITIES, "");
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_CDATA_SECTIONS, DOMConstants.DOM3_EXPLICIT_FALSE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_VALIDATE_IF_SCHEMA, DOMConstants.DOM3_EXPLICIT_FALSE);
fDOMConfigProperties.setProperty(DOMConstants.S_DOM3_PROPERTIES_NS
+ DOMConstants.DOM_DATATYPE_NORMALIZATION, DOMConstants.DOM3_EXPLICIT_FALSE);
} else if (name.equalsIgnoreCase(DOMConstants.DOM_NORMALIZE_CHARACTERS)) { } else if (name.equalsIgnoreCase(DOMConstants.DOM_NORMALIZE_CHARACTERS)) {
String msg = Utils.messages.createMessage( String msg = Utils.messages.createMessage(
MsgKey.ER_FEATURE_NOT_SUPPORTED, MsgKey.ER_FEATURE_NOT_SUPPORTED,

View File

@ -27,11 +27,9 @@ import java.io.InputStream;
import java.util.Properties; import java.util.Properties;
import com.sun.org.apache.xpath.internal.XPathContext; import com.sun.org.apache.xpath.internal.XPathContext;
import com.sun.org.apache.xpath.internal.objects.XNumber;
import com.sun.org.apache.xpath.internal.objects.XObject; import com.sun.org.apache.xpath.internal.objects.XObject;
import com.sun.org.apache.xpath.internal.objects.XString; import com.sun.org.apache.xpath.internal.objects.XString;
import com.sun.org.apache.xpath.internal.res.XPATHErrorResources; import com.sun.org.apache.xpath.internal.res.XPATHErrorResources;
import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
import com.sun.org.apache.xalan.internal.utils.SecuritySupport; import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
/** /**
@ -69,7 +67,7 @@ public class FuncSystemProperty extends FunctionOneArg
// property argument is to be looked for. // property argument is to be looked for.
Properties xsltInfo = new Properties(); Properties xsltInfo = new Properties();
loadPropertyFile(XSLT_PROPERTIES, xsltInfo); loadPropertyFile(xsltInfo);
if (indexOfNSSep > 0) if (indexOfNSSep > 0)
{ {
@ -159,25 +157,21 @@ public class FuncSystemProperty extends FunctionOneArg
} }
/** /**
* Retrieve a propery bundle from a specified file * Retrieve a property bundle from XSLT_PROPERTIES
* *
* @param file The string name of the property file. The name
* should already be fully qualified as path/filename
* @param target The target property bag the file will be placed into. * @param target The target property bag the file will be placed into.
*/ */
public void loadPropertyFile(String file, Properties target) private void loadPropertyFile(Properties target)
{ {
try try
{ {
// Use SecuritySupport class to provide priveleged access to property file // Use SecuritySupport class to provide privileged access to property file
InputStream is = SecuritySupport.getResourceAsStream(ObjectFactory.findClassLoader(), InputStream is = SecuritySupport.getResourceAsStream(XSLT_PROPERTIES);
file);
// get a buffered version // get a buffered version
BufferedInputStream bis = new BufferedInputStream(is); try (BufferedInputStream bis = new BufferedInputStream(is)) {
target.load(bis); // and load up the property bag from this
target.load(bis); // and load up the property bag from this }
bis.close(); // close out after reading
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -26,9 +26,7 @@
package javax.xml.datatype; package javax.xml.datatype;
import java.security.*; import java.security.*;
import java.net.*;
import java.io.*; import java.io.*;
import java.util.*;
/** /**
* This class is duplicated for each JAXP subpackage so keep it in sync. * This class is duplicated for each JAXP subpackage so keep it in sync.
@ -77,23 +75,6 @@ class SecuritySupport {
} }
} }
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = Object.class.getResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
boolean doesFileExist(final File f) { boolean doesFileExist(final File f) {
return ((Boolean) return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() { AccessController.doPrivileged(new PrivilegedAction() {

View File

@ -26,9 +26,7 @@
package javax.xml.parsers; package javax.xml.parsers;
import java.security.*; import java.security.*;
import java.net.*;
import java.io.*; import java.io.*;
import java.util.*;
/** /**
* This class is duplicated for each JAXP subpackage so keep it in sync. * This class is duplicated for each JAXP subpackage so keep it in sync.
@ -81,23 +79,6 @@ class SecuritySupport {
} }
} }
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = Object.class.getResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
boolean doesFileExist(final File f) { boolean doesFileExist(final File f) {
return ((Boolean) return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() { AccessController.doPrivileged(new PrivilegedAction() {

View File

@ -26,9 +26,7 @@
package javax.xml.stream; package javax.xml.stream;
import java.security.*; import java.security.*;
import java.net.*;
import java.io.*; import java.io.*;
import java.util.*;
/** /**
* This class is duplicated for each JAXP subpackage so keep it in sync. * This class is duplicated for each JAXP subpackage so keep it in sync.
@ -81,23 +79,6 @@ class SecuritySupport {
} }
} }
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = Object.class.getResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
boolean doesFileExist(final File f) { boolean doesFileExist(final File f) {
return ((Boolean) return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() { AccessController.doPrivileged(new PrivilegedAction() {

View File

@ -26,9 +26,7 @@
package javax.xml.transform; package javax.xml.transform;
import java.security.*; import java.security.*;
import java.net.*;
import java.io.*; import java.io.*;
import java.util.*;
/** /**
* This class is duplicated for each JAXP subpackage so keep it in sync. * This class is duplicated for each JAXP subpackage so keep it in sync.
@ -79,23 +77,6 @@ class SecuritySupport {
} }
} }
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = Object.class.getResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
boolean doesFileExist(final File f) { boolean doesFileExist(final File f) {
return ((Boolean) return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() { AccessController.doPrivileged(new PrivilegedAction() {

View File

@ -418,30 +418,8 @@ class SchemaFactoryFinder {
private static final Class<SchemaFactory> SERVICE_CLASS = SchemaFactory.class; private static final Class<SchemaFactory> SERVICE_CLASS = SchemaFactory.class;
// Used for debugging purposes
private static String which( Class<?> clazz ) { private static String which( Class<?> clazz ) {
return which( clazz.getName(), clazz.getClassLoader() ); return ss.getClassSource(clazz);
}
/**
* <p>Search the specified classloader for the given classname.</p>
*
* @param classname the fully qualified name of the class to search for
* @param loader the classloader to search
*
* @return the source location of the resource, or null if it wasn't found
*/
private static String which(String classname, ClassLoader loader) {
String classnameAsResource = classname.replace('.', '/') + ".class";
if( loader==null ) loader = ClassLoader.getSystemClassLoader();
//URL it = loader.getResource(classnameAsResource);
URL it = ss.getResourceAsURL(loader, classnameAsResource);
if (it != null) {
return it.toString();
} else {
return null;
}
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -25,12 +25,9 @@
package javax.xml.validation; package javax.xml.validation;
import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.security.*; import java.security.*;
import java.net.*;
import java.io.*; import java.io.*;
import java.util.*;
/** /**
* This class is duplicated for each JAXP subpackage so keep it in sync. * This class is duplicated for each JAXP subpackage so keep it in sync.
@ -43,9 +40,10 @@ class SecuritySupport {
ClassLoader getContextClassLoader() { ClassLoader getContextClassLoader() {
return (ClassLoader) return
AccessController.doPrivileged(new PrivilegedAction() { AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public Object run() { @Override
public ClassLoader run() {
ClassLoader cl = null; ClassLoader cl = null;
//try { //try {
cl = Thread.currentThread().getContextClassLoader(); cl = Thread.currentThread().getContextClassLoader();
@ -58,9 +56,9 @@ class SecuritySupport {
} }
String getSystemProperty(final String propName) { String getSystemProperty(final String propName) {
return (String) return AccessController.doPrivileged(new PrivilegedAction<String>() {
AccessController.doPrivileged(new PrivilegedAction() { @Override
public Object run() { public String run() {
return System.getProperty(propName); return System.getProperty(propName);
} }
}); });
@ -70,9 +68,10 @@ class SecuritySupport {
throws FileNotFoundException throws FileNotFoundException
{ {
try { try {
return (FileInputStream) return AccessController.doPrivileged(
AccessController.doPrivileged(new PrivilegedExceptionAction() { new PrivilegedExceptionAction<FileInputStream>() {
public Object run() throws FileNotFoundException { @Override
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(file); return new FileInputStream(file);
} }
}); });
@ -81,83 +80,29 @@ class SecuritySupport {
} }
} }
InputStream getURLInputStream(final URL url) // Used for debugging purposes
throws IOException String getClassSource(Class<?> cls) {
{ return AccessController.doPrivileged(new PrivilegedAction<String>() {
try { @Override
return (InputStream) public String run() {
AccessController.doPrivileged(new PrivilegedExceptionAction() { CodeSource cs = cls.getProtectionDomain().getCodeSource();
public Object run() throws IOException { if (cs != null) {
return url.openStream(); URL loc = cs.getLocation();
} return loc != null ? loc.toString() : "(no location)";
}); } else {
} catch (PrivilegedActionException e) { return "(no code source)";
throw (IOException)e.getException();
}
}
URL getResourceAsURL(final ClassLoader cl,
final String name)
{
return (URL)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
URL url;
if (cl == null) {
url = Object.class.getResource(name);
} else {
url = cl.getResource(name);
}
return url;
} }
}); }
} });
Enumeration getResources(final ClassLoader cl,
final String name) throws IOException
{
try{
return (Enumeration)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException{
Enumeration enumeration;
if (cl == null) {
enumeration = ClassLoader.getSystemResources(name);
} else {
enumeration = cl.getResources(name);
}
return enumeration;
}
});
}catch(PrivilegedActionException e){
throw (IOException)e.getException();
}
}
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = Object.class.getResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
} }
boolean doesFileExist(final File f) { boolean doesFileExist(final File f) {
return ((Boolean) return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
AccessController.doPrivileged(new PrivilegedAction() { @Override
public Object run() { public Boolean run() {
return new Boolean(f.exists()); return f.exists();
} }
})).booleanValue(); });
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -27,9 +27,7 @@ package javax.xml.xpath;
import java.net.URL; import java.net.URL;
import java.security.*; import java.security.*;
import java.net.*;
import java.io.*; import java.io.*;
import java.util.*;
/** /**
* This class is duplicated for each JAXP subpackage so keep it in sync. * This class is duplicated for each JAXP subpackage so keep it in sync.
@ -42,9 +40,9 @@ class SecuritySupport {
ClassLoader getContextClassLoader() { ClassLoader getContextClassLoader() {
return (ClassLoader) return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
AccessController.doPrivileged(new PrivilegedAction() { @Override
public Object run() { public ClassLoader run() {
ClassLoader cl = null; ClassLoader cl = null;
try { try {
cl = Thread.currentThread().getContextClassLoader(); cl = Thread.currentThread().getContextClassLoader();
@ -55,21 +53,22 @@ class SecuritySupport {
} }
String getSystemProperty(final String propName) { String getSystemProperty(final String propName) {
return (String) return AccessController.doPrivileged(new PrivilegedAction<String>() {
AccessController.doPrivileged(new PrivilegedAction() { @Override
public Object run() { public String run() {
return System.getProperty(propName); return System.getProperty(propName);
} }
}); });
} }
FileInputStream getFileInputStream(final File file) FileInputStream getFileInputStream(final File file)
throws FileNotFoundException throws FileNotFoundException
{ {
try { try {
return (FileInputStream) return AccessController.doPrivileged(
AccessController.doPrivileged(new PrivilegedExceptionAction() { new PrivilegedExceptionAction<FileInputStream>() {
public Object run() throws FileNotFoundException { @Override
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(file); return new FileInputStream(file);
} }
}); });
@ -78,83 +77,29 @@ class SecuritySupport {
} }
} }
InputStream getURLInputStream(final URL url) // Used for debugging purposes
throws IOException String getClassSource(Class<?> cls) {
{ return AccessController.doPrivileged(new PrivilegedAction<String>() {
try { @Override
return (InputStream) public String run() {
AccessController.doPrivileged(new PrivilegedExceptionAction() { CodeSource cs = cls.getProtectionDomain().getCodeSource();
public Object run() throws IOException { if (cs != null) {
return url.openStream(); URL loc = cs.getLocation();
} return loc != null ? loc.toString() : "(no location)";
}); } else {
} catch (PrivilegedActionException e) { return "(no code source)";
throw (IOException)e.getException();
}
}
URL getResourceAsURL(final ClassLoader cl,
final String name)
{
return (URL)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
URL url;
if (cl == null) {
url = Object.class.getResource(name);
} else {
url = cl.getResource(name);
}
return url;
} }
}); }
} });
Enumeration getResources(final ClassLoader cl,
final String name) throws IOException
{
try{
return (Enumeration)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException{
Enumeration enumeration;
if (cl == null) {
enumeration = ClassLoader.getSystemResources(name);
} else {
enumeration = cl.getResources(name);
}
return enumeration;
}
});
}catch(PrivilegedActionException e){
throw (IOException)e.getException();
}
}
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = Object.class.getResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
} }
boolean doesFileExist(final File f) { boolean doesFileExist(final File f) {
return ((Boolean) return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
AccessController.doPrivileged(new PrivilegedAction() { @Override
public Object run() { public Boolean run() {
return new Boolean(f.exists()); return f.exists();
} }
})).booleanValue(); });
} }
} }

View File

@ -414,30 +414,9 @@ class XPathFactoryFinder {
private static final Class<XPathFactory> SERVICE_CLASS = XPathFactory.class; private static final Class<XPathFactory> SERVICE_CLASS = XPathFactory.class;
private static String which( Class clazz ) { // Used for debugging purposes
return which( clazz.getName(), clazz.getClassLoader() ); private static String which( Class<?> clazz ) {
return ss.getClassSource(clazz);
} }
/**
* <p>Search the specified classloader for the given classname.</p>
*
* @param classname the fully qualified name of the class to search for
* @param loader the classloader to search
*
* @return the source location of the resource, or null if it wasn't found
*/
private static String which(String classname, ClassLoader loader) {
String classnameAsResource = classname.replace('.', '/') + ".class";
if( loader==null ) loader = ClassLoader.getSystemClassLoader();
//URL it = loader.getResource(classnameAsResource);
URL it = ss.getResourceAsURL(loader, classnameAsResource);
if (it != null) {
return it.toString();
} else {
return null;
}
}
} }

View File

@ -87,7 +87,7 @@ class SecuritySupport {
public Object run() { public Object run() {
InputStream ris; InputStream ris;
if (cl == null) { if (cl == null) {
ris = Object.class.getResourceAsStream(name); ris = SecuritySupport.class.getResourceAsStream(name);
} else { } else {
ris = cl.getResourceAsStream(name); ris = cl.getResourceAsStream(name);
} }

View File

@ -29,5 +29,8 @@ tier1 =
tier2 = \ tier2 = \
:jaxp_all :jaxp_all
# No tier 3 tests.
tier3 =
jaxp_all = \ jaxp_all = \
javax/xml/jaxp javax/xml/jaxp

View File

@ -101,7 +101,6 @@ public class LSSerializerTest {
/* /*
* @bug 8080906 * @bug 8080906
* It will fail in a Jigsaw build until JDK-8080266 is fixed.
*/ */
@Test @Test
public void testDefaultLSSerializer() throws Exception { public void testDefaultLSSerializer() throws Exception {
@ -134,6 +133,9 @@ public class LSSerializerTest {
DOMImplementation impl = doc.getImplementation(); DOMImplementation impl = doc.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0"); DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
LSSerializer writer = implLS.createLSSerializer(); LSSerializer writer = implLS.createLSSerializer();
System.out.println("Serializer is: " + implLS.getClass().getName() + " " + implLS);
DOMErrorHandlerImpl eh = new DOMErrorHandlerImpl(); DOMErrorHandlerImpl eh = new DOMErrorHandlerImpl();
writer.getDomConfig().setParameter("error-handler", eh); writer.getDomConfig().setParameter("error-handler", eh);
@ -200,6 +202,8 @@ public class LSSerializerTest {
DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation; DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;
LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
System.out.println("Serializer is: " + lsSerializer.getClass().getName() + " " + lsSerializer);
// get configuration // get configuration
DOMConfiguration domConfiguration = lsSerializer.getDomConfig(); DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
@ -294,6 +298,8 @@ public class LSSerializerTest {
DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation; DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;
LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
System.out.println("Serializer is: " + lsSerializer.getClass().getName() + " " + lsSerializer);
// get default serialization // get default serialization
String defaultSerialization = lsSerializer.writeToString(document); String defaultSerialization = lsSerializer.writeToString(document);

View File

@ -315,3 +315,4 @@ df100399ed27d0eaa57c137ca99819a0fee66178 jdk9-b64
c9785bc8ade98a16a050d7520b70c68363857e00 jdk9-b67 c9785bc8ade98a16a050d7520b70c68363857e00 jdk9-b67
b5878b03d1b2e105917d959fbfa3c57c22495803 jdk9-b68 b5878b03d1b2e105917d959fbfa3c57c22495803 jdk9-b68
f5911c6155c29ac24b6f9068273207e5ebd3a3df jdk9-b69 f5911c6155c29ac24b6f9068273207e5ebd3a3df jdk9-b69
94084caa27a3c8a09a7510aef596ebd64e97c569 jdk9-b70

View File

@ -23,6 +23,9 @@
* questions. * questions.
*/ */
/**
* This package defines APIs related to WS-Addressing.
*/
@javax.xml.bind.annotation.XmlSchema(namespace=W3CEndpointReference.NS, @javax.xml.bind.annotation.XmlSchema(namespace=W3CEndpointReference.NS,
location="http://www.w3.org/2006/03/addressing/ws-addr.xsd") location="http://www.w3.org/2006/03/addressing/ws-addr.xsd")
package javax.xml.ws.wsaddressing; package javax.xml.ws.wsaddressing;

View File

@ -1,30 +0,0 @@
<!--
Copyright (c) 2005, 2012, 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.
-->
<html>
<body>
This package defines APIs related to WS-Addressing.
</body>
</html>

View File

@ -312,3 +312,4 @@ ed94f3e7ba6bbfec0772de6d24e39543e13f6d88 jdk9-b65
1abd45df5480a04bff98fba1851d66a5230e67d4 jdk9-b67 1abd45df5480a04bff98fba1851d66a5230e67d4 jdk9-b67
046fd17bb9a0cdf6681124866df9626d17b0516a jdk9-b68 046fd17bb9a0cdf6681124866df9626d17b0516a jdk9-b68
551323004d0ce2f1d4b0e99552f7e0cdcebc6fca jdk9-b69 551323004d0ce2f1d4b0e99552f7e0cdcebc6fca jdk9-b69
a7f731125b7fb0e4b0186172f85a21e2d5139f7e jdk9-b70

View File

@ -26,6 +26,7 @@
include GensrcCommon.gmk include GensrcCommon.gmk
include GensrcLocaleData.gmk include GensrcLocaleData.gmk
include GensrcCLDR.gmk
include GensrcCharacterData.gmk include GensrcCharacterData.gmk
include GensrcMisc.gmk include GensrcMisc.gmk
include GensrcCharsetMapping.gmk include GensrcCharsetMapping.gmk

View File

@ -23,19 +23,30 @@
# questions. # questions.
# #
CLDRVERSION := 21.0.1 CLDRVERSION := 27.0.0
CLDRSRCDIR := $(JDK_TOPDIR)/src/jdk.localedata/share/classes/sun/util/cldr/resources/$(subst .,_,$(CLDRVERSION)) CLDRSRCDIR := $(JDK_TOPDIR)/src/jdk.localedata/share/classes/sun/util/cldr/resources/$(subst .,_,$(CLDRVERSION))
GENSRC_BASEDIR := $(SUPPORT_OUTPUTDIR)/gensrc/java.base
GENSRC_DIR := $(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata GENSRC_DIR := $(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata
CLDR_METAINFO_FILE := $(GENSRC_DIR)/sun/util/resources/cldr/provider/CLDRLocaleDataMetaInfo.java CLDR_BASEMETAINFO_FILE := $(GENSRC_DIR)/sun/util/cldr/CLDRBaseLocaleDataMetaInfo.java
CLDR_METAINFO_FILE := $(GENSRC_DIR)/sun/util/resources/cldr/provider/CLDRLocaleDataMetaInfo_jdk_localedata.java
CLDR_BASE_LOCALES := "en-US"
$(CLDR_BASEMETAINFO_FILE): $(wildcard $(CLDRSRCDIR)/common/dtd/*.dtd) \
$(wildcard $(CLDRSRCDIR)/common/main/en*.xml) \
$(wildcard $(CLDRSRCDIR)/common/supplemental/*.xml) \
$(BUILD_TOOLS_JDK)
$(MKDIR) -p $(GENSRC_BASEDIR)
$(TOOL_CLDRCONVERTER) -base $(CLDRSRCDIR) -baselocales $(CLDR_BASE_LOCALES) -basemodule -o $(GENSRC_BASEDIR)
$(CLDR_METAINFO_FILE): $(wildcard $(CLDRSRCDIR)/common/dtd/*.dtd) \ $(CLDR_METAINFO_FILE): $(wildcard $(CLDRSRCDIR)/common/dtd/*.dtd) \
$(wildcard $(CLDRSRCDIR)/common/main/*.xml) \ $(wildcard $(CLDRSRCDIR)/common/main/*.xml) \
$(wildcard $(CLDRSRCDIR)/common/supplemental/*.xml) \ $(wildcard $(CLDRSRCDIR)/common/supplemental/*.xml) \
$(BUILD_TOOLS_JDK) $(BUILD_TOOLS_JDK)
$(MKDIR) -p $(GENSRC_DIR) $(MKDIR) -p $(GENSRC_DIR)
$(TOOL_CLDRCONVERTER) -base $(CLDRSRCDIR) -o $(GENSRC_DIR) $(TOOL_CLDRCONVERTER) -base $(CLDRSRCDIR) -baselocales $(CLDR_BASE_LOCALES) -o $(GENSRC_DIR)
GENSRC_CLDR := $(CLDR_METAINFO_FILE) GENSRC_JAVA_BASE += $(CLDR_BASEMETAINFO_FILE)
GENSRC_JDK_LOCALEDATA += $(GENSRC_CLDR) GENSRC_JDK_LOCALEDATA += $(CLDR_METAINFO_FILE)

View File

@ -42,51 +42,54 @@ LOCALE_FILES := $(shell $(FIND) $(JDK_TOPDIR)/src/java.base/share/classes \
LOCALE_RESOURCES := $(sort $(subst .properties,,$(subst .java,,$(notdir $(LOCALE_FILES))))) LOCALE_RESOURCES := $(sort $(subst .properties,,$(subst .java,,$(notdir $(LOCALE_FILES)))))
# Include the list of resources found during the previous compile. # Include the list of resources found during the previous compile.
-include $(SUPPORT_OUTPUTDIR)/gensrc/java.base/_the.locale_resources -include $(SUPPORT_OUTPUTDIR)/gensrc/_the.locale_resources
MISSING_RESOURCES := $(filter-out $(LOCALE_RESOURCES), $(PREV_LOCALE_RESOURCES)) MISSING_RESOURCES := $(filter-out $(LOCALE_RESOURCES), $(PREV_LOCALE_RESOURCES))
NEW_RESOURCES := $(filter-out $(PREV_LOCALE_RESOURCES), $(LOCALE_RESOURCES)) NEW_RESOURCES := $(filter-out $(PREV_LOCALE_RESOURCES), $(LOCALE_RESOURCES))
ifneq (, $(MISSING_RESOURCES)$(NEW_RESOURCES)) ifneq (, $(MISSING_RESOURCES)$(NEW_RESOURCES))
# There is a difference in the number of supported resources. Trigger a regeneration. # There is a difference in the number of supported resources. Trigger a regeneration.
$(shell $(RM) $(SUPPORT_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/LocaleDataMetaInfo.java) $(shell $(RM) $(SUPPORT_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/BaseLocaleDataMetaInfo.java \
$(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonBaseLocaleDataMetaInfo.java \
$(SUPPORT_OUTPUTDIR)/gensrc/java.base/sun/util/cldr/CLDRBaseLocaleDataMetaInfo.java \
$(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/cldr/provider/CLDRLocaleDataMetaInfo_jdk_localedata.java)
endif endif
# The EN locales # The base locales
EN_LOCALES := en% BASE_LOCALES := en en-US
# Locales that don't have any resource files should be included here. # Locales that don't have any resource files should be included here.
ALL_NON_EN_LOCALES := ja-JP-JP nb-NO nn-NO th-TH-TH ALL_NON_BASE_LOCALES := ja-JP-JP nb-NO nn-NO th-TH-TH
SED_ENARGS := -e 's|$(HASH)warn This file is preprocessed before being compiled|// -- This file was mechanically generated: Do not edit! -- //|g' SED_BASEARGS := -e 's|$(HASH)warn This file is preprocessed before being compiled|// -- This file was mechanically generated: Do not edit! -- //|g'
SED_NONENARGS := $(SED_ENARGS) SED_NONBASEARGS := $(SED_BASEARGS)
# Fill in the languages and package names # Fill in the languages and package names
SED_ENARGS += -e 's/$(HASH)Lang$(HASH)/En/' \ SED_BASEARGS += -e 's/$(HASH)Lang$(HASH)/Base/' \
-e 's/$(HASH)Package$(HASH)/sun.util.locale.provider/' -e 's/$(HASH)Package$(HASH)/sun.util.locale.provider/'
SED_NONENARGS += -e 's/$(HASH)Lang$(HASH)/NonEn/' \ SED_NONBASEARGS += -e 's/$(HASH)Lang$(HASH)/NonBase/' \
-e 's/$(HASH)Package$(HASH)/sun.util.resources.provider/' -e 's/$(HASH)Package$(HASH)/sun.util.resources.provider/'
# This macro creates a sed expression that substitues for example: # This macro creates a sed expression that substitues for example:
# #FormatData_ENLocales# with: en% locales. # #FormatData_Locales# with: en-US locales.
define CaptureLocale define CaptureLocale
$1_LOCALES := $$(subst _,-,$$(filter-out $1, $$(subst $1_,,$$(filter $1_%, $(LOCALE_RESOURCES))))) $1_LOCALES := $$(subst _,-,$$(filter-out $1, $$(subst $1_,,$$(filter $1_%, $(LOCALE_RESOURCES)))))
$1_EN_LOCALES := $$(filter $(EN_LOCALES), $$($1_LOCALES)) $1_BASE_LOCALES := $$(filter $(BASE_LOCALES), $$($1_LOCALES))
$1_NON_EN_LOCALES := $$(filter-out $(EN_LOCALES), $$($1_LOCALES)) $1_NON_BASE_LOCALES := $$(filter-out $(BASE_LOCALES), $$($1_LOCALES))
# Special handling for Chinese locales to include implicit scripts # Special handling for Chinese locales to include implicit scripts
$1_NON_EN_LOCALES := $$(subst zh-CN,zh-CN$$(SPACE)zh-Hans-CN, $$($1_NON_EN_LOCALES)) $1_NON_BASE_LOCALES := $$(subst zh-CN,zh-CN$$(SPACE)zh-Hans-CN, $$($1_NON_BASE_LOCALES))
$1_NON_EN_LOCALES := $$(subst zh-SG,zh-SG$$(SPACE)zh-Hans-SG, $$($1_NON_EN_LOCALES)) $1_NON_BASE_LOCALES := $$(subst zh-SG,zh-SG$$(SPACE)zh-Hans-SG, $$($1_NON_BASE_LOCALES))
$1_NON_EN_LOCALES := $$(subst zh-HK,zh-HK$$(SPACE)zh-Hant-HK, $$($1_NON_EN_LOCALES)) $1_NON_BASE_LOCALES := $$(subst zh-HK,zh-HK$$(SPACE)zh-Hant-HK, $$($1_NON_BASE_LOCALES))
$1_NON_EN_LOCALES := $$(subst zh-MO,zh-MO$$(SPACE)zh-Hant-MO, $$($1_NON_EN_LOCALES)) $1_NON_BASE_LOCALES := $$(subst zh-MO,zh-MO$$(SPACE)zh-Hant-MO, $$($1_NON_BASE_LOCALES))
$1_NON_EN_LOCALES := $$(subst zh-TW,zh-TW$$(SPACE)zh-Hant-TW, $$($1_NON_EN_LOCALES)) $1_NON_BASE_LOCALES := $$(subst zh-TW,zh-TW$$(SPACE)zh-Hant-TW, $$($1_NON_BASE_LOCALES))
ALL_EN_LOCALES += $$($1_EN_LOCALES) ALL_BASE_LOCALES += $$($1_BASE_LOCALES)
ALL_NON_EN_LOCALES += $$($1_NON_EN_LOCALES) ALL_NON_BASE_LOCALES += $$($1_NON_BASE_LOCALES)
# Don't sed in a space if there are no locales. # Don't sed in a space if there are no locales.
SED_ENARGS += -e 's/$$(HASH)$1_Locales$$(HASH)/$$(if $$($1_EN_LOCALES),$$(SPACE)$$($1_EN_LOCALES),)/g' SED_BASEARGS += -e 's/$$(HASH)$1_Locales$$(HASH)/$$(if $$($1_BASE_LOCALES),$$(SPACE)$$($1_BASE_LOCALES),)/g'
SED_NONENARGS += -e 's/$$(HASH)$1_Locales$$(HASH)/$$(if $$($1_NON_EN_LOCALES),$$(SPACE)$$($1_NON_EN_LOCALES),)/g' SED_NONBASEARGS += -e 's/$$(HASH)$1_Locales$$(HASH)/$$(if $$($1_NON_BASE_LOCALES),$$(SPACE)$$($1_NON_BASE_LOCALES),)/g'
endef endef
#sun.text.resources.FormatData #sun.text.resources.FormatData
@ -113,27 +116,27 @@ $(eval $(call CaptureLocale,CurrencyNames))
#sun.util.resources.CalendarData #sun.util.resources.CalendarData
$(eval $(call CaptureLocale,CalendarData)) $(eval $(call CaptureLocale,CalendarData))
SED_ENARGS += -e 's/$(HASH)AvailableLocales_Locales$(HASH)/$(sort $(ALL_EN_LOCALES))/g' SED_BASEARGS += -e 's/$(HASH)AvailableLocales_Locales$(HASH)/$(sort $(ALL_BASE_LOCALES))/g'
SED_NONENARGS += -e 's/$(HASH)AvailableLocales_Locales$(HASH)/$(sort $(ALL_NON_EN_LOCALES))/g' SED_NONBASEARGS += -e 's/$(HASH)AvailableLocales_Locales$(HASH)/$(sort $(ALL_NON_BASE_LOCALES))/g'
$(SUPPORT_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/EnLocaleDataMetaInfo.java: \ $(SUPPORT_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/BaseLocaleDataMetaInfo.java: \
$(JDK_TOPDIR)/src/java.base/share/classes/sun/util/locale/provider/LocaleDataMetaInfo-XLocales.java.template $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/locale/provider/LocaleDataMetaInfo-XLocales.java.template
$(MKDIR) -p $(@D) $(MKDIR) -p $(@D)
$(ECHO) Creating sun/util/locale/provider/EnLocaleDataMetaInfo.java from $(words $(LOCALE_RESOURCES)) found resources. $(ECHO) Creating sun/util/locale/provider/BaseLocaleDataMetaInfo.java from $(words $(LOCALE_RESOURCES)) found resources.
$(PRINTF) "PREV_LOCALE_RESOURCES:=$(LOCALE_RESOURCES)" \ $(PRINTF) "PREV_LOCALE_RESOURCES:=$(LOCALE_RESOURCES)" \
> $(SUPPORT_OUTPUTDIR)/gensrc/_the.locale_resources > $(SUPPORT_OUTPUTDIR)/gensrc/_the.locale_resources
$(SED) $(SED_ENARGS) $< > $@ $(SED) $(SED_BASEARGS) $< > $@
$(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonEnLocaleDataMetaInfo.java: \ $(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonBaseLocaleDataMetaInfo.java: \
$(JDK_TOPDIR)/src/java.base/share/classes/sun/util/locale/provider/LocaleDataMetaInfo-XLocales.java.template $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/locale/provider/LocaleDataMetaInfo-XLocales.java.template
$(MKDIR) -p $(@D) $(MKDIR) -p $(@D)
$(ECHO) Creating sun/util/resources/provider/NonEnLocaleDataMetaInfo.java from $(words $(LOCALE_RESOURCES)) found resources. $(ECHO) Creating sun/util/resources/provider/NonBaseLocaleDataMetaInfo.java from $(words $(LOCALE_RESOURCES)) found resources.
$(PRINTF) "PREV_LOCALE_RESOURCES:=$(LOCALE_RESOURCES)" \ $(PRINTF) "PREV_LOCALE_RESOURCES:=$(LOCALE_RESOURCES)" \
> $(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata/_the.locale_resources > $(SUPPORT_OUTPUTDIR)/gensrc/_the.locale_resources
$(SED) $(SED_NONENARGS) $< > $@ $(SED) $(SED_NONBASEARGS) $< > $@
GENSRC_BASELOCALEDATA := $(SUPPORT_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/EnLocaleDataMetaInfo.java GENSRC_BASELOCALEDATA := $(SUPPORT_OUTPUTDIR)/gensrc/java.base/sun/util/locale/provider/BaseLocaleDataMetaInfo.java
GENSRC_LOCALEDATA := $(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonEnLocaleDataMetaInfo.java GENSRC_LOCALEDATA := $(SUPPORT_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/provider/NonBaseLocaleDataMetaInfo.java
################################################################################ ################################################################################

View File

@ -161,7 +161,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJAVA, \
-export:getLastErrorString \ -export:getLastErrorString \
jvm.lib $(BUILD_LIBFDLIBM) $(WIN_VERIFY_LIB) \ jvm.lib $(BUILD_LIBFDLIBM) $(WIN_VERIFY_LIB) \
shell32.lib delayimp.lib -DELAYLOAD:shell32.dll \ shell32.lib delayimp.lib -DELAYLOAD:shell32.dll \
advapi32.lib, \ advapi32.lib version.lib, \
VERSIONINFO_RESOURCE := $(GLOBAL_VERSION_INFO_RESOURCE), \ VERSIONINFO_RESOURCE := $(GLOBAL_VERSION_INFO_RESOURCE), \
RC_FLAGS := $(RC_FLAGS) \ RC_FLAGS := $(RC_FLAGS) \
-D "JDK_FNAME=java.dll" \ -D "JDK_FNAME=java.dll" \

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -121,6 +121,15 @@ abstract class AbstractLDMLHandler<V> extends DefaultHandler {
} }
} }
/**
* start an element that defines an alias entry, with the value provided by the element's alias.
*/
void pushAliasEntry(String qName, Attributes attributes, String key) {
if (!pushIfIgnored(qName, attributes)) {
currentContainer = new AliasEntry(qName, currentContainer, key);
}
}
/** /**
* start an element that defines a string entry, with the value provided by an attribute value. * start an element that defines a string entry, with the value provided by an attribute value.
*/ */

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. 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 build.tools.cldrconverter;
class AliasEntry extends StringEntry {
AliasEntry(String qName, Container parent, String key) {
super(qName, parent, key);
}
AliasEntry(String qName, Container parent, String key, String value) {
super(qName, parent, key, value);
}
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -32,6 +32,7 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
class Bundle { class Bundle {
static enum Type { static enum Type {
@ -81,7 +82,10 @@ class Bundle {
}; };
private final static String[] DATETIME_PATTERN_KEYS = { private final static String[] DATETIME_PATTERN_KEYS = {
"DateTimePatterns/date-time" "DateTimePatterns/full-dateTime",
"DateTimePatterns/long-dateTime",
"DateTimePatterns/medium-dateTime",
"DateTimePatterns/short-dateTime",
}; };
private final static String[] ERA_KEYS = { private final static String[] ERA_KEYS = {
@ -170,6 +174,7 @@ class Bundle {
for (index = 0; index < cldrBundles.length; index++) { for (index = 0; index < cldrBundles.length; index++) {
if (cldrBundles[index].equals(id)) { if (cldrBundles[index].equals(id)) {
myMap.putAll(CLDRConverter.getCLDRBundle(cldrBundles[index])); myMap.putAll(CLDRConverter.getCLDRBundle(cldrBundles[index]));
CLDRConverter.handleAliases(myMap);
break; break;
} }
} }
@ -179,10 +184,11 @@ class Bundle {
for (int i = cldrBundles.length - 1; i > index; i--) { for (int i = cldrBundles.length - 1; i > index; i--) {
if (!("no".equals(cldrBundles[i]) || cldrBundles[i].startsWith("no_"))) { if (!("no".equals(cldrBundles[i]) || cldrBundles[i].startsWith("no_"))) {
parentsMap.putAll(CLDRConverter.getCLDRBundle(cldrBundles[i])); parentsMap.putAll(CLDRConverter.getCLDRBundle(cldrBundles[i]));
CLDRConverter.handleAliases(parentsMap);
} }
} }
// Duplicate myMap as parentsMap for "root" so that the // Duplicate myMap as parentsMap for "root" so that the
// fallback works. This is a huck, though. // fallback works. This is a hack, though.
if ("root".equals(cldrBundles[0])) { if ("root".equals(cldrBundles[0])) {
assert parentsMap.isEmpty(); assert parentsMap.isEmpty();
parentsMap.putAll(myMap); parentsMap.putAll(myMap);
@ -370,6 +376,17 @@ class Bundle {
} }
} }
} }
// Remove all duplicates
if (Objects.nonNull(parentsMap)) {
for (Iterator<String> it = myMap.keySet().iterator(); it.hasNext();) {
String key = it.next();
if (Objects.deepEquals(parentsMap.get(key), myMap.get(key))) {
it.remove();
}
}
}
return myMap; return myMap;
} }
@ -506,11 +523,6 @@ class Bundle {
if (patterns.isEmpty()) { if (patterns.isEmpty()) {
return; return;
} }
for (String p : patterns) {
if (p == null) {
return;
}
}
String key = calendarPrefix + name; String key = calendarPrefix + name;
if (!rawPatterns.equals(patterns)) { if (!rawPatterns.equals(patterns)) {
myMap.put("java.time." + key, rawPatterns.toArray(new String[len])); myMap.put("java.time." + key, rawPatterns.toArray(new String[len]));
@ -630,7 +642,9 @@ class Bundle {
if (name.contains("Standard Time")) { if (name.contains("Standard Time")) {
name = name.replace("Standard Time", "Daylight Time"); name = name.replace("Standard Time", "Daylight Time");
} else if (name.endsWith("Mean Time")) { } else if (name.endsWith("Mean Time")) {
if (!name.startsWith("Greenwich ")) {
name = name.replace("Mean Time", "Summer Time"); name = name.replace("Mean Time", "Summer Time");
}
} else if (name.endsWith(" Time")) { } else if (name.endsWith(" Time")) {
name = name.replace(" Time", " Summer Time"); name = name.replace(" Time", " Summer Time");
} }
@ -644,8 +658,10 @@ class Bundle {
if (name.endsWith("Standard Time")) { if (name.endsWith("Standard Time")) {
name = name.replace("Standard Time", "Time"); name = name.replace("Standard Time", "Time");
} else if (name.endsWith("Mean Time")) { } else if (name.endsWith("Mean Time")) {
if (!name.startsWith("Greenwich ")) {
name = name.replace("Mean Time", "Time"); name = name.replace("Mean Time", "Time");
} }
}
map.put(TZ_GEN_LONG_KEY, name); map.put(TZ_GEN_LONG_KEY, name);
fillInAbbrs(TZ_GEN_LONG_KEY, TZ_GEN_SHORT_KEY, map); fillInAbbrs(TZ_GEN_LONG_KEY, TZ_GEN_SHORT_KEY, map);
} }
@ -712,6 +728,15 @@ class Bundle {
} }
break; break;
case 'l':
// 'l' is deprecated as a pattern character. Should be ignored.
break;
case 'u':
// Use 'y' for now.
appendN('y', count, sb);
break;
case 'v': case 'v':
case 'V': case 'V':
appendN('z', count, sb); appendN('z', count, sb);
@ -723,16 +748,14 @@ class Bundle {
} }
break; break;
case 'u':
case 'U': case 'U':
case 'q': case 'q':
case 'Q': case 'Q':
case 'l':
case 'g': case 'g':
case 'j': case 'j':
case 'A': case 'A':
throw new InternalError(String.format("Unsupported letter: '%c', count=%d%n", throw new InternalError(String.format("Unsupported letter: '%c', count=%d, id=%s%n",
cldrLetter, count)); cldrLetter, count, id));
default: default:
appendN(cldrLetter, count, sb); appendN(cldrLetter, count, sb);
break; break;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -32,6 +32,9 @@ import java.nio.file.FileSystems;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.ResourceBundle.Control;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotRecognizedException;
@ -64,12 +67,22 @@ public class CLDRConverter {
static final String TIMEZONE_ID_PREFIX = "timezone.id."; static final String TIMEZONE_ID_PREFIX = "timezone.id.";
static final String ZONE_NAME_PREFIX = "timezone.displayname."; static final String ZONE_NAME_PREFIX = "timezone.displayname.";
static final String METAZONE_ID_PREFIX = "metazone.id."; static final String METAZONE_ID_PREFIX = "metazone.id.";
static final String PARENT_LOCALE_PREFIX = "parentLocale.";
private static SupplementDataParseHandler handlerSuppl; private static SupplementDataParseHandler handlerSuppl;
static NumberingSystemsParseHandler handlerNumbering; static NumberingSystemsParseHandler handlerNumbering;
static MetaZonesParseHandler handlerMetaZones; static MetaZonesParseHandler handlerMetaZones;
private static BundleGenerator bundleGenerator; private static BundleGenerator bundleGenerator;
// java.base module related
static boolean isBaseModule = false;
static final Set<Locale> BASE_LOCALES = new HashSet<>();
// "parentLocales" map
private static final Map<String, SortedSet<String>> parentLocalesMap = new HashMap<>();
private static final ResourceBundle.Control defCon =
ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_DEFAULT);
static enum DraftType { static enum DraftType {
UNCONFIRMED, UNCONFIRMED,
PROVISIONAL, PROVISIONAL,
@ -142,6 +155,16 @@ public class CLDRConverter {
} }
break; break;
case "-baselocales":
// base locales
setupBaseLocales(args[++i]);
break;
case "-basemodule":
// indicates java.base module resource generation
isBaseModule = true;
break;
case "-o": case "-o":
// output directory // output directory
DESTINATION_DIR = args[++i]; DESTINATION_DIR = args[++i];
@ -179,8 +202,15 @@ public class CLDRConverter {
NUMBERING_SOURCE_FILE = CLDR_BASE + "common/supplemental/numberingSystems.xml"; NUMBERING_SOURCE_FILE = CLDR_BASE + "common/supplemental/numberingSystems.xml";
METAZONES_SOURCE_FILE = CLDR_BASE + "common/supplemental/metaZones.xml"; METAZONES_SOURCE_FILE = CLDR_BASE + "common/supplemental/metaZones.xml";
if (BASE_LOCALES.isEmpty()) {
setupBaseLocales("en-US");
}
bundleGenerator = new ResourceBundleGenerator(); bundleGenerator = new ResourceBundleGenerator();
// Parse data independent of locales
parseSupplemental();
List<Bundle> bundles = readBundleList(); List<Bundle> bundles = readBundleList();
convertBundles(bundles); convertBundles(bundles);
} }
@ -192,6 +222,9 @@ public class CLDRConverter {
+ "\t-draft [approved | provisional | unconfirmed]%n" + "\t-draft [approved | provisional | unconfirmed]%n"
+ "\t\t draft level for using data (default: approved)%n" + "\t\t draft level for using data (default: approved)%n"
+ "\t-base dir base directory for CLDR input files%n" + "\t-base dir base directory for CLDR input files%n"
+ "\t-basemodule generates bundles that go into java.base module%n"
+ "\t-baselocales loc(,loc)* locales that go into the base module%n"
+ "\t-o dir output directory (default: ./build/gensrc)%n"
+ "\t-o dir output directory (defaut: ./build/gensrc)%n" + "\t-o dir output directory (defaut: ./build/gensrc)%n"
+ "\t-utf8 use UTF-8 rather than \\uxxxx (for debug)%n"); + "\t-utf8 use UTF-8 rather than \\uxxxx (for debug)%n");
} }
@ -248,7 +281,6 @@ public class CLDRConverter {
} }
private static List<Bundle> readBundleList() throws Exception { private static List<Bundle> readBundleList() throws Exception {
ResourceBundle.Control defCon = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_DEFAULT);
List<Bundle> retList = new ArrayList<>(); List<Bundle> retList = new ArrayList<>();
Path path = FileSystems.getDefault().getPath(SOURCE_FILE_DIR); Path path = FileSystems.getDefault().getPath(SOURCE_FILE_DIR);
try (DirectoryStream<Path> dirStr = Files.newDirectoryStream(path)) { try (DirectoryStream<Path> dirStr = Files.newDirectoryStream(path)) {
@ -257,7 +289,7 @@ public class CLDRConverter {
if (fileName.endsWith(".xml")) { if (fileName.endsWith(".xml")) {
String id = fileName.substring(0, fileName.indexOf('.')); String id = fileName.substring(0, fileName.indexOf('.'));
Locale cldrLoc = Locale.forLanguageTag(toLanguageTag(id)); Locale cldrLoc = Locale.forLanguageTag(toLanguageTag(id));
List<Locale> candList = defCon.getCandidateLocales("", cldrLoc); List<Locale> candList = applyParentLocales("", defCon.getCandidateLocales("", cldrLoc));
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (Locale loc : candList) { for (Locale loc : candList) {
if (!loc.equals(Locale.ROOT)) { if (!loc.equals(Locale.ROOT)) {
@ -269,9 +301,9 @@ public class CLDRConverter {
sb.append("root"); sb.append("root");
} }
Bundle b = new Bundle(id, sb.toString(), null, null); Bundle b = new Bundle(id, sb.toString(), null, null);
// Insert the bundle for en at the top so that it will get // Insert the bundle for root at the top so that it will get
// processed first. // processed first.
if ("en".equals(id)) { if ("root".equals(id)) {
retList.add(0, b); retList.add(0, b);
} else { } else {
retList.add(b); retList.add(b);
@ -282,7 +314,7 @@ public class CLDRConverter {
return retList; return retList;
} }
private static Map<String, Map<String, Object>> cldrBundles = new HashMap<>(); private static final Map<String, Map<String, Object>> cldrBundles = new HashMap<>();
static Map<String, Object> getCLDRBundle(String id) throws Exception { static Map<String, Object> getCLDRBundle(String id) throws Exception {
Map<String, Object> bundle = cldrBundles.get(id); Map<String, Object> bundle = cldrBundles.get(id);
@ -319,12 +351,19 @@ public class CLDRConverter {
return bundle; return bundle;
} }
private static void convertBundles(List<Bundle> bundles) throws Exception { // Parsers for data in "supplemental" directory
//
private static void parseSupplemental() throws Exception {
// Parse SupplementalData file and store the information in the HashMap // Parse SupplementalData file and store the information in the HashMap
// Calendar information such as firstDay and minDay are stored in // Calendar information such as firstDay and minDay are stored in
// supplementalData.xml as of CLDR1.4. Individual territory is listed // supplementalData.xml as of CLDR1.4. Individual territory is listed
// with its ISO 3166 country code while default is listed using UNM49 // with its ISO 3166 country code while default is listed using UNM49
// region and composition numerical code (001 for World.) // region and composition numerical code (001 for World.)
//
// SupplementalData file also provides the "parent" locales which
// are othrwise not to be fallen back. Process them here as well.
//
info("..... Parsing supplementalData.xml .....");
SAXParserFactory factorySuppl = SAXParserFactory.newInstance(); SAXParserFactory factorySuppl = SAXParserFactory.newInstance();
factorySuppl.setValidating(true); factorySuppl.setValidating(true);
SAXParser parserSuppl = factorySuppl.newSAXParser(); SAXParser parserSuppl = factorySuppl.newSAXParser();
@ -332,8 +371,14 @@ public class CLDRConverter {
handlerSuppl = new SupplementDataParseHandler(); handlerSuppl = new SupplementDataParseHandler();
File fileSupply = new File(SPPL_SOURCE_FILE); File fileSupply = new File(SPPL_SOURCE_FILE);
parserSuppl.parse(fileSupply, handlerSuppl); parserSuppl.parse(fileSupply, handlerSuppl);
Map<String, Object> parentData = handlerSuppl.getData("root");
parentData.keySet().forEach(key -> {
parentLocalesMap.put(key, new TreeSet(
Arrays.asList(((String)parentData.get(key)).split(" "))));
});
// Parse numberingSystems to get digit zero character information. // Parse numberingSystems to get digit zero character information.
info("..... Parsing numberingSystem.xml .....");
SAXParserFactory numberingParser = SAXParserFactory.newInstance(); SAXParserFactory numberingParser = SAXParserFactory.newInstance();
numberingParser.setValidating(true); numberingParser.setValidating(true);
SAXParser parserNumbering = numberingParser.newSAXParser(); SAXParser parserNumbering = numberingParser.newSAXParser();
@ -343,6 +388,7 @@ public class CLDRConverter {
parserNumbering.parse(fileNumbering, handlerNumbering); parserNumbering.parse(fileNumbering, handlerNumbering);
// Parse metaZones to create mappings between Olson tzids and CLDR meta zone names // Parse metaZones to create mappings between Olson tzids and CLDR meta zone names
info("..... Parsing metaZones.xml .....");
SAXParserFactory metazonesParser = SAXParserFactory.newInstance(); SAXParserFactory metazonesParser = SAXParserFactory.newInstance();
metazonesParser.setValidating(true); metazonesParser.setValidating(true);
SAXParser parserMetaZones = metazonesParser.newSAXParser(); SAXParser parserMetaZones = metazonesParser.newSAXParser();
@ -350,14 +396,23 @@ public class CLDRConverter {
handlerMetaZones = new MetaZonesParseHandler(); handlerMetaZones = new MetaZonesParseHandler();
File fileMetaZones = new File(METAZONES_SOURCE_FILE); File fileMetaZones = new File(METAZONES_SOURCE_FILE);
parserNumbering.parse(fileMetaZones, handlerMetaZones); parserNumbering.parse(fileMetaZones, handlerMetaZones);
}
private static void convertBundles(List<Bundle> bundles) throws Exception {
// For generating information on supported locales. // For generating information on supported locales.
Map<String, SortedSet<String>> metaInfo = new HashMap<>(); Map<String, SortedSet<String>> metaInfo = new HashMap<>();
metaInfo.put("LocaleNames", new TreeSet<String>()); metaInfo.put("LocaleNames", new TreeSet<>());
metaInfo.put("CurrencyNames", new TreeSet<String>()); metaInfo.put("CurrencyNames", new TreeSet<>());
metaInfo.put("TimeZoneNames", new TreeSet<String>()); metaInfo.put("TimeZoneNames", new TreeSet<>());
metaInfo.put("CalendarData", new TreeSet<String>()); metaInfo.put("CalendarData", new TreeSet<>());
metaInfo.put("FormatData", new TreeSet<String>()); metaInfo.put("FormatData", new TreeSet<>());
metaInfo.put("AvailableLocales", new TreeSet<>());
// parent locales map. The mappings are put in base metaInfo file
// for now.
if (isBaseModule) {
metaInfo.putAll(parentLocalesMap);
}
for (Bundle bundle : bundles) { for (Bundle bundle : bundles) {
// Get the target map, which contains all the data that should be // Get the target map, which contains all the data that should be
@ -367,21 +422,7 @@ public class CLDRConverter {
EnumSet<Bundle.Type> bundleTypes = bundle.getBundleTypes(); EnumSet<Bundle.Type> bundleTypes = bundle.getBundleTypes();
// Fill in any missing resources in the base bundle from en and en-US data.
// This is because CLDR root.xml is supposed to be language neutral and doesn't
// provide some resource data. Currently, the runtime assumes that there are all
// resources though the parent resource bundle chain.
if (bundle.isRoot()) { if (bundle.isRoot()) {
Map<String, Object> enData = new HashMap<>();
// Create a superset of en-US and en bundles data in order to
// fill in any missing resources in the base bundle.
enData.putAll(Bundle.getBundle("en").getTargetMap());
enData.putAll(Bundle.getBundle("en_US").getTargetMap());
for (String key : enData.keySet()) {
if (!targetMap.containsKey(key)) {
targetMap.put(key, enData.get(key));
}
}
// Add DateTimePatternChars because CLDR no longer supports localized patterns. // Add DateTimePatternChars because CLDR no longer supports localized patterns.
targetMap.put("DateTimePatternChars", "GyMdkHmsSEDFwWahKzZ"); targetMap.put("DateTimePatternChars", "GyMdkHmsSEDFwWahKzZ");
} }
@ -418,60 +459,56 @@ public class CLDRConverter {
} }
if (bundleTypes.contains(Bundle.Type.FORMATDATA)) { if (bundleTypes.contains(Bundle.Type.FORMATDATA)) {
Map<String, Object> formatDataMap = extractFormatData(targetMap, bundle.getID()); Map<String, Object> formatDataMap = extractFormatData(targetMap, bundle.getID());
// LocaleData.getAvailableLocales depends on having FormatData bundles around
if (!formatDataMap.isEmpty() || bundle.isRoot()) { if (!formatDataMap.isEmpty() || bundle.isRoot()) {
metaInfo.get("FormatData").add(toLanguageTag(bundle.getID())); metaInfo.get("FormatData").add(toLanguageTag(bundle.getID()));
bundleGenerator.generateBundle("text", "FormatData", bundle.getID(), true, formatDataMap, BundleType.PLAIN); bundleGenerator.generateBundle("text", "FormatData", bundle.getID(), true, formatDataMap, BundleType.PLAIN);
} }
} }
// For testing // For AvailableLocales
SortedSet<String> allLocales = new TreeSet<>(); metaInfo.get("AvailableLocales").add(toLanguageTag(bundle.getID()));
allLocales.addAll(metaInfo.get("CurrencyNames"));
allLocales.addAll(metaInfo.get("LocaleNames"));
allLocales.addAll(metaInfo.get("CalendarData"));
allLocales.addAll(metaInfo.get("FormatData"));
metaInfo.put("AvailableLocales", allLocales);
} }
bundleGenerator.generateMetaInfo(metaInfo); bundleGenerator.generateMetaInfo(metaInfo);
} }
static final Map<String, String> aliases = new HashMap<>();
/**
* Translate the aliases into the real entries in the bundle map.
*/
static void handleAliases(Map<String, Object> bundleMap) {
Set bundleKeys = bundleMap.keySet();
try {
for (String key : aliases.keySet()) {
String targetKey = aliases.get(key);
if (bundleKeys.contains(targetKey)) {
bundleMap.putIfAbsent(key, bundleMap.get(targetKey));
}
}
} catch (Exception ex) {
Logger.getLogger(CLDRConverter.class.getName()).log(Level.SEVERE, null, ex);
}
}
/* /*
* Returns the language portion of the given id. * Returns the language portion of the given id.
* If id is "root", "" is returned. * If id is "root", "" is returned.
*/ */
static String getLanguageCode(String id) { static String getLanguageCode(String id) {
int index = id.indexOf('_'); return "root".equals(id) ? "" : Locale.forLanguageTag(id.replaceAll("_", "-")).getLanguage();
String lang = null;
if (index != -1) {
lang = id.substring(0, index);
} else {
lang = "root".equals(id) ? "" : id;
}
return lang;
} }
/** /**
* Examine if the id includes the country (territory) code. If it does, it returns * Examine if the id includes the country (territory) code. If it does, it returns
* the country code. * the country code.
* Otherwise, it returns null. eg. when the id is "zh_Hans_SG", it return "SG". * Otherwise, it returns null. eg. when the id is "zh_Hans_SG", it return "SG".
* For now, it does not return US M.49 code, e.g., '001', as those three digit numbers cannot
* be translated into package names.
*/ */
private static String getCountryCode(String id) { static String getCountryCode(String id) {
//Truncate a variant code with '@' if there is any String ctry = Locale.forLanguageTag(id.replaceAll("_", "-")).getCountry();
//(eg. de_DE@collation=phonebook,currency=DOM) return ctry.length() == 2 ? ctry : null;
if (id.indexOf('@') != -1) {
id = id.substring(0, id.indexOf('@'));
}
String[] tokens = id.split("_");
for (int index = 1; index < tokens.length; ++index) {
if (tokens[index].length() == 2
&& Character.isLetter(tokens[index].charAt(0))
&& Character.isLetter(tokens[index].charAt(1))) {
return tokens[index];
}
}
return null;
} }
private static class KeyComparator implements Comparator<String> { private static class KeyComparator implements Comparator<String> {
@ -598,6 +635,9 @@ public class CLDRConverter {
private static Map<String, Object> extractFormatData(Map<String, Object> map, String id) { private static Map<String, Object> extractFormatData(Map<String, Object> map, String id) {
Map<String, Object> formatData = new LinkedHashMap<>(); Map<String, Object> formatData = new LinkedHashMap<>();
for (CalendarType calendarType : CalendarType.values()) { for (CalendarType calendarType : CalendarType.values()) {
if (calendarType == CalendarType.GENERIC) {
continue;
}
String prefix = calendarType.keyElementName(); String prefix = calendarType.keyElementName();
for (String element : FORMAT_DATA_ELEMENTS) { for (String element : FORMAT_DATA_ELEMENTS) {
String key = prefix + element; String key = prefix + element;
@ -605,28 +645,15 @@ public class CLDRConverter {
copyIfPresent(map, key, formatData); copyIfPresent(map, key, formatData);
} }
} }
// Workaround for islamic-umalqura name support (JDK-8015986)
switch (id) {
case "ar":
map.put(CLDRConverter.CALENDAR_NAME_PREFIX
+ CalendarType.ISLAMIC_UMALQURA.lname(),
// derived from CLDR 24 draft
"\u0627\u0644\u062a\u0642\u0648\u064a\u0645 "
+"\u0627\u0644\u0625\u0633\u0644\u0627\u0645\u064a "
+"[\u0623\u0645 \u0627\u0644\u0642\u0631\u0649]");
break;
case "en":
map.put(CLDRConverter.CALENDAR_NAME_PREFIX
+ CalendarType.ISLAMIC_UMALQURA.lname(),
// derived from CLDR 24 draft
"Islamic Calendar [Umm al-Qura]");
break;
}
// Copy available calendar names
for (String key : map.keySet()) { for (String key : map.keySet()) {
// Copy available calendar names
if (key.startsWith(CLDRConverter.CALENDAR_NAME_PREFIX)) { if (key.startsWith(CLDRConverter.CALENDAR_NAME_PREFIX)) {
String type = key.substring(CLDRConverter.CALENDAR_NAME_PREFIX.length()); String type = key.substring(CLDRConverter.CALENDAR_NAME_PREFIX.length());
for (CalendarType calendarType : CalendarType.values()) { for (CalendarType calendarType : CalendarType.values()) {
if (calendarType == CalendarType.GENERIC) {
continue;
}
if (type.equals(calendarType.lname())) { if (type.equals(calendarType.lname())) {
Object value = map.get(key); Object value = map.get(key);
formatData.put(key, value); formatData.put(key, value);
@ -745,4 +772,43 @@ public class CLDRConverter {
} }
return tag.replaceAll("-", "_"); return tag.replaceAll("-", "_");
} }
private static void setupBaseLocales(String localeList) {
Arrays.stream(localeList.split(","))
.map(Locale::forLanguageTag)
.map(l -> Control.getControl(Control.FORMAT_DEFAULT)
.getCandidateLocales("", l))
.forEach(BASE_LOCALES::addAll);
}
// applying parent locale rules to the passed candidates list
// This has to match with the one in sun.util.cldr.CLDRLocaleProviderAdapter
private static Map<Locale, Locale> childToParentLocaleMap = null;
private static List<Locale> applyParentLocales(String baseName, List<Locale> candidates) {
if (Objects.isNull(childToParentLocaleMap)) {
childToParentLocaleMap = new HashMap<>();
parentLocalesMap.keySet().forEach(key -> {
String parent = key.substring(PARENT_LOCALE_PREFIX.length()).replaceAll("_", "-");
parentLocalesMap.get(key).stream().forEach(child -> {
childToParentLocaleMap.put(Locale.forLanguageTag(child),
"root".equals(parent) ? Locale.ROOT : Locale.forLanguageTag(parent));
});
});
}
// check irregular parents
for (int i = 0; i < candidates.size(); i++) {
Locale l = candidates.get(i);
Locale p = childToParentLocaleMap.get(l);
if (!l.equals(Locale.ROOT) &&
Objects.nonNull(p) &&
!candidates.get(i+1).equals(p)) {
List<Locale> applied = candidates.subList(0, i+1);
applied.addAll(applyParentLocales(baseName, defCon.getCandidateLocales(baseName, p)));
return applied;
}
}
return candidates;
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -29,19 +29,21 @@ import java.util.Locale;
/** /**
* Constants for the Calendars supported by JRE. * Constants for the Calendars supported by JRE.
* Note that "GENERIC" calendar data will NOT be extracted to JDK's ResourceBundles.
*/ */
enum CalendarType { enum CalendarType {
GREGORIAN("gregory"), BUDDHIST, JAPANESE, ROC, GENERIC, GREGORIAN("gregory"), BUDDHIST, JAPANESE, ROC,
ISLAMIC, ISLAMIC_CIVIL("islamicc"), ISLAMIC_UMALQURA("islamic-umalqura"); ISLAMIC, ISLAMIC_CIVIL("islamic-civil"), ISLAMIC_UMALQURA("islamic-umalqura");
private static final int[][] ERA_DATA = { private static final int[][] ERA_DATA = {
// start index, array length // start index, array length
{0, 2}, // generic
{0, 2}, // gregorian {0, 2}, // gregorian
{0, 1}, // buddhist {0, 1}, // buddhist
{232, 4}, // japanese (eras from Meiji) {232, 4}, // japanese (eras from Meiji)
{0, 2}, // roc (Minguo) {0, 2}, // roc (Minguo)
{0, 1}, // islamic (Hijrah) {0, 1}, // islamic (Hijrah)
{0, 1}, // islamicc (same as islamic) {0, 1}, // islamic-civil (same as islamic)
{0, 1}, // islamic-umalqura {0, 1}, // islamic-umalqura
}; };
@ -87,7 +89,7 @@ enum CalendarType {
static CalendarType forName(String name) { static CalendarType forName(String name) {
for (CalendarType type : values()) { for (CalendarType type : values()) {
if (type.lname.equals(name)) { if (type.lname.equals(name) || type.uname.equals(name)) {
return type; return type;
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -41,41 +41,46 @@ class CopyrightHeaders {
" * Copyright (c) 2012, %d, Oracle and/or its affiliates. All rights reserved.\n" + " * Copyright (c) 2012, %d, Oracle and/or its affiliates. All rights reserved.\n" +
" */\n"; " */\n";
// Last updated: - 1/16/2015, 1:42:31 PM
private static final String UNICODE = private static final String UNICODE =
"/*\n" + "/*\n" +
" * COPYRIGHT AND PERMISSION NOTICE\n" + " * COPYRIGHT AND PERMISSION NOTICE\n" +
" *\n" + " *\n" +
" * Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under\n" + " * Copyright (C) 1991-2015 Unicode, Inc. All rights reserved.\n" +
" * the Terms of Use in http://www.unicode.org/copyright.html.\n" + " * Distributed under the Terms of Use in \n" +
" * http://www.unicode.org/copyright.html.\n" +
" *\n" + " *\n" +
" * Permission is hereby granted, free of charge, to any person obtaining a copy\n" + " * Permission is hereby granted, free of charge, to any person obtaining\n" +
" * of the Unicode data files and any associated documentation (the \"Data\n" + " * a copy of the Unicode data files and any associated documentation\n" +
" * Files\") or Unicode software and any associated documentation (the\n" + " * (the \"Data Files\") or Unicode software and any associated documentation\n" +
" * \"Software\") to deal in the Data Files or Software without restriction,\n" + " * (the \"Software\") to deal in the Data Files or Software\n" +
" * including without limitation the rights to use, copy, modify, merge,\n" + " * without restriction, including without limitation the rights to use,\n" +
" * publish, distribute, and/or sell copies of the Data Files or Software, and\n" + " * copy, modify, merge, publish, distribute, and/or sell copies of\n" +
" * to permit persons to whom the Data Files or Software are furnished to do so,\n" + " * the Data Files or Software, and to permit persons to whom the Data Files\n" +
" * provided that (a) the above copyright notice(s) and this permission notice\n" + " * or Software are furnished to do so, provided that\n" +
" * appear with all copies of the Data Files or Software, (b) both the above\n" + " * (a) this copyright and permission notice appear with all copies \n" +
" * copyright notice(s) and this permission notice appear in associated\n" + " * of the Data Files or Software,\n" +
" * documentation, and (c) there is clear notice in each modified Data File or\n" + " * (b) this copyright and permission notice appear in associated \n" +
" * in the Software as well as in the documentation associated with the Data\n" + " * documentation, and\n" +
" * File(s) or Software that the data or software has been modified.\n" + " * (c) there is clear notice in each modified Data File or in the Software\n" +
" * as well as in the documentation associated with the Data File(s) or\n" +
" * Software that the data or software has been modified.\n" +
" *\n" + " *\n" +
" * THE DATA FILES AND SOFTWARE ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n" + " * THE DATA FILES AND SOFTWARE ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n" +
" * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" + " * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n" +
" * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF\n" + " * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n" +
" * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS\n" + " * NONINFRINGEMENT OF THIRD PARTY RIGHTS.\n" +
" * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR\n" + " * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS\n" +
" * CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n" + " * NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL\n" +
" * DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n" +
" * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n" + " * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n" +
" * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\n" + " * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n" +
" * OF THE DATA FILES OR SOFTWARE.\n" + " * PERFORMANCE OF THE DATA FILES OR SOFTWARE.\n" +
" *\n" + " *\n" +
" * Except as contained in this notice, the name of a copyright holder shall not\n" + " * Except as contained in this notice, the name of a copyright holder\n" +
" * be used in advertising or otherwise to promote the sale, use or other\n" + " * shall not be used in advertising or otherwise to promote the sale,\n" +
" * dealings in these Data Files or Software without prior written authorization\n" + " * use or other dealings in these Data Files or Software without prior\n" +
" * of the copyright holder.\n" + " * written authorization of the copyright holder.\n" +
" */\n"; " */\n";
private static String OPENJDK2012 = private static String OPENJDK2012 =

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -29,9 +29,11 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
@ -47,6 +49,8 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
private String zoneNameStyle; // "long" or "short" for time zone names private String zoneNameStyle; // "long" or "short" for time zone names
private String zonePrefix; private String zonePrefix;
private final String id; private final String id;
private String currentContext = ""; // "format"/"stand-alone"
private String currentWidth = ""; // "wide"/"narrow"/"abbreviated"
LDMLParseHandler(String id) { LDMLParseHandler(String id) {
this.id = id; this.id = id;
@ -78,20 +82,17 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
pushIgnoredContainer(qName); pushIgnoredContainer(qName);
} }
break; break;
case "language": case "language":
// for LocaleNames
// copy string
pushStringEntry(qName, attributes, CLDRConverter.LOCALE_NAME_PREFIX + attributes.getValue("type"));
break;
case "script": case "script":
// for LocaleNames
// copy string
pushStringEntry(qName, attributes, CLDRConverter.LOCALE_NAME_PREFIX + attributes.getValue("type"));
break;
case "territory": case "territory":
case "variant":
// for LocaleNames // for LocaleNames
// copy string // copy string
pushStringEntry(qName, attributes, CLDRConverter.LOCALE_NAME_PREFIX + attributes.getValue("type")); pushStringEntry(qName, attributes,
CLDRConverter.LOCALE_NAME_PREFIX +
(qName.equals("variant") ? "%%" : "") +
attributes.getValue("type"));
break; break;
// //
@ -112,9 +113,10 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
// Calendar or currency // Calendar or currency
case "displayName": case "displayName":
{ {
if (currentCalendarType != null) { if (currentContainer.getqName().equals("field")) {
pushStringEntry(qName, attributes, pushStringEntry(qName, attributes,
currentCalendarType.keyElementName() + "field." + getContainerKey()); (currentCalendarType != null ? currentCalendarType.keyElementName() : "")
+ "field." + getContainerKey());
} else { } else {
// for CurrencyNames // for CurrencyNames
// need to get the key from the containing <currency> element // need to get the key from the containing <currency> element
@ -149,10 +151,8 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
} }
break; break;
case "fields": case "fields":
if (currentCalendarType != null) { {
pushContainer(qName, attributes); pushContainer(qName, attributes);
} else {
pushIgnoredContainer(qName);
} }
break; break;
case "field": case "field":
@ -183,6 +183,7 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
// need to keep stand-alone and format, to allow for inheritance in CLDR // need to keep stand-alone and format, to allow for inheritance in CLDR
String type = attributes.getValue("type"); String type = attributes.getValue("type");
if ("stand-alone".equals(type) || "format".equals(type)) { if ("stand-alone".equals(type) || "format".equals(type)) {
currentContext = type;
pushKeyContainer(qName, attributes, type); pushKeyContainer(qName, attributes, type);
} else { } else {
pushIgnoredContainer(qName); pushIgnoredContainer(qName);
@ -194,8 +195,13 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
// for FormatData // for FormatData
// create string array for the two types that the JRE knows // create string array for the two types that the JRE knows
// keep info about the context type so we can sort out inheritance later // keep info about the context type so we can sort out inheritance later
if (currentCalendarType == null) {
pushIgnoredContainer(qName);
break;
}
String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName(); String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName();
switch (attributes.getValue("type")) { currentWidth = attributes.getValue("type");
switch (currentWidth) {
case "wide": case "wide":
pushStringArrayEntry(qName, attributes, prefix + "MonthNames/" + getContainerKey(), 13); pushStringArrayEntry(qName, attributes, prefix + "MonthNames/" + getContainerKey(), 13);
break; break;
@ -222,6 +228,7 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
// need to keep stand-alone and format, to allow for multiple inheritance in CLDR // need to keep stand-alone and format, to allow for multiple inheritance in CLDR
String type = attributes.getValue("type"); String type = attributes.getValue("type");
if ("stand-alone".equals(type) || "format".equals(type)) { if ("stand-alone".equals(type) || "format".equals(type)) {
currentContext = type;
pushKeyContainer(qName, attributes, type); pushKeyContainer(qName, attributes, type);
} else { } else {
pushIgnoredContainer(qName); pushIgnoredContainer(qName);
@ -234,7 +241,8 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
// create string array for the two types that the JRE knows // create string array for the two types that the JRE knows
// keep info about the context type so we can sort out inheritance later // keep info about the context type so we can sort out inheritance later
String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName(); String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName();
switch (attributes.getValue("type")) { currentWidth = attributes.getValue("type");
switch (currentWidth) {
case "wide": case "wide":
pushStringArrayEntry(qName, attributes, prefix + "DayNames/" + getContainerKey(), 7); pushStringArrayEntry(qName, attributes, prefix + "DayNames/" + getContainerKey(), 7);
break; break;
@ -263,6 +271,7 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
{ {
String type = attributes.getValue("type"); String type = attributes.getValue("type");
if ("stand-alone".equals(type) || "format".equals(type)) { if ("stand-alone".equals(type) || "format".equals(type)) {
currentContext = type;
pushKeyContainer(qName, attributes, type); pushKeyContainer(qName, attributes, type);
} else { } else {
pushIgnoredContainer(qName); pushIgnoredContainer(qName);
@ -272,7 +281,8 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
case "dayPeriodWidth": case "dayPeriodWidth":
// for FormatData // for FormatData
// create string array entry for am/pm. only keeping wide // create string array entry for am/pm. only keeping wide
switch (attributes.getValue("type")) { currentWidth = attributes.getValue("type");
switch (currentWidth) {
case "wide": case "wide":
pushStringArrayEntry(qName, attributes, "AmPmMarkers/" + getContainerKey(), 2); pushStringArrayEntry(qName, attributes, "AmPmMarkers/" + getContainerKey(), 2);
break; break;
@ -362,6 +372,7 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
// need to keep stand-alone and format, to allow for inheritance in CLDR // need to keep stand-alone and format, to allow for inheritance in CLDR
String type = attributes.getValue("type"); String type = attributes.getValue("type");
if ("stand-alone".equals(type) || "format".equals(type)) { if ("stand-alone".equals(type) || "format".equals(type)) {
currentContext = type;
pushKeyContainer(qName, attributes, type); pushKeyContainer(qName, attributes, type);
} else { } else {
pushIgnoredContainer(qName); pushIgnoredContainer(qName);
@ -373,7 +384,8 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
// for FormatData // for FormatData
// keep info about the context type so we can sort out inheritance later // keep info about the context type so we can sort out inheritance later
String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName(); String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName();
switch (attributes.getValue("type")) { currentWidth = attributes.getValue("type");
switch (currentWidth) {
case "wide": case "wide":
pushStringArrayEntry(qName, attributes, prefix + "QuarterNames/" + getContainerKey(), 4); pushStringArrayEntry(qName, attributes, prefix + "QuarterNames/" + getContainerKey(), 4);
break; break;
@ -450,12 +462,20 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
case "currencyFormat": case "currencyFormat":
// for FormatData // for FormatData
// copy string for later assembly into NumberPatterns // copy string for later assembly into NumberPatterns
if (attributes.getValue("type").equals("standard")) {
pushStringEntry(qName, attributes, "NumberPatterns/currency"); pushStringEntry(qName, attributes, "NumberPatterns/currency");
} else {
pushIgnoredContainer(qName);
}
break; break;
case "percentFormat": case "percentFormat":
// for FormatData // for FormatData
// copy string for later assembly into NumberPatterns // copy string for later assembly into NumberPatterns
if (attributes.getValue("type").equals("standard")) {
pushStringEntry(qName, attributes, "NumberPatterns/percent"); pushStringEntry(qName, attributes, "NumberPatterns/percent");
} else {
pushIgnoredContainer(qName);
}
break; break;
case "defaultNumberingSystem": case "defaultNumberingSystem":
// default numbering system if multiple numbering systems are used. // default numbering system if multiple numbering systems are used.
@ -582,12 +602,12 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
pushStringEntry(qName, attributes, prefix + "DateTimePatterns/" + attributes.getValue("type") + "-date"); pushStringEntry(qName, attributes, prefix + "DateTimePatterns/" + attributes.getValue("type") + "-date");
} }
break; break;
case "dateTimeFormat": case "dateTimeFormatLength":
{ {
// for FormatData // for FormatData
// copy string for later assembly into DateTimePatterns // copy string for later assembly into DateTimePatterns
String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName(); String prefix = (currentCalendarType == null) ? "" : currentCalendarType.keyElementName();
pushStringEntry(qName, attributes, prefix + "DateTimePatterns/date-time"); pushStringEntry(qName, attributes, prefix + "DateTimePatterns/" + attributes.getValue("type") + "-dateTime");
} }
break; break;
case "localizedPatternChars": case "localizedPatternChars":
@ -599,6 +619,20 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
} }
break; break;
// "alias" for root
case "alias":
{
if (id.equals("root") &&
!isIgnored(attributes) &&
currentCalendarType != null &&
!currentCalendarType.lname().startsWith("islamic-")) { // ignore Islamic variants
pushAliasEntry(qName, attributes, attributes.getValue("path"));
} else {
pushIgnoredContainer(qName);
}
}
break;
default: default:
// treat anything else as a container // treat anything else as a container
pushContainer(qName, attributes); pushContainer(qName, attributes);
@ -606,6 +640,184 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
} }
} }
private static final String[] CONTEXTS = {"stand-alone", "format"};
private static final String[] WIDTHS = {"wide", "narrow", "abbreviated"};
private static final String[] LENGTHS = {"full", "long", "medium", "short"};
private void populateWidthAlias(String type, Set<String> keys) {
for (String context : CONTEXTS) {
for (String width : WIDTHS) {
String keyName = toJDKKey(type+"Width", context, width);
if (keyName.length() > 0) {
keys.add(keyName + "," + context + "," + width);
}
}
}
}
private void populateFormatLengthAlias(String type, Set<String> keys) {
for (String length: LENGTHS) {
String keyName = toJDKKey(type+"FormatLength", currentContext, length);
if (keyName.length() > 0) {
keys.add(keyName + "," + currentContext + "," + length);
}
}
}
private Set<String> populateAliasKeys(String qName, String context, String width) {
HashSet<String> ret = new HashSet<>();
String keyName = qName;
switch (qName) {
case "monthWidth":
case "dayWidth":
case "quarterWidth":
case "dayPeriodWidth":
case "dateFormatLength":
case "timeFormatLength":
case "dateTimeFormatLength":
case "eraNames":
case "eraAbbr":
case "eraNarrow":
ret.add(toJDKKey(qName, context, width) + "," + context + "," + width);
break;
case "days":
populateWidthAlias("day", ret);
break;
case "months":
populateWidthAlias("month", ret);
break;
case "quarters":
populateWidthAlias("quarter", ret);
break;
case "dayPeriods":
populateWidthAlias("dayPeriod", ret);
break;
case "eras":
ret.add(toJDKKey("eraNames", context, width) + "," + context + "," + width);
ret.add(toJDKKey("eraAbbr", context, width) + "," + context + "," + width);
ret.add(toJDKKey("eraNarrow", context, width) + "," + context + "," + width);
break;
case "dateFormats":
populateFormatLengthAlias("date", ret);
break;
case "timeFormats":
populateFormatLengthAlias("time", ret);
break;
default:
break;
}
return ret;
}
private String translateWidthAlias(String qName, String context, String width) {
String keyName = qName;
String type = Character.toUpperCase(qName.charAt(0)) + qName.substring(1, qName.indexOf("Width"));
switch (width) {
case "wide":
keyName = type + "Names/" + context;
break;
case "abbreviated":
keyName = type + "Abbreviations/" + context;
break;
case "narrow":
keyName = type + "Narrows/" + context;
break;
default:
assert false;
}
return keyName;
}
private String toJDKKey(String containerqName, String context, String type) {
String keyName = containerqName;
switch (containerqName) {
case "monthWidth":
case "dayWidth":
case "quarterWidth":
keyName = translateWidthAlias(keyName, context, type);
break;
case "dayPeriodWidth":
switch (type) {
case "wide":
keyName = "AmPmMarkers/" + context;
break;
case "narrow":
keyName = "narrow.AmPmMarkers/" + context;
break;
case "abbreviated":
keyName = "";
break;
}
break;
case "dateFormatLength":
case "timeFormatLength":
case "dateTimeFormatLength":
keyName = "DateTimePatterns/" +
type + "-" +
keyName.substring(0, keyName.indexOf("FormatLength"));
break;
case "eraNames":
keyName = "long.Eras";
break;
case "eraAbbr":
keyName = "Eras";
break;
case "eraNarrow":
keyName = "narrow.Eras";
break;
case "dateFormats":
case "timeFormats":
case "days":
case "months":
case "quarters":
case "dayPeriods":
case "eras":
break;
default:
keyName = "";
break;
}
return keyName;
}
private String getTarget(String qName, String path, String calType, String context, String width) {
// qName
int lastSlash = path.lastIndexOf('/');
qName = path.substring(lastSlash+1);
int bracket = qName.indexOf('[');
if (bracket != -1) {
qName = qName.substring(0, bracket);
}
// calType
String typeKey = "/calendar[@type='";
int start = path.indexOf(typeKey);
if (start != -1) {
calType = path.substring(start+typeKey.length(), path.indexOf("']", start));
}
// context
typeKey = "Context[@type='";
start = path.indexOf(typeKey);
if (start != -1) {
context = (path.substring(start+typeKey.length(), path.indexOf("']", start)));
}
// width
typeKey = "Width[@type='";
start = path.indexOf(typeKey);
if (start != -1) {
width = path.substring(start+typeKey.length(), path.indexOf("']", start));
}
return calType + "." + toJDKKey(qName, context, width);
}
@Override @Override
public void endElement(String uri, String localName, String qName) throws SAXException { public void endElement(String uri, String localName, String qName) throws SAXException {
assert qName.equals(currentContainer.getqName()) : "current=" + currentContainer.getqName() + ", param=" + qName; assert qName.equals(currentContainer.getqName()) : "current=" + currentContainer.getqName() + ", param=" + qName;
@ -628,6 +840,7 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
case "timeZoneNames": case "timeZoneNames":
zonePrefix = null; zonePrefix = null;
break; break;
case "generic": case "generic":
case "standard": case "standard":
case "daylight": case "daylight":
@ -638,8 +851,52 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
valmap.put(entry.getKey(), (String) entry.getValue()); valmap.put(entry.getKey(), (String) entry.getValue());
} }
break; break;
case "monthWidth":
case "dayWidth":
case "dayPeriodWidth":
case "quarterWidth":
currentWidth = "";
putIfEntry();
break;
case "monthContext":
case "dayContext":
case "dayPeriodContext":
case "quarterContext":
currentContext = "";
putIfEntry();
break;
default: default:
if (currentContainer instanceof Entry) { putIfEntry();
}
currentContainer = currentContainer.getParent();
}
private void putIfEntry() {
if (currentContainer instanceof AliasEntry) {
Entry<?> entry = (Entry<?>) currentContainer;
String containerqName = entry.getParent().getqName();
Set<String> keyNames = populateAliasKeys(containerqName, currentContext, currentWidth);
if (!keyNames.isEmpty()) {
for (String keyName : keyNames) {
String[] tmp = keyName.split(",", 3);
String calType = currentCalendarType.lname();
String src = calType+"."+tmp[0];
String target = getTarget(containerqName,
entry.getKey(),
calType,
tmp[1].length()>0 ? tmp[1] : currentContext,
tmp[2].length()>0 ? tmp[2] : currentWidth);
if (target.substring(target.lastIndexOf('.')+1).equals(containerqName)) {
target = target.substring(0, target.indexOf('.'))+"."+tmp[0];
}
CLDRConverter.aliases.put(src.replaceFirst("^gregorian.", ""),
target.replaceFirst("^gregorian.", ""));
}
}
} else if (currentContainer instanceof Entry) {
Entry<?> entry = (Entry<?>) currentContainer; Entry<?> entry = (Entry<?>) currentContainer;
Object value = entry.getValue(); Object value = entry.getValue();
if (value != null) { if (value != null) {
@ -647,6 +904,4 @@ class LDMLParseHandler extends AbstractLDMLHandler<Object> {
} }
} }
} }
currentContainer = currentContainer.getParent();
} }
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -30,22 +30,62 @@ import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.Formatter; import java.util.Formatter;
import java.util.HashSet; import java.util.HashSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Locale;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.SortedSet; import java.util.SortedSet;
class ResourceBundleGenerator implements BundleGenerator { class ResourceBundleGenerator implements BundleGenerator {
// preferred timezones - keeping compatibility with JDK1.1 3 letter abbreviations
private static final String[] preferredTZIDs = {
"America/Los_Angeles",
"America/Denver",
"America/Phoenix",
"America/Chicago",
"America/New_York",
"America/Indianapolis",
"Pacific/Honolulu",
"America/Anchorage",
"America/Halifax",
"America/Sitka",
"America/St_Johns",
"Europe/Paris",
// Although CLDR does not support abbreviated zones, handle "GMT" as a
// special case here, as it is specified in the javadoc.
"GMT",
"Africa/Casablanca",
"Asia/Jerusalem",
"Asia/Tokyo",
"Europe/Bucharest",
"Asia/Shanghai",
};
// For duplicated values
private static final String META_VALUE_PREFIX = "metaValue_";
@Override @Override
public void generateBundle(String packageName, String baseName, String localeID, boolean useJava, public void generateBundle(String packageName, String baseName, String localeID, boolean useJava,
Map<String, ?> map, BundleType type) throws IOException { Map<String, ?> map, BundleType type) throws IOException {
String suffix = useJava ? ".java" : ".properties"; String suffix = useJava ? ".java" : ".properties";
String lang = CLDRConverter.getLanguageCode(localeID); String lang = CLDRConverter.getLanguageCode(localeID);
String ctry = CLDRConverter.getCountryCode(localeID);
String dirName = CLDRConverter.DESTINATION_DIR + File.separator + "sun" + File.separator String dirName = CLDRConverter.DESTINATION_DIR + File.separator + "sun" + File.separator
+ packageName + File.separator + "resources" + File.separator + "cldr"; + packageName + File.separator + "resources" + File.separator + "cldr";
if (lang.length() > 0) { if (lang.length() > 0) {
dirName = dirName + File.separator + lang; if (CLDRConverter.isBaseModule ^ isBaseLocale(localeID)) {
packageName = packageName + ".resources.cldr." + lang; return;
}
dirName = dirName + File.separator + lang +
(ctry != null && ctry.length() > 0 ? File.separator + ctry : "");
packageName = packageName + ".resources.cldr." + lang +
(ctry != null && ctry.length() > 0 ? "." + ctry : "");
} else { } else {
if (!CLDRConverter.isBaseModule) {
return;
}
packageName = packageName + ".resources.cldr"; packageName = packageName + ".resources.cldr";
} }
File dir = new File(dirName); File dir = new File(dirName);
@ -89,6 +129,65 @@ class ResourceBundleGenerator implements BundleGenerator {
for (String key : metaKeys) { for (String key : metaKeys) {
map.remove(key); map.remove(key);
} }
// Make it preferred ordered
LinkedHashMap<String, Object> newMap = new LinkedHashMap<>();
for (String preferred : preferredTZIDs) {
if (map.containsKey(preferred)) {
newMap.put(preferred, map.remove(preferred));
} else if ("GMT".equals(preferred) &&
metaKeys.contains(CLDRConverter.METAZONE_ID_PREFIX+preferred)) {
newMap.put(preferred, preferred);
}
}
newMap.putAll(map);
map = newMap;
} else {
// generic reduction of duplicated values
Map<String, Object> newMap = null;
for (String key : map.keySet()) {
Object val = map.get(key);
String metaVal = null;
for (Map.Entry<String, ?> entry : map.entrySet()) {
String k = entry.getKey();
if (!k.equals(key) &&
Objects.deepEquals(val, entry.getValue()) &&
!(Objects.nonNull(newMap) && newMap.containsKey(k))) {
if (Objects.isNull(newMap)) {
newMap = new HashMap<>();
fmt = new Formatter();
}
if (Objects.isNull(metaVal)) {
metaVal = META_VALUE_PREFIX + key.replaceAll("\\.", "_");
if (val instanceof String[]) {
fmt.format(" final String[] %s = new String[] {\n", metaVal);
for (String s : (String[])val) {
fmt.format(" \"%s\",\n", CLDRConverter.saveConvert(s, useJava));
}
fmt.format(" };\n");
} else {
fmt.format(" final String %s = \"%s\";\n", metaVal, CLDRConverter.saveConvert((String)val, useJava));
}
}
newMap.put(k, metaVal);
}
}
if (Objects.nonNull(metaVal)) {
newMap.put(key, metaVal);
}
}
if (Objects.nonNull(newMap)) {
for (String key : map.keySet()) {
newMap.putIfAbsent(key, map.get(key));
}
map = newMap;
}
} }
try (PrintWriter out = new PrintWriter(file, encoding)) { try (PrintWriter out = new PrintWriter(file, encoding)) {
@ -114,7 +213,8 @@ class ResourceBundleGenerator implements BundleGenerator {
if (value == null) { if (value == null) {
CLDRConverter.warning("null value for " + key); CLDRConverter.warning("null value for " + key);
} else if (value instanceof String) { } else if (value instanceof String) {
if (type == BundleType.TIMEZONE) { if (type == BundleType.TIMEZONE ||
((String)value).startsWith(META_VALUE_PREFIX)) {
out.printf(" { \"%s\", %s },\n", key, CLDRConverter.saveConvert((String) value, useJava)); out.printf(" { \"%s\", %s },\n", key, CLDRConverter.saveConvert((String) value, useJava));
} else { } else {
out.printf(" { \"%s\", \"%s\" },\n", key, CLDRConverter.saveConvert((String) value, useJava)); out.printf(" { \"%s\", \"%s\" },\n", key, CLDRConverter.saveConvert((String) value, useJava));
@ -139,18 +239,22 @@ class ResourceBundleGenerator implements BundleGenerator {
} }
} }
private static final String METAINFO_CLASS = "CLDRLocaleDataMetaInfo";
@Override @Override
public void generateMetaInfo(Map<String, SortedSet<String>> metaInfo) throws IOException { public void generateMetaInfo(Map<String, SortedSet<String>> metaInfo) throws IOException {
String dirName = CLDRConverter.DESTINATION_DIR + File.separator + "sun" + File.separator + "util" + String dirName = CLDRConverter.DESTINATION_DIR + File.separator + "sun" + File.separator + "util" +
File.separator + "resources" + File.separator + "cldr" + File.separator + File.separator +
"provider" + File.separator ; (CLDRConverter.isBaseModule ? "cldr" + File.separator + File.separator :
"resources" + File.separator + "cldr" + File.separator + "provider" + File.separator);
File dir = new File(dirName); File dir = new File(dirName);
if (!dir.exists()) { if (!dir.exists()) {
dir.mkdirs(); dir.mkdirs();
} }
File file = new File(dir, METAINFO_CLASS + ".java"); String className =
(CLDRConverter.isBaseModule ? "CLDRBaseLocaleDataMetaInfo" :
"CLDRLocaleDataMetaInfo_" +
CLDRConverter.DESTINATION_DIR.substring(CLDRConverter.DESTINATION_DIR.lastIndexOf('/')+1)
.replaceAll("\\.", "_"));
File file = new File(dir, className + ".java");
if (!file.exists()) { if (!file.exists()) {
file.createNewFile(); file.createNewFile();
} }
@ -159,34 +263,71 @@ class ResourceBundleGenerator implements BundleGenerator {
try (PrintWriter out = new PrintWriter(file, "us-ascii")) { try (PrintWriter out = new PrintWriter(file, "us-ascii")) {
out.println(CopyrightHeaders.getOpenJDKCopyright()); out.println(CopyrightHeaders.getOpenJDKCopyright());
out.println("package sun.util.resources.cldr.provider;\n\n" out.println((CLDRConverter.isBaseModule ? "package sun.util.cldr;\n\n" :
"package sun.util.resources.cldr.provider;\n\n")
+ "import java.util.HashMap;\n"
+ "import java.util.Map;\n"
+ "import java.util.ListResourceBundle;\n" + "import java.util.ListResourceBundle;\n"
+ "import sun.util.locale.provider.LocaleProviderAdapter;\n" + "import sun.util.locale.provider.LocaleProviderAdapter;\n"
+ "import sun.util.locale.provider.LocaleDataMetaInfo;\n"); + "import sun.util.locale.provider.LocaleDataMetaInfo;\n");
out.printf("public class %s extends ListResourceBundle implements LocaleDataMetaInfo {\n", METAINFO_CLASS); out.printf("public class %s extends ListResourceBundle implements LocaleDataMetaInfo {\n", className);
out.println(" @Override\n" + out.println(" @Override\n" +
" protected final Object[][] getContents() {\n" + " protected final Object[][] getContents() {\n" +
" final Object[][] data = new Object[][] {"); " final Object[][] data = new Object[][] {");
for (String key : metaInfo.keySet()) { for (String key : metaInfo.keySet()) {
out.printf(" { \"%s\",\n", key); out.printf(" { \"%s\",\n", key);
out.printf(" \"%s\" },\n", toLocaleList(metaInfo.get(key))); out.printf(" \"%s\" },\n",
toLocaleList(key.equals("FormatData") ? metaInfo.get("AvailableLocales") :
metaInfo.get(key),
key.startsWith(CLDRConverter.PARENT_LOCALE_PREFIX)));
} }
out.println(" };\n return data;\n }\n\n"); out.println(" };\n return data;\n }\n\n");
out.println(" public LocaleProviderAdapter.Type getType() {\n" + out.println(" @Override\n" +
" public LocaleProviderAdapter.Type getType() {\n" +
" return LocaleProviderAdapter.Type.CLDR;\n" + " return LocaleProviderAdapter.Type.CLDR;\n" +
" }\n\n"); " }\n\n");
out.println(" public String availableLanguageTags(String category) {\n" + out.println(" @Override\n" +
" public String availableLanguageTags(String category) {\n" +
" return getString(category);\n" + " return getString(category);\n" +
" };\n}"); " };\n\n");
if (CLDRConverter.isBaseModule) {
out.printf(" public Map<String, String> parentLocales() {\n" +
" Map<String, String> ret = new HashMap<>();\n" +
" keySet().stream()\n" +
" .filter(key -> key.startsWith(\"%s\"))\n" +
" .forEach(key -> ret.put(key.substring(%d), getString(key)));\n" +
" return ret.isEmpty() ? null : ret;\n" +
" };\n}",
CLDRConverter.PARENT_LOCALE_PREFIX,
CLDRConverter.PARENT_LOCALE_PREFIX.length());
} else {
out.println("}");
}
} }
} }
private static String toLocaleList(SortedSet<String> set) { private static final Locale.Builder LOCALE_BUILDER = new Locale.Builder();
private static boolean isBaseLocale(String localeID) {
localeID = localeID.replaceAll("-", "_");
// ignore script here
Locale locale = LOCALE_BUILDER
.clear()
.setLanguage(CLDRConverter.getLanguageCode(localeID))
.setRegion(CLDRConverter.getCountryCode(localeID))
.build();
return CLDRConverter.BASE_LOCALES.contains(locale);
}
private static String toLocaleList(SortedSet<String> set, boolean all) {
StringBuilder sb = new StringBuilder(set.size() * 6); StringBuilder sb = new StringBuilder(set.size() * 6);
for (String id : set) { for (String id : set) {
if (!"root".equals(id)) { if (!"root".equals(id)) {
if (!all && CLDRConverter.isBaseModule ^ isBaseLocale(id)) {
continue;
}
if (sb.length() > 0) { if (sb.length() > 0) {
sb.append(' '); sb.append(' ');
} }

View File

@ -51,12 +51,21 @@ class SupplementDataParseHandler extends AbstractLDMLHandler<Object> {
// When parsing the locale neutral file (supplementalData.xml), // When parsing the locale neutral file (supplementalData.xml),
// we need to rely on the country code because // we need to rely on the country code because
// the weekData is listed using country code. // the weekData is listed using country code.
//
// weekData are generated per each country
private final Map<String, Object> firstDayMap; private final Map<String, Object> firstDayMap;
private final Map<String, Object> minDaysMap; private final Map<String, Object> minDaysMap;
// Parent locales. These information will only be
// generated towards the base meta info, with the format of
//
// parentLocale.<parent_locale_id>=<child_locale_id>(" "<child_locale_id>)+
private final Map<String, String> parentLocalesMap;
SupplementDataParseHandler() { SupplementDataParseHandler() {
firstDayMap = new HashMap<>(); firstDayMap = new HashMap<>();
minDaysMap = new HashMap<>(); minDaysMap = new HashMap<>();
parentLocalesMap = new HashMap<>();
} }
/** /**
@ -68,16 +77,23 @@ class SupplementDataParseHandler extends AbstractLDMLHandler<Object> {
* although this should not happen because supplementalData.xml includes * although this should not happen because supplementalData.xml includes
* default value for the world ("001") for firstDay and minDays. * default value for the world ("001") for firstDay and minDays.
*/ */
Map<String, Object> getData(String country) { Map<String, Object> getData(String id) {
Map<String, Object> values = new HashMap<>(); Map<String, Object> values = new HashMap<>();
String countryData = getWeekData(country, JAVA_FIRSTDAY, firstDayMap); if ("root".equals(id)) {
parentLocalesMap.keySet().forEach(key -> {
values.put(CLDRConverter.PARENT_LOCALE_PREFIX+key,
parentLocalesMap.get(key));
});
} else {
String countryData = getWeekData(id, JAVA_FIRSTDAY, firstDayMap);
if (countryData != null) { if (countryData != null) {
values.put(JAVA_FIRSTDAY, countryData); values.put(JAVA_FIRSTDAY, countryData);
} }
String minDaysData = getWeekData(country, JAVA_MINDAY, minDaysMap); String minDaysData = getWeekData(id, JAVA_MINDAY, minDaysMap);
if (minDaysData != null) { if (minDaysData != null) {
values.put(JAVA_MINDAY, minDaysData); values.put(JAVA_MINDAY, minDaysData);
} }
}
return values.isEmpty() ? null : values; return values.isEmpty() ? null : values;
} }
@ -144,6 +160,13 @@ class SupplementDataParseHandler extends AbstractLDMLHandler<Object> {
minDaysMap.put(attributes.getValue("territories"), attributes.getValue("count")); minDaysMap.put(attributes.getValue("territories"), attributes.getValue("count"));
} }
break; break;
case "parentLocale":
if (!isIgnored(attributes)) {
parentLocalesMap.put(
attributes.getValue("parent").replaceAll("_", "-"),
attributes.getValue("locales").replaceAll("_", "-"));
}
break;
default: default:
// treat anything else as a container // treat anything else as a container
pushContainer(qName, attributes); pushContainer(qName, attributes);

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.invoke;
import java.lang.annotation.*;
/**
* Internal marker for some methods in the JSR 292 implementation.
*/
/*non-public*/
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@interface InjectedProfile {
}

View File

@ -669,6 +669,11 @@ class InvokerBytecodeGenerator {
switch (intr) { switch (intr) {
case SELECT_ALTERNATIVE: case SELECT_ALTERNATIVE:
assert isSelectAlternative(i); assert isSelectAlternative(i);
if (PROFILE_GWT) {
assert(name.arguments[0] instanceof Name &&
nameRefersTo((Name)name.arguments[0], MethodHandleImpl.class, "profileBoolean"));
mv.visitAnnotation("Ljava/lang/invoke/InjectedProfile;", true);
}
onStack = emitSelectAlternative(name, lambdaForm.names[i+1]); onStack = emitSelectAlternative(name, lambdaForm.names[i+1]);
i++; // skip MH.invokeBasic of the selectAlternative result i++; // skip MH.invokeBasic of the selectAlternative result
continue; continue;

View File

@ -0,0 +1,267 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.file;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.Spliterator;
import java.util.function.Consumer;
/**
* A file-based lines spliterator, leveraging a shared mapped byte buffer and
* associated file channel, covering lines of a file for character encodings
* where line feed characters can be easily identified from character encoded
* bytes.
*
* <p>
* When the root spliterator is first split a mapped byte buffer will be created
* over the file for it's size that was observed when the stream was created.
* Thus a mapped byte buffer is only required for parallel stream execution.
* Sub-spliterators will share that mapped byte buffer. Splitting will use the
* mapped byte buffer to find the closest line feed characters(s) to the left or
* right of the mid-point of covered range of bytes of the file. If a line feed
* is found then the spliterator is split with returned spliterator containing
* the identified line feed characters(s) at the end of it's covered range of
* bytes.
*
* <p>
* Traversing will create a buffered reader, derived from the file channel, for
* the range of bytes of the file. The lines are then read from that buffered
* reader. Once traversing commences no further splitting can be performed and
* the reference to the mapped byte buffer will be set to null.
*/
final class FileChannelLinesSpliterator implements Spliterator<String> {
static final Set<String> SUPPORTED_CHARSET_NAMES;
static {
SUPPORTED_CHARSET_NAMES = new HashSet<>();
SUPPORTED_CHARSET_NAMES.add(StandardCharsets.UTF_8.name());
SUPPORTED_CHARSET_NAMES.add(StandardCharsets.ISO_8859_1.name());
SUPPORTED_CHARSET_NAMES.add(StandardCharsets.US_ASCII.name());
}
private final FileChannel fc;
private final Charset cs;
private int index;
private final int fence;
// Null before first split, non-null when splitting, null when traversing
private ByteBuffer buffer;
// Non-null when traversing
private BufferedReader reader;
FileChannelLinesSpliterator(FileChannel fc, Charset cs, int index, int fence) {
this.fc = fc;
this.cs = cs;
this.index = index;
this.fence = fence;
}
private FileChannelLinesSpliterator(FileChannel fc, Charset cs, int index, int fence, ByteBuffer buffer) {
this.fc = fc;
this.buffer = buffer;
this.cs = cs;
this.index = index;
this.fence = fence;
}
@Override
public boolean tryAdvance(Consumer<? super String> action) {
String line = readLine();
if (line != null) {
action.accept(line);
return true;
} else {
return false;
}
}
@Override
public void forEachRemaining(Consumer<? super String> action) {
String line;
while ((line = readLine()) != null) {
action.accept(line);
}
}
private BufferedReader getBufferedReader() {
/**
* A readable byte channel that reads bytes from an underlying
* file channel over a specified range.
*/
ReadableByteChannel rrbc = new ReadableByteChannel() {
@Override
public int read(ByteBuffer dst) throws IOException {
int bytesToRead = fence - index;
if (bytesToRead == 0)
return -1;
int bytesRead;
if (bytesToRead < dst.remaining()) {
// The number of bytes to read is less than remaining
// bytes in the buffer
// Snapshot the limit, reduce it, read, then restore
int oldLimit = dst.limit();
dst.limit(dst.position() + bytesToRead);
bytesRead = fc.read(dst, index);
dst.limit(oldLimit);
} else {
bytesRead = fc.read(dst, index);
}
if (bytesRead == -1) {
index = fence;
return bytesRead;
}
index += bytesRead;
return bytesRead;
}
@Override
public boolean isOpen() {
return fc.isOpen();
}
@Override
public void close() throws IOException {
fc.close();
}
};
return new BufferedReader(Channels.newReader(rrbc, cs.newDecoder(), -1));
}
private String readLine() {
if (reader == null) {
reader = getBufferedReader();
buffer = null;
}
try {
return reader.readLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private ByteBuffer getMappedByteBuffer() {
// TODO can the mapped byte buffer be explicitly unmapped?
// It's possible, via a shared-secret mechanism, when either
// 1) the spliterator starts traversing, although traversal can
// happen concurrently for mulitple spliterators, so care is
// needed in this case; or
// 2) when the stream is closed using some shared holder to pass
// the mapped byte buffer when it is created.
try {
return fc.map(FileChannel.MapMode.READ_ONLY, 0, fence);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public Spliterator<String> trySplit() {
// Cannot split after partial traverse
if (reader != null)
return null;
ByteBuffer b;
if ((b = buffer) == null) {
b = buffer = getMappedByteBuffer();
}
final int hi = fence, lo = index;
// Check if line separator hits the mid point
int mid = (lo + hi) >>> 1;
int c = b.get(mid);
if (c == '\n') {
mid++;
} else if (c == '\r') {
// Check if a line separator of "\r\n"
if (++mid < hi && b.get(mid) == '\n') {
mid++;
}
} else {
// TODO give up after a certain distance from the mid point?
// Scan to the left and right of the mid point
int midL = mid - 1;
int midR = mid + 1;
mid = 0;
while (midL > lo && midR < hi) {
// Sample to the left
c = b.get(midL--);
if (c == '\n' || c == '\r') {
// If c is "\r" then no need to check for "\r\n"
// since the subsequent value was previously checked
mid = midL + 2;
break;
}
// Sample to the right
c = b.get(midR++);
if (c == '\n' || c == '\r') {
mid = midR;
// Check if line-separator is "\r\n"
if (c == '\r' && mid < hi && b.get(mid) == '\n') {
mid++;
}
break;
}
}
}
// The left spliterator will have the line-separator at the end
return (mid > lo && mid < hi)
? new FileChannelLinesSpliterator(fc, cs, lo, index = mid, b)
: null;
}
@Override
public long estimateSize() {
// Use the number of bytes as an estimate.
// We could divide by a constant that is the average number of
// characters per-line, but that constant will be factored out.
return fence - index;
}
@Override
public long getExactSizeIfKnown() {
return -1;
}
@Override
public int characteristics() {
return Spliterator.ORDERED | Spliterator.NONNULL;
}
}

View File

@ -38,6 +38,7 @@ import java.io.Reader;
import java.io.UncheckedIOException; import java.io.UncheckedIOException;
import java.io.Writer; import java.io.Writer;
import java.nio.channels.Channels; import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel; import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetDecoder;
@ -3735,6 +3736,7 @@ public final class Files {
} }
} }
/** /**
* Read all lines from a file as a {@code Stream}. Unlike {@link * Read all lines from a file as a {@code Stream}. Unlike {@link
* #readAllLines(Path, Charset) readAllLines}, this method does not read * #readAllLines(Path, Charset) readAllLines}, this method does not read
@ -3748,6 +3750,10 @@ public final class Files {
* <p> The returned stream contains a reference to an open file. The file * <p> The returned stream contains a reference to an open file. The file
* is closed by closing the stream. * is closed by closing the stream.
* *
* <p> The file contents should not be modified during the execution of the
* terminal stream operation. Otherwise, the result of the terminal stream
* operation is undefined.
*
* <p> After this method returns, then any subsequent I/O exception that * <p> After this method returns, then any subsequent I/O exception that
* occurs while reading from the file or when a malformed or unmappable byte * occurs while reading from the file or when a malformed or unmappable byte
* sequence is read, is wrapped in an {@link UncheckedIOException} that will * sequence is read, is wrapped in an {@link UncheckedIOException} that will
@ -3761,6 +3767,30 @@ public final class Files {
* control structure to ensure that the stream's open file is closed promptly * control structure to ensure that the stream's open file is closed promptly
* after the stream's operations have completed. * after the stream's operations have completed.
* *
* @implNote
* This implementation supports good parallel stream performance for the
* standard charsets {@link StandardCharsets#UTF_8 UTF-8},
* {@link StandardCharsets#US_ASCII US-ASCII} and
* {@link StandardCharsets#ISO_8859_1 ISO-8859-1}. Such
* <em>line-optimal</em> charsets have the property that the encoded bytes
* of a line feed ('\n') or a carriage return ('\r') are efficiently
* identifiable from other encoded characters when randomly accessing the
* bytes of the file.
*
* <p> For non-<em>line-optimal</em> charsets the stream source's
* spliterator has poor splitting properties, similar to that of a
* spliterator associated with an iterator or that associated with a stream
* returned from {@link BufferedReader#lines()}. Poor splitting properties
* can result in poor parallel stream performance.
*
* <p> For <em>line-optimal</em> charsets the stream source's spliterator
* has good splitting properties, assuming the file contains a regular
* sequence of lines. Good splitting properties can result in good parallel
* stream performance. The spliterator for a <em>line-optimal</em> charset
* takes advantage of the charset properties (a line feed or a carriage
* return being efficient identifiable) such that when splitting it can
* approximately divide the number of covered lines in half.
*
* @param path * @param path
* the path to the file * the path to the file
* @param cs * @param cs
@ -3781,7 +3811,50 @@ public final class Files {
* @since 1.8 * @since 1.8
*/ */
public static Stream<String> lines(Path path, Charset cs) throws IOException { public static Stream<String> lines(Path path, Charset cs) throws IOException {
BufferedReader br = Files.newBufferedReader(path, cs); // Use the good splitting spliterator if:
// 1) the path is associated with the default file system;
// 2) the character set is supported; and
// 3) the file size is such that all bytes can be indexed by int values
// (this limitation is imposed by ByteBuffer)
if (path.getFileSystem() == FileSystems.getDefault() &&
FileChannelLinesSpliterator.SUPPORTED_CHARSET_NAMES.contains(cs.name())) {
FileChannel fc = FileChannel.open(path, StandardOpenOption.READ);
Stream<String> fcls = createFileChannelLinesStream(fc, cs);
if (fcls != null) {
return fcls;
}
fc.close();
}
return createBufferedReaderLinesStream(Files.newBufferedReader(path, cs));
}
private static Stream<String> createFileChannelLinesStream(FileChannel fc, Charset cs) throws IOException {
try {
// Obtaining the size from the FileChannel is much faster
// than obtaining using path.toFile().length()
long length = fc.size();
if (length <= Integer.MAX_VALUE) {
Spliterator<String> s = new FileChannelLinesSpliterator(fc, cs, 0, (int) length);
return StreamSupport.stream(s, false)
.onClose(Files.asUncheckedRunnable(fc));
}
} catch (Error|RuntimeException|IOException e) {
try {
fc.close();
} catch (IOException ex) {
try {
e.addSuppressed(ex);
} catch (Throwable ignore) {
}
}
throw e;
}
return null;
}
private static Stream<String> createBufferedReaderLinesStream(BufferedReader br) {
try { try {
return br.lines().onClose(asUncheckedRunnable(br)); return br.lines().onClose(asUncheckedRunnable(br));
} catch (Error|RuntimeException e) { } catch (Error|RuntimeException e) {
@ -3790,7 +3863,8 @@ public final class Files {
} catch (IOException ex) { } catch (IOException ex) {
try { try {
e.addSuppressed(ex); e.addSuppressed(ex);
} catch (Throwable ignore) {} } catch (Throwable ignore) {
}
} }
throw e; throw e;
} }
@ -3804,6 +3878,10 @@ public final class Files {
* <p> The returned stream contains a reference to an open file. The file * <p> The returned stream contains a reference to an open file. The file
* is closed by closing the stream. * is closed by closing the stream.
* *
* <p> The file contents should not be modified during the execution of the
* terminal stream operation. Otherwise, the result of the terminal stream
* operation is undefined.
*
* <p> This method works as if invoking it were equivalent to evaluating the * <p> This method works as if invoking it were equivalent to evaluating the
* expression: * expression:
* <pre>{@code * <pre>{@code

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -41,30 +41,22 @@ import java.util.function.Function;
* *
* <ul> * <ul>
* *
* <li>Algorithms (such as DSA, RSA, MD5 or SHA-1). * <li>Algorithms (such as DSA, RSA, or SHA-256).
* *
* <li>Key generation, conversion, and management facilities (such as for * <li>Key generation, conversion, and management facilities (such as for
* algorithm-specific keys). * algorithm-specific keys).
* *
*</ul> * </ul>
*
* <p>Each provider has a name and a version number, and is configured
* in each runtime it is installed in.
*
* <p>See <a href =
* "../../../technotes/guides/security/crypto/CryptoSpec.html#Provider">The Provider Class</a>
* in the "Java Cryptography Architecture API Specification &amp; Reference"
* for information about how a particular type of provider, the
* cryptographic service provider, works and is installed. However,
* please note that a provider can be used to implement any security
* service in Java that uses a pluggable architecture with a choice
* of implementations that fit underneath.
* *
* <p>Some provider implementations may encounter unrecoverable internal * <p>Some provider implementations may encounter unrecoverable internal
* errors during their operation, for example a failure to communicate with a * errors during their operation, for example a failure to communicate with a
* security token. A {@link ProviderException} should be used to indicate * security token. A {@link ProviderException} should be used to indicate
* such errors. * such errors.
* *
* <p>Please note that a provider can be used to implement any security
* service in Java that uses a pluggable architecture with a choice
* of implementations that fit underneath.
*
* <p>The service type {@code Provider} is reserved for use by the * <p>The service type {@code Provider} is reserved for use by the
* security framework. Services of this type cannot be added, removed, * security framework. Services of this type cannot be added, removed,
* or modified by applications. * or modified by applications.
@ -82,6 +74,28 @@ import java.util.function.Function;
* <td>{@code provider.getClass().getName()}</td> * <td>{@code provider.getClass().getName()}</td>
* </table> * </table>
* *
* <p>Each provider has a name and a version number. A provider normally
* identifies itself with a file named {@code java.security.Provider}
* in the resource directory {@code META-INF/services}.
* Security providers are looked up via the {@link ServiceLoader} mechanism
* using the {@link ClassLoader#getSystemClassLoader application class loader}.
*
* <p>Providers may be configured such that they are automatically
* installed and made available at runtime via the
* {@link Security#getProviders() Security.getProviders()} method.
* The mechanism for configuring and installing security providers is
* implementation-specific.
*
* @implNote
* The JDK implementation supports static registration of the security
* providers via the {@code conf/security/java.security} file in the Java
* installation directory. These providers are automatically installed by
* the JDK runtime, see <a href =
* "../../../technotes/guides/security/crypto/CryptoSpec.html#Provider">The Provider Class</a>
* in the "Java Cryptography Architecture API Specification &amp; Reference"
* for information about how a particular type of provider, the cryptographic
* service provider, works and is installed.
*
* @author Benjamin Renaud * @author Benjamin Renaud
* @author Andreas Sterbenz * @author Andreas Sterbenz
*/ */
@ -121,6 +135,18 @@ public abstract class Provider extends Properties {
private transient boolean initialized; private transient boolean initialized;
private static Object newInstanceUtil(final Class<?> clazz,
final Class<?> ctrParamClz, final Object ctorParamObj)
throws Exception {
if (ctrParamClz == null) {
Constructor<?> con = clazz.getConstructor();
return con.newInstance();
} else {
Constructor<?> con = clazz.getConstructor(ctrParamClz);
return con.newInstance(ctorParamObj);
}
}
/** /**
* Constructs a provider with the specified name, version number, * Constructs a provider with the specified name, version number,
* and information. * and information.
@ -139,6 +165,34 @@ public abstract class Provider extends Properties {
initialized = true; initialized = true;
} }
/**
* Apply the supplied configuration argument to this provider instance
* and return the configured provider. Note that if this provider cannot
* be configured in-place, a new provider will be created and returned.
* Therefore, callers should always use the returned provider.
*
* @implSpec
* The default implementation throws {@code UnsupportedOperationException}.
* Subclasses should override this method only if a configuration argument
* is supported.
*
* @param configArg the configuration information for configuring this
* provider.
*
* @throws UnsupportedOperationException if a configuration argument is
* not supported.
* @throws NullPointerException if the supplied configuration argument is
null.
* @throws InvalidParameterException if the supplied configuration argument
* is invalid.
* @return a provider configured with the supplied configuration argument.
*
* @since 1.9
*/
public Provider configure(String configArg) {
throw new UnsupportedOperationException("configure is not supported");
}
/** /**
* Returns the name of this provider. * Returns the name of this provider.
* *
@ -212,8 +266,8 @@ public abstract class Provider extends Properties {
/** /**
* Reads a property list (key and element pairs) from the input stream. * Reads a property list (key and element pairs) from the input stream.
* *
* @param inStream the input stream. * @param inStream the input stream.
* @exception IOException if an error occurred when reading from the * @exception IOException if an error occurred when reading from the
* input stream. * input stream.
* @see java.util.Properties#load * @see java.util.Properties#load
*/ */
@ -1579,39 +1633,35 @@ public abstract class Provider extends Properties {
} }
registered = true; registered = true;
} }
Class<?> ctrParamClz;
try { try {
EngineDescription cap = knownEngines.get(type); EngineDescription cap = knownEngines.get(type);
if (cap == null) { if (cap == null) {
// unknown engine type, use generic code // unknown engine type, use generic code
// this is the code path future for non-core // this is the code path future for non-core
// optional packages // optional packages
return newInstanceGeneric(constructorParameter); ctrParamClz = constructorParameter == null?
} null : constructorParameter.getClass();
if (cap.constructorParameterClassName == null) {
if (constructorParameter != null) {
throw new InvalidParameterException
("constructorParameter not used with " + type
+ " engines");
}
Class<?> clazz = getImplClass();
Class<?>[] empty = {};
Constructor<?> con = clazz.getConstructor(empty);
return con.newInstance();
} else { } else {
Class<?> paramClass = cap.getConstructorParameterClass(); ctrParamClz = cap.constructorParameterClassName == null?
null : Class.forName(cap.constructorParameterClassName);
if (constructorParameter != null) { if (constructorParameter != null) {
Class<?> argClass = constructorParameter.getClass(); if (ctrParamClz == null) {
if (paramClass.isAssignableFrom(argClass) == false) {
throw new InvalidParameterException throw new InvalidParameterException
("constructorParameter must be instanceof " ("constructorParameter not used with " + type
+ cap.constructorParameterClassName.replace('$', '.') + " engines");
+ " for engine type " + type); } else {
Class<?> argClass = constructorParameter.getClass();
if (ctrParamClz.isAssignableFrom(argClass) == false) {
throw new InvalidParameterException
("constructorParameter must be instanceof "
+ cap.constructorParameterClassName.replace('$', '.')
+ " for engine type " + type);
}
} }
} }
Class<?> clazz = getImplClass();
Constructor<?> cons = clazz.getConstructor(paramClass);
return cons.newInstance(constructorParameter);
} }
return newInstanceUtil(getImplClass(), ctrParamClz, constructorParameter);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw e; throw e;
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
@ -1654,43 +1704,6 @@ public abstract class Provider extends Properties {
} }
} }
/**
* Generic code path for unknown engine types. Call the
* no-args constructor if constructorParameter is null, otherwise
* use the first matching constructor.
*/
private Object newInstanceGeneric(Object constructorParameter)
throws Exception {
Class<?> clazz = getImplClass();
if (constructorParameter == null) {
// create instance with public no-arg constructor if it exists
try {
Class<?>[] empty = {};
Constructor<?> con = clazz.getConstructor(empty);
return con.newInstance();
} catch (NoSuchMethodException e) {
throw new NoSuchAlgorithmException("No public no-arg "
+ "constructor found in class " + className);
}
}
Class<?> argClass = constructorParameter.getClass();
Constructor<?>[] cons = clazz.getConstructors();
// find first public constructor that can take the
// argument as parameter
for (Constructor<?> con : cons) {
Class<?>[] paramTypes = con.getParameterTypes();
if (paramTypes.length != 1) {
continue;
}
if (paramTypes[0].isAssignableFrom(argClass) == false) {
continue;
}
return con.newInstance(constructorParameter);
}
throw new NoSuchAlgorithmException("No public constructor matching "
+ argClass.getName() + " found in class " + className);
}
/** /**
* Test whether this Service can use the specified parameter. * Test whether this Service can use the specified parameter.
* Returns false if this service cannot use the parameter. Returns * Returns false if this service cannot use the parameter. Returns

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -41,7 +41,7 @@ import sun.security.jca.*;
* *
* <p>The default values of security properties are read from an * <p>The default values of security properties are read from an
* implementation-specific location, which is typically the properties file * implementation-specific location, which is typically the properties file
* {@code lib/security/java.security} in the Java installation directory. * {@code conf/security/java.security} in the Java installation directory.
* *
* @author Benjamin Renaud * @author Benjamin Renaud
*/ */

View File

@ -737,7 +737,7 @@ public class Base64 {
// anything left is invalid, if is not MIME. // anything left is invalid, if is not MIME.
// if MIME, ignore all non-base64 character // if MIME, ignore all non-base64 character
while (sp < sl) { while (sp < sl) {
if (isMIME && base64[src[sp++]] < 0) if (isMIME && base64[src[sp++] & 0xff] < 0)
continue; continue;
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Input byte array has incorrect ending byte at " + sp); "Input byte array has incorrect ending byte at " + sp);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -242,8 +242,6 @@ public class DoubleSummaryStatistics implements DoubleConsumer {
} }
/** /**
* {@inheritDoc}
*
* Returns a non-empty string representation of this object suitable for * Returns a non-empty string representation of this object suitable for
* debugging. The exact presentation format is unspecified and may vary * debugging. The exact presentation format is unspecified and may vary
* between implementations and versions. * between implementations and versions.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -150,14 +150,12 @@ public class IntSummaryStatistics implements IntConsumer {
return getCount() > 0 ? (double) getSum() / getCount() : 0.0d; return getCount() > 0 ? (double) getSum() / getCount() : 0.0d;
} }
@Override
/** /**
* {@inheritDoc}
*
* Returns a non-empty string representation of this object suitable for * Returns a non-empty string representation of this object suitable for
* debugging. The exact presentation format is unspecified and may vary * debugging. The exact presentation format is unspecified and may vary
* between implementations and versions. * between implementations and versions.
*/ */
@Override
public String toString() { public String toString() {
return String.format( return String.format(
"%s{count=%d, sum=%d, min=%d, average=%f, max=%d}", "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -162,14 +162,12 @@ public class LongSummaryStatistics implements LongConsumer, IntConsumer {
return getCount() > 0 ? (double) getSum() / getCount() : 0.0d; return getCount() > 0 ? (double) getSum() / getCount() : 0.0d;
} }
@Override
/** /**
* {@inheritDoc}
*
* Returns a non-empty string representation of this object suitable for * Returns a non-empty string representation of this object suitable for
* debugging. The exact presentation format is unspecified and may vary * debugging. The exact presentation format is unspecified and may vary
* between implementations and versions. * between implementations and versions.
*/ */
@Override
public String toString() { public String toString() {
return String.format( return String.format(
"%s{count=%d, sum=%d, min=%d, average=%f, max=%d}", "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",

View File

@ -112,29 +112,36 @@ import java.util.Locale;
* provider returns null instead of a name, the lookup will proceed as * provider returns null instead of a name, the lookup will proceed as
* described above as if the locale was not supported. * described above as if the locale was not supported.
* <p> * <p>
* Starting from JDK8, the search order of locale sensitive services can * The search order of locale sensitive services can
* be configured by using the "java.locale.providers" system property. * be configured by using the "java.locale.providers" system property.
* This system property declares the user's preferred order for looking up * This system property declares the user's preferred order for looking up
* the locale sensitive services separated by a comma. It is only read at * the locale sensitive services separated by a comma. It is only read at
* the Java runtime startup, so the later call to System.setProperty() won't * the Java runtime startup, so the later call to System.setProperty() won't
* affect the order. * affect the order.
* <p> * <p>
* Java Runtime Environment provides the following four locale providers:
* <ul>
* <li> "CLDR": A provider based on Unicode Consortium's
* <a href="http://cldr.unicode.org/">CLDR Project</a>.
* <li> "JRE": represents the locale sensitive services that is compatible
* with the prior JDK releases (same with JDK8's "JRE").
* <li> "SPI": represents the locale sensitive services implementing the subclasses of
* this {@code LocaleServiceProvider} class.
* <li> "HOST": A provider that reflects the user's custom settings in the
* underlying operating system. This provider may not be available, depending
* on the Java Runtime Environment implementation.
* </ul>
* <p>
* For example, if the following is specified in the property: * For example, if the following is specified in the property:
* <pre> * <pre>
* java.locale.providers=SPI,JRE * java.locale.providers=SPI,CLDR,JRE
* </pre> * </pre>
* where "SPI" represents the locale sensitive services implemented in the * the locale sensitive services in the SPI providers are looked up first. If the
* installed SPI providers, and "JRE" represents the locale sensitive services * desired locale sensitive service is not available, then the runtime looks for CLDR,
* in the Java Runtime Environment, the locale sensitive services in the SPI * JRE in that order.
* providers are looked up first.
* <p> * <p>
* There are two other possible locale sensitive service providers, i.e., "CLDR" * The default order for looking up the preferred locale providers is "CLDR,JRE,SPI",
* which is a provider based on Unicode Consortium's * so specifying "CLDR,JRE,SPI" is identical to the default behavior.
* <a href="http://cldr.unicode.org/">CLDR Project</a>, and "HOST" which is a
* provider that reflects the user's custom settings in the underlying operating
* system. These two providers may not be available, depending on the Java Runtime
* Environment implementation. Specifying "JRE,SPI" is identical to the default
* behavior, which is compatibile with the prior releases.
* *
* @since 1.6 * @since 1.6
*/ */

View File

@ -249,6 +249,11 @@ abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>
// If the last intermediate operation is stateful then // If the last intermediate operation is stateful then
// evaluate directly to avoid an extra collection step // evaluate directly to avoid an extra collection step
if (isParallel() && previousStage != null && opIsStateful()) { if (isParallel() && previousStage != null && opIsStateful()) {
// Set the depth of this, last, pipeline stage to zero to slice the
// pipeline such that this operation will not be included in the
// upstream slice and upstream operations will not be included
// in this slice
depth = 0;
return opEvaluateParallel(previousStage, previousStage.sourceSpliterator(0), generator); return opEvaluateParallel(previousStage, previousStage.sourceSpliterator(0), generator);
} }
else { else {
@ -402,47 +407,19 @@ abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>
throw new IllegalStateException(MSG_CONSUMED); throw new IllegalStateException(MSG_CONSUMED);
} }
boolean hasTerminalFlags = terminalFlags != 0;
if (isParallel() && sourceStage.sourceAnyStateful) { if (isParallel() && sourceStage.sourceAnyStateful) {
// Adjust pipeline stages if there are stateful ops,
// and find the last short circuiting op, if any, that
// defines the head stage for back-propagation of terminal flags
@SuppressWarnings("rawtypes")
AbstractPipeline backPropagationHead = sourceStage;
int depth = 1;
for (@SuppressWarnings("rawtypes") AbstractPipeline p = sourceStage.nextStage;
p != null;
p = p.nextStage) {
if (p.opIsStateful()) {
if (StreamOpFlag.SHORT_CIRCUIT.isKnown(p.sourceOrOpFlags)) {
// If the stateful operation is a short-circuit operation
// then move the back propagation head forwards
// NOTE: there are no size-injecting ops
backPropagationHead = p;
}
depth = 0;
}
p.depth = depth++;
}
// Adapt the source spliterator, evaluating each stateful op // Adapt the source spliterator, evaluating each stateful op
// in the pipeline up to and including this pipeline stage // in the pipeline up to and including this pipeline stage.
// Flags for each pipeline stage are adjusted accordingly // The depth and flags of each pipeline stage are adjusted accordingly.
boolean backPropagate = false; int depth = 1;
int upstreamTerminalFlags = terminalFlags & StreamOpFlag.UPSTREAM_TERMINAL_OP_MASK;
for (@SuppressWarnings("rawtypes") AbstractPipeline u = sourceStage, p = sourceStage.nextStage, e = this; for (@SuppressWarnings("rawtypes") AbstractPipeline u = sourceStage, p = sourceStage.nextStage, e = this;
u != e; u != e;
u = p, p = p.nextStage) { u = p, p = p.nextStage) {
if (hasTerminalFlags &&
(backPropagate || (backPropagate = (u == backPropagationHead)))) {
// Back-propagate flags from the terminal operation
u.combinedFlags = StreamOpFlag.combineOpFlags(upstreamTerminalFlags, u.combinedFlags);
}
int thisOpFlags = p.sourceOrOpFlags; int thisOpFlags = p.sourceOrOpFlags;
if (p.opIsStateful()) { if (p.opIsStateful()) {
depth = 0;
if (StreamOpFlag.SHORT_CIRCUIT.isKnown(thisOpFlags)) { if (StreamOpFlag.SHORT_CIRCUIT.isKnown(thisOpFlags)) {
// Clear the short circuit flag for next pipeline stage // Clear the short circuit flag for next pipeline stage
// This stage encapsulates short-circuiting, the next // This stage encapsulates short-circuiting, the next
@ -460,11 +437,12 @@ abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>
? (thisOpFlags & ~StreamOpFlag.NOT_SIZED) | StreamOpFlag.IS_SIZED ? (thisOpFlags & ~StreamOpFlag.NOT_SIZED) | StreamOpFlag.IS_SIZED
: (thisOpFlags & ~StreamOpFlag.IS_SIZED) | StreamOpFlag.NOT_SIZED; : (thisOpFlags & ~StreamOpFlag.IS_SIZED) | StreamOpFlag.NOT_SIZED;
} }
p.depth = depth++;
p.combinedFlags = StreamOpFlag.combineOpFlags(thisOpFlags, u.combinedFlags); p.combinedFlags = StreamOpFlag.combineOpFlags(thisOpFlags, u.combinedFlags);
} }
} }
if (hasTerminalFlags) { if (terminalFlags != 0) {
// Apply flags from the terminal operation to last pipeline stage // Apply flags from the terminal operation to last pipeline stage
combinedFlags = StreamOpFlag.combineOpFlags(terminalFlags, combinedFlags); combinedFlags = StreamOpFlag.combineOpFlags(terminalFlags, combinedFlags);
} }
@ -472,7 +450,6 @@ abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>
return spliterator; return spliterator;
} }
// PipelineHelper // PipelineHelper
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -27,14 +27,15 @@ package sun.security.jca;
import java.io.File; import java.io.File;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.util.*;
import java.security.*; import java.security.*;
import sun.security.util.PropertyExpander; import sun.security.util.PropertyExpander;
/** /**
* Class representing a configured provider. Encapsulates configuration * Class representing a configured provider which encapsulates configuration
* (className plus optional argument), the provider loading logic, and * (provider name + optional argument), the provider loading logic, and
* the loaded Provider object itself. * the loaded Provider object itself.
* *
* @author Andreas Sterbenz * @author Andreas Sterbenz
@ -45,9 +46,8 @@ final class ProviderConfig {
private final static sun.security.util.Debug debug = private final static sun.security.util.Debug debug =
sun.security.util.Debug.getInstance("jca", "ProviderConfig"); sun.security.util.Debug.getInstance("jca", "ProviderConfig");
// classname of the SunPKCS11-Solaris provider // suffix for identifying the SunPKCS11-Solaris provider
private static final String P11_SOL_NAME = private static final String P11_SOL_NAME = "SunPKCS11";
"sun.security.pkcs11.SunPKCS11";
// config file argument of the SunPKCS11-Solaris provider // config file argument of the SunPKCS11-Solaris provider
private static final String P11_SOL_ARG = private static final String P11_SOL_ARG =
@ -56,15 +56,10 @@ final class ProviderConfig {
// maximum number of times to try loading a provider before giving up // maximum number of times to try loading a provider before giving up
private final static int MAX_LOAD_TRIES = 30; private final static int MAX_LOAD_TRIES = 30;
// parameters for the Provider(String) constructor, // could be provider name (module) or provider class name (legacy)
// use by doLoadProvider() private final String provName;
private final static Class<?>[] CL_STRING = { String.class };
// name of the provider class // argument to the Provider.configure() call, never null
private final String className;
// argument to the provider constructor,
// empty string indicates no-arg constructor
private final String argument; private final String argument;
// number of times we have already tried to load this provider // number of times we have already tried to load this provider
@ -77,20 +72,20 @@ final class ProviderConfig {
// used to detect recursion // used to detect recursion
private boolean isLoading; private boolean isLoading;
ProviderConfig(String className, String argument) { ProviderConfig(String provName, String argument) {
if (className.equals(P11_SOL_NAME) && argument.equals(P11_SOL_ARG)) { if (provName.endsWith(P11_SOL_NAME) && argument.equals(P11_SOL_ARG)) {
checkSunPKCS11Solaris(); checkSunPKCS11Solaris();
} }
this.className = className; this.provName = provName;
this.argument = expand(argument); this.argument = expand(argument);
} }
ProviderConfig(String className) { ProviderConfig(String provName) {
this(className, ""); this(provName, "");
} }
ProviderConfig(Provider provider) { ProviderConfig(Provider provider) {
this.className = provider.getClass().getName(); this.provName = provider.getName();
this.argument = ""; this.argument = "";
this.provider = provider; this.provider = provider;
} }
@ -144,19 +139,20 @@ final class ProviderConfig {
return false; return false;
} }
ProviderConfig other = (ProviderConfig)obj; ProviderConfig other = (ProviderConfig)obj;
return this.className.equals(other.className) return this.provName.equals(other.provName)
&& this.argument.equals(other.argument); && this.argument.equals(other.argument);
} }
public int hashCode() { public int hashCode() {
return className.hashCode() + argument.hashCode(); return provName.hashCode() + argument.hashCode();
} }
public String toString() { public String toString() {
if (hasArgument()) { if (hasArgument()) {
return className + "('" + argument + "')"; return provName + "('" + argument + "')";
} else { } else {
return className; return provName;
} }
} }
@ -172,21 +168,33 @@ final class ProviderConfig {
if (shouldLoad() == false) { if (shouldLoad() == false) {
return null; return null;
} }
if (isLoading) {
// because this method is synchronized, this can only // Create providers which are in java.base directly
// happen if there is recursion. if (provName.equals("SUN") || provName.equals("sun.security.provider.Sun")) {
if (debug != null) { p = new sun.security.provider.Sun();
debug.println("Recursion loading provider: " + this); } else if (provName.equals("SunRsaSign") || provName.equals("sun.security.rsa.SunRsaSign")) {
new Exception("Call trace").printStackTrace(); p = new sun.security.rsa.SunRsaSign();
} else if (provName.equals("SunJCE") || provName.equals("com.sun.crypto.provider.SunJCE")) {
p = new com.sun.crypto.provider.SunJCE();
} else if (provName.equals("SunJSSE") || provName.equals("com.sun.net.ssl.internal.ssl.Provider")) {
p = new com.sun.net.ssl.internal.ssl.Provider();
} else {
if (isLoading) {
// because this method is synchronized, this can only
// happen if there is recursion.
if (debug != null) {
debug.println("Recursion loading provider: " + this);
new Exception("Call trace").printStackTrace();
}
return null;
}
try {
isLoading = true;
tries++;
p = doLoadProvider();
} finally {
isLoading = false;
} }
return null;
}
try {
isLoading = true;
tries++;
p = doLoadProvider();
} finally {
isLoading = false;
} }
provider = p; provider = p;
return p; return p;
@ -206,55 +214,39 @@ final class ProviderConfig {
return AccessController.doPrivileged(new PrivilegedAction<Provider>() { return AccessController.doPrivileged(new PrivilegedAction<Provider>() {
public Provider run() { public Provider run() {
if (debug != null) { if (debug != null) {
debug.println("Loading provider: " + ProviderConfig.this); debug.println("Loading provider " + ProviderConfig.this);
} }
ProviderLoader pl = new ProviderLoader();
try { try {
ClassLoader cl = ClassLoader.getSystemClassLoader(); Provider p = pl.load(provName);
Class<?> provClass; if (p != null) {
if (cl != null) { if (hasArgument()) {
provClass = cl.loadClass(className); p = p.configure(argument);
} else { }
provClass = Class.forName(className); if (debug != null) {
} debug.println("Loaded provider " + p.getName());
Object obj;
if (hasArgument() == false) {
obj = provClass.newInstance();
} else {
Constructor<?> cons = provClass.getConstructor(CL_STRING);
obj = cons.newInstance(argument);
}
if (obj instanceof Provider) {
if (debug != null) {
debug.println("Loaded provider " + obj);
} }
return (Provider)obj;
} else { } else {
if (debug != null) { if (debug != null) {
debug.println(className + " is not a provider"); debug.println("Error loading provider " +
ProviderConfig.this);
}
disableLoad();
}
return p;
} catch (Exception e) {
if (e instanceof ProviderException) {
// pass up
throw e;
} else {
if (debug != null) {
debug.println("Error loading provider " +
ProviderConfig.this);
e.printStackTrace();
} }
disableLoad(); disableLoad();
return null; return null;
} }
} catch (Exception e) {
Throwable t;
if (e instanceof InvocationTargetException) {
t = ((InvocationTargetException)e).getCause();
} else {
t = e;
}
if (debug != null) {
debug.println("Error loading provider " + ProviderConfig.this);
t.printStackTrace();
}
// provider indicates fatal error, pass through exception
if (t instanceof ProviderException) {
throw (ProviderException)t;
}
// provider indicates that loading should not be retried
if (t instanceof UnsupportedOperationException) {
disableLoad();
}
return null;
} catch (ExceptionInInitializerError err) { } catch (ExceptionInInitializerError err) {
// no sufficient permission to initialize provider class // no sufficient permission to initialize provider class
if (debug != null) { if (debug != null) {
@ -289,4 +281,119 @@ final class ProviderConfig {
}); });
} }
// Inner class for loading security providers listed in java.security file
private static final class ProviderLoader {
private final ServiceLoader<Provider> services;
ProviderLoader() {
// VM should already been booted at this point, if not
// - Only providers in java.base should be loaded, don't use
// ServiceLoader
// - ClassLoader.getSystemClassLoader() will throw InternalError
services = ServiceLoader.load(java.security.Provider.class,
ClassLoader.getSystemClassLoader());
}
/**
* Loads the provider with the specified class name.
*
* @param name the name of the provider
* @return the Provider, or null if it cannot be found or loaded
* @throws ProviderException all other exceptions are ignored
*/
public Provider load(String pn) {
if (debug != null) {
debug.println("Attempt to load " + pn + " using SL");
}
Iterator<Provider> iter = services.iterator();
while (iter.hasNext()) {
try {
Provider p = iter.next();
String pName = p.getName();
if (debug != null) {
debug.println("Found SL Provider named " + pName);
}
if (pName.equals(pn)) {
return p;
}
} catch (SecurityException | ServiceConfigurationError |
InvalidParameterException ex) {
// if provider loading fail due to security permission,
// log it and move on to next provider
if (debug != null) {
debug.println("Encountered " + ex +
" while iterating through SL, ignore and move on");
ex.printStackTrace();
}
}
}
// No success with ServiceLoader. Try loading provider the legacy,
// i.e. pre-module, way via reflection
try {
return legacyLoad(pn);
} catch (ProviderException pe) {
// pass through
throw pe;
} catch (Exception ex) {
// logged and ignored
if (debug != null) {
debug.println("Encountered " + ex +
" during legacy load of " + pn);
ex.printStackTrace();
}
return null;
}
}
private Provider legacyLoad(String classname) {
if (debug != null) {
debug.println("Loading legacy provider: " + classname);
}
try {
Class<?> provClass =
ClassLoader.getSystemClassLoader().loadClass(classname);
// only continue if the specified class extends Provider
if (!Provider.class.isAssignableFrom(provClass)) {
if (debug != null) {
debug.println(classname + " is not a provider");
}
return null;
}
Provider p = AccessController.doPrivileged
(new PrivilegedExceptionAction<Provider>() {
public Provider run() throws Exception {
return (Provider) provClass.newInstance();
}
});
return p;
} catch (Exception e) {
Throwable t;
if (e instanceof InvocationTargetException) {
t = ((InvocationTargetException)e).getCause();
} else {
t = e;
}
if (debug != null) {
debug.println("Error loading legacy provider " + classname);
t.printStackTrace();
}
// provider indicates fatal error, pass through exception
if (t instanceof ProviderException) {
throw (ProviderException) t;
}
return null;
} catch (ExceptionInInitializerError | NoClassDefFoundError err) {
// no sufficient permission to access/initialize provider class
if (debug != null) {
debug.println("Error loading legacy provider " + classname);
err.printStackTrace();
}
return null;
}
}
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -178,9 +178,9 @@ public final class ProviderList {
if (k == -1) { if (k == -1) {
config = new ProviderConfig(entry); config = new ProviderConfig(entry);
} else { } else {
String className = entry.substring(0, k); String provName = entry.substring(0, k);
String argument = entry.substring(k + 1).trim(); String argument = entry.substring(k + 1).trim();
config = new ProviderConfig(className, argument); config = new ProviderConfig(provName, argument);
} }
// Get rid of duplicate providers. // Get rid of duplicate providers.
@ -200,10 +200,10 @@ public final class ProviderList {
* bootclasspath and cannot be in signed JAR files. This is to avoid * bootclasspath and cannot be in signed JAR files. This is to avoid
* possible recursion and deadlock during verification. * possible recursion and deadlock during verification.
*/ */
ProviderList getJarList(String[] jarClassNames) { ProviderList getJarList(String[] jarProvNames) {
List<ProviderConfig> newConfigs = new ArrayList<>(); List<ProviderConfig> newConfigs = new ArrayList<>();
for (String className : jarClassNames) { for (String provName : jarProvNames) {
ProviderConfig newConfig = new ProviderConfig(className); ProviderConfig newConfig = new ProviderConfig(provName);
for (ProviderConfig config : configs) { for (ProviderConfig config : configs) {
// if the equivalent object is present in this provider list, // if the equivalent object is present in this provider list,
// use the old object rather than the new object. // use the old object rather than the new object.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -58,9 +58,13 @@ public class Providers {
// empty // empty
} }
// we need special handling to resolve circularities when loading // After the switch to modules, JDK providers are all in modules and JDK
// signed JAR files during startup. The code below is part of that. // no longer needs to load signed jars during start up.
//
// However, for earlier releases, it need special handling to resolve
// circularities when loading signed JAR files during startup. The code
// below is part of that.
//
// Basically, before we load data from a signed JAR file, we parse // Basically, before we load data from a signed JAR file, we parse
// the PKCS#7 file and verify the signature. We need a // the PKCS#7 file and verify the signature. We need a
// CertificateFactory, Signatures, etc. to do that. We have to make // CertificateFactory, Signatures, etc. to do that. We have to make
@ -75,35 +79,24 @@ public class Providers {
// The code here is used by sun.security.util.SignatureFileVerifier. // The code here is used by sun.security.util.SignatureFileVerifier.
// See there for details. // See there for details.
private static final String BACKUP_PROVIDER_CLASSNAME = // Hardcoded names of providers to use for JAR verification.
"sun.security.provider.VerificationProvider";
// Hardcoded classnames of providers to use for JAR verification.
// MUST NOT be on the bootclasspath and not in signed JAR files. // MUST NOT be on the bootclasspath and not in signed JAR files.
private static final String[] jarVerificationProviders = { private static final String[] jarVerificationProviders = {
"sun.security.provider.Sun", "SUN",
"sun.security.rsa.SunRsaSign", "SunRsaSign",
// Note: SunEC *is* in a signed JAR file, but it's not signed // Note: when SunEC is in a signed JAR file, it's not signed
// by EC itself. So it's still safe to be listed here. // by EC algorithms. So it's still safe to be listed here.
// Need to use class name here, otherwise it cannot be loaded for
// jar verification. Only those providers in java.base are created
// directly by ProviderConfig class.
"sun.security.ec.SunEC", "sun.security.ec.SunEC",
BACKUP_PROVIDER_CLASSNAME,
}; };
// Return to Sun provider or its backup. // Return Sun provider.
// This method should only be called by // This method should only be called by
// sun.security.util.ManifestEntryVerifier and java.security.SecureRandom. // sun.security.util.ManifestEntryVerifier and java.security.SecureRandom.
public static Provider getSunProvider() { public static Provider getSunProvider() {
try { return new sun.security.provider.Sun();
Class<?> clazz = Class.forName(jarVerificationProviders[0]);
return (Provider)clazz.newInstance();
} catch (Exception e) {
try {
Class<?> clazz = Class.forName(BACKUP_PROVIDER_CLASSNAME);
return (Provider)clazz.newInstance();
} catch (Exception ee) {
throw new RuntimeException("Sun provider not found", e);
}
}
} }
/** /**
@ -115,6 +108,16 @@ public class Providers {
public static Object startJarVerification() { public static Object startJarVerification() {
ProviderList currentList = getProviderList(); ProviderList currentList = getProviderList();
ProviderList jarList = currentList.getJarList(jarVerificationProviders); ProviderList jarList = currentList.getJarList(jarVerificationProviders);
if (jarList.getProvider("SUN") == null) {
// add backup provider
Provider p;
try {
p = new sun.security.provider.VerificationProvider();
} catch (Exception e) {
throw new RuntimeException("Missing provider for jar verification", e);
}
ProviderList.add(jarList, p);
}
// return the old thread-local provider list, usually null // return the old thread-local provider list, usually null
return beginThreadProviderList(jarList); return beginThreadProviderList(jarList);
} }

View File

@ -728,21 +728,19 @@ public final class Main {
provClass = Class.forName(provName); provClass = Class.forName(provName);
} }
String provArg = provider.snd; Object obj = provClass.newInstance();
Object obj;
if (provArg == null) {
obj = provClass.newInstance();
} else {
Constructor<?> c = provClass.getConstructor(PARAM_STRING);
obj = c.newInstance(provArg);
}
if (!(obj instanceof Provider)) { if (!(obj instanceof Provider)) {
MessageFormat form = new MessageFormat MessageFormat form = new MessageFormat
(rb.getString("provName.not.a.provider")); (rb.getString("provName.not.a.provider"));
Object[] source = {provName}; Object[] source = {provName};
throw new Exception(form.format(source)); throw new Exception(form.format(source));
} }
Security.addProvider((Provider)obj); Provider p = (Provider) obj;
String provArg = provider.snd;
if (provArg != null) {
p = p.configure(provArg);
}
Security.addProvider(p);
} }
} }

View File

@ -858,9 +858,6 @@ public class FormatData extends ParallelListResourceBundle {
} }
}, },
{ "DateTimePatternChars", "GyMdkHmsSEDFwWahKzZ" }, { "DateTimePatternChars", "GyMdkHmsSEDFwWahKzZ" },
// Workaround for islamic-umalqura name support (JDK-8015986)
{ "calendarname.islamic-umalqura", "Islamic Umm al-Qura Calendar" },
}; };
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -26,37 +26,41 @@
/* /*
* COPYRIGHT AND PERMISSION NOTICE * COPYRIGHT AND PERMISSION NOTICE
* *
* Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under * Copyright (C) 1991-2015 Unicode, Inc. All rights reserved.
* the Terms of Use in http://www.unicode.org/copyright.html. * Distributed under the Terms of Use in
* http://www.unicode.org/copyright.html.
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining
* of the Unicode data files and any associated documentation (the "Data * a copy of the Unicode data files and any associated documentation
* Files") or Unicode software and any associated documentation (the * (the "Data Files") or Unicode software and any associated documentation
* "Software") to deal in the Data Files or Software without restriction, * (the "Software") to deal in the Data Files or Software
* including without limitation the rights to use, copy, modify, merge, * without restriction, including without limitation the rights to use,
* publish, distribute, and/or sell copies of the Data Files or Software, and * copy, modify, merge, publish, distribute, and/or sell copies of
* to permit persons to whom the Data Files or Software are furnished to do so, * the Data Files or Software, and to permit persons to whom the Data Files
* provided that (a) the above copyright notice(s) and this permission notice * or Software are furnished to do so, provided that
* appear with all copies of the Data Files or Software, (b) both the above * (a) this copyright and permission notice appear with all copies
* copyright notice(s) and this permission notice appear in associated * of the Data Files or Software,
* documentation, and (c) there is clear notice in each modified Data File or * (b) this copyright and permission notice appear in associated
* in the Software as well as in the documentation associated with the Data * documentation, and
* File(s) or Software that the data or software has been modified. * (c) there is clear notice in each modified Data File or in the Software
* as well as in the documentation associated with the Data File(s) or
* Software that the data or software has been modified.
* *
* THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * NONINFRINGEMENT OF THIRD PARTY RIGHTS.
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
* DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* OF THE DATA FILES OR SOFTWARE. * PERFORMANCE OF THE DATA FILES OR SOFTWARE.
* *
* Except as contained in this notice, the name of a copyright holder shall not * Except as contained in this notice, the name of a copyright holder
* be used in advertising or otherwise to promote the sale, use or other * shall not be used in advertising or otherwise to promote the sale,
* dealings in these Data Files or Software without prior written authorization * use or other dealings in these Data Files or Software without prior
* of the copyright holder. * written authorization of the copyright holder.
*/ */
// Note: this file has been generated by a tool. // Note: this file has been generated by a tool.
@ -68,6 +72,21 @@ import sun.util.resources.OpenListResourceBundle;
public class JavaTimeSupplementary extends OpenListResourceBundle { public class JavaTimeSupplementary extends OpenListResourceBundle {
@Override @Override
protected final Object[][] getContents() { protected final Object[][] getContents() {
final String[] rocMonthNarrows = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"",
};
return new Object[][] { return new Object[][] {
{ "QuarterAbbreviations", { "QuarterAbbreviations",
new String[] { new String[] {
@ -93,22 +112,6 @@ public class JavaTimeSupplementary extends OpenListResourceBundle {
"4", "4",
} }
}, },
{ "calendarname.buddhist",
"Buddhist Calendar" },
{ "calendarname.gregorian",
"Gregorian Calendar" },
{ "calendarname.gregory",
"Gregorian Calendar" },
{ "calendarname.islamic",
"Islamic Calendar" },
{ "calendarname.islamic-civil",
"Islamic-Civil Calendar" },
{ "calendarname.islamicc",
"Islamic-Civil Calendar" },
{ "calendarname.japanese",
"Japanese Calendar" },
{ "calendarname.roc",
"Minguo Calendar" },
{ "field.dayperiod", { "field.dayperiod",
"Dayperiod" }, "Dayperiod" },
{ "field.era", { "field.era",
@ -129,12 +132,51 @@ public class JavaTimeSupplementary extends OpenListResourceBundle {
"Year" }, "Year" },
{ "field.zone", { "field.zone",
"Zone" }, "Zone" },
{ "islamic.AmPmMarkers",
new String[] {
"AM",
"PM",
}
},
{ "islamic.DatePatterns", { "islamic.DatePatterns",
new String[] { new String[] {
"EEEE, MMMM d, y GGGG", "GGGG y MMMM d, EEEE",
"MMMM d, y GGGG", "GGGG y MMMM d",
"MMM d, y GGGG", "GGGG y MMM d",
"M/d/yy GGGG", "G y-MM-dd",
}
},
{ "islamic.DayAbbreviations",
new String[] {
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
}
},
{ "islamic.DayNames",
new String[] {
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
}
},
{ "islamic.DayNarrows",
new String[] {
"S",
"M",
"T",
"W",
"T",
"F",
"S",
} }
}, },
{ "islamic.Eras", { "islamic.Eras",
@ -178,20 +220,47 @@ public class JavaTimeSupplementary extends OpenListResourceBundle {
} }
}, },
{ "islamic.MonthNarrows", { "islamic.MonthNarrows",
rocMonthNarrows },
{ "islamic.QuarterNames",
new String[] {
"Q1",
"Q2",
"Q3",
"Q4",
}
},
{ "islamic.QuarterNarrows",
new String[] { new String[] {
"1", "1",
"2", "2",
"3", "3",
"4", "4",
"5", }
"6", },
"7", { "islamic.TimePatterns",
"8", new String[] {
"9", "HH:mm:ss zzzz",
"10", "HH:mm:ss z",
"11", "HH:mm:ss",
"12", "HH:mm",
}
},
{ "islamic.long.Eras",
new String[] {
"", "",
"AH",
}
},
{ "islamic.narrow.AmPmMarkers",
new String[] {
"a",
"p",
}
},
{ "islamic.narrow.Eras",
new String[] {
"",
"AH",
} }
}, },
{ "islamic.short.Eras", { "islamic.short.Eras",
@ -202,10 +271,16 @@ public class JavaTimeSupplementary extends OpenListResourceBundle {
}, },
{ "java.time.buddhist.DatePatterns", { "java.time.buddhist.DatePatterns",
new String[] { new String[] {
"EEEE, G y MMMM dd", "G y MMMM d, EEEE",
"G y MMMM d", "G y MMMM d",
"G y MMM d", "G y MMM d",
"GGGGG yyyy-MM-dd", "GGGGG y-MM-dd",
}
},
{ "java.time.buddhist.long.Eras",
new String[] {
"BC",
"BE",
} }
}, },
{ "java.time.buddhist.short.Eras", { "java.time.buddhist.short.Eras",
@ -216,10 +291,10 @@ public class JavaTimeSupplementary extends OpenListResourceBundle {
}, },
{ "java.time.islamic.DatePatterns", { "java.time.islamic.DatePatterns",
new String[] { new String[] {
"EEEE, MMMM d, y G", "G y MMMM d, EEEE",
"MMMM d, y G", "G y MMMM d",
"MMM d, y G", "G y MMM d",
"M/d/yy G", "GGGGG y-MM-dd",
} }
}, },
{ "java.time.japanese.DatePatterns", { "java.time.japanese.DatePatterns",
@ -248,12 +323,18 @@ public class JavaTimeSupplementary extends OpenListResourceBundle {
"Heisei", "Heisei",
} }
}, },
{ "java.time.long.Eras",
new String[] {
"BCE",
"CE",
}
},
{ "java.time.roc.DatePatterns", { "java.time.roc.DatePatterns",
new String[] { new String[] {
"EEEE, G y MMMM dd", "G y MMMM d, EEEE",
"G y MMMM d", "G y MMMM d",
"G y MMM d", "G y MMM d",
"GGGGG yyy-MM-dd", "GGGGG y-MM-dd",
} }
}, },
{ "java.time.short.Eras", { "java.time.short.Eras",
@ -262,12 +343,40 @@ public class JavaTimeSupplementary extends OpenListResourceBundle {
"AD", "AD",
} }
}, },
{ "roc.AmPmMarkers",
new String[] {
"AM",
"PM",
}
},
{ "roc.DatePatterns", { "roc.DatePatterns",
new String[] { new String[] {
"EEEE, GGGG y MMMM dd", "GGGG y MMMM d, EEEE",
"GGGG y MMMM d", "GGGG y MMMM d",
"GGGG y MMM d", "GGGG y MMM d",
"G yyy-MM-dd", "G y-MM-dd",
}
},
{ "roc.DayNames",
new String[] {
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
}
},
{ "roc.DayNarrows",
new String[] {
"S",
"M",
"T",
"W",
"T",
"F",
"S",
} }
}, },
{ "roc.Eras", { "roc.Eras",
@ -276,6 +385,84 @@ public class JavaTimeSupplementary extends OpenListResourceBundle {
"R.O.C.", "R.O.C.",
} }
}, },
{ "roc.MonthAbbreviations",
new String[] {
"M01",
"M02",
"M03",
"M04",
"M05",
"M06",
"M07",
"M08",
"M09",
"M10",
"M11",
"M12",
"",
}
},
{ "roc.MonthNames",
new String[] {
"M01",
"M02",
"M03",
"M04",
"M05",
"M06",
"M07",
"M08",
"M09",
"M10",
"M11",
"M12",
"",
}
},
{ "roc.MonthNarrows",
rocMonthNarrows },
{ "roc.QuarterNames",
new String[] {
"Q1",
"Q2",
"Q3",
"Q4",
}
},
{ "roc.QuarterNarrows",
new String[] {
"1",
"2",
"3",
"4",
}
},
{ "roc.TimePatterns",
new String[] {
"HH:mm:ss zzzz",
"HH:mm:ss z",
"HH:mm:ss",
"HH:mm",
}
},
{ "roc.long.Eras",
new String[] {
"Before R.O.C.",
"R.O.C.",
}
},
{ "roc.narrow.AmPmMarkers",
new String[] {
"a",
"p",
}
},
{ "roc.narrow.Eras",
new String[] {
"Before R.O.C.",
"R.O.C.",
}
},
{ "roc.short.Eras", { "roc.short.Eras",
new String[] { new String[] {
"Before R.O.C.", "Before R.O.C.",

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -26,37 +26,41 @@
/* /*
* COPYRIGHT AND PERMISSION NOTICE * COPYRIGHT AND PERMISSION NOTICE
* *
* Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under * Copyright (C) 1991-2015 Unicode, Inc. All rights reserved.
* the Terms of Use in http://www.unicode.org/copyright.html. * Distributed under the Terms of Use in
* http://www.unicode.org/copyright.html.
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining
* of the Unicode data files and any associated documentation (the "Data * a copy of the Unicode data files and any associated documentation
* Files") or Unicode software and any associated documentation (the * (the "Data Files") or Unicode software and any associated documentation
* "Software") to deal in the Data Files or Software without restriction, * (the "Software") to deal in the Data Files or Software
* including without limitation the rights to use, copy, modify, merge, * without restriction, including without limitation the rights to use,
* publish, distribute, and/or sell copies of the Data Files or Software, and * copy, modify, merge, publish, distribute, and/or sell copies of
* to permit persons to whom the Data Files or Software are furnished to do so, * the Data Files or Software, and to permit persons to whom the Data Files
* provided that (a) the above copyright notice(s) and this permission notice * or Software are furnished to do so, provided that
* appear with all copies of the Data Files or Software, (b) both the above * (a) this copyright and permission notice appear with all copies
* copyright notice(s) and this permission notice appear in associated * of the Data Files or Software,
* documentation, and (c) there is clear notice in each modified Data File or * (b) this copyright and permission notice appear in associated
* in the Software as well as in the documentation associated with the Data * documentation, and
* File(s) or Software that the data or software has been modified. * (c) there is clear notice in each modified Data File or in the Software
* as well as in the documentation associated with the Data File(s) or
* Software that the data or software has been modified.
* *
* THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * NONINFRINGEMENT OF THIRD PARTY RIGHTS.
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
* DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* OF THE DATA FILES OR SOFTWARE. * PERFORMANCE OF THE DATA FILES OR SOFTWARE.
* *
* Except as contained in this notice, the name of a copyright holder shall not * Except as contained in this notice, the name of a copyright holder
* be used in advertising or otherwise to promote the sale, use or other * shall not be used in advertising or otherwise to promote the sale,
* dealings in these Data Files or Software without prior written authorization * use or other dealings in these Data Files or Software without prior
* of the copyright holder. * written authorization of the copyright holder.
*/ */
// Note: this file has been generated by a tool. // Note: this file has been generated by a tool.
@ -69,14 +73,6 @@ public class JavaTimeSupplementary_en extends OpenListResourceBundle {
@Override @Override
protected final Object[][] getContents() { protected final Object[][] getContents() {
return new Object[][] { return new Object[][] {
{ "QuarterAbbreviations",
new String[] {
"Q1",
"Q2",
"Q3",
"Q4",
}
},
{ "QuarterNames", { "QuarterNames",
new String[] { new String[] {
"1st quarter", "1st quarter",
@ -94,31 +90,15 @@ public class JavaTimeSupplementary_en extends OpenListResourceBundle {
{ "calendarname.islamic", { "calendarname.islamic",
"Islamic Calendar" }, "Islamic Calendar" },
{ "calendarname.islamic-civil", { "calendarname.islamic-civil",
"Islamic-Civil Calendar" }, "Islamic Calendar (tabular, civil epoch)" },
{ "calendarname.islamicc", { "calendarname.islamic-umalqura",
"Islamic-Civil Calendar" }, "Islamic Calendar (Umm al-Qura)" },
{ "calendarname.japanese", { "calendarname.japanese",
"Japanese Calendar" }, "Japanese Calendar" },
{ "calendarname.roc", { "calendarname.roc",
"Minguo Calendar" }, "Minguo Calendar" },
{ "field.dayperiod", { "field.dayperiod",
"AM/PM" }, "AM/PM" },
{ "field.era",
"Era" },
{ "field.hour",
"Hour" },
{ "field.minute",
"Minute" },
{ "field.month",
"Month" },
{ "field.second",
"Second" },
{ "field.week",
"Week" },
{ "field.weekday",
"Day of the Week" },
{ "field.year",
"Year" },
{ "field.zone", { "field.zone",
"Time Zone" }, "Time Zone" },
{ "islamic.DatePatterns", { "islamic.DatePatterns",
@ -126,7 +106,42 @@ public class JavaTimeSupplementary_en extends OpenListResourceBundle {
"EEEE, MMMM d, y GGGG", "EEEE, MMMM d, y GGGG",
"MMMM d, y GGGG", "MMMM d, y GGGG",
"MMM d, y GGGG", "MMM d, y GGGG",
"M/d/yy GGGG", "M/d/y G",
}
},
{ "islamic.DayNames",
new String[] {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
}
},
{ "islamic.QuarterAbbreviations",
new String[] {
"Q1",
"Q2",
"Q3",
"Q4",
}
},
{ "islamic.QuarterNames",
new String[] {
"1st quarter",
"2nd quarter",
"3rd quarter",
"4th quarter",
}
},
{ "islamic.TimePatterns",
new String[] {
"h:mm:ss a zzzz",
"h:mm:ss a z",
"h:mm:ss a",
"h:mm a",
} }
}, },
{ "java.time.buddhist.DatePatterns", { "java.time.buddhist.DatePatterns",
@ -134,7 +149,13 @@ public class JavaTimeSupplementary_en extends OpenListResourceBundle {
"EEEE, MMMM d, y G", "EEEE, MMMM d, y G",
"MMMM d, y G", "MMMM d, y G",
"MMM d, y G", "MMM d, y G",
"M/d/yy GGGGG", "M/d/y GGGGG",
}
},
{ "java.time.buddhist.short.Eras",
new String[] {
"BC",
"BE",
} }
}, },
{ "java.time.islamic.DatePatterns", { "java.time.islamic.DatePatterns",
@ -142,7 +163,7 @@ public class JavaTimeSupplementary_en extends OpenListResourceBundle {
"EEEE, MMMM d, y G", "EEEE, MMMM d, y G",
"MMMM d, y G", "MMMM d, y G",
"MMM d, y G", "MMM d, y G",
"M/d/yy G", "M/d/y GGGGG",
} }
}, },
{ "java.time.japanese.DatePatterns", { "java.time.japanese.DatePatterns",
@ -150,7 +171,7 @@ public class JavaTimeSupplementary_en extends OpenListResourceBundle {
"EEEE, MMMM d, y G", "EEEE, MMMM d, y G",
"MMMM d, y G", "MMMM d, y G",
"MMM d, y G", "MMM d, y G",
"M/d/yy GGGGG", "M/d/y GGGGG",
} }
}, },
{ "java.time.long.Eras", { "java.time.long.Eras",
@ -164,13 +185,7 @@ public class JavaTimeSupplementary_en extends OpenListResourceBundle {
"EEEE, MMMM d, y G", "EEEE, MMMM d, y G",
"MMMM d, y G", "MMMM d, y G",
"MMM d, y G", "MMM d, y G",
"M/d/yy GGGGG", "M/d/y GGGGG",
}
},
{ "java.time.short.Eras",
new String[] {
"BC",
"AD",
} }
}, },
{ "roc.DatePatterns", { "roc.DatePatterns",
@ -178,7 +193,128 @@ public class JavaTimeSupplementary_en extends OpenListResourceBundle {
"EEEE, MMMM d, y GGGG", "EEEE, MMMM d, y GGGG",
"MMMM d, y GGGG", "MMMM d, y GGGG",
"MMM d, y GGGG", "MMM d, y GGGG",
"M/d/yy G", "M/d/y G",
}
},
{ "roc.DayAbbreviations",
new String[] {
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
}
},
{ "roc.DayNames",
new String[] {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
}
},
{ "roc.Eras",
new String[] {
"Before R.O.C.",
"Minguo",
}
},
{ "roc.MonthAbbreviations",
new String[] {
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
"",
}
},
{ "roc.MonthNames",
new String[] {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
"",
}
},
{ "roc.MonthNarrows",
new String[] {
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
"",
}
},
{ "roc.QuarterAbbreviations",
new String[] {
"Q1",
"Q2",
"Q3",
"Q4",
}
},
{ "roc.QuarterNames",
new String[] {
"1st quarter",
"2nd quarter",
"3rd quarter",
"4th quarter",
}
},
{ "roc.TimePatterns",
new String[] {
"h:mm:ss a zzzz",
"h:mm:ss a z",
"h:mm:ss a",
"h:mm a",
}
},
{ "roc.long.Eras",
new String[] {
"Before R.O.C.",
"Minguo",
}
},
{ "roc.narrow.Eras",
new String[] {
"Before R.O.C.",
"Minguo",
}
},
{ "roc.short.Eras",
new String[] {
"Before R.O.C.",
"Minguo",
} }
}, },
}; };

View File

@ -1,106 +0,0 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under
* the Terms of Use in http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of the Unicode data files and any associated documentation (the "Data
* Files") or Unicode software and any associated documentation (the
* "Software") to deal in the Data Files or Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Data Files or Software, and
* to permit persons to whom the Data Files or Software are furnished to do so,
* provided that (a) the above copyright notice(s) and this permission notice
* appear with all copies of the Data Files or Software, (b) both the above
* copyright notice(s) and this permission notice appear in associated
* documentation, and (c) there is clear notice in each modified Data File or
* in the Software as well as in the documentation associated with the Data
* File(s) or Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in these Data Files or Software without prior written authorization
* of the copyright holder.
*/
// Note: this file has been generated by a tool.
package sun.text.resources.en;
import sun.util.resources.OpenListResourceBundle;
public class JavaTimeSupplementary_en_SG extends OpenListResourceBundle {
@Override
protected final Object[][] getContents() {
return new Object[][] {
{ "java.time.buddhist.DatePatterns",
new String[] {
"EEEE, d MMMM, y G",
"d MMMM, y G",
"d MMM, y G",
"d/M/yy GGGGG",
}
},
{ "java.time.japanese.DatePatterns",
new String[] {
"EEEE, d MMMM, y G",
"d MMMM, y G",
"d MMM, y G",
"d/M/yy GGGGG",
}
},
{ "java.time.roc.DatePatterns",
new String[] {
"EEEE, d MMMM, y G",
"d MMMM, y G",
"d MMM, y G",
"d/M/yy GGGGG",
}
},
{ "roc.DatePatterns",
new String[] {
"EEEE, d MMMM, y GGGG",
"d MMMM, y GGGG",
"d MMM, y GGGG",
"d/M/yy G",
}
},
};
}
}

View File

@ -38,7 +38,7 @@
* *
*/ */
package sun.text.resources.en; package sun.text.resources.en.US;
import sun.util.resources.ParallelListResourceBundle; import sun.util.resources.ParallelListResourceBundle;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -30,9 +30,14 @@ import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction; import java.security.PrivilegedExceptionAction;
import java.text.spi.BreakIteratorProvider; import java.text.spi.BreakIteratorProvider;
import java.text.spi.CollatorProvider; import java.text.spi.CollatorProvider;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.Set; import java.util.Set;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@ -48,11 +53,16 @@ import sun.util.locale.provider.LocaleDataMetaInfo;
*/ */
public class CLDRLocaleProviderAdapter extends JRELocaleProviderAdapter { public class CLDRLocaleProviderAdapter extends JRELocaleProviderAdapter {
private final LocaleDataMetaInfo metaInfo; private static final CLDRBaseLocaleDataMetaInfo baseMetaInfo = new CLDRBaseLocaleDataMetaInfo();
// Assumption: CLDR has only one non-Base module.
private final LocaleDataMetaInfo nonBaseMetaInfo;
// parent locales map
private static volatile Map<Locale, Locale> parentLocalesMap = null;
public CLDRLocaleProviderAdapter() { public CLDRLocaleProviderAdapter() {
try { try {
metaInfo = AccessController.doPrivileged(new PrivilegedExceptionAction<LocaleDataMetaInfo>() { nonBaseMetaInfo = AccessController.doPrivileged(new PrivilegedExceptionAction<LocaleDataMetaInfo>() {
@Override @Override
public LocaleDataMetaInfo run() { public LocaleDataMetaInfo run() {
for (LocaleDataMetaInfo ldmi : ServiceLoader.loadInstalled(LocaleDataMetaInfo.class)) { for (LocaleDataMetaInfo ldmi : ServiceLoader.loadInstalled(LocaleDataMetaInfo.class)) {
@ -70,7 +80,7 @@ public class CLDRLocaleProviderAdapter extends JRELocaleProviderAdapter {
throw new UnsupportedOperationException(e); throw new UnsupportedOperationException(e);
} }
if (metaInfo == null) { if (nonBaseMetaInfo == null) {
throw new UnsupportedOperationException("CLDR locale data could not be found."); throw new UnsupportedOperationException("CLDR locale data could not be found.");
} }
} }
@ -107,7 +117,16 @@ public class CLDRLocaleProviderAdapter extends JRELocaleProviderAdapter {
@Override @Override
protected Set<String> createLanguageTagSet(String category) { protected Set<String> createLanguageTagSet(String category) {
String supportedLocaleString = metaInfo.availableLanguageTags(category); // Directly call Base tags, as we know it's in the base module.
String supportedLocaleString = baseMetaInfo.availableLanguageTags(category);
String nonBaseTags = nonBaseMetaInfo.availableLanguageTags(category);
if (nonBaseTags != null) {
if (supportedLocaleString != null) {
supportedLocaleString += " " + nonBaseTags;
} else {
supportedLocaleString = nonBaseTags;
}
}
if (supportedLocaleString == null) { if (supportedLocaleString == null) {
return Collections.emptySet(); return Collections.emptySet();
} }
@ -118,4 +137,46 @@ public class CLDRLocaleProviderAdapter extends JRELocaleProviderAdapter {
} }
return tagset; return tagset;
} }
// Implementation of ResourceBundleBasedAdapter
@Override
public List<Locale> getCandidateLocales(String baseName, Locale locale) {
List<Locale> candidates = super.getCandidateLocales(baseName, locale);
return applyParentLocales(baseName, candidates);
}
private List<Locale> applyParentLocales(String baseName, List<Locale> candidates) {
if (Objects.isNull(parentLocalesMap)) {
Map<Locale, Locale> map = new HashMap<>();
Map<String, String> parentLocales = baseMetaInfo.parentLocales();
parentLocales.keySet().forEach(parent -> {
Arrays.asList(parentLocales.get(parent).split(" ")).stream().forEach(child -> {
map.put(Locale.forLanguageTag(child),
"root".equals(parent) ? Locale.ROOT : Locale.forLanguageTag(parent));
});
});
parentLocalesMap = Collections.unmodifiableMap(map);
}
// check irregular parents
for (int i = 0; i < candidates.size(); i++) {
Locale l = candidates.get(i);
Locale p = parentLocalesMap.get(l);
if (!l.equals(Locale.ROOT) &&
Objects.nonNull(p) &&
!candidates.get(i+1).equals(p)) {
List<Locale> applied = candidates.subList(0, i+1);
applied.addAll(applyParentLocales(baseName, super.getCandidateLocales(baseName, p)));
return applied;
}
}
return candidates;
}
@Override
public boolean isSupportedProviderLocale(Locale locale, Set<String> langtags) {
return Locale.ROOT.equals(locale) ||
langtags.contains(locale.stripExtensions().toLanguageTag());
}
} }

View File

@ -186,6 +186,6 @@ public class BreakIteratorProviderImpl extends BreakIteratorProvider
@Override @Override
public boolean isSupportedLocale(Locale locale) { public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.isSupportedLocale(locale, type, langtags); return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
} }
} }

View File

@ -63,6 +63,14 @@ public class CalendarNameProviderImpl extends CalendarNameProvider implements Av
if (key != null) { if (key != null) {
LocaleResources lr = LocaleProviderAdapter.forType(type).getLocaleResources(locale); LocaleResources lr = LocaleProviderAdapter.forType(type).getLocaleResources(locale);
String[] strings = javatime ? lr.getJavaTimeNames(key) : lr.getCalendarNames(key); String[] strings = javatime ? lr.getJavaTimeNames(key) : lr.getCalendarNames(key);
// If standalone names are requested and no "standalone." resources are found,
// try the default ones instead.
if (strings == null && key.indexOf("standalone.") != -1) {
key = key.replaceFirst("standalone.", "");
strings = javatime ? lr.getJavaTimeNames(key) : lr.getCalendarNames(key);
}
if (strings != null && strings.length > 0) { if (strings != null && strings.length > 0) {
if (field == DAY_OF_WEEK || field == YEAR) { if (field == DAY_OF_WEEK || field == YEAR) {
--value; --value;
@ -118,6 +126,14 @@ public class CalendarNameProviderImpl extends CalendarNameProvider implements Av
if (key != null) { if (key != null) {
LocaleResources lr = LocaleProviderAdapter.forType(type).getLocaleResources(locale); LocaleResources lr = LocaleProviderAdapter.forType(type).getLocaleResources(locale);
String[] strings = javatime ? lr.getJavaTimeNames(key) : lr.getCalendarNames(key); String[] strings = javatime ? lr.getJavaTimeNames(key) : lr.getCalendarNames(key);
// If standalone names are requested and no "standalone." resources are found,
// try the default ones instead.
if (strings == null && key.indexOf("standalone.") != -1) {
key = key.replaceFirst("standalone.", "");
strings = javatime ? lr.getJavaTimeNames(key) : lr.getCalendarNames(key);
}
if (strings != null) { if (strings != null) {
if (!hasDuplicates(strings)) { if (!hasDuplicates(strings)) {
if (field == YEAR) { if (field == YEAR) {
@ -281,8 +297,8 @@ public class CalendarNameProviderImpl extends CalendarNameProvider implements Av
break; break;
case DAY_OF_WEEK: case DAY_OF_WEEK:
// support standalone narrow day names // support standalone day names
if (isStandalone && isNarrow) { if (isStandalone) {
key.append("standalone."); key.append("standalone.");
} }
key.append("Day").append(toStyleName(baseStyle)); key.append("Day").append(toStyleName(baseStyle));

View File

@ -75,7 +75,7 @@ public class CollatorProviderImpl extends CollatorProvider implements AvailableL
@Override @Override
public boolean isSupportedLocale(Locale locale) { public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.isSupportedLocale(locale, type, langtags); return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
} }
/** /**

View File

@ -63,7 +63,7 @@ public class DateFormatProviderImpl extends DateFormatProvider implements Availa
@Override @Override
public boolean isSupportedLocale(Locale locale) { public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.isSupportedLocale(locale, type, langtags); return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
} }
/** /**

View File

@ -60,7 +60,7 @@ public class DateFormatSymbolsProviderImpl extends DateFormatSymbolsProvider imp
@Override @Override
public boolean isSupportedLocale(Locale locale) { public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.isSupportedLocale(locale, type, langtags); return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
} }
/** /**

View File

@ -60,7 +60,7 @@ public class DecimalFormatSymbolsProviderImpl extends DecimalFormatSymbolsProvid
@Override @Override
public boolean isSupportedLocale(Locale locale) { public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.isSupportedLocale(locale, type, langtags); return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
} }
/** /**

View File

@ -66,4 +66,9 @@ public class FallbackLocaleProviderAdapter extends JRELocaleProviderAdapter {
protected Set<String> createLanguageTagSet(String category) { protected Set<String> createLanguageTagSet(String category) {
return rootTagSet; return rootTagSet;
} }
@Override
public boolean isSupportedProviderLocale(Locale locale, Set<String>langtags) {
return Locale.ROOT.equals(locale);
}
} }

View File

@ -36,7 +36,9 @@ import java.text.spi.DecimalFormatSymbolsProvider;
import java.text.spi.NumberFormatProvider; import java.text.spi.NumberFormatProvider;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.ResourceBundle;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.Set; import java.util.Set;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@ -379,6 +381,13 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R
return localeData; return localeData;
} }
@Override
public List<Locale> getCandidateLocales(String baseName, Locale locale) {
return ResourceBundle.Control
.getNoFallbackControl(ResourceBundle.Control.FORMAT_DEFAULT)
.getCandidateLocales(baseName, locale);
}
/** /**
* Returns a list of the installed locales. Currently, this simply returns * Returns a list of the installed locales. Currently, this simply returns
* the list of locales for which a sun.text.resources.FormatData bundle * the list of locales for which a sun.text.resources.FormatData bundle
@ -417,12 +426,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R
} }
private static String createSupportedLocaleString(String category) { private static String createSupportedLocaleString(String category) {
// Directly call English tags, as we know it's in the base module. // Directly call Base tags, as we know it's in the base module.
String supportedLocaleString = EnLocaleDataMetaInfo.getSupportedLocaleString(category); String supportedLocaleString = BaseLocaleDataMetaInfo.getSupportedLocaleString(category);
// Use ServiceLoader to dynamically acquire installed locales' tags. // Use ServiceLoader to dynamically acquire installed locales' tags.
try { try {
String nonENTags = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() { String nonBaseTags = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
@Override @Override
public String run() { public String run() {
String tags = null; String tags = null;
@ -443,8 +452,8 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R
} }
}); });
if (nonENTags != null) { if (nonBaseTags != null) {
supportedLocaleString += " " + nonENTags; supportedLocaleString += " " + nonBaseTags;
} }
} catch (Exception e) { } catch (Exception e) {
// catch any exception, and ignore them as if non-EN locales do not exist. // catch any exception, and ignore them as if non-EN locales do not exist.
@ -497,4 +506,22 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R
} }
return locales; return locales;
} }
@Override
public boolean isSupportedProviderLocale(Locale locale, Set<String> langtags) {
if (Locale.ROOT.equals(locale)) {
return true;
}
locale = locale.stripExtensions();
if (langtags.contains(locale.toLanguageTag())) {
return true;
}
String oldname = locale.toString().replace('_', '-');
return langtags.contains(oldname) ||
"ja-JP-JP".equals(oldname) ||
"th-TH-TH".equals(oldname) ||
"no-NO-NY".equals(oldname);
}
} }

View File

@ -60,7 +60,7 @@ public class LocaleNameProviderImpl extends LocaleNameProvider implements Availa
@Override @Override
public boolean isSupportedLocale(Locale locale) { public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.isSupportedLocale(locale, type, langtags); return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
} }
/** /**

View File

@ -88,8 +88,7 @@ public abstract class LocaleProviderAdapter {
} }
/** /**
* LocaleProviderAdapter preference list. The default list is intended * LocaleProviderAdapter preference list.
* to behave the same manner in JDK7.
*/ */
private static final List<Type> adapterPreference; private static final List<Type> adapterPreference;
@ -177,7 +176,14 @@ public abstract class LocaleProviderAdapter {
defaultLocaleProviderAdapter = Type.JRE; defaultLocaleProviderAdapter = Type.JRE;
} }
} else { } else {
// Default preference list // Default preference list.
try {
cldrLocaleProviderAdapter = new CLDRLocaleProviderAdapter();
typeList.add(Type.CLDR);
defaultLocaleProviderAdapter = Type.CLDR;
} catch (UnsupportedOperationException e) {
LocaleServiceProviderPool.config(LocaleProviderAdapter.class, e.toString());
}
typeList.add(Type.JRE); typeList.add(Type.JRE);
typeList.add(Type.SPI); typeList.add(Type.SPI);
defaultLocaleProviderAdapter = Type.JRE; defaultLocaleProviderAdapter = Type.JRE;
@ -213,7 +219,10 @@ public abstract class LocaleProviderAdapter {
public static LocaleProviderAdapter getResourceBundleBased() { public static LocaleProviderAdapter getResourceBundleBased() {
for (Type type : getAdapterPreference()) { for (Type type : getAdapterPreference()) {
if (type == Type.JRE || type == Type.CLDR || type == Type.FALLBACK) { if (type == Type.JRE || type == Type.CLDR || type == Type.FALLBACK) {
return forType(type); LocaleProviderAdapter adapter = forType(type);
if (adapter != null) {
return adapter;
}
} }
} }
// Shouldn't happen. // Shouldn't happen.
@ -295,28 +304,9 @@ public abstract class LocaleProviderAdapter {
* A utility method for implementing the default LocaleServiceProvider.isSupportedLocale * A utility method for implementing the default LocaleServiceProvider.isSupportedLocale
* for the JRE, CLDR, and FALLBACK adapters. * for the JRE, CLDR, and FALLBACK adapters.
*/ */
public static boolean isSupportedLocale(Locale locale, LocaleProviderAdapter.Type type, Set<String> langtags) { public boolean isSupportedProviderLocale(Locale locale, Set<String> langtags) {
LocaleProviderAdapter.Type type = getAdapterType();
assert type == Type.JRE || type == Type.CLDR || type == Type.FALLBACK; assert type == Type.JRE || type == Type.CLDR || type == Type.FALLBACK;
if (Locale.ROOT.equals(locale)) {
return true;
}
if (type == Type.FALLBACK) {
// no other locales except ROOT are supported for FALLBACK
return false;
}
locale = locale.stripExtensions();
if (langtags.contains(locale.toLanguageTag())) {
return true;
}
if (type == Type.JRE) {
String oldname = locale.toString().replace('_', '-');
return langtags.contains(oldname) ||
"ja-JP-JP".equals(oldname) ||
"th-TH-TH".equals(oldname) ||
"no-NO-NY".equals(oldname);
}
return false; return false;
} }

View File

@ -402,11 +402,12 @@ public class LocaleResources {
if (timeStyle >= 0) { if (timeStyle >= 0) {
if (dateStyle >= 0) { if (dateStyle >= 0) {
String dateTimePattern = null; String dateTimePattern = null;
int dateTimeStyle = Math.max(dateStyle, timeStyle);
if (prefix != null) { if (prefix != null) {
dateTimePattern = getDateTimePattern(prefix, "DateTimePatterns", 0, calType); dateTimePattern = getDateTimePattern(prefix, "DateTimePatterns", dateTimeStyle, calType);
} }
if (dateTimePattern == null) { if (dateTimePattern == null) {
dateTimePattern = getDateTimePattern(null, "DateTimePatterns", 0, calType); dateTimePattern = getDateTimePattern(null, "DateTimePatterns", dateTimeStyle, calType);
} }
switch (dateTimePattern) { switch (dateTimePattern) {
case "{1} {0}": case "{1} {0}":
@ -416,7 +417,7 @@ public class LocaleResources {
pattern = timePattern + " " + datePattern; pattern = timePattern + " " + datePattern;
break; break;
default: default:
pattern = MessageFormat.format(dateTimePattern, timePattern, datePattern); pattern = MessageFormat.format(dateTimePattern.replaceAll("'", "''"), timePattern, datePattern);
break; break;
} }
} else { } else {
@ -492,7 +493,10 @@ public class LocaleResources {
assert prefix != null; assert prefix != null;
return null; return null;
} }
return ((String[])value)[styleIndex];
// for DateTimePatterns. CLDR has multiple styles, while JRE has one.
String[] styles = (String[])value;
return (styles.length > 1 ? styles[styleIndex] : styles[0]);
} }
private static class ResourceReference extends SoftReference<Object> { private static class ResourceReference extends SoftReference<Object> {

View File

@ -86,7 +86,7 @@ public class NumberFormatProviderImpl extends NumberFormatProvider implements Av
@Override @Override
public boolean isSupportedLocale(Locale locale) { public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.isSupportedLocale(locale, type, langtags); return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
} }
/** /**

View File

@ -25,6 +25,8 @@
package sun.util.locale.provider; package sun.util.locale.provider;
import java.util.List;
import java.util.Locale;
import sun.util.resources.LocaleData; import sun.util.resources.LocaleData;
/** /**
@ -34,4 +36,9 @@ import sun.util.resources.LocaleData;
*/ */
public interface ResourceBundleBasedAdapter { public interface ResourceBundleBasedAdapter {
public LocaleData getLocaleData(); public LocaleData getLocaleData();
/**
* candidate locales customization
*/
public List<Locale> getCandidateLocales(String baseName, Locale locale);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -30,6 +30,7 @@ import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.spi.TimeZoneNameProvider; import java.util.spi.TimeZoneNameProvider;
import sun.util.calendar.ZoneInfoFile;
/** /**
* Concrete implementation of the * Concrete implementation of the
@ -42,6 +43,7 @@ import java.util.spi.TimeZoneNameProvider;
public class TimeZoneNameProviderImpl extends TimeZoneNameProvider { public class TimeZoneNameProviderImpl extends TimeZoneNameProvider {
private final LocaleProviderAdapter.Type type; private final LocaleProviderAdapter.Type type;
private final Set<String> langtags; private final Set<String> langtags;
private static final String CLDR_NO_INHERITANCE_MARKER = "\u2205\u2205\u2205";
TimeZoneNameProviderImpl(LocaleProviderAdapter.Type type, Set<String> langtags) { TimeZoneNameProviderImpl(LocaleProviderAdapter.Type type, Set<String> langtags) {
this.type = type; this.type = type;
@ -62,7 +64,7 @@ public class TimeZoneNameProviderImpl extends TimeZoneNameProvider {
@Override @Override
public boolean isSupportedLocale(Locale locale) { public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.isSupportedLocale(locale, type, langtags); return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
} }
/** /**
@ -121,7 +123,28 @@ public class TimeZoneNameProviderImpl extends TimeZoneNameProvider {
private String[] getDisplayNameArray(String id, Locale locale) { private String[] getDisplayNameArray(String id, Locale locale) {
Objects.requireNonNull(id); Objects.requireNonNull(id);
Objects.requireNonNull(locale); Objects.requireNonNull(locale);
return LocaleProviderAdapter.forType(type).getLocaleResources(locale).getTimeZoneNames(id);
String[] ret =
LocaleProviderAdapter.forType(type).getLocaleResources(locale).getTimeZoneNames(id);
if (Objects.nonNull(ret) && type == LocaleProviderAdapter.Type.CLDR) {
// check for CLDR's "no inheritance marker"
for (int index = 0; index < ret.length; index++) {
TimeZone tz = null;
if (CLDR_NO_INHERITANCE_MARKER.equals(ret[index])) {
if (Objects.isNull(tz)) {
tz = TimeZone.getTimeZone(id);
}
int offset = tz.getRawOffset();
if (index == 3 || index == 4) { // daylight
offset += tz.getDSTSavings();
}
ret[index] = ZoneInfoFile.toCustomID(offset);
}
}
}
return ret;
} }
/** /**

View File

@ -51,6 +51,7 @@ import java.util.ResourceBundle;
import java.util.Set; import java.util.Set;
import sun.util.locale.provider.JRELocaleProviderAdapter; import sun.util.locale.provider.JRELocaleProviderAdapter;
import sun.util.locale.provider.LocaleProviderAdapter; import sun.util.locale.provider.LocaleProviderAdapter;
import sun.util.locale.provider.ResourceBundleBasedAdapter;
import static sun.util.locale.provider.LocaleProviderAdapter.Type.CLDR; import static sun.util.locale.provider.LocaleProviderAdapter.Type.CLDR;
import static sun.util.locale.provider.LocaleProviderAdapter.Type.JRE; import static sun.util.locale.provider.LocaleProviderAdapter.Type.JRE;
@ -205,16 +206,19 @@ public class LocaleData {
*/ */
@Override @Override
public List<Locale> getCandidateLocales(String baseName, Locale locale) { public List<Locale> getCandidateLocales(String baseName, Locale locale) {
List<Locale> candidates = super.getCandidateLocales(baseName, locale); LocaleProviderAdapter.Type type = baseName.contains(DOTCLDR) ? CLDR : JRE;
LocaleProviderAdapter adapter = LocaleProviderAdapter.forType(type);
List<Locale> candidates = adapter instanceof ResourceBundleBasedAdapter ?
((ResourceBundleBasedAdapter)adapter).getCandidateLocales(baseName, locale) :
super.getCandidateLocales(baseName, locale);
// Weed out Locales which are known to have no resource bundles // Weed out Locales which are known to have no resource bundles
int lastDot = baseName.lastIndexOf('.'); int lastDot = baseName.lastIndexOf('.');
String category = (lastDot >= 0) ? baseName.substring(lastDot + 1) : baseName; String category = (lastDot >= 0) ? baseName.substring(lastDot + 1) : baseName;
LocaleProviderAdapter.Type type = baseName.contains(DOTCLDR) ? CLDR : JRE;
LocaleProviderAdapter adapter = LocaleProviderAdapter.forType(type);
Set<String> langtags = ((JRELocaleProviderAdapter)adapter).getLanguageTagSet(category); Set<String> langtags = ((JRELocaleProviderAdapter)adapter).getLanguageTagSet(category);
if (!langtags.isEmpty()) { if (!langtags.isEmpty()) {
for (Iterator<Locale> itr = candidates.iterator(); itr.hasNext();) { for (Iterator<Locale> itr = candidates.iterator(); itr.hasNext();) {
if (!LocaleProviderAdapter.isSupportedLocale(itr.next(), type, langtags)) { if (!adapter.isSupportedProviderLocale(itr.next(), langtags)) {
itr.remove(); itr.remove();
} }
} }
@ -247,17 +251,18 @@ public class LocaleData {
private static final String DOTCLDR = ".cldr"; private static final String DOTCLDR = ".cldr";
/** /**
* Changes baseName to its per-language package name and * Changes baseName to its per-language/country package name and
* calls the super class implementation. For example, * calls the super class implementation. For example,
* if the baseName is "sun.text.resources.FormatData" and locale is ja_JP, * if the baseName is "sun.text.resources.FormatData" and locale is ja_JP,
* the baseName is changed to "sun.text.resources.ja.FormatData". If * the baseName is changed to "sun.text.resources.ja.JP.FormatData". If
* baseName contains "cldr", such as "sun.text.resources.cldr.FormatData", * baseName contains "cldr", such as "sun.text.resources.cldr.FormatData",
* the name is changed to "sun.text.resources.cldr.jp.FormatData". * the name is changed to "sun.text.resources.cldr.ja.JP.FormatData".
*/ */
@Override @Override
public String toBundleName(String baseName, Locale locale) { public String toBundleName(String baseName, Locale locale) {
String newBaseName = baseName; String newBaseName = baseName;
String lang = locale.getLanguage(); String lang = locale.getLanguage();
String ctry = locale.getCountry();
if (lang.length() > 0) { if (lang.length() > 0) {
if (baseName.startsWith(JRE.getUtilResourcesPackage()) if (baseName.startsWith(JRE.getUtilResourcesPackage())
|| baseName.startsWith(JRE.getTextResourcesPackage())) { || baseName.startsWith(JRE.getTextResourcesPackage())) {
@ -268,7 +273,8 @@ public class LocaleData {
if (baseName.indexOf(DOTCLDR, index) > 0) { if (baseName.indexOf(DOTCLDR, index) > 0) {
index += DOTCLDR.length(); index += DOTCLDR.length();
} }
newBaseName = baseName.substring(0, index + 1) + lang ctry = (ctry.length() == 2) ? ("." + ctry) : "";
newBaseName = baseName.substring(0, index + 1) + lang + ctry
+ baseName.substring(index); + baseName.substring(index);
} }
} }

View File

@ -46,6 +46,7 @@ grant codeBase "jrt:/jdk.crypto.ec" {
grant codeBase "jrt:/jdk.crypto.pkcs11" { grant codeBase "jrt:/jdk.crypto.pkcs11" {
permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*"; permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*";
permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch";
permission java.lang.RuntimePermission "loadLibrary.j2pkcs11"; permission java.lang.RuntimePermission "loadLibrary.j2pkcs11";
// needs "security.pkcs11.allowSingleThreadedModules" // needs "security.pkcs11.allowSingleThreadedModules"

View File

@ -66,7 +66,7 @@
# List of providers and their preference orders (see above): # List of providers and their preference orders (see above):
# #
#ifdef solaris #ifdef solaris
security.provider.tbd=com.oracle.security.ucrypto.UcryptoProvider ${java.home}/conf/security/ucrypto-solaris.cfg security.provider.tbd=com.oracle.security.ucrypto.UcryptoProvider
security.provider.tbd=sun.security.pkcs11.SunPKCS11 ${java.home}/conf/security/sunpkcs11-solaris.cfg security.provider.tbd=sun.security.pkcs11.SunPKCS11 ${java.home}/conf/security/sunpkcs11-solaris.cfg
#endif #endif
security.provider.tbd=sun.security.provider.Sun security.provider.tbd=sun.security.provider.Sun
@ -79,12 +79,17 @@ security.provider.tbd=com.sun.security.sasl.Provider
security.provider.tbd=org.jcp.xml.dsig.internal.dom.XMLDSigRI security.provider.tbd=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.tbd=sun.security.smartcardio.SunPCSC security.provider.tbd=sun.security.smartcardio.SunPCSC
security.provider.tbd=sun.security.provider.certpath.ldap.JdkLDAP security.provider.tbd=sun.security.provider.certpath.ldap.JdkLDAP
security.provider.tbd=com.sun.security.sasl.gsskerb.JdkSASL
#ifdef windows #ifdef windows
security.provider.tbd=sun.security.mscapi.SunMSCAPI security.provider.tbd=sun.security.mscapi.SunMSCAPI
#endif #endif
#ifdef macosx #ifdef macosx
security.provider.tbd=apple.security.AppleProvider security.provider.tbd=apple.security.AppleProvider
#endif #endif
#ifndef solaris
security.provider.tbd=sun.security.pkcs11.SunPKCS11
#endif
# #
# Sun Provider SecureRandom seed source. # Sun Provider SecureRandom seed source.

View File

@ -52,6 +52,8 @@
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/> <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
<!-- Windows 8.1 --> <!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/> <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application> </application>
</compatibility> </compatibility>

View File

@ -351,8 +351,8 @@ java_props_t *
GetJavaProperties(JNIEnv* env) GetJavaProperties(JNIEnv* env)
{ {
static java_props_t sprops = {0}; static java_props_t sprops = {0};
int majorVersion;
OSVERSIONINFOEX ver; int minorVersion;
if (sprops.line_separator) { if (sprops.line_separator) {
return &sprops; return &sprops;
@ -383,21 +383,67 @@ GetJavaProperties(JNIEnv* env)
/* OS properties */ /* OS properties */
{ {
char buf[100]; char buf[100];
SYSTEM_INFO si; boolean is_workstation;
PGNSI pGNSI; boolean is_64bit;
DWORD platformId;
{
OSVERSIONINFOEX ver;
ver.dwOSVersionInfoSize = sizeof(ver);
GetVersionEx((OSVERSIONINFO *) &ver);
majorVersion = ver.dwMajorVersion;
minorVersion = ver.dwMinorVersion;
is_workstation = (ver.wProductType == VER_NT_WORKSTATION);
platformId = ver.dwPlatformId;
sprops.patch_level = _strdup(ver.szCSDVersion);
}
ver.dwOSVersionInfoSize = sizeof(ver); {
GetVersionEx((OSVERSIONINFO *) &ver); SYSTEM_INFO si;
ZeroMemory(&si, sizeof(SYSTEM_INFO));
GetNativeSystemInfo(&si);
ZeroMemory(&si, sizeof(SYSTEM_INFO)); is_64bit = (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64);
// Call GetNativeSystemInfo if supported or GetSystemInfo otherwise. }
pGNSI = (PGNSI) GetProcAddress( do {
GetModuleHandle(TEXT("kernel32.dll")), // Read the major and minor version number from kernel32.dll
"GetNativeSystemInfo"); VS_FIXEDFILEINFO *file_info;
if(NULL != pGNSI) WCHAR kernel32_path[MAX_PATH];
pGNSI(&si); DWORD version_size;
else LPTSTR version_info;
GetSystemInfo(&si); UINT len, ret;
// Get the full path to \Windows\System32\kernel32.dll and use that for
// determining what version of Windows we're running on.
len = MAX_PATH - (UINT)strlen("\\kernel32.dll") - 1;
ret = GetSystemDirectoryW(kernel32_path, len);
if (ret == 0 || ret > len) {
break;
}
wcsncat(kernel32_path, L"\\kernel32.dll", MAX_PATH - ret);
version_size = GetFileVersionInfoSizeW(kernel32_path, NULL);
if (version_size == 0) {
break;
}
version_info = (LPTSTR)malloc(version_size);
if (version_info == NULL) {
break;
}
if (!GetFileVersionInfoW(kernel32_path, 0, version_size, version_info)) {
free(version_info);
break;
}
if (!VerQueryValueW(version_info, L"\\", (LPVOID*)&file_info, &len)) {
free(version_info);
break;
}
majorVersion = HIWORD(file_info->dwProductVersionMS);
minorVersion = LOWORD(file_info->dwProductVersionMS);
free(version_info);
} while (0);
/* /*
* From msdn page on OSVERSIONINFOEX, current as of this * From msdn page on OSVERSIONINFOEX, current as of this
@ -423,17 +469,15 @@ GetJavaProperties(JNIEnv* env)
* Windows Server 2008 R2 6 1 (!VER_NT_WORKSTATION) * Windows Server 2008 R2 6 1 (!VER_NT_WORKSTATION)
* Windows 8 6 2 (VER_NT_WORKSTATION) * Windows 8 6 2 (VER_NT_WORKSTATION)
* Windows Server 2012 6 2 (!VER_NT_WORKSTATION) * Windows Server 2012 6 2 (!VER_NT_WORKSTATION)
* Windows 10 10 0 (VER_NT_WORKSTATION)
* *
* This mapping will presumably be augmented as new Windows * This mapping will presumably be augmented as new Windows
* versions are released. * versions are released.
*/ */
switch (ver.dwPlatformId) { switch (platformId) {
case VER_PLATFORM_WIN32s:
sprops.os_name = "Windows 3.1";
break;
case VER_PLATFORM_WIN32_WINDOWS: case VER_PLATFORM_WIN32_WINDOWS:
if (ver.dwMajorVersion == 4) { if (majorVersion == 4) {
switch (ver.dwMinorVersion) { switch (minorVersion) {
case 0: sprops.os_name = "Windows 95"; break; case 0: sprops.os_name = "Windows 95"; break;
case 10: sprops.os_name = "Windows 98"; break; case 10: sprops.os_name = "Windows 98"; break;
case 90: sprops.os_name = "Windows Me"; break; case 90: sprops.os_name = "Windows Me"; break;
@ -444,10 +488,10 @@ GetJavaProperties(JNIEnv* env)
} }
break; break;
case VER_PLATFORM_WIN32_NT: case VER_PLATFORM_WIN32_NT:
if (ver.dwMajorVersion <= 4) { if (majorVersion <= 4) {
sprops.os_name = "Windows NT"; sprops.os_name = "Windows NT";
} else if (ver.dwMajorVersion == 5) { } else if (majorVersion == 5) {
switch (ver.dwMinorVersion) { switch (minorVersion) {
case 0: sprops.os_name = "Windows 2000"; break; case 0: sprops.os_name = "Windows 2000"; break;
case 1: sprops.os_name = "Windows XP"; break; case 1: sprops.os_name = "Windows XP"; break;
case 2: case 2:
@ -462,8 +506,7 @@ GetJavaProperties(JNIEnv* env)
* If it is, the operating system is Windows XP 64 bit; * If it is, the operating system is Windows XP 64 bit;
* otherwise, it is Windows Server 2003." * otherwise, it is Windows Server 2003."
*/ */
if(ver.wProductType == VER_NT_WORKSTATION && if (is_workstation && is_64bit) {
si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
sprops.os_name = "Windows XP"; /* 64 bit */ sprops.os_name = "Windows XP"; /* 64 bit */
} else { } else {
sprops.os_name = "Windows 2003"; sprops.os_name = "Windows 2003";
@ -471,12 +514,12 @@ GetJavaProperties(JNIEnv* env)
break; break;
default: sprops.os_name = "Windows NT (unknown)"; break; default: sprops.os_name = "Windows NT (unknown)"; break;
} }
} else if (ver.dwMajorVersion == 6) { } else if (majorVersion == 6) {
/* /*
* See table in MSDN OSVERSIONINFOEX documentation. * See table in MSDN OSVERSIONINFOEX documentation.
*/ */
if (ver.wProductType == VER_NT_WORKSTATION) { if (is_workstation) {
switch (ver.dwMinorVersion) { switch (minorVersion) {
case 0: sprops.os_name = "Windows Vista"; break; case 0: sprops.os_name = "Windows Vista"; break;
case 1: sprops.os_name = "Windows 7"; break; case 1: sprops.os_name = "Windows 7"; break;
case 2: sprops.os_name = "Windows 8"; break; case 2: sprops.os_name = "Windows 8"; break;
@ -484,7 +527,7 @@ GetJavaProperties(JNIEnv* env)
default: sprops.os_name = "Windows NT (unknown)"; default: sprops.os_name = "Windows NT (unknown)";
} }
} else { } else {
switch (ver.dwMinorVersion) { switch (minorVersion) {
case 0: sprops.os_name = "Windows Server 2008"; break; case 0: sprops.os_name = "Windows Server 2008"; break;
case 1: sprops.os_name = "Windows Server 2008 R2"; break; case 1: sprops.os_name = "Windows Server 2008 R2"; break;
case 2: sprops.os_name = "Windows Server 2012"; break; case 2: sprops.os_name = "Windows Server 2012"; break;
@ -492,6 +535,17 @@ GetJavaProperties(JNIEnv* env)
default: sprops.os_name = "Windows NT (unknown)"; default: sprops.os_name = "Windows NT (unknown)";
} }
} }
} else if (majorVersion == 10) {
if (is_workstation) {
switch (minorVersion) {
case 0: sprops.os_name = "Windows 10"; break;
default: sprops.os_name = "Windows NT (unknown)";
}
} else {
switch (minorVersion) {
default: sprops.os_name = "Windows NT (unknown)";
}
}
} else { } else {
sprops.os_name = "Windows NT (unknown)"; sprops.os_name = "Windows NT (unknown)";
} }
@ -500,7 +554,7 @@ GetJavaProperties(JNIEnv* env)
sprops.os_name = "Windows (unknown)"; sprops.os_name = "Windows (unknown)";
break; break;
} }
sprintf(buf, "%d.%d", ver.dwMajorVersion, ver.dwMinorVersion); sprintf(buf, "%d.%d", majorVersion, minorVersion);
sprops.os_version = _strdup(buf); sprops.os_version = _strdup(buf);
#if _M_IA64 #if _M_IA64
sprops.os_arch = "ia64"; sprops.os_arch = "ia64";
@ -511,9 +565,6 @@ GetJavaProperties(JNIEnv* env)
#else #else
sprops.os_arch = "unknown"; sprops.os_arch = "unknown";
#endif #endif
sprops.patch_level = _strdup(ver.szCSDVersion);
sprops.desktop = "windows"; sprops.desktop = "windows";
} }
@ -624,7 +675,7 @@ GetJavaProperties(JNIEnv* env)
&display_encoding); &display_encoding);
sprops.sun_jnu_encoding = getEncodingInternal(systemDefaultLCID); sprops.sun_jnu_encoding = getEncodingInternal(systemDefaultLCID);
if (LANGIDFROMLCID(userDefaultLCID) == 0x0c04 && ver.dwMajorVersion == 6) { if (LANGIDFROMLCID(userDefaultLCID) == 0x0c04 && majorVersion == 6) {
// MS claims "Vista has built-in support for HKSCS-2004. // MS claims "Vista has built-in support for HKSCS-2004.
// All of the HKSCS-2004 characters have Unicode 4.1. // All of the HKSCS-2004 characters have Unicode 4.1.
// PUA code point assignments". But what it really means // PUA code point assignments". But what it really means

View File

@ -27,11 +27,7 @@ package sun.security.provider.certpath.ldap;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.security.Provider; import java.security.*;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidParameterException;
import java.security.InvalidAlgorithmParameterException;
import java.security.ProviderException;
import java.security.cert.CertStoreParameters; import java.security.cert.CertStoreParameters;
/** /**
@ -75,16 +71,22 @@ public final class JdkLDAP extends Provider {
public JdkLDAP() { public JdkLDAP() {
super("JdkLDAP", 1.9d, "JdkLDAP Provider (implements LDAP CertStore)"); super("JdkLDAP", 1.9d, "JdkLDAP Provider (implements LDAP CertStore)");
HashMap<String, String> attrs = new HashMap<>(2); final Provider p = this;
attrs.put("LDAPSchema", "RFC2587"); AccessController.doPrivileged(new PrivilegedAction<Void>() {
attrs.put("ImplementedIn", "Software"); public Void run() {
HashMap<String, String> attrs = new HashMap<>(2);
attrs.put("LDAPSchema", "RFC2587");
attrs.put("ImplementedIn", "Software");
/* /*
* CertStore * CertStore
* attrs: LDAPSchema, ImplementedIn * attrs: LDAPSchema, ImplementedIn
*/ */
putService(new ProviderService(this, "CertStore", putService(new ProviderService(p, "CertStore",
"LDAP", "sun.security.provider.certpath.ldap.LDAPCertStore", "LDAP", "sun.security.provider.certpath.ldap.LDAPCertStore",
null, attrs)); null, attrs));
return null;
}
});
} }
} }

View File

@ -140,37 +140,32 @@ public final class DelegationPermission extends BasicPermission
*/ */
@Override @Override
public boolean implies(Permission p) { public boolean implies(Permission p) {
if (!(p instanceof DelegationPermission)) return equals(p);
return false;
DelegationPermission that = (DelegationPermission) p;
if (this.subordinate.equals(that.subordinate) &&
this.service.equals(that.service))
return true;
return false;
} }
/** /**
* Checks two DelegationPermission objects for equality. * Checks two DelegationPermission objects for equality.
* *
* @param obj the object to test for equality with this object. * @param obj the object to test for equality with this object.
* *
* @return true if {@code obj} is a DelegationPermission, and * @return true if {@code obj} is a DelegationPermission, and
* has the same subordinate and service principal as this. * has the same subordinate and service principal as this
* DelegationPermission object. * DelegationPermission object.
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == this) if (obj == this) {
return true; return true;
}
if (! (obj instanceof DelegationPermission)) if (!(obj instanceof DelegationPermission)) {
return false; return false;
}
DelegationPermission that = (DelegationPermission) obj; DelegationPermission that = (DelegationPermission) obj;
return implies(that);
return this.subordinate.equals(that.subordinate) &&
this.service.equals(that.service);
} }
/** /**
@ -180,7 +175,7 @@ public final class DelegationPermission extends BasicPermission
*/ */
@Override @Override
public int hashCode() { public int hashCode() {
return getName().hashCode(); return 17 * subordinate.hashCode() + 31 * service.hashCode();
} }
/** /**
@ -223,42 +218,6 @@ public final class DelegationPermission extends BasicPermission
init(getName()); init(getName());
} }
/*
public static void main(String args[]) throws Exception {
DelegationPermission this_ =
new DelegationPermission(args[0]);
DelegationPermission that_ =
new DelegationPermission(args[1]);
System.out.println("-----\n");
System.out.println("this.implies(that) = " + this_.implies(that_));
System.out.println("-----\n");
System.out.println("this = "+this_);
System.out.println("-----\n");
System.out.println("that = "+that_);
System.out.println("-----\n");
KrbDelegationPermissionCollection nps =
new KrbDelegationPermissionCollection();
nps.add(this_);
nps.add(new DelegationPermission("\"host/foo.example.com@EXAMPLE.COM\" \"CN=Gary Ellison/OU=JSN/O=SUNW/L=Palo Alto/ST=CA/C=US\""));
try {
nps.add(new DelegationPermission("host/foo.example.com@EXAMPLE.COM \"CN=Gary Ellison/OU=JSN/O=SUNW/L=Palo Alto/ST=CA/C=US\""));
} catch (Exception e) {
System.err.println(e);
}
System.out.println("nps.implies(that) = " + nps.implies(that_));
System.out.println("-----\n");
Enumeration e = nps.elements();
while (e.hasMoreElements()) {
DelegationPermission x =
(DelegationPermission) e.nextElement();
System.out.println("nps.e = " + x);
}
}
*/
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -27,6 +27,12 @@ package sun.security.jgss;
import java.security.Provider; import java.security.Provider;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidParameterException;
import java.security.ProviderException;
import sun.security.jgss.krb5.Krb5MechFactory;
import sun.security.jgss.spnego.SpNegoMechFactory;
/** /**
* Defines the Sun JGSS provider. * Defines the Sun JGSS provider.
@ -58,23 +64,54 @@ public final class SunProvider extends Provider {
"(Kerberos v5, SPNEGO)"; "(Kerberos v5, SPNEGO)";
// "(Kerberos v5, Dummy GSS-API Mechanism)"; // "(Kerberos v5, Dummy GSS-API Mechanism)";
private static final class ProviderService extends Provider.Service {
ProviderService(Provider p, String type, String algo, String cn) {
super(p, type, algo, cn, null, null);
}
@Override
public Object newInstance(Object ctrParamObj)
throws NoSuchAlgorithmException {
String type = getType();
if (ctrParamObj != null) {
throw new InvalidParameterException
("constructorParameter not used with " + type +
" engines");
}
String algo = getAlgorithm();
try {
if (type.equals("GssApiMechanism")) {
if (algo.equals("1.2.840.113554.1.2.2")) {
return new Krb5MechFactory();
} else if (algo.equals("1.3.6.1.5.5.2")) {
return new SpNegoMechFactory();
}
}
} catch (Exception ex) {
throw new NoSuchAlgorithmException
("Error constructing " + type + " for " +
algo + " using SunJGSS", ex);
}
throw new ProviderException("No impl for " + algo +
" " + type);
}
}
public static final SunProvider INSTANCE = new SunProvider(); public static final SunProvider INSTANCE = new SunProvider();
public SunProvider() { public SunProvider() {
/* We are the Sun JGSS provider */ /* We are the Sun JGSS provider */
super("SunJGSS", 1.9d, INFO); super("SunJGSS", 1.9d, INFO);
AccessController.doPrivileged( final Provider p = this;
new java.security.PrivilegedAction<Void>() { AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() { public Void run() {
put("GssApiMechanism.1.2.840.113554.1.2.2", putService(new ProviderService(p, "GssApiMechanism",
"sun.security.jgss.krb5.Krb5MechFactory"); "1.2.840.113554.1.2.2",
put("GssApiMechanism.1.3.6.1.5.5.2", "sun.security.jgss.krb5.Krb5MechFactory"));
"sun.security.jgss.spnego.SpNegoMechFactory"); putService(new ProviderService(p, "GssApiMechanism",
/* "1.3.6.1.5.5.2",
put("GssApiMechanism.1.3.6.1.4.1.42.2.26.1.2", "sun.security.jgss.spnego.SpNegoMechFactory"));
"sun.security.jgss.dummy.DummyMechFactory");
*/
return null; return null;
} }
}); });

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -26,6 +26,9 @@ package com.sun.security.sasl;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidParameterException;
import java.security.ProviderException;
/** /**
* The SASL provider. * The SASL provider.
@ -34,12 +37,10 @@ import java.security.PrivilegedAction;
* - PLAIN * - PLAIN
* - CRAM-MD5 * - CRAM-MD5
* - DIGEST-MD5 * - DIGEST-MD5
* - GSSAPI/Kerberos v5
* - NTLM * - NTLM
* And server support for * And server support for
* - CRAM-MD5 * - CRAM-MD5
* - DIGEST-MD5 * - DIGEST-MD5
* - GSSAPI/Kerberos v5
* - NTLM * - NTLM
*/ */
@ -49,38 +50,78 @@ public final class Provider extends java.security.Provider {
private static final String info = "Sun SASL provider" + private static final String info = "Sun SASL provider" +
"(implements client mechanisms for: " + "(implements client mechanisms for: " +
"DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5, NTLM;" + "DIGEST-MD5, EXTERNAL, PLAIN, CRAM-MD5, NTLM;" +
" server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5, NTLM)"; " server mechanisms for: DIGEST-MD5, CRAM-MD5, NTLM)";
private static final class ProviderService
extends java.security.Provider.Service {
ProviderService(java.security.Provider p, String type, String algo,
String cn) {
super(p, type, algo, cn, null, null);
}
@Override
public Object newInstance(Object ctrParamObj)
throws NoSuchAlgorithmException {
String type = getType();
if (ctrParamObj != null) {
throw new InvalidParameterException
("constructorParameter not used with " + type + " engines");
}
String algo = getAlgorithm();
try {
// DIGEST-MD5, NTLM uses same impl class for client and server
if (algo.equals("DIGEST-MD5")) {
return new com.sun.security.sasl.digest.FactoryImpl();
}
if (algo.equals("NTLM")) {
return new com.sun.security.sasl.ntlm.FactoryImpl();
}
if (type.equals("SaslClientFactory")) {
if (algo.equals("EXTERNAL") || algo.equals("PLAIN") ||
algo.equals("CRAM-MD5")) {
return new com.sun.security.sasl.ClientFactoryImpl();
}
} else if (type.equals("SaslServerFactory")) {
if (algo.equals("CRAM-MD5")) {
return new com.sun.security.sasl.ServerFactoryImpl();
}
}
} catch (Exception ex) {
throw new NoSuchAlgorithmException("Error constructing " +
type + " for " + algo + " using SunSASL", ex);
}
throw new ProviderException("No impl for " + algo +
" " + type);
}
}
public Provider() { public Provider() {
super("SunSASL", 1.9d, info); super("SunSASL", 1.9d, info);
final Provider p = this;
AccessController.doPrivileged(new PrivilegedAction<Void>() { AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() { public Void run() {
// Client mechanisms // Client mechanisms
put("SaslClientFactory.DIGEST-MD5", putService(new ProviderService(p, "SaslClientFactory",
"com.sun.security.sasl.digest.FactoryImpl"); "DIGEST-MD5", "com.sun.security.sasl.digest.FactoryImpl"));
put("SaslClientFactory.NTLM", putService(new ProviderService(p, "SaslClientFactory",
"com.sun.security.sasl.ntlm.FactoryImpl"); "NTLM", "com.sun.security.sasl.ntlm.FactoryImpl"));
put("SaslClientFactory.GSSAPI", putService(new ProviderService(p, "SaslClientFactory",
"com.sun.security.sasl.gsskerb.FactoryImpl"); "EXTERNAL", "com.sun.security.sasl.ClientFactoryImpl"));
putService(new ProviderService(p, "SaslClientFactory",
put("SaslClientFactory.EXTERNAL", "PLAIN", "com.sun.security.sasl.ClientFactoryImpl"));
"com.sun.security.sasl.ClientFactoryImpl"); putService(new ProviderService(p, "SaslClientFactory",
put("SaslClientFactory.PLAIN", "CRAM-MD5", "com.sun.security.sasl.ClientFactoryImpl"));
"com.sun.security.sasl.ClientFactoryImpl");
put("SaslClientFactory.CRAM-MD5",
"com.sun.security.sasl.ClientFactoryImpl");
// Server mechanisms // Server mechanisms
put("SaslServerFactory.CRAM-MD5", putService(new ProviderService(p, "SaslServerFactory",
"com.sun.security.sasl.ServerFactoryImpl"); "CRAM-MD5", "com.sun.security.sasl.ServerFactoryImpl"));
put("SaslServerFactory.GSSAPI", putService(new ProviderService(p, "SaslServerFactory",
"com.sun.security.sasl.gsskerb.FactoryImpl"); "DIGEST-MD5", "com.sun.security.sasl.digest.FactoryImpl"));
put("SaslServerFactory.DIGEST-MD5", putService(new ProviderService(p, "SaslServerFactory",
"com.sun.security.sasl.digest.FactoryImpl"); "NTLM", "com.sun.security.sasl.ntlm.FactoryImpl"));
put("SaslServerFactory.NTLM",
"com.sun.security.sasl.ntlm.FactoryImpl");
return null; return null;
} }
}); });

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -33,7 +33,10 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.HashSet; import java.util.HashSet;
import java.util.Collections; import java.util.Collections;
import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider; import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security; import java.security.Security;
/** /**
@ -360,7 +363,7 @@ public class Sasl {
SaslClient mech = null; SaslClient mech = null;
SaslClientFactory fac; SaslClientFactory fac;
String className; Service service;
String mechName; String mechName;
for (int i = 0; i < mechanisms.length; i++) { for (int i = 0; i < mechanisms.length; i++) {
@ -370,31 +373,32 @@ public class Sasl {
} else if (mechName.length() == 0) { } else if (mechName.length() == 0) {
continue; continue;
} }
String mechFilter = "SaslClientFactory." + mechName; String type = "SaslClientFactory";
Provider[] provs = Security.getProviders(mechFilter); Provider[] provs = Security.getProviders(type + "." + mechName);
for (int j = 0; provs != null && j < provs.length; j++) { if (provs != null) {
className = provs[j].getProperty(mechFilter); for (Provider p : provs) {
if (className == null) { service = p.getService(type, mechName);
// Case is ignored if (service == null) {
continue; // no such service exists
} continue;
}
fac = (SaslClientFactory) loadFactory(provs[j], className); fac = (SaslClientFactory) loadFactory(service);
if (fac != null) { if (fac != null) {
mech = fac.createSaslClient( mech = fac.createSaslClient(
new String[]{mechanisms[i]}, authorizationId, new String[]{mechanisms[i]}, authorizationId,
protocol, serverName, props, cbh); protocol, serverName, props, cbh);
if (mech != null) { if (mech != null) {
return mech; return mech;
}
} }
} }
} }
} }
return null; return null;
} }
private static Object loadFactory(Provider p, String className) private static Object loadFactory(Service service)
throws SaslException { throws SaslException {
try { try {
/* /*
@ -406,18 +410,9 @@ public class Sasl {
* have "getClassLoader" permission, or a SecurityException * have "getClassLoader" permission, or a SecurityException
* will be thrown. * will be thrown.
*/ */
ClassLoader cl = p.getClass().getClassLoader(); return service.newInstance(null);
Class<?> implClass; } catch (InvalidParameterException | NoSuchAlgorithmException e) {
implClass = Class.forName(className, true, cl); throw new SaslException("Cannot instantiate service " + service, e);
return implClass.newInstance();
} catch (ClassNotFoundException e) {
throw new SaslException("Cannot load class " + className, e);
} catch (InstantiationException e) {
throw new SaslException("Cannot instantiate class " + className, e);
} catch (IllegalAccessException e) {
throw new SaslException("Cannot access class " + className, e);
} catch (SecurityException e) {
throw new SaslException("Cannot access class " + className, e);
} }
} }
@ -503,7 +498,7 @@ public class Sasl {
SaslServer mech = null; SaslServer mech = null;
SaslServerFactory fac; SaslServerFactory fac;
String className; Service service;
if (mechanism == null) { if (mechanism == null) {
throw new NullPointerException("Mechanism name cannot be null"); throw new NullPointerException("Mechanism name cannot be null");
@ -511,24 +506,25 @@ public class Sasl {
return null; return null;
} }
String mechFilter = "SaslServerFactory." + mechanism; String type = "SaslServerFactory";
Provider[] provs = Security.getProviders(mechFilter); Provider[] provs = Security.getProviders(type + "." + mechanism);
for (int j = 0; provs != null && j < provs.length; j++) { if (provs != null) {
className = provs[j].getProperty(mechFilter); for (Provider p : provs) {
if (className == null) { service = p.getService(type, mechanism);
throw new SaslException("Provider does not support " + if (service == null) {
mechFilter); throw new SaslException("Provider does not support " +
} mechanism + " " + type);
fac = (SaslServerFactory) loadFactory(provs[j], className); }
if (fac != null) { fac = (SaslServerFactory) loadFactory(service);
mech = fac.createSaslServer( if (fac != null) {
mechanism, protocol, serverName, props, cbh); mech = fac.createSaslServer(
if (mech != null) { mechanism, protocol, serverName, props, cbh);
return mech; if (mech != null) {
return mech;
}
} }
} }
} }
return null; return null;
} }
@ -582,36 +578,21 @@ public class Sasl {
return result; return result;
} }
Provider[] provs = Security.getProviders();
Provider[] providers = Security.getProviders();
HashSet<String> classes = new HashSet<String>();
Object fac; Object fac;
for (int i = 0; i < providers.length; i++) { for (Provider p : provs) {
classes.clear();
// Check the keys for each provider. Iterator<Service> iter = p.getServices().iterator();
for (Enumeration<Object> e = providers[i].keys(); e.hasMoreElements(); ) { while (iter.hasNext()) {
String currentKey = (String)e.nextElement(); Service s = iter.next();
if (currentKey.startsWith(serviceName)) { if (s.getType().equals(serviceName)) {
// We should skip the currentKey if it contains a try {
// whitespace. The reason is: such an entry in the fac = loadFactory(s);
// provider property contains attributes for the if (fac != null) {
// implementation of an algorithm. We are only interested result.add(fac);
// in entries which lead to the implementation
// classes.
if (currentKey.indexOf(' ') < 0) {
String className = providers[i].getProperty(currentKey);
if (!classes.contains(className)) {
classes.add(className);
try {
fac = loadFactory(providers[i], className);
if (fac != null) {
result.add(fac);
}
}catch (Exception ignore) {
}
} }
} catch (Exception ignore) {
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -39,11 +39,39 @@ public final class SunPCSC extends Provider {
private static final long serialVersionUID = 6168388284028876579L; private static final long serialVersionUID = 6168388284028876579L;
private static final class ProviderService extends Provider.Service {
ProviderService(Provider p, String type, String algo, String cn) {
super(p, type, algo, cn, null, null);
}
@Override
public Object newInstance(Object ctrParamObj)
throws NoSuchAlgorithmException {
String type = getType();
String algo = getAlgorithm();
try {
if (type.equals("TerminalFactory") &&
algo.equals("PC/SC")) {
return new SunPCSC.Factory(ctrParamObj);
}
} catch (Exception ex) {
throw new NoSuchAlgorithmException("Error constructing " +
type + " for " + algo + " using SunPCSC", ex);
}
throw new ProviderException("No impl for " + algo +
" " + type);
}
}
public SunPCSC() { public SunPCSC() {
super("SunPCSC", 1.9d, "Sun PC/SC provider"); super("SunPCSC", 1.9d, "Sun PC/SC provider");
final Provider p = this;
AccessController.doPrivileged(new PrivilegedAction<Void>() { AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() { public Void run() {
put("TerminalFactory.PC/SC", "sun.security.smartcardio.SunPCSC$Factory"); putService(new ProviderService(p, "TerminalFactory",
"PC/SC", "sun.security.smartcardio.SunPCSC$Factory"));
return null; return null;
} }
}); });

View File

@ -28,7 +28,7 @@
* =========================================================================== * ===========================================================================
*/ */
/* /*
* Copyright (c) 2005, 2014 Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015 Oracle and/or its affiliates. All rights reserved.
*/ */
/* /*
* $Id: XMLDSigRI.java 1400021 2012-10-19 10:16:04Z coheigea $ * $Id: XMLDSigRI.java 1400021 2012-10-19 10:16:04Z coheigea $
@ -59,102 +59,156 @@ public final class XMLDSigRI extends Provider {
"C14N 1.0, C14N 1.1, Exclusive C14N, Base64, Enveloped, XPath, " + "C14N 1.0, C14N 1.1, Exclusive C14N, Base64, Enveloped, XPath, " +
"XPath2, XSLT TransformServices)"; "XPath2, XSLT TransformServices)";
private static final class ProviderService extends Provider.Service {
ProviderService(Provider p, String type, String algo, String cn) {
super(p, type, algo, cn, null, null);
}
ProviderService(Provider p, String type, String algo, String cn,
String[] aliases) {
super(p, type, algo, cn,
(aliases == null? null : Arrays.asList(aliases)), null);
}
ProviderService(Provider p, String type, String algo, String cn,
String[] aliases, HashMap<String, String> attrs) {
super(p, type, algo, cn,
(aliases == null? null : Arrays.asList(aliases)), attrs);
}
@Override
public Object newInstance(Object ctrParamObj)
throws NoSuchAlgorithmException {
String type = getType();
if (ctrParamObj != null) {
throw new InvalidParameterException
("constructorParameter not used with " + type + " engines");
}
String algo = getAlgorithm();
try {
if (type.equals("XMLSignatureFactory")) {
if (algo.equals("DOM")) {
return new DOMXMLSignatureFactory();
}
} else if (type.equals("KeyInfoFactory")) {
if (algo.equals("DOM")) {
return new DOMKeyInfoFactory();
}
} else if (type.equals("TransformService")) {
if (algo.equals(CanonicalizationMethod.INCLUSIVE) ||
algo.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS)) {
return new DOMCanonicalXMLC14NMethod();
} else if (algo.equals("http://www.w3.org/2006/12/xml-c14n11") ||
algo.equals("http://www.w3.org/2006/12/xml-c14n11#WithComments")) {
return new DOMCanonicalXMLC14N11Method();
} else if (algo.equals(CanonicalizationMethod.EXCLUSIVE) ||
algo.equals(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS)) {
return new DOMExcC14NMethod();
} else if (algo.equals(Transform.BASE64)) {
return new DOMBase64Transform();
} else if (algo.equals(Transform.ENVELOPED)) {
return new DOMEnvelopedTransform();
} else if (algo.equals(Transform.XPATH2)) {
return new DOMXPathFilter2Transform();
} else if (algo.equals(Transform.XPATH)) {
return new DOMXPathTransform();
} else if (algo.equals(Transform.XSLT)) {
return new DOMXSLTTransform();
}
}
} catch (Exception ex) {
throw new NoSuchAlgorithmException("Error constructing " +
type + " for " + algo + " using XMLDSig", ex);
}
throw new ProviderException("No impl for " + algo +
" " + type);
}
}
public XMLDSigRI() { public XMLDSigRI() {
/* We are the XMLDSig provider */ /* We are the XMLDSig provider */
super("XMLDSig", 1.9d, INFO); super("XMLDSig", 1.9d, INFO);
final Map<Object, Object> map = new HashMap<Object, Object>(); final Provider p = this;
map.put("XMLSignatureFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory");
map.put("KeyInfoFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMKeyInfoFactory");
// Inclusive C14N
map.put("TransformService." + CanonicalizationMethod.INCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE",
CanonicalizationMethod.INCLUSIVE);
map.put("TransformService." + CanonicalizationMethod.INCLUSIVE +
" MechanismType", "DOM");
// InclusiveWithComments C14N
map.put("TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS);
map.put("TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Inclusive C14N 1.1
map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11" +
" MechanismType", "DOM");
// InclusiveWithComments C14N 1.1
map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments" +
" MechanismType", "DOM");
// Exclusive C14N
map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
map.put("Alg.Alias.TransformService.EXCLUSIVE",
CanonicalizationMethod.EXCLUSIVE);
map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE +
" MechanismType", "DOM");
// ExclusiveWithComments C14N
map.put("TransformService." +
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod");
map.put("Alg.Alias.TransformService.EXCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS);
map.put("TransformService." +
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Base64 Transform
map.put("TransformService." + Transform.BASE64,
"org.jcp.xml.dsig.internal.dom.DOMBase64Transform");
map.put("Alg.Alias.TransformService.BASE64", Transform.BASE64);
map.put("TransformService." + Transform.BASE64 +
" MechanismType", "DOM");
// Enveloped Transform
map.put("TransformService." + Transform.ENVELOPED,
"org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform");
map.put("Alg.Alias.TransformService.ENVELOPED", Transform.ENVELOPED);
map.put("TransformService." + Transform.ENVELOPED +
" MechanismType", "DOM");
// XPath2 Transform
map.put("TransformService." + Transform.XPATH2,
"org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform");
map.put("Alg.Alias.TransformService.XPATH2", Transform.XPATH2);
map.put("TransformService." + Transform.XPATH2 +
" MechanismType", "DOM");
// XPath Transform
map.put("TransformService." + Transform.XPATH,
"org.jcp.xml.dsig.internal.dom.DOMXPathTransform");
map.put("Alg.Alias.TransformService.XPATH", Transform.XPATH);
map.put("TransformService." + Transform.XPATH +
" MechanismType", "DOM");
// XSLT Transform
map.put("TransformService." + Transform.XSLT,
"org.jcp.xml.dsig.internal.dom.DOMXSLTTransform");
map.put("Alg.Alias.TransformService.XSLT", Transform.XSLT);
map.put("TransformService." + Transform.XSLT + " MechanismType", "DOM");
AccessController.doPrivileged(new PrivilegedAction<Void>() { AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() { public Void run() {
putAll(map); HashMap<String, String> MECH_TYPE = new HashMap<>();
MECH_TYPE.put("MechanismType", "DOM");
putService(new ProviderService(p, "XMLSignatureFactory",
"DOM", "org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory"));
putService(new ProviderService(p, "KeyInfoFactory",
"DOM", "org.jcp.xml.dsig.internal.dom.DOMKeyInfoFactory"));
// Inclusive C14N
putService(new ProviderService(p, "TransformService",
CanonicalizationMethod.INCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod",
new String[] {"INCLUSIVE"}, MECH_TYPE));
// InclusiveWithComments C14N
putService(new ProviderService(p, "TransformService",
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod",
new String[] {"INCLUSIVE_WITH_COMMENTS"}, MECH_TYPE));
// Inclusive C14N 1.1
putService(new ProviderService(p, "TransformService",
"http://www.w3.org/2006/12/xml-c14n11",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method",
null, MECH_TYPE));
// InclusiveWithComments C14N 1.1
putService(new ProviderService(p, "TransformService",
"http://www.w3.org/2006/12/xml-c14n11#WithComments",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method",
null, MECH_TYPE));
// Exclusive C14N
putService(new ProviderService(p, "TransformService",
CanonicalizationMethod.EXCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod",
new String[] {"EXCLUSIVE"}, MECH_TYPE));
// ExclusiveWithComments C14N
putService(new ProviderService(p, "TransformService",
CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod",
new String[] {"EXCLUSIVE_WITH_COMMENTS"}, MECH_TYPE));
// Base64 Transform
putService(new ProviderService(p, "TransformService",
Transform.BASE64,
"org.jcp.xml.dsig.internal.dom.DOMBase64Transform",
new String[] {"BASE64"}, MECH_TYPE));
// Enveloped Transform
putService(new ProviderService(p, "TransformService",
Transform.ENVELOPED,
"org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform",
new String[] {"ENVELOPED"}, MECH_TYPE));
// XPath2 Transform
putService(new ProviderService(p, "TransformService",
Transform.XPATH2,
"org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform",
new String[] {"XPATH2"}, MECH_TYPE));
// XPath Transform
putService(new ProviderService(p, "TransformService",
Transform.XPATH,
"org.jcp.xml.dsig.internal.dom.DOMXPathTransform",
new String[] {"XPATH"}, MECH_TYPE));
// XSLT Transform
putService(new ProviderService(p, "TransformService",
Transform.XSLT,
"org.jcp.xml.dsig.internal.dom.DOMXSLTTransform",
new String[] {"XSLT"}, MECH_TYPE));
return null; return null;
} }
}); });

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -27,7 +27,10 @@ package sun.security.ec;
import java.util.*; import java.util.*;
import java.security.*; import java.security.*;
import sun.security.action.PutAllAction; import java.util.regex.Pattern;
import sun.security.util.CurveDB;
import sun.security.util.NamedCurve;
import sun.security.util.ECParameters;
/** /**
* Provider class for the Elliptic Curve provider. * Provider class for the Elliptic Curve provider.
@ -65,19 +68,206 @@ public final class SunEC extends Provider {
} }
} }
public SunEC() { private static class ProviderService extends Provider.Service {
super("SunEC", 1.9d, "Sun Elliptic Curve provider (EC, ECDSA, ECDH)");
// if there is no security manager installed, put directly into ProviderService(Provider p, String type, String algo, String cn) {
// the provider. Otherwise, create a temporary map and use a super(p, type, algo, cn, null, null);
// doPrivileged() call at the end to transfer the contents }
if (System.getSecurityManager() == null) {
SunECEntries.putEntries(this, useFullImplementation); ProviderService(Provider p, String type, String algo, String cn,
} else { String[] aliases, HashMap<String, String> attrs) {
Map<Object, Object> map = new HashMap<Object, Object>(); super(p, type, algo, cn,
SunECEntries.putEntries(map, useFullImplementation); (aliases == null? null : Arrays.asList(aliases)), attrs);
AccessController.doPrivileged(new PutAllAction(this, map)); }
@Override
public Object newInstance(Object ctrParamObj)
throws NoSuchAlgorithmException {
String type = getType();
if (ctrParamObj != null) {
throw new InvalidParameterException
("constructorParameter not used with " + type + " engines");
}
String algo = getAlgorithm();
try {
if (type.equals("Signature")) {
boolean inP1363 = algo.endsWith("inP1363Format");
if (inP1363) {
algo = algo.substring(0, algo.length() - 13);
}
if (algo.equals("SHA1withECDSA")) {
return (inP1363? new ECDSASignature.SHA1inP1363Format() :
new ECDSASignature.SHA1());
} else if (algo.equals("SHA224withECDSA")) {
return (inP1363? new ECDSASignature.SHA224inP1363Format() :
new ECDSASignature.SHA224());
} else if (algo.equals("SHA256withECDSA")) {
return (inP1363? new ECDSASignature.SHA256inP1363Format() :
new ECDSASignature.SHA256());
} else if (algo.equals("SHA384withECDSA")) {
return (inP1363? new ECDSASignature.SHA384inP1363Format() :
new ECDSASignature.SHA384());
} else if (algo.equals("SHA512withECDSA")) {
return (inP1363? new ECDSASignature.SHA512inP1363Format() :
new ECDSASignature.SHA512());
} else if (algo.equals("NONEwithECDSA")) {
return (inP1363? new ECDSASignature.RawinP1363Format() :
new ECDSASignature.Raw());
}
} else if (type.equals("KeyFactory")) {
if (algo.equals("EC")) {
return new ECKeyFactory();
}
} else if (type.equals("AlgorithmParameters")) {
if (algo.equals("EC")) {
return new sun.security.util.ECParameters();
}
} else if (type.equals("KeyPairGenerator")) {
if (algo.equals("EC")) {
return new ECKeyPairGenerator();
}
} else if (type.equals("KeyAgreement")) {
if (algo.equals("ECDH")) {
return new ECDHKeyAgreement();
}
}
} catch (Exception ex) {
throw new NoSuchAlgorithmException("Error constructing " +
type + " for " + algo + " using SunEC", ex);
}
throw new ProviderException("No impl for " + algo +
" " + type);
} }
} }
public SunEC() {
super("SunEC", 1.9d, "Sun Elliptic Curve provider (EC, ECDSA, ECDH)");
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
putEntries(useFullImplementation);
return null;
}
});
}
void putEntries(boolean useFullImplementation) {
HashMap<String, String> ATTRS = new HashMap<>(3);
ATTRS.put("ImplementedIn", "Software");
String ecKeyClasses = "java.security.interfaces.ECPublicKey" +
"|java.security.interfaces.ECPrivateKey";
ATTRS.put("SupportedKeyClasses", ecKeyClasses);
ATTRS.put("KeySize", "256");
/*
* Key Factory engine
*/
putService(new ProviderService(this, "KeyFactory",
"EC", "sun.security.ec.ECKeyFactory",
new String[] { "EllipticCurve" }, ATTRS));
/*
* Algorithm Parameter engine
*/
// "AlgorithmParameters.EC SupportedCurves" prop used by unit test
boolean firstCurve = true;
StringBuilder names = new StringBuilder();
Pattern nameSplitPattern = Pattern.compile(CurveDB.SPLIT_PATTERN);
Collection<? extends NamedCurve> supportedCurves =
CurveDB.getSupportedCurves();
for (NamedCurve namedCurve : supportedCurves) {
if (!firstCurve) {
names.append("|");
} else {
firstCurve = false;
}
names.append("[");
String[] commonNames = nameSplitPattern.split(namedCurve.getName());
for (String commonName : commonNames) {
names.append(commonName.trim());
names.append(",");
}
names.append(namedCurve.getObjectId());
names.append("]");
}
HashMap<String, String> apAttrs = new HashMap<>(ATTRS);
apAttrs.put("SupportedCurves", names.toString());
putService(new ProviderService(this, "AlgorithmParameters",
"EC", "sun.security.util.ECParameters",
new String[] { "EllipticCurve", "1.2.840.10045.2.1", "OID.1.2.840.10045.2.1" },
apAttrs));
/*
* Register the algorithms below only when the full ECC implementation
* is available
*/
if (!useFullImplementation) {
return;
}
/*
* Signature engines
*/
putService(new ProviderService(this, "Signature",
"NONEwithECDSA", "sun.security.ec.ECDSASignature$Raw",
null, ATTRS));
putService(new ProviderService(this, "Signature",
"SHA1withECDSA", "sun.security.ec.ECDSASignature$SHA1",
new String[] { "1.2.840.10045.4.1", "OID.1.2.840.10045.4.1" },
ATTRS));
putService(new ProviderService(this, "Signature",
"SHA224withECDSA", "sun.security.ec.ECDSASignature$SHA224",
new String[] { "1.2.840.10045.4.3.1", "OID.1.2.840.10045.4.3.1"},
ATTRS));
putService(new ProviderService(this, "Signature",
"SHA256withECDSA", "sun.security.ec.ECDSASignature$SHA256",
new String[] { "1.2.840.10045.4.3.2", "OID.1.2.840.10045.4.3.2"},
ATTRS));
putService(new ProviderService(this, "Signature",
"SHA384withECDSA", "sun.security.ec.ECDSASignature$SHA384",
new String[] { "1.2.840.10045.4.3.3", "OID.1.2.840.10045.4.3.3" },
ATTRS));
putService(new ProviderService(this, "Signature",
"SHA512withECDSA", "sun.security.ec.ECDSASignature$SHA512",
new String[] { "1.2.840.10045.4.3.4", "OID.1.2.840.10045.4.3.4" },
ATTRS));
putService(new ProviderService(this, "Signature",
"NONEwithECDSAinP1363Format",
"sun.security.ec.ECDSASignature$RawinP1363Format"));
putService(new ProviderService(this, "Signature",
"SHA1withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA1inP1363Format"));
putService(new ProviderService(this, "Signature",
"SHA224withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA224inP1363Format"));
putService(new ProviderService(this, "Signature",
"SHA256withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA256inP1363Format"));
putService(new ProviderService(this, "Signature",
"SHA384withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA384inP1363Format"));
putService(new ProviderService(this, "Signature",
"SHA512withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA512inP1363Format"));
/*
* Key Pair Generator engine
*/
putService(new ProviderService(this, "KeyPairGenerator",
"EC", "sun.security.ec.ECKeyPairGenerator",
new String[] { "EllipticCurve" }, ATTRS));
/*
* Key Agreement engine
*/
putService(new ProviderService(this, "KeyAgreement",
"ECDH", "sun.security.ec.ECDHKeyAgreement", null, ATTRS));
}
} }

View File

@ -1,184 +0,0 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. 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.ec;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Pattern;
import sun.security.util.CurveDB;
import sun.security.util.NamedCurve;
/**
* Defines the entries of the SunEC provider.
*
* @since 1.7
*/
final class SunECEntries {
private SunECEntries() {
// empty
}
static void putEntries(Map<Object, Object> map,
boolean useFullImplementation) {
/*
* Key Factory engine
*/
map.put("KeyFactory.EC", "sun.security.ec.ECKeyFactory");
map.put("Alg.Alias.KeyFactory.EllipticCurve", "EC");
map.put("KeyFactory.EC ImplementedIn", "Software");
/*
* Algorithm Parameter engine
*/
map.put("AlgorithmParameters.EC", "sun.security.util.ECParameters");
map.put("Alg.Alias.AlgorithmParameters.EllipticCurve", "EC");
map.put("Alg.Alias.AlgorithmParameters.1.2.840.10045.2.1", "EC");
map.put("AlgorithmParameters.EC KeySize", "256");
map.put("AlgorithmParameters.EC ImplementedIn", "Software");
// "AlgorithmParameters.EC SupportedCurves" prop used by unit test
boolean firstCurve = true;
StringBuilder names = new StringBuilder();
Pattern nameSplitPattern = Pattern.compile(CurveDB.SPLIT_PATTERN);
Collection<? extends NamedCurve> supportedCurves =
CurveDB.getSupportedCurves();
for (NamedCurve namedCurve : supportedCurves) {
if (!firstCurve) {
names.append("|");
} else {
firstCurve = false;
}
names.append("[");
String[] commonNames = nameSplitPattern.split(namedCurve.getName());
for (String commonName : commonNames) {
names.append(commonName.trim());
names.append(",");
}
names.append(namedCurve.getObjectId());
names.append("]");
}
map.put("AlgorithmParameters.EC SupportedCurves", names.toString());
/*
* Register the algorithms below only when the full ECC implementation
* is available
*/
if (!useFullImplementation) {
return;
}
/*
* Signature engines
*/
map.put("Signature.NONEwithECDSA",
"sun.security.ec.ECDSASignature$Raw");
map.put("Signature.SHA1withECDSA",
"sun.security.ec.ECDSASignature$SHA1");
map.put("Alg.Alias.Signature.OID.1.2.840.10045.4.1", "SHA1withECDSA");
map.put("Alg.Alias.Signature.1.2.840.10045.4.1", "SHA1withECDSA");
map.put("Signature.SHA224withECDSA",
"sun.security.ec.ECDSASignature$SHA224");
map.put("Alg.Alias.Signature.OID.1.2.840.10045.4.3.1", "SHA224withECDSA");
map.put("Alg.Alias.Signature.1.2.840.10045.4.3.1", "SHA224withECDSA");
map.put("Signature.SHA256withECDSA",
"sun.security.ec.ECDSASignature$SHA256");
map.put("Alg.Alias.Signature.OID.1.2.840.10045.4.3.2", "SHA256withECDSA");
map.put("Alg.Alias.Signature.1.2.840.10045.4.3.2", "SHA256withECDSA");
map.put("Signature.SHA384withECDSA",
"sun.security.ec.ECDSASignature$SHA384");
map.put("Alg.Alias.Signature.OID.1.2.840.10045.4.3.3", "SHA384withECDSA");
map.put("Alg.Alias.Signature.1.2.840.10045.4.3.3", "SHA384withECDSA");
map.put("Signature.SHA512withECDSA",
"sun.security.ec.ECDSASignature$SHA512");
map.put("Alg.Alias.Signature.OID.1.2.840.10045.4.3.4", "SHA512withECDSA");
map.put("Alg.Alias.Signature.1.2.840.10045.4.3.4", "SHA512withECDSA");
map.put("Signature.NONEwithECDSAinP1363Format",
"sun.security.ec.ECDSASignature$RawinP1363Format");
map.put("Signature.SHA1withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA1inP1363Format");
map.put("Signature.SHA224withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA224inP1363Format");
map.put("Signature.SHA256withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA256inP1363Format");
map.put("Signature.SHA384withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA384inP1363Format");
map.put("Signature.SHA512withECDSAinP1363Format",
"sun.security.ec.ECDSASignature$SHA512inP1363Format");
String ecKeyClasses = "java.security.interfaces.ECPublicKey" +
"|java.security.interfaces.ECPrivateKey";
map.put("Signature.NONEwithECDSA SupportedKeyClasses", ecKeyClasses);
map.put("Signature.SHA1withECDSA SupportedKeyClasses", ecKeyClasses);
map.put("Signature.SHA224withECDSA SupportedKeyClasses", ecKeyClasses);
map.put("Signature.SHA256withECDSA SupportedKeyClasses", ecKeyClasses);
map.put("Signature.SHA384withECDSA SupportedKeyClasses", ecKeyClasses);
map.put("Signature.SHA512withECDSA SupportedKeyClasses", ecKeyClasses);
map.put("Signature.SHA1withECDSA KeySize", "256");
map.put("Signature.NONEwithECDSA ImplementedIn", "Software");
map.put("Signature.SHA1withECDSA ImplementedIn", "Software");
map.put("Signature.SHA224withECDSA ImplementedIn", "Software");
map.put("Signature.SHA256withECDSA ImplementedIn", "Software");
map.put("Signature.SHA384withECDSA ImplementedIn", "Software");
map.put("Signature.SHA512withECDSA ImplementedIn", "Software");
/*
* Key Pair Generator engine
*/
map.put("KeyPairGenerator.EC", "sun.security.ec.ECKeyPairGenerator");
map.put("Alg.Alias.KeyPairGenerator.EllipticCurve", "EC");
map.put("KeyPairGenerator.EC KeySize", "256");
map.put("KeyPairGenerator.EC ImplementedIn", "Software");
/*
* Key Agreement engine
*/
map.put("KeyAgreement.ECDH", "sun.security.ec.ECDHKeyAgreement");
map.put("KeyAgreement.ECDH SupportedKeyClasses", ecKeyClasses);
map.put("KeyAgreement.ECDH ImplementedIn", "Software");
}
}

View File

@ -42,12 +42,7 @@ import java.security.cert.Certificate;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory; import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPrivateCrtKey;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.UUID;
/** /**
* Implementation of key store for Windows using the Microsoft Crypto API. * Implementation of key store for Windows using the Microsoft Crypto API.
@ -141,7 +136,7 @@ abstract class KeyStore extends KeyStoreSpi {
key.getPrimeExponentQ().toByteArray(), key.getPrimeExponentQ().toByteArray(),
key.getCrtCoefficient().toByteArray()); key.getCrtCoefficient().toByteArray());
privateKey = storePrivateKey(keyBlob, privateKey = storePrivateKey(Objects.requireNonNull(keyBlob),
"{" + UUID.randomUUID().toString() + "}", keyBitLength); "{" + UUID.randomUUID().toString() + "}", keyBitLength);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -28,8 +28,11 @@ package sun.security.mscapi;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.security.Provider; import java.security.Provider;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidParameterException;
import java.security.ProviderException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Arrays;
/** /**
* A Cryptographic Service Provider for the Microsoft Crypto API. * A Cryptographic Service Provider for the Microsoft Crypto API.
@ -52,97 +55,153 @@ public final class SunMSCAPI extends Provider {
}); });
} }
private static final class ProviderService extends Provider.Service {
ProviderService(Provider p, String type, String algo, String cn) {
super(p, type, algo, cn, null, null);
}
ProviderService(Provider p, String type, String algo, String cn,
String[] aliases, HashMap<String, String> attrs) {
super(p, type, algo, cn,
(aliases == null? null : Arrays.asList(aliases)), attrs);
}
@Override
public Object newInstance(Object ctrParamObj)
throws NoSuchAlgorithmException {
String type = getType();
if (ctrParamObj != null) {
throw new InvalidParameterException
("constructorParameter not used with " + type +
" engines");
}
String algo = getAlgorithm();
try {
if (type.equals("SecureRandom")) {
if (algo.equals("Windows-PRNG")) {
return new PRNG();
}
} else if (type.equals("KeyStore")) {
if (algo.equals("Windows-MY")) {
return new KeyStore.MY();
} else if (algo.equals("Windows-ROOT")) {
return new KeyStore.ROOT();
}
} else if (type.equals("Signature")) {
if (algo.equals("NONEwithRSA")) {
return new RSASignature.Raw();
} else if (algo.equals("SHA1withRSA")) {
return new RSASignature.SHA1();
} else if (algo.equals("SHA256withRSA")) {
return new RSASignature.SHA256();
} else if (algo.equals("SHA384withRSA")) {
return new RSASignature.SHA384();
} else if (algo.equals("SHA512withRSA")) {
return new RSASignature.SHA512();
} else if (algo.equals("MD5withRSA")) {
return new RSASignature.MD5();
} else if (algo.equals("MD2withRSA")) {
return new RSASignature.MD2();
}
} else if (type.equals("KeyPairGenerator")) {
if (algo.equals("RSA")) {
return new RSAKeyPairGenerator();
}
} else if (type.equals("Cipher")) {
if (algo.equals("RSA") ||
algo.equals("RSA/ECB/PKCS1Padding")) {
return new RSACipher();
}
}
} catch (Exception ex) {
throw new NoSuchAlgorithmException
("Error constructing " + type + " for " +
algo + " using SunMSCAPI", ex);
}
throw new ProviderException("No impl for " + algo +
" " + type);
}
}
public SunMSCAPI() { public SunMSCAPI() {
super("SunMSCAPI", 1.9d, INFO); super("SunMSCAPI", 1.9d, INFO);
// if there is no security manager installed, put directly into final Provider p = this;
// the provider. Otherwise, create a temporary map and use a AccessController.doPrivileged(new PrivilegedAction<Void>() {
// doPrivileged() call at the end to transfer the contents public Void run() {
final Map<Object, Object> map = /*
(System.getSecurityManager() == null) * Secure random
? this : new HashMap<Object, Object>(); */
putService(new ProviderService(p, "SecureRandom",
"Windows-PRNG", "sun.security.mscapi.PRNG"));
/* /*
* Secure random * Key store
*/ */
map.put("SecureRandom.Windows-PRNG", "sun.security.mscapi.PRNG"); putService(new ProviderService(p, "KeyStore",
"Windows-MY", "sun.security.mscapi.KeyStore$MY"));
putService(new ProviderService(p, "KeyStore",
"Windows-ROOT", "sun.security.mscapi.KeyStore$ROOT"));
/* /*
* Key store * Signature engines
*/ */
map.put("KeyStore.Windows-MY", "sun.security.mscapi.KeyStore$MY"); HashMap<String, String> attrs = new HashMap<>(1);
map.put("KeyStore.Windows-ROOT", "sun.security.mscapi.KeyStore$ROOT"); attrs.put("SupportedKeyClasses", "sun.security.mscapi.Key");
/* // NONEwithRSA must be supplied with a pre-computed message digest.
* Signature engines // Only the following digest algorithms are supported: MD5, SHA-1,
*/ // SHA-256, SHA-384, SHA-512 and a special-purpose digest
// NONEwithRSA must be supplied with a pre-computed message digest. // algorithm which is a concatenation of SHA-1 and MD5 digests.
// Only the following digest algorithms are supported: MD5, SHA-1, putService(new ProviderService(p, "Signature",
// SHA-256, SHA-384, SHA-512 and a special-purpose digest "NONEwithRSA", "sun.security.mscapi.RSASignature$Raw",
// algorithm which is a concatenation of SHA-1 and MD5 digests. null, attrs));
map.put("Signature.NONEwithRSA", putService(new ProviderService(p, "Signature",
"sun.security.mscapi.RSASignature$Raw"); "SHA1withRSA", "sun.security.mscapi.RSASignature$SHA1",
map.put("Signature.SHA1withRSA", null, attrs));
"sun.security.mscapi.RSASignature$SHA1"); putService(new ProviderService(p, "Signature",
map.put("Signature.SHA256withRSA", "SHA256withRSA", "sun.security.mscapi.RSASignature$SHA256",
"sun.security.mscapi.RSASignature$SHA256"); new String[] { "1.2.840.113549.1.1.11", "OID.1.2.840.113549.1.1.11" },
map.put("Alg.Alias.Signature.1.2.840.113549.1.1.11", "SHA256withRSA"); attrs));
map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.11", "SHA256withRSA"); putService(new ProviderService(p, "Signature",
map.put("Signature.SHA384withRSA", "SHA384withRSA", "sun.security.mscapi.RSASignature$SHA384",
"sun.security.mscapi.RSASignature$SHA384"); new String[] { "1.2.840.113549.1.1.12", "OID.1.2.840.113549.1.1.12" },
map.put("Alg.Alias.Signature.1.2.840.113549.1.1.12", "SHA384withRSA"); attrs));
map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.12", "SHA384withRSA"); putService(new ProviderService(p, "Signature",
"SHA512withRSA", "sun.security.mscapi.RSASignature$SHA512",
new String[] { "1.2.840.113549.1.1.13", "OID.1.2.840.113549.1.1.13" },
attrs));
putService(new ProviderService(p, "Signature",
"MD5withRSA", "sun.security.mscapi.RSASignature$MD5",
null, attrs));
putService(new ProviderService(p, "Signature",
"MD2withRSA", "sun.security.mscapi.RSASignature$MD2",
null, attrs));
map.put("Signature.SHA512withRSA", /*
"sun.security.mscapi.RSASignature$SHA512"); * Key Pair Generator engines
map.put("Alg.Alias.Signature.1.2.840.113549.1.1.13", "SHA512withRSA"); */
map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.13", "SHA512withRSA"); attrs.clear();
attrs.put("KeySize", "1024");
putService(new ProviderService(p, "KeyPairGenerator",
"RSA", "sun.security.mscapi.RSAKeyPairGenerator",
null, attrs));
map.put("Signature.MD5withRSA", /*
"sun.security.mscapi.RSASignature$MD5"); * Cipher engines
map.put("Signature.MD2withRSA", */
"sun.security.mscapi.RSASignature$MD2"); attrs.clear();
attrs.put("SupportedModes", "ECB");
// supported key classes attrs.put("SupportedPaddings", "PKCS1PADDING");
map.put("Signature.NONEwithRSA SupportedKeyClasses", attrs.put("SupportedKeyClasses", "sun.security.mscapi.Key");
"sun.security.mscapi.Key"); putService(new ProviderService(p, "Cipher",
map.put("Signature.SHA1withRSA SupportedKeyClasses", "RSA", "sun.security.mscapi.RSACipher",
"sun.security.mscapi.Key"); null, attrs));
map.put("Signature.SHA256withRSA SupportedKeyClasses", putService(new ProviderService(p, "Cipher",
"sun.security.mscapi.Key"); "RSA/ECB/PKCS1Padding", "sun.security.mscapi.RSACipher",
map.put("Signature.SHA384withRSA SupportedKeyClasses", null, attrs));
"sun.security.mscapi.Key");
map.put("Signature.SHA512withRSA SupportedKeyClasses",
"sun.security.mscapi.Key");
map.put("Signature.MD5withRSA SupportedKeyClasses",
"sun.security.mscapi.Key");
map.put("Signature.MD2withRSA SupportedKeyClasses",
"sun.security.mscapi.Key");
/*
* Key Pair Generator engines
*/
map.put("KeyPairGenerator.RSA",
"sun.security.mscapi.RSAKeyPairGenerator");
map.put("KeyPairGenerator.RSA KeySize", "1024");
/*
* Cipher engines
*/
map.put("Cipher.RSA", "sun.security.mscapi.RSACipher");
map.put("Cipher.RSA/ECB/PKCS1Padding",
"sun.security.mscapi.RSACipher");
map.put("Cipher.RSA SupportedModes", "ECB");
map.put("Cipher.RSA SupportedPaddings", "PKCS1PADDING");
map.put("Cipher.RSA SupportedKeyClasses", "sun.security.mscapi.Key");
if (map != this) {
final Provider provider = this;
PrivilegedAction<Void> putAllAction = () -> {
provider.putAll(map);
return null; return null;
}; }
AccessController.doPrivileged(putAllAction); });
}
} }
} }

View File

@ -1659,29 +1659,36 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getModulus
int convertToLittleEndian(JNIEnv *env, jbyteArray source, jbyte* destination, int convertToLittleEndian(JNIEnv *env, jbyteArray source, jbyte* destination,
int destinationLength) { int destinationLength) {
int count = 0;
int sourceLength = env->GetArrayLength(source); int sourceLength = env->GetArrayLength(source);
if (sourceLength < destinationLength) {
return -1;
}
jbyte* sourceBytes = env->GetByteArrayElements(source, 0); jbyte* sourceBytes = env->GetByteArrayElements(source, 0);
if (sourceBytes == NULL) { if (sourceBytes == NULL) {
return -1; return -1;
} }
int copyLen = sourceLength;
if (sourceLength > destinationLength) {
// source might include an extra sign byte
if (sourceLength == destinationLength + 1 && sourceBytes[0] == 0) {
copyLen--;
} else {
return -1;
}
}
// Copy bytes from the end of the source array to the beginning of the // Copy bytes from the end of the source array to the beginning of the
// destination array (until the destination array is full). // destination array (until the destination array is full).
// This ensures that the sign byte from the source array will be excluded. // This ensures that the sign byte from the source array will be excluded.
for (int i = 0; i < destinationLength; i++) { for (int i = 0; i < copyLen; i++) {
destination[i] = sourceBytes[sourceLength - i - 1]; destination[i] = sourceBytes[sourceLength - 1 - i];
count++; }
if (copyLen < destinationLength) {
memset(destination + copyLen, 0, destinationLength - copyLen);
} }
if (sourceBytes)
env->ReleaseByteArrayElements(source, sourceBytes, JNI_ABORT);
return count; env->ReleaseByteArrayElements(source, sourceBytes, JNI_ABORT);
return destinationLength;
} }
/* /*

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -69,30 +69,6 @@ final class Config {
} }
} }
// temporary storage for configurations
// needed because the SunPKCS11 needs to call the superclass constructor
// in provider before accessing any instance variables
private final static Map<String,Config> configMap =
new HashMap<String,Config>();
static Config getConfig(final String name, final InputStream stream) {
Config config = configMap.get(name);
if (config != null) {
return config;
}
try {
config = new Config(name, stream);
configMap.put(name, config);
return config;
} catch (Exception e) {
throw new ProviderException("Error parsing configuration", e);
}
}
static Config removeConfig(String name) {
return configMap.remove(name);
}
private final static boolean DEBUG = false; private final static boolean DEBUG = false;
private static void debug(Object o) { private static void debug(Object o) {
@ -101,6 +77,9 @@ final class Config {
} }
} }
// file name containing this configuration
private String filename;
// Reader and StringTokenizer used during parsing // Reader and StringTokenizer used during parsing
private Reader reader; private Reader reader;
@ -201,18 +180,15 @@ final class Config {
// memory footprint (true). // memory footprint (true).
private boolean nssOptimizeSpace = false; private boolean nssOptimizeSpace = false;
private Config(String filename, InputStream in) throws IOException { Config(String fn) throws IOException {
if (in == null) { this.filename = fn;
if (filename.startsWith("--")) { if (filename.startsWith("--")) {
// inline config // inline config
String config = filename.substring(2).replace("\\n", "\n"); String config = filename.substring(2).replace("\\n", "\n");
reader = new StringReader(config); reader = new StringReader(config);
} else { } else {
in = new FileInputStream(expand(filename)); reader = new BufferedReader(new InputStreamReader
} (new FileInputStream(expand(filename))));
}
if (reader == null) {
reader = new BufferedReader(new InputStreamReader(in));
} }
parsedKeywords = new HashSet<String>(); parsedKeywords = new HashSet<String>();
st = new StreamTokenizer(reader); st = new StreamTokenizer(reader);
@ -220,6 +196,10 @@ final class Config {
parse(); parse();
} }
String getFileName() {
return filename;
}
String getName() { String getName() {
return name; return name;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -514,8 +514,7 @@ public final class Secmod {
private SunPKCS11 newProvider() { private SunPKCS11 newProvider() {
try { try {
InputStream in = new ByteArrayInputStream(config.getBytes("UTF8")); return new SunPKCS11(new Config("--" + config));
return new SunPKCS11(in);
} catch (Exception e) { } catch (Exception e) {
// XXX // XXX
throw new ProviderException(e); throw new ProviderException(e);

View File

@ -63,14 +63,9 @@ public final class SunPKCS11 extends AuthProvider {
static final Debug debug = Debug.getInstance("sunpkcs11"); static final Debug debug = Debug.getInstance("sunpkcs11");
private static int dummyConfigId;
// the PKCS11 object through which we make the native calls // the PKCS11 object through which we make the native calls
final PKCS11 p11; final PKCS11 p11;
// name of the configuration file
private final String configName;
// configuration information // configuration information
final Config config; final Config config;
@ -95,17 +90,33 @@ public final class SunPKCS11 extends AuthProvider {
} }
public SunPKCS11() { public SunPKCS11() {
super("SunPKCS11-Dummy", 1.9d, "SunPKCS11-Dummy"); super("SunPKCS11", 1.9d, "Unconfigured and unusable PKCS11 provider");
throw new ProviderException p11 = null;
("SunPKCS11 requires configuration file argument"); config = null;
slotID = 0;
pHandler = null;
removable = false;
nssModule = null;
nssUseSecmodTrust = false;
token = null;
poller = null;
} }
public SunPKCS11(String configName) { @Override
this(checkNull(configName), null); public Provider configure(String configArg) throws InvalidParameterException {
} final String newConfigName = checkNull(configArg);
try {
public SunPKCS11(InputStream configStream) { return AccessController.doPrivileged(new PrivilegedExceptionAction<Provider>() {
this(getDummyConfigName(), checkNull(configStream)); @Override
public Provider run() throws Exception {
return new SunPKCS11(new Config(newConfigName));
}
});
} catch (PrivilegedActionException pae) {
InvalidParameterException ipe =
new InvalidParameterException("Error configuring SunPKCS11 provider");
throw (InvalidParameterException) ipe.initCause(pae.getException());
}
} }
private static <T> T checkNull(T obj) { private static <T> T checkNull(T obj) {
@ -115,25 +126,13 @@ public final class SunPKCS11 extends AuthProvider {
return obj; return obj;
} }
private static synchronized String getDummyConfigName() { // Used by Secmod
int id = ++dummyConfigId; SunPKCS11(Config c) {
return "---DummyConfig-" + id + "---"; super("SunPKCS11-" + c.getName(), 1.9d, c.getDescription());
} this.config = c;
/**
* @deprecated use new SunPKCS11(String) or new SunPKCS11(InputStream)
* instead
*/
@Deprecated
public SunPKCS11(String configName, InputStream configStream) {
super("SunPKCS11-" +
Config.getConfig(configName, configStream).getName(),
1.9d, Config.getConfig(configName, configStream).getDescription());
this.configName = configName;
this.config = Config.removeConfig(configName);
if (debug != null) { if (debug != null) {
System.out.println("SunPKCS11 loading " + configName); System.out.println("SunPKCS11 loading " + config.getFileName());
} }
String library = config.getLibrary(); String library = config.getLibrary();
@ -811,7 +810,7 @@ public final class SunPKCS11 extends AuthProvider {
if (poller != null) { if (poller != null) {
return; return;
} }
TokenPoller poller = new TokenPoller(this); final TokenPoller poller = new TokenPoller(this);
Thread t = new ManagedLocalsThread(poller, "Poller " + getName()); Thread t = new ManagedLocalsThread(poller, "Poller " + getName());
t.setDaemon(true); t.setDaemon(true);
t.setPriority(Thread.MIN_PRIORITY); t.setPriority(Thread.MIN_PRIORITY);
@ -1456,7 +1455,7 @@ public final class SunPKCS11 extends AuthProvider {
SunPKCS11Rep(SunPKCS11 provider) throws NotSerializableException { SunPKCS11Rep(SunPKCS11 provider) throws NotSerializableException {
providerName = provider.getName(); providerName = provider.getName();
configName = provider.configName; configName = provider.config.getFileName();
if (Security.getProvider(providerName) != provider) { if (Security.getProvider(providerName) != provider) {
throw new NotSerializableException("Only SunPKCS11 providers " throw new NotSerializableException("Only SunPKCS11 providers "
+ "installed in java.security.Security can be serialized"); + "installed in java.security.Security can be serialized");
@ -1465,7 +1464,7 @@ public final class SunPKCS11 extends AuthProvider {
private Object readResolve() throws ObjectStreamException { private Object readResolve() throws ObjectStreamException {
SunPKCS11 p = (SunPKCS11)Security.getProvider(providerName); SunPKCS11 p = (SunPKCS11)Security.getProvider(providerName);
if ((p == null) || (p.configName.equals(configName) == false)) { if ((p == null) || (p.config.getFileName().equals(configName) == false)) {
throw new NotSerializableException("Could not find " throw new NotSerializableException("Could not find "
+ providerName + " in installed providers"); + providerName + " in installed providers");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -55,11 +55,17 @@ class NativeCipher extends CipherSpi {
public AesEcbNoPadding() throws NoSuchAlgorithmException { public AesEcbNoPadding() throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_ECB); super(UcryptoMech.CRYPTO_AES_ECB);
} }
public AesEcbNoPadding(int keySize) throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_ECB, keySize);
}
} }
public static final class AesCbcNoPadding extends NativeCipher { public static final class AesCbcNoPadding extends NativeCipher {
public AesCbcNoPadding() throws NoSuchAlgorithmException { public AesCbcNoPadding() throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_CBC); super(UcryptoMech.CRYPTO_AES_CBC);
} }
public AesCbcNoPadding(int keySize) throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_CBC, keySize);
}
} }
public static final class AesCtrNoPadding extends NativeCipher { public static final class AesCtrNoPadding extends NativeCipher {
public AesCtrNoPadding() throws NoSuchAlgorithmException { public AesCtrNoPadding() throws NoSuchAlgorithmException {
@ -72,38 +78,6 @@ class NativeCipher extends CipherSpi {
} }
} }
// public implementation classes with fixed key sizes
public static final class Aes128EcbNoPadding extends NativeCipher {
public Aes128EcbNoPadding() throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_ECB, 16);
}
}
public static final class Aes128CbcNoPadding extends NativeCipher {
public Aes128CbcNoPadding() throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_CBC, 16);
}
}
public static final class Aes192EcbNoPadding extends NativeCipher {
public Aes192EcbNoPadding() throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_ECB, 24);
}
}
public static final class Aes192CbcNoPadding extends NativeCipher {
public Aes192CbcNoPadding() throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_CBC, 24);
}
}
public static final class Aes256EcbNoPadding extends NativeCipher {
public Aes256EcbNoPadding() throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_ECB, 32);
}
}
public static final class Aes256CbcNoPadding extends NativeCipher {
public Aes256CbcNoPadding() throws NoSuchAlgorithmException {
super(UcryptoMech.CRYPTO_AES_CBC, 32);
}
}
// ok as constants since AES is all we support // ok as constants since AES is all we support
public static final int AES_BLOCK_SIZE = 16; public static final int AES_BLOCK_SIZE = 16;
public static final String AES_KEY_ALGO = "AES"; public static final String AES_KEY_ALGO = "AES";

View File

@ -48,20 +48,8 @@ class NativeGCMCipher extends NativeCipher {
public AesGcmNoPadding() throws NoSuchAlgorithmException { public AesGcmNoPadding() throws NoSuchAlgorithmException {
super(-1); super(-1);
} }
} public AesGcmNoPadding(int keySize) throws NoSuchAlgorithmException {
public static final class Aes128GcmNoPadding extends NativeGCMCipher { super(keySize);
public Aes128GcmNoPadding() throws NoSuchAlgorithmException {
super(16);
}
}
public static final class Aes192GcmNoPadding extends NativeGCMCipher {
public Aes192GcmNoPadding() throws NoSuchAlgorithmException {
super(24);
}
}
public static final class Aes256GcmNoPadding extends NativeGCMCipher {
public Aes256GcmNoPadding() throws NoSuchAlgorithmException {
super(32);
} }
} }

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