This commit is contained in:
J. Duke 2017-07-05 22:08:49 +02:00
commit 2bc3adf21a
201 changed files with 5683 additions and 2032 deletions

View File

@ -375,3 +375,4 @@ f5902d3841b82cac6e7716a20c24e8e916fb14a8 jdk-9+129
d94d54a3192fea79234c3ac55cd0b4052d45e954 jdk-9+130
8728756c2f70a79a90188f4019cfd6b9a275765c jdk-9+131
a24702d4d5ab0015a5c553ed57f66fce7d85155e jdk-9+132
be1218f792a450dfb5d4b1f82616b9d95a6a732e jdk-9+133

View File

@ -375,3 +375,4 @@ c3e83ccab3bb1733ae903d681879a33f85ed465c jdk-9+129
77f9692d5976ae155773dd3e07533616bb95bae1 jdk-9+130
f7e1d5337c2e550fe553df7a3886bbed80292ecd jdk-9+131
1ab4b9399c4cba584f66c1c088188f2f565fbf9c jdk-9+132
2021bfedf1c478a4808a7711a6090682a12f4c0e jdk-9+133

View File

@ -535,3 +535,4 @@ e96b34b76d863ed1fa04e0eeb3f297ac17b490fd jdk-9+129
7d54c7056328b6a2bf4877458b8f4d8cd870f93b jdk-9+130
943bf73b49c33c2d7cbd796f6a4ae3c7a00ae932 jdk-9+131
713951c08aa26813375175c2ab6cc99ff2a56903 jdk-9+132
a25e0fb6033245ab075136e744d362ce765464cd jdk-9+133

View File

@ -316,12 +316,8 @@ size_t G1Analytics::predict_pending_cards() const {
return get_new_size_prediction(_pending_cards_seq);
}
double G1Analytics::oldest_known_gc_end_time_sec() const {
return _recent_prev_end_times_for_all_gcs_sec->oldest();
}
double G1Analytics::last_known_gc_end_time_sec() const {
return _recent_prev_end_times_for_all_gcs_sec->last();
return _recent_prev_end_times_for_all_gcs_sec->oldest();
}
void G1Analytics::update_recent_gc_times(double end_time_sec,

View File

@ -155,7 +155,6 @@ public:
void update_recent_gc_times(double end_time_sec, double elapsed_ms);
void compute_pause_time_ratio(double interval_ms, double pause_time_ms);
double oldest_known_gc_end_time_sec() const;
double last_known_gc_end_time_sec() const;
};

View File

@ -28,7 +28,6 @@
#include "classfile/symbolTable.hpp"
#include "code/codeCache.hpp"
#include "code/icBuffer.hpp"
#include "gc/g1/g1Analytics.hpp"
#include "gc/g1/bufferingOopClosure.hpp"
#include "gc/g1/concurrentG1Refine.hpp"
#include "gc/g1/concurrentG1RefineThread.hpp"
@ -2474,19 +2473,8 @@ size_t G1CollectedHeap::max_capacity() const {
}
jlong G1CollectedHeap::millis_since_last_gc() {
jlong now = os::elapsed_counter() / NANOSECS_PER_MILLISEC;
const G1Analytics* analytics = _g1_policy->analytics();
double last = analytics->last_known_gc_end_time_sec();
jlong ret_val = now - (last * 1000);
if (ret_val < 0) {
// See the notes in GenCollectedHeap::millis_since_last_gc()
// for more information about the implementation.
log_warning(gc)("Detected clock going backwards. "
"Milliseconds since last GC would be " JLONG_FORMAT
". returning zero instead.", ret_val);
return 0;
}
return ret_val;
// assert(false, "NYI");
return 0;
}
void G1CollectedHeap::prepare_for_verify() {

View File

@ -604,7 +604,7 @@ void G1DefaultPolicy::record_collection_pause_end(double pause_time_ms, size_t c
_analytics->report_alloc_rate_ms(alloc_rate_ms);
double interval_ms =
(end_time_sec - _analytics->oldest_known_gc_end_time_sec()) * 1000.0;
(end_time_sec - _analytics->last_known_gc_end_time_sec()) * 1000.0;
_analytics->update_recent_gc_times(end_time_sec, pause_time_ms);
_analytics->compute_pause_time_ratio(interval_ms, pause_time_ms);
}

View File

@ -1256,21 +1256,21 @@ class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure {
};
jlong GenCollectedHeap::millis_since_last_gc() {
// javaTimeNanos() is guaranteed to be monotonically non-decreasing
// provided the underlying platform provides such a time source
// (and it is bug free). So we still have to guard against getting
// back a time later than 'now'.
// We need a monotonically non-decreasing time in ms but
// os::javaTimeMillis() does not guarantee monotonicity.
jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
GenTimeOfLastGCClosure tolgc_cl(now);
// iterate over generations getting the oldest
// time that a generation was collected
generation_iterate(&tolgc_cl, false);
// javaTimeNanos() is guaranteed to be monotonically non-decreasing
// provided the underlying platform provides such a time source
// (and it is bug free). So we still have to guard against getting
// back a time later than 'now'.
jlong retVal = now - tolgc_cl.time();
if (retVal < 0) {
log_warning(gc)("Detected clock going backwards. "
"Milliseconds since last GC would be " JLONG_FORMAT
". returning zero instead.", retVal);
NOT_PRODUCT(log_warning(gc)("time warp: " JLONG_FORMAT, retVal);)
return 0;
}
return retVal;

View File

@ -375,3 +375,4 @@ bdc3c0b737efbf899709eb3121ce760dcfb51151 jdk-9+127
e66cdc2de6b02443911d386fc9217b0d824d0686 jdk-9+130
874082a9b565a7092a40bfa934a6e3e3c3455a60 jdk-9+131
907445d85e680ea410fe2c83c0ec64b5508e4f3e jdk-9+132
9490ba2e5e41685c858a0ca2a6ec87611eb011c6 jdk-9+133

View File

@ -1,15 +1,15 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
* Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@ -169,6 +169,14 @@ public class ErrorMessages extends ListResourceBundle {
{ErrorMsg.INVALID_URI_ERR,
"Invalid URI ''{0}''."},
/*
* Note to translators: This message is displayed when the URI
* mentioned in the substitution text is not well-formed syntactically.
*/
{ErrorMsg.CATALOG_EXCEPTION,
"JAXP08090001: The CatalogResolver is enabled with the catalog \"{0}\", "
+ "but a CatalogException is returned."},
/*
* Note to translators: The file or URI named in the substitution text
* exists but could not be opened.

View File

@ -1,15 +1,15 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
* Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@ -17,9 +17,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: ErrorMsg.java,v 1.2.4.1 2005/09/15 10:18:01 pvedula Exp $
*/
package com.sun.org.apache.xalan.internal.xsltc.compiler.util;
@ -60,6 +57,7 @@ public final class ErrorMsg {
public static final String ARGUMENT_CONVERSION_ERR = "ARGUMENT_CONVERSION_ERR";
public static final String FILE_NOT_FOUND_ERR = "FILE_NOT_FOUND_ERR";
public static final String INVALID_URI_ERR = "INVALID_URI_ERR";
public static final String CATALOG_EXCEPTION = "CATALOG_EXCEPTION";
public static final String FILE_ACCESS_ERR = "FILE_ACCESS_ERR";
public static final String MISSING_ROOT_ERR = "MISSING_ROOT_ERR";
public static final String NAMESPACE_UNDEF_ERR = "NAMESPACE_UNDEF_ERR";

View File

@ -51,10 +51,11 @@ import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.xml.XMLConstants;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogFeatures.Feature;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogUriResolver;
import javax.xml.catalog.CatalogResolver;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.ErrorListener;
@ -241,7 +242,7 @@ public class TransformerFactoryImpl
// type checking
private Map<String, Class> _xsltcExtensionFunctions;
CatalogUriResolver _catalogUriResolver;
CatalogResolver _catalogUriResolver;
CatalogFeatures _catalogFeatures;
CatalogFeatures.Builder cfBuilder = CatalogFeatures.builder();
// Catalog features
@ -634,7 +635,7 @@ public class TransformerFactoryImpl
}
// Inefficient, but array is small
for (int i = 0; i < features.length; i++) {
for (int i =0; i < features.length; i++) {
if (name.equals(features[i])) {
return true;
}
@ -923,7 +924,7 @@ public class TransformerFactoryImpl
String transletClassName = getTransletBaseName(source);
if (_packageName != null)
transletClassName = _packageName + "." + transletClassName;
transletClassName = _packageName + "." + transletClassName;
if (_jarFileName != null)
bytecodes = getBytecodesFromJar(source, transletClassName);
@ -1327,7 +1328,7 @@ public class TransformerFactoryImpl
if (source == null && _catalogFiles != null &&
_xmlFeatures.getFeature(JdkXmlFeatures.XmlFeature.USE_CATALOG)) {
if (_catalogUriResolver == null) {
_catalogUriResolver = CatalogManager.catalogUriResolver(_catalogFeatures);
_catalogUriResolver = CatalogManager.catalogResolver(_catalogFeatures);
}
source = _catalogUriResolver.resolve(href, context);
}
@ -1340,6 +1341,10 @@ public class TransformerFactoryImpl
final ErrorMsg msg = new ErrorMsg(ErrorMsg.INVALID_URI_ERR, href + "\n" + e.getMessage(), this);
xsltc.getParser().reportError(Constants.FATAL, msg);
}
catch (CatalogException e) {
final ErrorMsg msg = new ErrorMsg(ErrorMsg.CATALOG_EXCEPTION, href + "\n" + e.getMessage(), this);
xsltc.getParser().reportError(Constants.FATAL, msg);
}
return null;
}

View File

@ -60,9 +60,10 @@ import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.xml.XMLConstants;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogUriResolver;
import javax.xml.catalog.CatalogResolver;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
@ -224,7 +225,7 @@ public final class TransformerImpl extends Transformer
// Catalog features
CatalogFeatures _catalogFeatures;
CatalogUriResolver _catalogUriResolver;
CatalogResolver _catalogUriResolver;
// Catalog is enabled by default
boolean _useCatalog = true;
@ -1337,7 +1338,7 @@ public final class TransformerImpl extends Transformer
if (resolvedSource == null && _useCatalog &&
_catalogFeatures.get(CatalogFeatures.Feature.FILES) != null) {
if (_catalogUriResolver == null) {
_catalogUriResolver = CatalogManager.catalogUriResolver(_catalogFeatures);
_catalogUriResolver = CatalogManager.catalogResolver(_catalogFeatures);
}
resolvedSource = _catalogUriResolver.resolve(href, baseURI);
}
@ -1350,7 +1351,7 @@ public final class TransformerImpl extends Transformer
return getDOM(resolvedSource);
}
catch (TransformerException e) {
catch (TransformerException | CatalogException e) {
if (_errorListener != null)
postErrorToListener("File not found: " + e.getMessage());
return(null);

View File

@ -511,7 +511,8 @@ public class XMLDocumentFragmentScannerImpl
//fDocumentHandler.endElement(getElementQName(),null);
break;
default :
throw new InternalError("processing event: " + event);
// Errors should have already been handled by the Scanner
return false;
}
//System.out.println("here in before calling next");

View File

@ -20,8 +20,6 @@
package com.sun.org.apache.xerces.internal.impl ;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
import com.sun.org.apache.xerces.internal.impl.io.ASCIIReader;
import com.sun.org.apache.xerces.internal.impl.io.UCSReader;
import com.sun.org.apache.xerces.internal.impl.io.UTF8Reader;
@ -42,7 +40,6 @@ import com.sun.xml.internal.stream.StaxEntityResolverWrapper;
import com.sun.xml.internal.stream.StaxXMLInputSource;
import com.sun.xml.internal.stream.XMLEntityStorage;
import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
@ -59,7 +56,6 @@ import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogFeatures.Feature;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import javax.xml.stream.XMLInputFactory;
import javax.xml.transform.Source;
import jdk.xml.internal.JdkXmlUtils;
@ -420,7 +416,6 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
private boolean fUseCatalog = true;
CatalogFeatures fCatalogFeatures;
CatalogResolver fCatalogResolver;
CatalogUriResolver fCatalogUriResolver;
private String fCatalogFile;
private String fDefer;
@ -1044,12 +1039,18 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
}
fCatalogFile = fCatalogFeatures.get(Feature.FILES);
if (fUseCatalog && fCatalogFile != null) {
if (fCatalogResolver == null) {
fCatalogResolver = CatalogManager.catalogResolver(fCatalogFeatures);
}
InputSource is = fCatalogResolver.resolveEntity(publicId, literalSystemId);
if (is != null && !is.isEmpty()) {
staxInputSource = new StaxXMLInputSource(new XMLInputSource(is, true), true);
try {
if (fCatalogResolver == null) {
fCatalogResolver = CatalogManager.catalogResolver(fCatalogFeatures);
}
InputSource is = fCatalogResolver.resolveEntity(publicId, literalSystemId);
if (is != null && !is.isEmpty()) {
staxInputSource = new StaxXMLInputSource(new XMLInputSource(is, true), true);
}
} catch (CatalogException e) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,"CatalogException",
new Object[]{SecuritySupport.sanitizePath(fCatalogFile)},
XMLErrorReporter.SEVERITY_FATAL_ERROR, e );
}
}
}
@ -1140,7 +1141,7 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
if (fUseCatalog && fCatalogFile != null) {
/*
since the method can be called from various processors, both
CatalogResolver and CatalogUriResolver are used to attempt to find
EntityResolver and URIResolver are used to attempt to find
a match
*/
InputSource is = null;
@ -1153,13 +1154,20 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
is = fCatalogResolver.resolveEntity(pid, literalSystemId);
}
} catch (CatalogException e) {}
if (is != null && !is.isEmpty()) {
xmlInputSource = new XMLInputSource(is, true);
} else if (literalSystemId != null) {
if (fCatalogUriResolver == null) {
fCatalogUriResolver = CatalogManager.catalogUriResolver(fCatalogFeatures);
if (fCatalogResolver == null) {
fCatalogResolver = CatalogManager.catalogResolver(fCatalogFeatures);
}
Source source = null;
try {
source = fCatalogResolver.resolve(literalSystemId, baseSystemId);
} catch (CatalogException e) {
throw new XNIException(e);
}
Source source = fCatalogUriResolver.resolve(literalSystemId, baseSystemId);
if (source != null && !source.isEmpty()) {
xmlInputSource = new XMLInputSource(publicId, source.getSystemId(), baseSystemId, true);
}

View File

@ -303,3 +303,5 @@
MaxElementDepthLimit=JAXP00010006: The element \"{0}\" has a depth of \"{1}\" that exceeds the limit \"{2}\" set by \"{3}\".
EntityReplacementLimit=JAXP00010007: The total number of nodes in entity references is \"{0}\" that is over the limit \"{1}\" set by \"{2}\".
# Catalog 09
CatalogException=JAXP00090001: The CatalogResolver is enabled with the catalog \"{0}\", but a CatalogException is returned.

View File

@ -1,13 +1,13 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Copyright 2001, 2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@ -28,6 +28,7 @@ import com.sun.org.apache.xerces.internal.xni.XNIException;
import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier;
import com.sun.org.apache.xerces.internal.xni.parser.XMLEntityResolver;
import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
import javax.xml.catalog.CatalogException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
@ -132,6 +133,10 @@ public class EntityResolverWrapper
}
throw new XNIException(ex);
}
catch (CatalogException e) {
throw new XNIException(e);
}
}
// unable to resolve entity

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@ -75,7 +75,6 @@ import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import javax.xml.transform.Source;
import jdk.xml.internal.JdkXmlUtils;
import org.xml.sax.InputSource;
@ -371,7 +370,6 @@ public class XIncludeHandler
private boolean fUseCatalog = true;
CatalogFeatures fCatalogFeatures;
CatalogResolver fCatalogResolver;
CatalogUriResolver fCatalogUriResolver;
private String fCatalogFile;
private String fDefer;
@ -1638,10 +1636,10 @@ public class XIncludeHandler
*/
Source source = null;
try {
if (fCatalogUriResolver == null) {
fCatalogUriResolver = CatalogManager.catalogUriResolver(fCatalogFeatures);
if (fCatalogResolver == null) {
fCatalogResolver = CatalogManager.catalogResolver(fCatalogFeatures);
}
source = fCatalogUriResolver.resolve(href, fCurrentBaseURI.getExpandedSystemId());
source = fCatalogResolver.resolve(href, fCurrentBaseURI.getExpandedSystemId());
} catch (CatalogException e) {}
if (source != null && !source.isEmpty()) {
@ -1669,7 +1667,7 @@ public class XIncludeHandler
includedSource.getBaseSystemId(), accept, acceptLanguage);
}
}
catch (IOException e) {
catch (IOException | CatalogException e) {
reportResourceError(
"XMLResourceError",
new Object[] { href, e.getMessage()});

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -33,6 +33,7 @@ import javax.xml.stream.XMLStreamReader;
import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier;
import com.sun.org.apache.xerces.internal.xni.XNIException;
import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
import javax.xml.catalog.CatalogException;
/**
*
@ -58,11 +59,11 @@ public class StaxEntityResolverWrapper {
public StaxXMLInputSource resolveEntity(XMLResourceIdentifier resourceIdentifier)
throws XNIException, java.io.IOException {
Object object = null ;
try{
try {
object = fStaxResolver.resolveEntity(resourceIdentifier.getPublicId(), resourceIdentifier.getLiteralSystemId(),
resourceIdentifier.getBaseSystemId(), null);
return getStaxInputSource(object) ;
}catch(XMLStreamException streamException){
} catch(XMLStreamException | CatalogException streamException){
throw new XNIException(streamException) ;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2016, 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
@ -42,9 +42,9 @@ import java.util.stream.Stream;
* <p>
* A catalog can be used in two situations:
* <ul>
* <li>Locate the replacement text for an external entity;
* <li>Locate the external resources with a public or system identifier;
* </li>
* <li>Locate an alternate URI reference for a resource.
* <li>Locate an alternate URI reference with an URI.
* </li>
* </ul>
* <p>

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -76,17 +76,6 @@ public final class CatalogManager {
return new CatalogResolverImpl(catalog);
}
/**
* Creates an instance of a {@code CatalogUriResolver} using the specified catalog.
*
* @param catalog the catalog instance
* @return an instance of a {@code CatalogResolver}
*/
public static CatalogUriResolver catalogUriResolver(Catalog catalog) {
if (catalog == null) CatalogMessages.reportNPEOnNull("catalog", null);
return new CatalogUriResolverImpl(catalog);
}
/**
* Creates an instance of a {@code CatalogResolver} using the specified feature
* settings and path to one or more catalog files.
@ -115,33 +104,4 @@ public final class CatalogManager {
Catalog catalog = catalog(features, paths);
return new CatalogResolverImpl(catalog);
}
/**
* Creates an instance of a {@code CatalogUriResolver} using the specified
* feature settings and path to one or more catalog files.
* <p>
* If {@code paths} is empty, system property {@code javax.xml.catalog.files}
* will be read to locate the initial list of catalog files.
* <p>
* If more than one catalog files are specified through the paths argument or
* {@code javax.xml.catalog.files} property, the first entry is considered
* the main catalog, while others are treated as alternative catalogs after
* those referenced by the {@code nextCatalog} elements in the main catalog.
* <p>
* As specified in
* <a href="https://www.oasis-open.org/committees/download.php/14809/xml-catalogs.html#s.res.fail">
* XML Catalogs, OASIS Standard V1.1</a>, invalid path entries will be ignored.
* No error will be reported. In case all entries are invalid, the resolver
* will return as no mapping is found.
*
* @param features the catalog features
* @param paths the path(s) to one or more catalogs
*
* @return an instance of a {@code CatalogUriResolver}
* @throws CatalogException If an error occurs while parsing the catalog
*/
public static CatalogUriResolver catalogUriResolver(CatalogFeatures features, String... paths) {
Catalog catalog = catalog(features, paths);
return new CatalogUriResolverImpl(catalog);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2016, 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
@ -24,32 +24,90 @@
*/
package javax.xml.catalog;
import java.io.InputStream;
import javax.xml.stream.XMLResolver;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
/**
* A SAX EntityResolver that uses catalogs to resolve references.
* A Catalog Resolver that implements SAX {@link org.xml.sax.EntityResolver},
* StAX {@link javax.xml.stream.XMLResolver},
* DOM LS {@link org.w3c.dom.ls.LSResourceResolver} used by Schema Validation, and
* Transform {@link javax.xml.transform.URIResolver}, and resolves
* external references using catalogs.
* <p>
* The <a href="https://www.oasis-open.org/committees/download.php/14809/xml-catalogs.html">
* Catalog Standard</a> distinguished {@code external identifiers} from {@code uri entries}
* as being used to solely identify DTDs, while {@code uri entries} for
* other resources such as stylesheets and schema. The Java APIs, such as
* {@link javax.xml.stream.XMLResolver} and {@link org.w3c.dom.ls.LSResourceResolver}
* however, make no such distinction.
* In consistent with the existing Java API, this CatalogResolver recognizes a
* system identifier as an URI and will search both {@code system} and {@code uri}
* entries in a catalog in order to find a matching entry.
* <p>
* The search is started in the current catalog. If a match is found,
* no further attempt will be made. Only if there is no match in the current
* catalog, will alternate catalogs including delegate and next catalogs be considered.
* <p>
* <h3>Search Order</h3>
* The resolver will first search the system-type of entries with the specified
* {@code systemId}. The system entries include {@code system},
* {@code rewriteSystem} and {@code systemSuffix} entries.
* <p>
* If no match is found, {@code public} entries may be searched in accordance with
* the {@code prefer} attribute.
* <p>
* <b>The {@code prefer} attribute</b>: if the {@code prefer} is public,
* and there is no match found through the system entries, {@code public} entries
* will be considered. If it is not specified, the {@code prefer} is public
* by default (Note that by the OASIS standard, system entries will always
* be considered before public entries. Prefer public means that public entries
* will be matched when both system and public identifiers are specified.
* In general therefore, prefer public is recommended.)
* <p>
* If no match is found with the {@code systemId} and {@code public} identifier,
* the resolver will continue searching {@code uri} entries
* with the specified {@code systemId} or {@code href}. The {@code uri} entries
* include {@code uri}, {@code rewriteURI}, and {@code uriSuffix} entries.
*
* <p>
* <h3>Error Handling</h3>
* The interfaces that the CatalogResolver extend specified checked exceptions, including:
* <ul>
* <li>
* {@link org.xml.sax.SAXException} and {@link java.io.IOException} by
* {@link org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)}
* </li>
* <li>
* {@link javax.xml.stream.XMLStreamException} by
* {@link javax.xml.stream.XMLResolver#resolveEntity(java.lang.String, java.lang.String, java.lang.String, java.lang.String)}
* </li>
* <li>
* {@link javax.xml.transform.TransformerException} by
* {@link javax.xml.transform.URIResolver#resolve(java.lang.String, java.lang.String)}
* </li>
* </ul>
* <p>
* The CatalogResolver however, will throw {@link javax.xml.catalog.CatalogException}
* only when {@code javax.xml.catalog.resolve} is specified as {@code strict}.
* For applications that expect to handle the checked Exceptions, it may be
* necessary to use a custom resolver to wrap the CatalogResolver or implement it
* with a {@link javax.xml.catalog.Catalog} object.
*
* @since 9
*/
public interface CatalogResolver extends EntityResolver {
public interface CatalogResolver extends EntityResolver, XMLResolver,
URIResolver, LSResourceResolver {
/**
* The method searches through the catalog entries in the main and
* alternative catalogs to attempt to find a match with the specified publicId
* or systemId.
* <p>
* For resolving external entities, system entries will be matched before
* the public entries.
* <p>
* <b>The {@code prefer} attribute</b>: if the {@code prefer} is public,
* and there is no match found through the system entries, public entries
* will be considered. If it is not specified, the {@code prefer} is public
* by default (Note that by the OASIS standard, system entries will always
* be considered first when the external system identifier is specified.
* Prefer public means that public entries will be matched when both system
* and public identifiers are specified. In general therefore, prefer
* public is recommended.)
* Implements {@link org.xml.sax.EntityResolver}. The method searches through
* the catalog entries in the main and alternative catalogs to attempt to find
* a match with the specified {@code publicId} or systemId.
*
* @param publicId the public identifier of the external entity being
* referenced, or null if none was supplied
@ -59,15 +117,123 @@ public interface CatalogResolver extends EntityResolver {
* requires a system identifier on all external entities, so this value is
* always specified.
*
* @return a {@link org.xml.sax.InputSource} object if a mapping is found. If no mapping is
* found, returns a {@link org.xml.sax.InputSource} object containing an empty
* {@link java.io.Reader} if the {@code javax.xml.catalog.resolve} property
* is set to {@code ignore}; returns null if the
* @return a {@link org.xml.sax.InputSource} object if a mapping is found.
* If no mapping is found, returns a {@link org.xml.sax.InputSource} object
* containing an empty {@link java.io.Reader} if the
* {@code javax.xml.catalog.resolve} property is set to {@code ignore};
* returns null if the
* {@code javax.xml.catalog.resolve} property is set to {@code continue}.
*
* @throws CatalogException if no mapping is found and
* {@code javax.xml.catalog.resolve} is specified as strict
* {@code javax.xml.catalog.resolve} is specified as {@code strict}
*/
@Override
public InputSource resolveEntity(String publicId, String systemId);
/**
* Implements URIResolver. The method searches through the catalog entries
* in the main and alternative catalogs to attempt to find a match
* with the specified {@code href} attribute. The {@code href} attribute will
* be used literally, with no attempt to be made absolute to the {@code base}.
* <p>
* If the value is an URN, the {@code href} attribute is recognized as a
* {@code publicId}, and used to search {@code public} entries.
* If the value is an URI, it is taken as a {@code systemId}, and used to
* search both {@code system} and {@code uri} entries.
*
*
* @param href the href attribute that specifies the URI of a style sheet,
* which may be relative or absolute
* @param base The base URI against which the href attribute will be made
* absolute if the absolute URI is required
*
* @return a {@link javax.xml.transform.Source} object if a mapping is found.
* If no mapping is found, returns an empty {@link javax.xml.transform.Source}
* object if the {@code javax.xml.catalog.resolve} property is set to
* {@code ignore};
* returns a {@link javax.xml.transform.Source} object with the original URI
* (href, or href resolved with base if base is not null) if the
* {@code javax.xml.catalog.resolve} property is set to {@code continue}.
*
* @throws CatalogException if no mapping is found and
* {@code javax.xml.catalog.resolve} is specified as {@code strict}
*/
@Override
public Source resolve(String href, String base);
/**
* Implements {@link javax.xml.stream.XMLResolver}. For the purpose of resolving
* {@code publicId} and {@code systemId}, this method is equivalent to
* {@link #resolveEntity(java.lang.String, java.lang.String) }.
* <p>
* The {@code systemId} will be used literally, with no attempt to be made
* absolute to the {@code baseUri}. The {@code baseUri} and {@code namespace}
* are not used in the search for a match in a catalog. However, a relative
* {@code systemId} in an xml source may have been made absolute by the parser
* with the {@code baseURI}, thus making it unable to find a {@code system} entry.
* In such a case, a {@code systemSuffix} entry is recommended over a
* {@code system} entry.
*
* @param publicId the public identifier of the external entity being
* referenced, or null if none was supplied
*
* @param systemId the system identifier of the external entity being
* referenced. A system identifier is required on all external entities. XML
* requires a system identifier on all external entities, so this value is
* always specified.
* @param baseUri the absolute base URI, not used by the CatalogResolver
* @param namespace the namespace of the entity to resolve, not used by the
* CatalogResolver.
*
* @return an {@link java.io.InputStream} object if a mapping is found; null
* if no mapping is found and the {@code javax.xml.catalog.resolve} property
* is set to {@code continue} or {@code ignore}. Note that for XMLResolver,
* it is not possible to ignore a reference, {@code ignore} is therefore
* treated the same as {@code continue}.
*
* @throws CatalogException if no mapping is found and
* {@code javax.xml.catalog.resolve} is specified as {@code strict}
*/
@Override
public InputStream resolveEntity(String publicId, String systemId,
String baseUri, String namespace);
/**
* Implements {@link org.w3c.dom.ls.LSResourceResolver}. For the purpose of
* resolving {@code publicId} and {@code systemId}, this method is equivalent
* to {@link #resolveEntity(java.lang.String, java.lang.String) }.
* <p>
* The {@code systemId} will be used literally, with no attempt to be made
* absolute to the {@code baseUri}. The {@code baseUri}, {@code namespaceUri}
* and {@code type} are not used in the search for a match in a catalog.
* However, a relative {@code systemId} in a source may have been made absolute
* by the parser with the {@code baseURI}, thus making it unable to find a
* {@code system} entry. In such a case, a {@code systemSuffix} entry is
* recommended over a {@code system} entry.
*
* @param type the type of the resource being resolved,
* not used by the CatalogResolver
* @param namespaceUri the namespace of the resource being resolved,
* not used by the CatalogResolver
* @param publicId the public identifier of the external entity being
* referenced, or {@code null} if no public identifier was
* supplied or if the resource is not an entity.
* @param systemId the system identifier, an URI reference of the
* external resource being referenced
* @param baseUri the absolute base URI, not used by the CatalogResolver
*
* @return a {@link org.w3c.dom.ls.LSInput} object if a mapping is found; null
* if no mapping is found and the {@code javax.xml.catalog.resolve} property
* is set to {@code continue} or {@code ignore}. Note that for
* {@link org.w3c.dom.ls.LSResourceResolver}, it is not possible to ignore a
* reference, {@code ignore} is therefore treated the same as {@code continue}.
*
* @throws CatalogException if no mapping is found and
* {@code javax.xml.catalog.resolve} is specified as {@code strict}
*/
@Override
public LSInput resolveResource(String type, String namespaceUri,
String publicId, String systemId, String baseUri);
}

View File

@ -24,15 +24,27 @@
*/
package javax.xml.catalog;
import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.Iterator;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import org.w3c.dom.ls.LSInput;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* A SAX EntityResolver/JAXP URIResolver that uses catalogs.
* Implements CatalogResolver.
*
* <p>
* This class implements both a SAX EntityResolver and a JAXP URIResolver.
* This class implements a SAX EntityResolver, StAX XMLResolver,
* Schema Validation LSResourceResolver and Transform URIResolver.
*
*
* @since 9
@ -49,9 +61,14 @@ final class CatalogResolverImpl implements CatalogResolver {
this.catalog = catalog;
}
/*
Implements the EntityResolver interface
*/
@Override
public InputSource resolveEntity(String publicId, String systemId) {
//8150187: NPE expected if the system identifier is null for CatalogResolver
CatalogMessages.reportNPEOnNull("systemId", systemId);
//Normalize publicId and systemId
systemId = Normalizer.normalizeURI(Util.getNotNullOrEmpty(systemId));
publicId = Normalizer.normalizePublicId(Normalizer.decodeURN(Util.getNotNullOrEmpty(publicId)));
@ -87,4 +104,242 @@ final class CatalogResolverImpl implements CatalogResolver {
return null;
}
/*
Implements the URIResolver interface
*/
CatalogResolverImpl entityResolver;
@Override
public Source resolve(String href, String base) {
CatalogMessages.reportNPEOnNull("href", href);
href = Util.getNotNullOrEmpty(href);
base = Util.getNotNullOrEmpty(base);
String result = null;
CatalogImpl c = (CatalogImpl)catalog;
String uri = Normalizer.normalizeURI(href);
//check whether uri is an urn
if (uri != null && uri.startsWith(Util.URN)) {
String publicId = Normalizer.decodeURN(uri);
if (publicId != null) {
result = Util.resolve(c, publicId, null);
}
}
//if no match with a public id, continue search for an URI
if (result == null) {
//remove fragment if any.
int hashPos = uri.indexOf("#");
if (hashPos >= 0) {
uri = uri.substring(0, hashPos);
}
//search the current catalog
result = Util.resolve(c, null, uri);
}
//Report error or return the URI as is when no match is found
if (result == null) {
GroupEntry.ResolveType resolveType = c.getResolve();
switch (resolveType) {
case IGNORE:
return new SAXSource(new InputSource(new StringReader("")));
case STRICT:
CatalogMessages.reportError(CatalogMessages.ERR_NO_URI_MATCH,
new Object[]{href, base});
}
try {
URL url = null;
if (base == null) {
url = new URL(uri);
result = url.toString();
} else {
URL baseURL = new URL(base);
url = (href.length() == 0 ? baseURL : new URL(baseURL, uri));
result = url.toString();
}
} catch (java.net.MalformedURLException mue) {
CatalogMessages.reportError(CatalogMessages.ERR_CREATING_URI,
new Object[]{href, base});
}
}
SAXSource source = new SAXSource();
source.setInputSource(new InputSource(result));
setEntityResolver(source);
return source;
}
/**
* Establish an entityResolver for newly resolved URIs.
* <p>
* This is called from the URIResolver to set an EntityResolver on the SAX
* parser to be used for new XML documents that are encountered as a result
* of the document() function, xsl:import, or xsl:include. This is done
* because the XSLT processor calls out to the SAXParserFactory itself to
* create a new SAXParser to parse the new document. The new parser does not
* automatically inherit the EntityResolver of the original (although
* arguably it should). Quote from JAXP specification on Class
* SAXTransformerFactory:
* <p>
* {@code If an application wants to set the ErrorHandler or EntityResolver
* for an XMLReader used during a transformation, it should use a URIResolver
* to return the SAXSource which provides (with getXMLReader) a reference to
* the XMLReader}
*
*/
private void setEntityResolver(SAXSource source) {
XMLReader reader = source.getXMLReader();
if (reader == null) {
SAXParserFactory spFactory = new SAXParserFactoryImpl();
spFactory.setNamespaceAware(true);
try {
reader = spFactory.newSAXParser().getXMLReader();
} catch (ParserConfigurationException | SAXException ex) {
CatalogMessages.reportRunTimeError(CatalogMessages.ERR_PARSER_CONF, ex);
}
}
if (entityResolver != null) {
entityResolver = new CatalogResolverImpl(catalog);
}
reader.setEntityResolver(entityResolver);
source.setXMLReader(reader);
}
@Override
public InputStream resolveEntity(String publicId, String systemId, String baseUri, String namespace) {
InputSource is = resolveEntity(publicId, systemId);
if (is != null && !is.isEmpty()) {
try {
return new URL(is.getSystemId()).openStream();
} catch (IOException ex) {
//considered as no mapping.
}
}
GroupEntry.ResolveType resolveType = ((CatalogImpl) catalog).getResolve();
switch (resolveType) {
case IGNORE:
return null;
case STRICT:
CatalogMessages.reportError(CatalogMessages.ERR_NO_MATCH,
new Object[]{publicId, systemId});
}
//no action, allow the parser to continue
return null;
}
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
InputSource is = resolveEntity(publicId, systemId);
if (is != null && !is.isEmpty()) {
return new LSInputImpl(is.getSystemId());
}
GroupEntry.ResolveType resolveType = ((CatalogImpl) catalog).getResolve();
switch (resolveType) {
case IGNORE:
return null;
case STRICT:
CatalogMessages.reportError(CatalogMessages.ERR_NO_MATCH,
new Object[]{publicId, systemId});
}
//no action, allow the parser to continue
return null;
}
/**
* Implements LSInput. All that we need is the systemId since the Catalog
* has already resolved it.
*/
class LSInputImpl implements LSInput {
private String systemId;
public LSInputImpl(String systemId) {
this.systemId = systemId;
}
@Override
public Reader getCharacterStream() {
return null;
}
@Override
public void setCharacterStream(Reader characterStream) {
}
@Override
public InputStream getByteStream() {
return null;
}
@Override
public void setByteStream(InputStream byteStream) {
}
@Override
public String getStringData() {
return null;
}
@Override
public void setStringData(String stringData) {
}
@Override
public String getSystemId() {
return systemId;
}
@Override
public void setSystemId(String systemId) {
this.systemId = systemId;
}
@Override
public String getPublicId() {
return null;
}
@Override
public void setPublicId(String publicId) {
}
@Override
public String getBaseURI() {
return null;
}
@Override
public void setBaseURI(String baseURI) {
}
@Override
public String getEncoding() {
return null;
}
@Override
public void setEncoding(String encoding) {
}
@Override
public boolean getCertifiedText() {
return false;
}
@Override
public void setCertifiedText(boolean certifiedText) {
}
}
}

View File

@ -1,58 +0,0 @@
/*
* 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 javax.xml.catalog;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
/**
* A JAXP URIResolver that uses catalogs to resolve references.
*
* @since 9
*/
public interface CatalogUriResolver extends URIResolver {
/**
* The method searches through the catalog entries in the main and
* alternative catalogs to attempt to find a match with the specified URI.
*
* @param href an href attribute, which may be relative or absolute
* @param base The base URI against which the href attribute will be made
* absolute if the absolute URI is required
*
* @return a {@link javax.xml.transform.Source} object if a mapping is found.
* If no mapping is found, returns an empty {@link javax.xml.transform.Source}
* object if the {@code javax.xml.catalog.resolve} property is set to
* {@code ignore};
* returns a {@link javax.xml.transform.Source} object with the original URI
* (href, or href resolved with base if base is not null) if the
* {@code javax.xml.catalog.resolve} property is set to {@code continue}.
*
* @throws CatalogException if no mapping is found and
* {@code javax.xml.catalog.resolve} is specified as strict
*/
@Override
public Source resolve(String href, String base);
}

View File

@ -1,191 +0,0 @@
/*
* Copyright (c) 2015, 2016, 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 javax.xml.catalog;
import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
import java.io.StringReader;
import java.net.URL;
import java.util.Iterator;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* A SAX EntityResolver/JAXP URIResolver that uses catalogs.
* <p>
* This class implements both a SAX EntityResolver and a JAXP URIResolver.
*
*
* @since 9
*/
final class CatalogUriResolverImpl implements CatalogUriResolver {
Catalog catalog;
CatalogResolverImpl entityResolver;
/**
* Construct an instance of the CatalogResolver from a Catalog.
*
* @param catalog A Catalog.
*/
public CatalogUriResolverImpl(Catalog catalog) {
this.catalog = catalog;
}
@Override
public Source resolve(String href, String base) {
href = Util.getNotNullOrEmpty(href);
base = Util.getNotNullOrEmpty(base);
if (href == null) return null;
String result = null;
CatalogImpl c = (CatalogImpl)catalog;
String uri = Normalizer.normalizeURI(href);
//check whether uri is an urn
if (uri != null && uri.startsWith(Util.URN)) {
String publicId = Normalizer.decodeURN(uri);
if (publicId != null) {
result = Util.resolve(c, publicId, null);
}
}
//if no match with a public id, continue search for an URI
if (result == null) {
//remove fragment if any.
int hashPos = uri.indexOf("#");
if (hashPos >= 0) {
uri = uri.substring(0, hashPos);
}
//search the current catalog
result = resolve(c, uri);
}
//Report error or return the URI as is when no match is found
if (result == null) {
GroupEntry.ResolveType resolveType = c.getResolve();
switch (resolveType) {
case IGNORE:
return new SAXSource(new InputSource(new StringReader("")));
case STRICT:
CatalogMessages.reportError(CatalogMessages.ERR_NO_URI_MATCH,
new Object[]{href, base});
}
try {
URL url = null;
if (base == null) {
url = new URL(uri);
result = url.toString();
} else {
URL baseURL = new URL(base);
url = (href.length() == 0 ? baseURL : new URL(baseURL, uri));
result = url.toString();
}
} catch (java.net.MalformedURLException mue) {
CatalogMessages.reportError(CatalogMessages.ERR_CREATING_URI,
new Object[]{href, base});
}
}
SAXSource source = new SAXSource();
source.setInputSource(new InputSource(result));
setEntityResolver(source);
return source;
}
/**
* Resolves the publicId or systemId to one specified in the catalog.
* @param catalog the catalog
* @param href an href attribute, which may be relative or absolute
* @return the resolved systemId if a match is found, null otherwise
*/
String resolve(CatalogImpl catalog, String href) {
String result = null;
//search the current catalog
catalog.reset();
if (href != null) {
result = catalog.matchURI(href);
}
//mark the catalog as having been searched before trying alternatives
catalog.markAsSearched();
//search alternative catalogs
if (result == null) {
Iterator<Catalog> iter = catalog.catalogs().iterator();
while (iter.hasNext()) {
result = resolve((CatalogImpl)iter.next(), href);
if (result != null) {
break;
}
}
}
return result;
}
/**
* Establish an entityResolver for newly resolved URIs.
* <p>
* This is called from the URIResolver to set an EntityResolver on the SAX
* parser to be used for new XML documents that are encountered as a result
* of the document() function, xsl:import, or xsl:include. This is done
* because the XSLT processor calls out to the SAXParserFactory itself to
* create a new SAXParser to parse the new document. The new parser does not
* automatically inherit the EntityResolver of the original (although
* arguably it should). Quote from JAXP specification on Class
* SAXTransformerFactory:
* <p>
* {@code If an application wants to set the ErrorHandler or EntityResolver
* for an XMLReader used during a transformation, it should use a URIResolver
* to return the SAXSource which provides (with getXMLReader) a reference to
* the XMLReader}
*
*/
private void setEntityResolver(SAXSource source) {
XMLReader reader = source.getXMLReader();
if (reader == null) {
SAXParserFactory spFactory = new SAXParserFactoryImpl();
spFactory.setNamespaceAware(true);
try {
reader = spFactory.newSAXParser().getXMLReader();
} catch (ParserConfigurationException | SAXException ex) {
CatalogMessages.reportRunTimeError(CatalogMessages.ERR_PARSER_CONF, ex);
}
}
if (entityResolver != null) {
entityResolver = new CatalogResolverImpl(catalog);
}
reader.setEntityResolver(entityResolver);
source.setXMLReader(reader);
}
}

View File

@ -55,6 +55,9 @@ class Util {
* prefer "public": attempts to resolve with a system entry;
* attempts to resolve with a public entry if no matching
* system entry is found.
*
* If no match is found, continue searching uri entries
*
* @param catalog the catalog
* @param publicId the publicId
* @param systemId the systemId
@ -77,6 +80,10 @@ class Util {
resolvedSystemId = catalog.matchPublic(publicId);
}
if (resolvedSystemId == null && systemId != null) {
resolvedSystemId = catalog.matchURI(systemId);
}
//mark the catalog as having been searched before trying alternatives
catalog.markAsSearched();

View File

@ -64,4 +64,3 @@ public class CatalogReferCircularityTest {
{ "catalogReferCircle-left.xml" } };
}
}

View File

@ -69,4 +69,3 @@ public class DefaultFeaturesTest {
{ Feature.RESOLVE, CatalogTestUtils.RESOLVE_STRICT } };
}
}

View File

@ -86,4 +86,3 @@ public class DeferFeatureTest {
return (int) method.invoke(catalog);
}
}

View File

@ -100,4 +100,3 @@ public class DelegatePublicTest {
return catalogResolver("delegatePublic.xml");
}
}

View File

@ -100,4 +100,3 @@ public class DelegateSystemTest {
return catalogResolver("delegateSystem.xml");
}
}

View File

@ -27,8 +27,8 @@ import static catalog.CatalogTestUtils.catalogUriResolver;
import static catalog.ResolutionChecker.checkUriResolution;
import static catalog.ResolutionChecker.expectExceptionOnUri;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
@ -95,8 +95,7 @@ public class DelegateUriTest {
CatalogException.class } };
}
private CatalogUriResolver createResolver() {
private CatalogResolver createResolver() {
return catalogUriResolver("delegateUri.xml");
}
}

View File

@ -131,4 +131,3 @@ public class GroupTest {
return catalogResolver(CATALOG_GROUP);
}
}

View File

@ -33,7 +33,6 @@ import static catalog.ResolutionChecker.checkUriResolution;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
@ -56,6 +55,7 @@ public class LoadCatalogTest {
private static final String CATALOG_DUMMY = "dummy.xml";
private static final String ID_ALICE = "http://remote/dtd/alice/docAlice.dtd";
private static final String ID_ALICE_URI = "http://remote/dtd/uri/alice/docAlice.dtd";
private static final String ID_DUMMY = "http://remote/dtd/doc.dtd";
@Test(dataProvider = "entityResolver")
@ -79,8 +79,8 @@ public class LoadCatalogTest {
}
@Test(dataProvider = "uriResolver")
public void testMatchOnUriResolver(CatalogUriResolver resolver) {
checkUriResolution(resolver, ID_ALICE,
public void testMatchOnUriResolver(CatalogResolver resolver) {
checkUriResolution(resolver, ID_ALICE_URI,
"http://local/dtd/docAliceURI.dtd");
}
@ -121,4 +121,3 @@ public class LoadCatalogTest {
{ new String[] { CATALOG_LOADCATALOGFILES } } };
}
}

View File

@ -30,7 +30,6 @@ import static catalog.ResolutionChecker.checkSysIdResolution;
import static catalog.ResolutionChecker.checkUriResolution;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
@ -154,9 +153,8 @@ public class NextCatalogTest {
CATALOG_NEXTCATALOGRIGHT);
}
private CatalogUriResolver createUriResolver() {
private CatalogResolver createUriResolver() {
return catalogUriResolver(CATALOG_NEXTCATALOGLEFT,
CATALOG_NEXTCATALOGRIGHT);
}
}

View File

@ -30,7 +30,6 @@ import static catalog.ResolutionChecker.checkSysIdResolution;
import static catalog.ResolutionChecker.checkUriResolution;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
@ -111,8 +110,7 @@ public class NormalizationTest {
return catalogResolver(CATALOG_NORMALIZATION);
}
private CatalogUriResolver createUriResolver() {
private CatalogResolver createUriResolver() {
return catalogUriResolver(CATALOG_NORMALIZATION);
}
}

View File

@ -81,4 +81,3 @@ public class PreferFeatureTest {
"preferFeature.xml");
}
}

View File

@ -92,4 +92,3 @@ public class PreferTest {
return catalogResolver("prefer.xml");
}
}

View File

@ -70,4 +70,3 @@ public class PublicFamilyTest {
return catalogResolver("publicFamily.xml");
}
}

View File

@ -92,4 +92,3 @@ public class PublicTest {
return catalogResolver(CATALOG_PUBLIC);
}
}

View File

@ -38,7 +38,6 @@ import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogFeatures.Feature;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@ -93,7 +92,7 @@ public class ResolveFeatureTest {
*/
@Test
public void testContinueResolutionOnUriResolver() {
CatalogUriResolver resolver = createUriResolver(RESOLVE_CONTINUE);
CatalogResolver resolver = createUriResolver(RESOLVE_CONTINUE);
resolver.resolve("http://remote/dtd/bob/docBobDummy.dtd", null);
checkUriResolution(resolver, "http://remote/dtd/bob/docBob.dtd",
"http://local/base/dtd/docBobURI.dtd");
@ -123,7 +122,7 @@ public class ResolveFeatureTest {
return catalogResolver(createFeature(resolve), CATALOG_SYSTEM);
}
private CatalogUriResolver createUriResolver(String resolve) {
private CatalogResolver createUriResolver(String resolve) {
return catalogUriResolver(createFeature(resolve), CATALOG_URI);
}
@ -131,4 +130,3 @@ public class ResolveFeatureTest {
return builder().with(Feature.RESOLVE, resolve).build();
}
}

View File

@ -95,4 +95,3 @@ public class RewriteSystemTest {
return catalogResolver("rewriteSystem.xml");
}
}

View File

@ -24,11 +24,11 @@
package catalog;
import static catalog.CatalogTestUtils.catalogUriResolver;
import static catalog.ResolutionChecker.checkNoMatch;
import static catalog.ResolutionChecker.checkNoUriMatch;
import static catalog.ResolutionChecker.checkUriResolution;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
@ -88,11 +88,10 @@ public class RewriteUriTest {
*/
@Test(expectedExceptions = CatalogException.class)
public void testNoMatch() {
checkNoMatch(createResolver());
checkNoUriMatch(createResolver());
}
private CatalogUriResolver createResolver() {
private CatalogResolver createResolver() {
return catalogUriResolver("rewriteUri.xml");
}
}

View File

@ -36,7 +36,6 @@ import static javax.xml.catalog.CatalogFeatures.Feature.FILES;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@ -68,7 +67,7 @@ public class SpecifyCatalogTest {
}
/*
* CatalogUriResolver specifies catalog via feature javax.xml.catalog.files.
* CatalogResolver specifies catalog via feature javax.xml.catalog.files.
*/
@Test
public void specifyCatalogOnUriResolver() {
@ -102,7 +101,7 @@ public class SpecifyCatalogTest {
checkSysIdResolution(resolver, ID_SYS, matchedUri);
}
private void checkResolutionOnUriResolver(CatalogUriResolver resolver,
private void checkResolutionOnUriResolver(CatalogResolver resolver,
String matchedUri) {
checkUriResolution(resolver, ID_URI, matchedUri);
}
@ -111,4 +110,3 @@ public class SpecifyCatalogTest {
return builder().with(FILES, getCatalogPath(catalogName)).build();
}
}

View File

@ -84,4 +84,3 @@ public class SystemFamilyTest {
return catalogResolver("systemFamily.xml");
}
}

View File

@ -95,4 +95,3 @@ public class SystemSuffixTest {
return catalogResolver("systemSuffix.xml");
}
}

View File

@ -92,4 +92,3 @@ public class SystemTest {
return catalogResolver(CATALOG_SYSTEM);
}
}

View File

@ -24,11 +24,11 @@
package catalog;
import static catalog.CatalogTestUtils.catalogUriResolver;
import static catalog.ResolutionChecker.checkNoMatch;
import static catalog.ResolutionChecker.checkNoUriMatch;
import static catalog.ResolutionChecker.checkUriResolution;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
@ -58,7 +58,7 @@ public class UriFamilyTest {
return new Object[][] {
// The matched URI of the specified URI reference is defined in
// a uri entry.
{ "http://remote/dtd/alice/docAlice.dtd",
{ "http://remote/dtd/uri/alice/docAlice.dtd",
"http://local/base/dtd/docAliceURI.dtd" },
// The matched URI of the specified URI reference is defined in
@ -77,11 +77,10 @@ public class UriFamilyTest {
*/
@Test(expectedExceptions = CatalogException.class)
public void testNoMatch() {
checkNoMatch(createResolver());
checkNoUriMatch(createResolver());
}
private CatalogUriResolver createResolver() {
private CatalogResolver createResolver() {
return catalogUriResolver("uriFamily.xml");
}
}

View File

@ -24,11 +24,11 @@
package catalog;
import static catalog.CatalogTestUtils.catalogUriResolver;
import static catalog.ResolutionChecker.checkNoMatch;
import static catalog.ResolutionChecker.checkNoUriMatch;
import static catalog.ResolutionChecker.checkUriResolution;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
@ -88,11 +88,10 @@ public class UriSuffixTest {
*/
@Test(expectedExceptions = CatalogException.class)
public void testNoMatch() {
checkNoMatch(createResolver());
checkNoUriMatch(createResolver());
}
private CatalogUriResolver createResolver() {
private CatalogResolver createResolver() {
return catalogUriResolver("uriSuffix.xml");
}
}

View File

@ -26,12 +26,12 @@ package catalog;
import static catalog.CatalogTestUtils.CATALOG_URI;
import static catalog.CatalogTestUtils.RESOLVE_CONTINUE;
import static catalog.CatalogTestUtils.catalogUriResolver;
import static catalog.ResolutionChecker.checkNoMatch;
import static catalog.ResolutionChecker.checkNoUriMatch;
import static catalog.ResolutionChecker.checkUriResolution;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
@ -58,7 +58,7 @@ public class UriTest {
return new Object[][] {
// The matched URI of the specified URI reference is defined in
// a uri entry. The match is an absolute path.
{ "http://remote/dtd/alice/docAlice.dtd",
{ "http://remote/dtd/uri/alice/docAlice.dtd",
"http://local/dtd/docAliceURI.dtd" },
// The matched URI of the specified URI reference is defined in
@ -76,7 +76,7 @@ public class UriTest {
}
/*
* Specify base location via method CatalogUriResolver.resolve(href, base).
* Specify base location via method CatalogResolver.resolve(href, base).
*/
@Test
public void testSpecifyBaseByAPI() {
@ -84,7 +84,7 @@ public class UriTest {
"http://remote/dtd/carl/docCarl.dtd",
"http://local/carlBase/dtd/docCarlURI.dtd");
CatalogUriResolver continueResolver = catalogUriResolver(
CatalogResolver continueResolver = catalogUriResolver(
CatalogFeatures.builder().with(CatalogFeatures.Feature.RESOLVE,
RESOLVE_CONTINUE).build(), CATALOG_URI);
checkUriResolution(continueResolver, "docCarl.dtd",
@ -97,11 +97,10 @@ public class UriTest {
*/
@Test(expectedExceptions = CatalogException.class)
public void testNoMatch() {
checkNoMatch(createResolver());
checkNoUriMatch(createResolver());
}
private CatalogUriResolver createResolver() {
private CatalogResolver createResolver() {
return catalogUriResolver(CATALOG_URI);
}
}

View File

@ -67,4 +67,3 @@ public class UrnUnwrappingTest {
return catalogResolver("urnUnwrapping.xml");
}
}

View File

@ -98,8 +98,7 @@ public class ValidateCatalogTest {
"http://remote/dtd/alice/docAlice.dtd",
"http://local/dtd/docAliceSys.dtd");
checkUriResolution(catalogUriResolver(catalogName, CATALOG_URI),
"http://remote/dtd/alice/docAlice.dtd",
"http://remote/dtd/uri/alice/docAlice.dtd",
"http://local/dtd/docAliceURI.dtd");
}
}

View File

@ -2,7 +2,7 @@
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<system systemId="http://remote/dtd/alice/docAlice.dtd" uri="http://local/dtd/docAliceSys.dtd" />
<uri name="http://remote/dtd/alice/docAlice.dtd" uri="http://local/dtd/docAliceURI.dtd" />
<uri name="http://remote/dtd/uri/alice/docAlice.dtd" uri="http://local/dtd/docAliceURI.dtd" />
<delegateSystem systemIdStartString="http://remote/dtd/alice/" catalog="delegateSystem-alice.xml" />
<delegatePublic publicIdStartString="-//REMOTE//DTD ALICE DOCALICE" catalog="delegatePublic-alice.xml" />

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" xml:base="http://local/base/dtd/">
<uri name="http://remote/dtd/alice/docAlice.dtd" uri="http://local/dtd/docAliceURI.dtd" />
<uri name="http://remote/dtd/uri/alice/docAlice.dtd" uri="http://local/dtd/docAliceURI.dtd" />
<uri name="http://remote/dtd/bob/docBob.dtd" uri="docBobURI.dtd" />

View File

@ -4,7 +4,7 @@
<delegateURI uriStartString="http://remote/dtd/alice/" catalog="delegateURI-alice.xml" />
<uriSuffix uriSuffix="docAlice.dtd" uri="docAliceUS.dtd" />
<rewriteURI uriStartString="http://remote/dtd/alice/" rewritePrefix="http://local/base/ru/" />
<uri name="http://remote/dtd/alice/docAlice.dtd" uri="docAliceURI.dtd" />
<uri name="http://remote/dtd/uri/alice/docAlice.dtd" uri="docAliceURI.dtd" />
<delegateURI uriStartString="http://remote/dtd/bob/" catalog="delegateURI-bob.xml" />
<uriSuffix uriSuffix="docBob.dtd" uri="docBobUS.dtd" />

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2016, 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
@ -42,7 +42,6 @@ import java.util.HashMap;
import java.util.Map;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
/*
* This case tests if the properties FILES, DEFER, PREFER, RESOLVE in
@ -96,7 +95,7 @@ public class PropertiesTest {
}
private static void testPropertiesOnUriResolver() {
CatalogUriResolver uriResolver = catalogUriResolver((String[]) null);
CatalogResolver uriResolver = catalogUriResolver((String[]) null);
uriResolver.resolve("http://remote/uri/dtd/docDummy.dtd", null);
"http://local/base/dtd/docURI.dtd".equals(uriResolver.resolve(
"http://remote/dtd/doc.dtd", null).getSystemId());

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2016, 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
@ -35,7 +35,6 @@ import java.util.stream.Stream;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import jaxp.library.JAXPTestUtilities;
@ -101,18 +100,18 @@ final class CatalogTestUtils {
/*
* Creates catalogUriResolver with a set of catalogs.
*/
static CatalogUriResolver catalogUriResolver(String... catalogName) {
static CatalogResolver catalogUriResolver(String... catalogName) {
return catalogUriResolver(CatalogFeatures.defaults(), catalogName);
}
/*
* Creates catalogUriResolver with a feature and a set of catalogs.
*/
static CatalogUriResolver catalogUriResolver(
static CatalogResolver catalogUriResolver(
CatalogFeatures features, String... catalogName) {
return (catalogName == null) ?
CatalogManager.catalogUriResolver(features) :
CatalogManager.catalogUriResolver(features, getCatalogPaths(catalogName));
CatalogManager.catalogResolver(features) :
CatalogManager.catalogResolver(features, getCatalogPaths(catalogName));
}
// Gets the paths of the specified catalogs.

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2016, 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
@ -24,7 +24,6 @@
package catalog;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.Assert;
@ -65,7 +64,7 @@ class ResolutionChecker {
* Checks the resolution result for specified URI references
* with the specified base location.
*/
static void checkUriResolution(CatalogUriResolver resolver,
static void checkUriResolution(CatalogResolver resolver,
String href, String base, String matchedUri) {
Assert.assertEquals(resolver.resolve(href, base).getSystemId(),
matchedUri);
@ -74,7 +73,7 @@ class ResolutionChecker {
/*
* Checks the resolution result for specified URI references.
*/
static void checkUriResolution(CatalogUriResolver resolver,
static void checkUriResolution(CatalogResolver resolver,
String href, String matchedUri) {
checkUriResolution(resolver, href, null, matchedUri);
}
@ -92,9 +91,9 @@ class ResolutionChecker {
/*
* With strict resolution, if no match is found,
* CatalogUriResolver should throw CatalogException.
* CatalogResolver should throw CatalogException.
*/
static void checkNoMatch(CatalogUriResolver resolver) {
static void checkNoUriMatch(CatalogResolver resolver) {
resolver.resolve("http://uri/noMatch/docNoMatch.dtd", getNotSpecified(null));
}
@ -139,7 +138,7 @@ class ResolutionChecker {
* URI reference with a specified base location.
*/
static <T extends Throwable> void expectExceptionOnUri(
CatalogUriResolver resolver, String href, String base,
CatalogResolver resolver, String href, String base,
Class<T> expectedExceptionClass) {
expectThrows(expectedExceptionClass, () -> {
resolver.resolve(href, base);
@ -151,7 +150,7 @@ class ResolutionChecker {
* URI reference without any specified base location.
*/
static <T extends Throwable> void expectExceptionOnUri(
CatalogUriResolver resolver, String href,
CatalogResolver resolver, String href,
Class<T> expectedExceptionClass) {
expectExceptionOnUri(resolver, href, null, expectedExceptionClass);
}

View File

@ -327,4 +327,3 @@ public class CatalogSupport extends CatalogSupportBase {
};
}
}

View File

@ -11,32 +11,32 @@
<!-- public publicId="datatypes" uri="datatypes.dtd"/-->
<!-- XInclude -->
<uri name="XI_simple.xml" uri="XI_simple4Catalog.xml"/>
<uri name="XI_utf8.xml" uri="XI_utf8.xml"/>
<uri name="XI_utf8Catalog.xml" uri="XI_utf8Catalog.xml"/>
<uri name="XI_test2.xml" uri="XI_test2.xml"/>
<system systemId="XI_simple.xml" uri="XI_simple4Catalog.xml"/>
<system systemId="XI_utf8.xml" uri="XI_utf8.xml"/>
<system systemId="XI_utf8Catalog.xml" uri="XI_utf8Catalog.xml"/>
<system systemId="XI_test2.xml" uri="XI_test2.xml"/>
<system systemId="XI_red.dtd" uri="XI_red.dtd"/>
<!-- xsd import can be mapped using the namespace or systemId -->
<!--public publicId="http://www.w3.org/XML/1998/namespace" uri="xml.xsd"/-->
<!--uri name="http://www.w3.org/XML/1998/namespace" uri="xml.xsd"/-->
<uri name="http://www.w3.org/2001/pathto/xml.xsd" uri="xml.xsd"/>
<system systemId="http://www.w3.org/2001/pathto/xml.xsd" uri="xml.xsd"/>
<!-- schema include -->
<uri name="pathto/XSDInclude_person.xsd" uri="XSDInclude_person.xsd"/>
<uri name="pathto/XSDInclude_product.xsd" uri="XSDInclude_product.xsd"/>
<system systemId="pathto/XSDInclude_person.xsd" uri="XSDInclude_person.xsd"/>
<system systemId="pathto/XSDInclude_product.xsd" uri="XSDInclude_product.xsd"/>
<!-- for relative path, use Suffix -->
<systemSuffix systemIdSuffix="pathto/val_test.xsd" uri="val_test.xsd"/>
<!-- XSL import and include -->
<uri name="pathto/XSLImport_html.xsl" uri="XSLImport_html.xsl"/>
<uri name="pathto/XSLInclude_header.xsl" uri="XSLInclude_header.xsl"/>
<uri name="pathto/XSLInclude_footer.xsl" uri="XSLInclude_footer.xsl"/>
<system systemId="pathto/XSLImport_html.xsl" uri="XSLImport_html.xsl"/>
<system systemId="pathto/XSLInclude_header.xsl" uri="XSLInclude_header.xsl"/>
<system systemId="pathto/XSLInclude_footer.xsl" uri="XSLInclude_footer.xsl"/>
<!-- and DTDs -->
<system systemId="http://openjdk.java.net/xml/catalog/dtd/XSLDTD.dtd" uri="XSLDTD.dtd"/>
<system systemId="http://openjdk.java.net/xml/catalog/dtd/include.dtd" uri="include.dtd"/>
<!-- XSLT document function -->
<uri name="pathto/DocFunc2.xml" uri="DocFuncCatalog.xml"/>
<system systemId="pathto/DocFunc2.xml" uri="DocFuncCatalog.xml"/>
</catalog>

View File

@ -268,4 +268,3 @@ public class CatalogSupport1 extends CatalogSupportBase {
}
}

View File

@ -270,4 +270,3 @@ public class CatalogSupport2 extends CatalogSupportBase {
};
}
}

View File

@ -280,4 +280,3 @@ public class CatalogSupport3 extends CatalogSupportBase {
};
}
}

View File

@ -269,4 +269,3 @@ public class CatalogSupport4 extends CatalogSupportBase {
};
}
}

View File

@ -0,0 +1,250 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package catalog;
import java.io.File;
import java.io.StringReader;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*
* @test
* @bug 8158084 8163232
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm -DrunSecMngr=true catalog.CatalogSupport5
* @run testng/othervm catalog.CatalogSupport5
* @summary extends CatalogSupport tests, verifies that when errors occur,
* relevant checked Exceptions are returned.
*/
/**
* The CatalogResolver will throw CatalogException when there is no match and
* the resolve property is strict. The Exception should be caught with the existing
* mechanisms so that the checked Exception corresponding to the process can be
* returned.
*
* @author huizhe.wang@oracle.com
*/
@Listeners({jaxp.library.FilePolicy.class, jaxp.library.NetAccessPolicy.class})
public class CatalogSupport5 extends CatalogSupportBase {
/*
* Initializing fields
*/
@BeforeClass
public void setUpClass() throws Exception {
setUp();
}
/*
Verifies the Catalog support on SAXParser.
*/
@Test(dataProvider = "data_SAXC", expectedExceptions = SAXException.class)
public void testSAXC(boolean setUseCatalog, boolean useCatalog, String catalog, String
xml, MyHandler handler, String expected) throws Exception {
testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
}
/*
Verifies the Catalog support on XMLReader.
*/
@Test(dataProvider = "data_SAXC", expectedExceptions = SAXException.class)
public void testXMLReaderC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
}
/*
Verifies the Catalog support on XInclude.
*/
@Test(dataProvider = "data_XIC", expectedExceptions = SAXException.class)
public void testXIncludeC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected);
}
/*
Verifies the Catalog support on DOM parser.
*/
@Test(dataProvider = "data_DOMC", expectedExceptions = SAXException.class)
public void testDOMC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
}
/*
Verifies the Catalog support on resolving DTD, xsd import and include in
Schema files.
*/
@Test(dataProvider = "data_SchemaC", expectedExceptions = SAXException.class)
public void testValidationC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xsd, LSResourceResolver resolver)
throws Exception {
testValidation(setUseCatalog, useCatalog, catalog, xsd, resolver) ;
}
@Test(dataProvider = "data_ValidatorC", expectedExceptions = SAXException.class)
public void testValidatorC(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2)
throws Exception {
testValidator(setUseCatalog1, setUseCatalog2, useCatalog, source,
resolver1, resolver2, catalog1, catalog2);
}
/*
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC", expectedExceptions = TransformerException.class)
public void testXSLImportC(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception {
testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
}
/*
@bug 8158084 8162442
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC", expectedExceptions = TransformerException.class)
public void testXSLImportWTemplatesC(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception {
testXSLImportWTemplates(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
}
/*
DataProvider: for testing the SAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_SAXC")
public Object[][] getDataSAXC() {
return new Object[][]{
{false, true, xml_bogus_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
};
}
/*
DataProvider: for testing XInclude
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_XIC")
public Object[][] getDataXIC() {
return new Object[][]{
{false, true, xml_bogus_catalog, xml_xInclude, new MyHandler(elementInXISimple), contentInUIutf8Catalog},
};
}
/*
DataProvider: for testing DOM parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_DOMC")
public Object[][] getDataDOMC() {
return new Object[][]{
{false, true, xml_bogus_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
};
}
/*
DataProvider: for testing Schema validation
Data: set use_catalog, use_catalog, catalog file, xsd file, a LSResourceResolver
*/
@DataProvider(name = "data_SchemaC")
public Object[][] getDataSchemaC() {
return new Object[][]{
// for resolving DTD in xsd
{false, true, xml_bogus_catalog, xsd_xmlSchema, null},
// for resolving xsd import
{false, true, xml_bogus_catalog, xsd_xmlSchema_import, null},
// for resolving xsd include
{false, true, xml_bogus_catalog, xsd_include_company, null}
};
}
/*
DataProvider: for testing Schema Validator
Data: setUseCatalog1, setUseCatalog2, useCatalog, source, resolver1, resolver2,
catalog1, catalog2
*/
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
SAXSource ss = new SAXSource(new InputSource(xml_val_test));
ss.setSystemId(xml_val_test_id);
StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id);
StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id);
StreamSource source = new StreamSource(new File(xml_val_test));
return new Object[][]{
// use catalog
{false, false, true, ds, null, null, xml_bogus_catalog, null},
{false, false, true, ds, null, null, null, xml_bogus_catalog},
{false, false, true, ss, null, null, xml_bogus_catalog, null},
{false, false, true, ss, null, null, null, xml_bogus_catalog},
{false, false, true, stax, null, null, xml_bogus_catalog, null},
{false, false, true, stax1, null, null, null, xml_bogus_catalog},
{false, false, true, source, null, null, xml_bogus_catalog, null},
{false, false, true, source, null, null, null, xml_bogus_catalog},
};
}
/*
DataProvider: for testing XSL import and include
Data: set use_catalog, use_catalog, catalog file, xsl file, xml file, a URIResolver, expected
*/
@DataProvider(name = "data_XSLC")
public Object[][] getDataXSLC() {
SAXSource xslSourceDTD = new SAXSource(new InputSource(new StringReader(xsl_includeDTD)));
StreamSource xmlSourceDTD = new StreamSource(new StringReader(xml_xslDTD));
SAXSource xslDocSource = new SAXSource(new InputSource(new File(xsl_doc).toURI().toASCIIString()));
StreamSource xmlDocSource = new StreamSource(new File(xml_doc));
return new Object[][]{
// for resolving DTD, import and include in xsl
{false, true, xml_bogus_catalog, xslSourceDTD, xmlSourceDTD, null, ""},
// for resolving reference by the document function
{false, true, xml_bogus_catalog, xslDocSource, xmlDocSource, null, "Resolved by a catalog"},
};
}
}

View File

@ -35,9 +35,9 @@ import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import javax.xml.XMLConstants;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogResolver;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
@ -61,7 +61,6 @@ import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.testng.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@ -677,6 +676,29 @@ public class CatalogSupportBase {
}
/**
* Extends MyHandler and overrides resolveEntity with a CatalogResolver
*/
class MyCatalogHandler extends MyHandler {
CatalogResolver cr;
public MyCatalogHandler(CatalogResolver cr, String elementName) {
super(elementName);
this.cr = cr;
}
@Override
public InputSource resolveEntity(String publicId, String systemId) {
return cr.resolveEntity(publicId, systemId);
}
@Override
public InputSource resolveEntity(String name, String publicId,
String baseURI, String systemId) {
return cr.resolveEntity(publicId, systemId);
}
}
/**
* Extends MyHandler and overrides resolveEntity
*/
@ -935,4 +957,3 @@ public class CatalogSupportBase {
}
}
}

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<!-- DTDs and external entities -->
<uri name="http://openjdk.java.net/xml/catalog/dtd/system.dtd" uri="system.dtd"/>
<!-- XMLSchema refers to XMLSchema.dtd -->
<public publicId="-//W3C//DTD XMLSCHEMA 200102//EN" uri="XMLSchema.dtd"/>
<!-- XMLSchema.dtd refers to datatypes.dtd -->
<uriSuffix uriSuffix="datatypes.dtd" uri="datatypes.dtd"/>
<!-- XMLSchema.dtd refers to datatypes.dtd, can use public entry as well -->
<!-- public publicId="datatypes" uri="datatypes.dtd"/-->
<!-- XInclude -->
<uri name="XI_simple.xml" uri="XI_simple4Catalog.xml"/>
<uri name="XI_utf8.xml" uri="XI_utf8.xml"/>
<uri name="XI_utf8Catalog.xml" uri="XI_utf8Catalog.xml"/>
<uri name="XI_test2.xml" uri="XI_test2.xml"/>
<uri name="XI_red.dtd" uri="XI_red.dtd"/>
<!-- xsd import can be mapped using the namespace or systemId -->
<!--public publicId="http://www.w3.org/XML/1998/namespace" uri="xml.xsd"/-->
<!--uri name="http://www.w3.org/XML/1998/namespace" uri="xml.xsd"/-->
<uri name="http://www.w3.org/2001/pathto/xml.xsd" uri="xml.xsd"/>
<!-- schema include -->
<uri name="pathto/XSDInclude_person.xsd" uri="XSDInclude_person.xsd"/>
<uri name="pathto/XSDInclude_product.xsd" uri="XSDInclude_product.xsd"/>
<!-- for relative path, use Suffix -->
<uriSuffix uriSuffix="pathto/val_test.xsd" uri="val_test.xsd"/>
<!-- XSL import and include -->
<uri name="pathto/XSLImport_html.xsl" uri="XSLImport_html.xsl"/>
<uri name="pathto/XSLInclude_header.xsl" uri="XSLInclude_header.xsl"/>
<uri name="pathto/XSLInclude_footer.xsl" uri="XSLInclude_footer.xsl"/>
<!-- and DTDs -->
<uri name="http://openjdk.java.net/xml/catalog/dtd/XSLDTD.dtd" uri="XSLDTD.dtd"/>
<uri name="http://openjdk.java.net/xml/catalog/dtd/include.dtd" uri="include.dtd"/>
<!-- XSLT document function -->
<uri name="pathto/DocFunc2.xml" uri="DocFuncCatalog.xml"/>
</catalog>

View File

@ -26,23 +26,37 @@ import static jaxp.library.JAXPTestUtilities.clearSystemProperty;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import static jaxp.library.JAXPTestUtilities.setSystemProperty;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.file.Paths;
import java.util.PropertyPermission;
import javax.xml.XMLConstants;
import javax.xml.catalog.Catalog;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogFeatures.Feature;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import jaxp.library.JAXPTestUtilities;
import org.testng.Assert;
@ -59,29 +73,235 @@ import org.xml.sax.ext.DefaultHandler2;
/*
* @test
* @bug 8081248 8144966 8146606 8146237 8151154 8150969 8151162 8152527 8154220
* @bug 8081248 8144966 8146606 8146237 8151154 8150969 8151162 8152527 8154220 8163232
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm -DrunSecMngr=true catalog.CatalogTest
* @run testng/othervm catalog.CatalogTest
* @summary Tests basic Catalog functions.
*/
@Listeners({jaxp.library.FilePolicy.class})
public class CatalogTest {
public class CatalogTest extends CatalogSupportBase {
static final String KEY_FILES = "javax.xml.catalog.files";
public String filepath;
/*
* Initializing fields
*/
@BeforeClass
public void setUpClass() throws Exception {
String file1 = getClass().getResource("first_cat.xml").getFile();
if (getSystemProperty("os.name").contains("Windows")) {
filepath = file1.substring(1, file1.lastIndexOf("/") + 1);
} else {
filepath = file1.substring(0, file1.lastIndexOf("/") + 1);
super.setUp();
}
/*
* @bug 8163232
* Verifies that the CatalogResolver supports the following XML Resolvers:
javax.xml.stream.XMLResolver
javax.xml.transform.URIResolver
org.w3c.dom.ls.LSResourceResolver
org.xml.sax.EntityResolver
*
* Plus, system and uri entries can equally be used.
*/
/*
* Verifies the support for org.xml.sax.EntityResolver.
* Expected: the parser returns the expected string.
*/
@Test(dataProvider = "supportXMLResolver")
public void supportEntityResolver(String catalogFile, String xml, String expected) throws Exception {
String xmlSource = getClass().getResource(xml).getFile();
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
MyCatalogHandler handler = new MyCatalogHandler(cr, elementInSystem);
SAXParser parser = getSAXParser(false, true, null);
parser.parse(xmlSource, handler);
Assert.assertEquals(handler.getResult().trim(), expected);
}
/*
* Verifies the support for javax.xml.stream.XMLResolver.
* Expected: the parser returns the expected string.
*/
@Test(dataProvider = "supportXMLResolver")
public void supportXMLResolver(String catalogFile, String xml, String expected) throws Exception {
String xmlSource = getClass().getResource(xml).getFile();
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
XMLInputFactory xifactory = XMLInputFactory.newInstance();
xifactory.setProperty(XMLInputFactory.IS_COALESCING, true);
xifactory.setProperty(XMLInputFactory.RESOLVER, cr);
File file = new File(xmlSource);
String systemId = file.toURI().toString();
InputStream entityxml = new FileInputStream(file);
XMLStreamReader streamReader = xifactory.createXMLStreamReader(systemId, entityxml);
String result = null;
while (streamReader.hasNext()) {
int eventType = streamReader.next();
if (eventType == XMLStreamConstants.START_ELEMENT) {
eventType = streamReader.next();
if (eventType == XMLStreamConstants.CHARACTERS) {
result = streamReader.getText();
}
}
}
System.out.println(": expected [" + expected + "] <> actual [" + result.trim() + "]");
Assert.assertEquals(result.trim(), expected);
}
/*
* Verifies the support for org.w3c.dom.ls.LSResourceResolver by ShemaFactory.
* Success: parsing goes through with no error
* Fail: throws Exception if references are not resolved (by the CatalogResolver)
*/
@Test(dataProvider = "supportLSResourceResolver")
public void supportLSResourceResolver(String catalogFile, Source schemaSource) throws SAXException {
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setResourceResolver(cr);
Schema schema = factory.newSchema(schemaSource);
}
/*
* Verifies the support for org.w3c.dom.ls.LSResourceResolver by Validator.
* Success: parsing goes through with no error
* Fail: throws Exception if references are not resolved (by the CatalogResolver)
*/
@Test(dataProvider = "supportLSResourceResolver1")
public void supportLSResourceResolver1(String catalogFile, Source source) throws Exception {
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Validator validator = factory.newSchema().newValidator();
validator.setResourceResolver(cr);
validator.validate(source);
}
/*
* Verifies the support for javax.xml.transform.URIResolver.
* Success: parsing goes through with no error
* Fail: throws Exception if references are not resolved (by the CatalogResolver)
*/
@Test(dataProvider = "supportURIResolver")
public void supportURIResolver(String catalogFile, Source xsl, Source xml, String expected) throws Exception {
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
TransformerFactory factory = TransformerFactory.newInstance();
factory.setURIResolver(cr);
Transformer transformer = factory.newTransformer(xsl);
StringWriter out = new StringWriter();
transformer.transform(xml, new StreamResult(out));
if (expected != null) {
Assert.assertTrue(out.toString().contains(expected), "supportURIResolver");
}
}
/*
DataProvider: used to verify the support of XML Resolvers.
Data columns:
catalog filepath, xml source file, expected result
*/
@DataProvider(name = "supportXMLResolver")
public Object[][] supportXMLResolver() {
String catalogFile = getClass().getResource("catalog.xml").getFile();
String catalogFileUri = getClass().getResource("catalog_uri.xml").getFile();
return new Object[][]{
{catalogFile, "system.xml", "Test system entry"},
{catalogFile, "rewritesystem.xml", "Test rewritesystem entry"},
{catalogFile, "rewritesystem1.xml", "Test rewritesystem entry"},
{catalogFile, "systemsuffix.xml", "Test systemsuffix entry"},
{catalogFile, "delegatesystem.xml", "Test delegatesystem entry"},
{catalogFile, "public.xml", "Test public entry"},
{catalogFile, "delegatepublic.xml", "Test delegatepublic entry"},
// using uri entries
{catalogFileUri, "system.xml", "Test system entry"},
{catalogFileUri, "rewritesystem.xml", "Test rewritesystem entry"},
{catalogFileUri, "rewritesystem1.xml", "Test rewritesystem entry"},
{catalogFileUri, "systemsuffix.xml", "Test systemsuffix entry"},
{catalogFileUri, "delegateuri.xml", "Test delegateuri entry"},
{catalogFileUri, "public.xml", "Test public entry"},
};
}
/*
DataProvider: used to verify the support of LSResourceResolver by SchemaFactory.
Data columns:
catalog filepath, schema source file
*/
@DataProvider(name = "supportLSResourceResolver")
public Object[][] supportLSResourceResolver() {
String catalogFile = getClass().getResource("CatalogSupport.xml").getFile();
String catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").getFile();
/*
* XMLSchema.xsd has a reference to XMLSchema.dtd which in turn refers to
* datatypes.dtd
*/
return new Object[][]{
{catalogFile, new StreamSource(new StringReader(xsd_xmlSchema))},
{catalogFile, new StreamSource(new StringReader(xsd_xmlSchema_import))},
{catalogFile, new StreamSource(new StringReader(xsd_include_company))},
{catalogFileUri, new StreamSource(new StringReader(xsd_xmlSchema))},
{catalogFileUri, new StreamSource(new StringReader(xsd_xmlSchema_import))},
{catalogFileUri, new StreamSource(new StringReader(xsd_include_company))},
};
}
/*
DataProvider: used to verify the support of LSResourceResolver by Validator.
Data columns:
catalog filepath, source file
*/
@DataProvider(name = "supportLSResourceResolver1")
public Object[][] supportLSResourceResolver1() {
String catalogFile = getClass().getResource("CatalogSupport.xml").getFile();
String catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").getFile();
/*
* val_test.xml has a reference to system.dtd and val_test.xsd
*/
SAXSource ss = new SAXSource(new InputSource(xml_val_test));
ss.setSystemId(xml_val_test_id);
return new Object[][]{
{catalogFile, ss},
{catalogFileUri, ss},
};
}
/*
DataProvider: used to verify the support of LSResourceResolver by Validator.
Data columns:
catalog filepath, xsl source, xml source file
*/
@DataProvider(name = "supportURIResolver")
public Object[][] supportURIResolver() {
String catalogFile = getClass().getResource("CatalogSupport.xml").getFile();
String catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").getFile();
SAXSource xslSource = new SAXSource(new InputSource(new File(xsl_doc).toURI().toASCIIString()));
/*
* val_test.xml has a reference to system.dtd and val_test.xsd
*/
SAXSource ss = new SAXSource(new InputSource(xml_val_test));
ss.setSystemId(xml_val_test_id);
return new Object[][]{
{catalogFile, new SAXSource(new InputSource(new File(xsl_doc).toURI().toASCIIString())),
new StreamSource(new File(xml_doc)), "Resolved by a catalog"},
{catalogFileUri, new SAXSource(new InputSource(new StringReader(xsl_include))),
new StreamSource(new StringReader(xml_xsl)), null},
};
}
/*
@ -110,7 +330,7 @@ public class CatalogTest {
@Test(dataProvider = "resolveUri")
public void testMatch1(String cFile, String href, String expectedFile, String expectedUri, String msg) {
String catalogFile = getClass().getResource(cFile).getFile();
CatalogUriResolver cur = CatalogManager.catalogUriResolver(CatalogFeatures.defaults(), catalogFile);
CatalogResolver cur = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
Source source = cur.resolve(href, null);
Assert.assertNotNull(source, "Source returned is null");
Assert.assertEquals(expectedUri, source.getSystemId(), msg);
@ -275,7 +495,7 @@ public class CatalogTest {
try {
CatalogUriResolver resolver = CatalogManager.catalogUriResolver(CatalogFeatures.defaults(), catalog);
CatalogResolver resolver = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog);
String actualSystemId = resolver.resolve("http://remote.com/import/import.xsl", null).getSystemId();
Assert.assertTrue(!actualSystemId.contains("//"), "result contains duplicate slashes");
} catch (Exception e) {
@ -383,7 +603,7 @@ public class CatalogTest {
/*
DataProvider: used to verify CatalogUriResolver's resolve function.
DataProvider: used to verify CatalogResolver's resolve function.
Data columns:
catalog, uri or publicId, expectedFile, expectedUri, msg
@ -571,4 +791,3 @@ public class CatalogTest {
}
}
}

View File

@ -26,4 +26,4 @@
<system systemId="http://remote/dtd/alice/docAlice.dtd" uri="http://local/dtd/docAliceSys.dtd" />
</group>
</catalog>
</catalog>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<catalog
xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<!-- using uri entries -->
<uri name="http://openjdk.java.net/xml/catalog/dtd/system.dtd" uri="system.dtd"/>
<rewriteURI uriStartString="http://openjdk.java.net/"
rewritePrefix="files" />
<rewriteURI uriStartString="http://openjdk.java.net/xml/catalog/dtd/"
rewritePrefix="files" />
<uriSuffix uriSuffix="systemsuffix.dtd" uri="systemsuffix.dtd"/>
<delegateURI uriStartString="http://java.com/xml/catalog/dtd/" catalog="files/delegatecatalog_uri.xml"/>
<uri name="-//OPENJDK//XML CATALOG DTD//1.0" uri="public.dtd"/>
<delegateURI uriStartString="-//JAVASE//XML CATALOG DTD//DELEGATEPULIC" catalog="files/delegatecatalog_uri.xml"/>
</catalog>

View File

@ -0,0 +1,5 @@
<?xml version="1.0"?>
<!DOCTYPE catalogtest PUBLIC "-//JAVASE//XML CATALOG DTD//DELEGATEURI"
"http://java.com/xml/catalog/dtd/delegateuri.dtd">
<catalogtest>Test &delegateuri; entry</catalogtest>

View File

@ -22,4 +22,4 @@
<system systemId="http://java.com/xml/catalog/dtd/delegatesystem.dtd" uri="delegatesystem.dtd"/>
</catalog>
</catalog>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<catalog
xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<uri name="http://java.com/xml/catalog/dtd/delegateuri.dtd" uri="delegateuri.dtd"/>
</catalog>

View File

@ -0,0 +1,2 @@
<!ENTITY delegateuri "delegateuri">

View File

@ -1,5 +1,5 @@
<?xml version="1.0"?>
<!DOCTYPE catalogtest PUBLIC "-//OPENJDK//XML CATALOG DTD//1.0"
<!DOCTYPE catalogtest PUBLIC "-//OPENJDK//XML CATALOG DTD SYSTEM//1.0"
"http://openjdk.java.net/xml/catalog/dtd/system.dtd">
<catalogtest>Test &system; entry</catalogtest>
<catalogtest>Test &system; entry</catalogtest>

View File

@ -0,0 +1,98 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package parsers;
import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/*
* @test
* @bug 8157797
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm -DrunSecMngr=true parsers.HandleError
* @run testng/othervm parsers.HandleError
* @summary Tests that the parser handles errors properly.
*/
@Listeners({jaxp.library.BasePolicy.class})
public class HandleError {
/*
* Verifies that the parser returns with no unexpected "java.lang.InternalError"
* when continue-after-fatal-error is requested.
*/
@Test
public void test() throws Exception {
String invalidXml = "<a>";
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true);
SAXParser parser = saxParserFactory.newSAXParser();
parser.parse(new InputSource(new StringReader(invalidXml)), new DefaultHandler() {
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.err.printf("%s%n", e.getMessage());
}
});
}
/*
* Verifies that the parser throws SAXParseException when parsing error is
* encountered when:
* continue-after-fatal-error is not set, the default it false
* continue-after-fatal-error is explicitly set to false
*/
@Test(dataProvider = "setFeature", expectedExceptions = SAXParseException.class)
public void test1(boolean setFeature, boolean value) throws Exception {
String invalidXml = "<a>";
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
if (setFeature) {
saxParserFactory.setFeature("http://apache.org/xml/features/continue-after-fatal-error", value);
}
SAXParser parser = saxParserFactory.newSAXParser();
parser.parse(new InputSource(new StringReader(invalidXml)), new DefaultHandler());
}
/*
DataProvider: used to set feature "continue-after-fatal-error"
Data columns:
flag to indicate the feature is to be set, the value of the feature
*/
@DataProvider(name = "setFeature")
public Object[][] getFeatureSetting() {
return new Object[][]{
{false, false},
{true, false},
};
}
}

View File

@ -378,3 +378,4 @@ fe4e11bd2423635dc0f5f5cb9a64eb2f2cce7f4c jdk-9+128
39c6293131d91aec7f2f5120395e070a937b8858 jdk-9+130
783e7e2c587f2c7e1b9998a46d90ec196ab2a195 jdk-9+131
9fff2477a4cadf2a9618a76f1f4fe0f20bb5ff3b jdk-9+132
05e99eefda2b58d1ed176e411302d9d6b35dca16 jdk-9+133

View File

@ -375,3 +375,4 @@ c40c8739bcdc88892ff58ebee3fd8a3f287be94d jdk-9+123
6c827500e34587061af97ad6fef0e859280255c5 jdk-9+130
8c57f4c293bbc5609928308a6d91ba765760b5f9 jdk-9+131
d5c70818cd8a82e76632c8c815bdb4f75f53aeaf jdk-9+132
3cdae27c90b5e41afe75eab904fda19fac076330 jdk-9+133

View File

@ -34,7 +34,7 @@ include GendataTZDB.gmk
include GendataBlacklistedCerts.gmk
include GendataPolicyJars.gmk
include GendataCryptoPolicy.gmk
################################################################################
@ -64,13 +64,19 @@ TARGETS += $(GENDATA_CURDATA)
GENDATA_JAVA_SECURITY_SRC := $(JDK_TOPDIR)/src/java.base/share/conf/security/java.security
GENDATA_JAVA_SECURITY := $(SUPPORT_OUTPUTDIR)/modules_conf/java.base/security/java.security
ifeq ($(UNLIMITED_CRYPTO), true)
CRYPTO.POLICY := unlimited
else
CRYPTO.POLICY := limited
endif
# RESTRICTED_PKGS_SRC is optionally set in custom extension for this makefile
$(GENDATA_JAVA_SECURITY): $(BUILD_TOOLS) $(GENDATA_JAVA_SECURITY_SRC) $(RESTRICTED_PKGS_SRC)
$(call LogInfo, Generating java.security)
$(call MakeDir, $(@D))
$(TOOL_MAKEJAVASECURITY) $(GENDATA_JAVA_SECURITY_SRC) $@ $(OPENJDK_TARGET_OS) \
$(OPENJDK_TARGET_CPU_ARCH) $(RESTRICTED_PKGS_SRC)
$(OPENJDK_TARGET_CPU_ARCH) $(CRYPTO.POLICY) $(RESTRICTED_PKGS_SRC)
TARGETS += $(GENDATA_JAVA_SECURITY)

View File

@ -0,0 +1,72 @@
#
# Copyright (c) 2013, 2016, 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.
#
#
# In pre-JDK9 releases, Oracle JDK has had a separately downloadable set
# of policy files which has been a nightmare for deployment.
#
# We now create 2 complete initial sets of policy files and package into
# 2 different directories. The crypto.policy Security property will select
# the active policy.
#
# It will be up to the user/deployer to make an informed choice
# as to whether they are legally entitled to use the unlimited policy
# file in their environment. The $(UNLIMITED_CRYPTO) make variable
# determines the default directory/policy.
#
default: all
include $(SPEC)
include MakeBase.gmk
################################################################################
POLICY_DIR := $(SUPPORT_OUTPUTDIR)/modules_conf/java.base/security/policy
LIMITED_POLICY_DIR := $(POLICY_DIR)/limited
UNLIMITED_POLICY_DIR := $(POLICY_DIR)/unlimited
POLICY_SRC_DIR := $(JDK_TOPDIR)/src/java.base/share/conf/security/policy
LIMITED_POLICY_SRC_DIR := $(POLICY_SRC_DIR)/limited
UNLIMITED_POLICY_SRC_DIR := $(POLICY_SRC_DIR)/unlimited
$(POLICY_DIR)/README.txt: $(POLICY_SRC_DIR)/README.txt
$(install-file)
$(LIMITED_POLICY_DIR)/%: $(LIMITED_POLICY_SRC_DIR)/%
$(install-file)
$(UNLIMITED_POLICY_DIR)/%: $(UNLIMITED_POLICY_SRC_DIR)/%
$(install-file)
TARGETS += \
$(POLICY_DIR)/README.txt \
$(LIMITED_POLICY_DIR)/default_US_export.policy \
$(LIMITED_POLICY_DIR)/default_local.policy \
$(LIMITED_POLICY_DIR)/exempt_local.policy \
$(UNLIMITED_POLICY_DIR)/default_US_export.policy \
$(UNLIMITED_POLICY_DIR)/default_local.policy \
################################################################################

View File

@ -1,150 +0,0 @@
#
# Copyright (c) 2013, 2016, 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.
#
default: all
include $(SPEC)
include MakeBase.gmk
include JarArchive.gmk
################################################################################
US_EXPORT_POLICY_JAR_DST := \
$(SUPPORT_OUTPUTDIR)/modules_libs/java.base/security/US_export_policy.jar
US_EXPORT_POLICY_JAR_LIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/US_export_policy.jar
US_EXPORT_POLICY_JAR_UNLIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/US_export_policy.jar
#
# TODO fix so that SetupJarArchive does not write files into SRCS
# then we don't need this extra copying
#
# NOTE: We currently do not place restrictions on our limited export
# policy. This was not a typo. This means we are shipping the same file
# for both limited and unlimited US_export_policy.jar. Only the local
# policy file currently has restrictions.
#
US_EXPORT_POLICY_JAR_SRC_DIR := \
$(JDK_TOPDIR)/make/data/cryptopolicy/unlimited
US_EXPORT_POLICY_JAR_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/US_export_policy_jar.tmp
$(US_EXPORT_POLICY_JAR_TMP)/%: $(US_EXPORT_POLICY_JAR_SRC_DIR)/%
$(install-file)
US_EXPORT_POLICY_JAR_DEPS := \
$(US_EXPORT_POLICY_JAR_TMP)/default_US_export.policy
$(eval $(call SetupJarArchive, BUILD_US_EXPORT_POLICY_JAR, \
DEPENDENCIES := $(US_EXPORT_POLICY_JAR_DEPS), \
SRCS := $(US_EXPORT_POLICY_JAR_TMP), \
SUFFIXES := .policy, \
JAR := $(US_EXPORT_POLICY_JAR_UNLIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
SKIP_METAINF := true, \
))
$(US_EXPORT_POLICY_JAR_LIMITED): \
$(US_EXPORT_POLICY_JAR_UNLIMITED)
$(call LogInfo, Copying unlimited $(patsubst $(OUTPUT_ROOT)/%,%,$@))
$(install-file)
TARGETS += $(US_EXPORT_POLICY_JAR_LIMITED) $(US_EXPORT_POLICY_JAR_UNLIMITED)
ifeq ($(UNLIMITED_CRYPTO), true)
$(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_UNLIMITED)
$(install-file)
else
$(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_LIMITED)
$(install-file)
endif
POLICY_JARS += $(US_EXPORT_POLICY_JAR_DST)
################################################################################
LOCAL_POLICY_JAR_DST := \
$(SUPPORT_OUTPUTDIR)/modules_libs/java.base/security/local_policy.jar
LOCAL_POLICY_JAR_LIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/local_policy.jar
LOCAL_POLICY_JAR_UNLIMITED := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/local_policy.jar
#
# TODO fix so that SetupJarArchive does not write files into SRCS
# then we don't need this extra copying
#
LOCAL_POLICY_JAR_LIMITED_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/limited/local_policy_jar.tmp
LOCAL_POLICY_JAR_UNLIMITED_TMP := \
$(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/local_policy_jar.tmp
$(LOCAL_POLICY_JAR_LIMITED_TMP)/%: \
$(JDK_TOPDIR)/make/data/cryptopolicy/limited/%
$(install-file)
$(LOCAL_POLICY_JAR_UNLIMITED_TMP)/%: \
$(JDK_TOPDIR)/make/data/cryptopolicy/unlimited/%
$(install-file)
$(eval $(call SetupJarArchive, BUILD_LOCAL_POLICY_JAR_LIMITED, \
DEPENDENCIES := $(LOCAL_POLICY_JAR_LIMITED_TMP)/exempt_local.policy \
$(LOCAL_POLICY_JAR_LIMITED_TMP)/default_local.policy, \
SRCS := $(LOCAL_POLICY_JAR_LIMITED_TMP), \
SUFFIXES := .policy, \
JAR := $(LOCAL_POLICY_JAR_LIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: limited, \
SKIP_METAINF := true, \
))
$(eval $(call SetupJarArchive, BUILD_LOCAL_POLICY_JAR_UNLIMITED, \
DEPENDENCIES := $(LOCAL_POLICY_JAR_UNLIMITED_TMP)/default_local.policy, \
SRCS := $(LOCAL_POLICY_JAR_UNLIMITED_TMP), \
SUFFIXES := .policy, \
JAR := $(LOCAL_POLICY_JAR_UNLIMITED), \
EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
SKIP_METAINF := true, \
))
TARGETS += $(LOCAL_POLICY_JAR_LIMITED) $(LOCAL_POLICY_JAR_UNLIMITED)
ifeq ($(UNLIMITED_CRYPTO), true)
$(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_UNLIMITED)
$(install-file)
else
$(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_LIMITED)
$(install-file)
endif
POLICY_JARS += $(LOCAL_POLICY_JAR_DST)
TARGETS += $(POLICY_JARS)
################################################################################
$(eval $(call IncludeCustomExtension, jdk, gendata/GendataPolicyJars.gmk))

View File

@ -36,3 +36,9 @@ $(eval $(call SetupBuildLauncher, jdeps, \
CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \
-DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \
))
$(eval $(call SetupBuildLauncher, jdeprscan, \
MAIN_CLASS := com.sun.tools.jdeprscan.Main, \
CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \
-DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \
))

View File

@ -1,5 +1,5 @@
#
# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2011, 2016, 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
@ -38,8 +38,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJ2PKCS11, \
CFLAGS := $(CFLAGS_JDKLIB) $(addprefix -I, $(LIBJ2PKCS11_SRC)) \
$(LIBJAVA_HEADER_FLAGS) \
-I$(SUPPORT_OUTPUTDIR)/headers/jdk.crypto.pkcs11, \
DISABLED_WARNINGS_solstudio := E_DECLARATION_IN_CODE, \
DISABLED_WARNINGS_microsoft := 4013 4267, \
MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libj2pkcs11/mapfile-vers, \
LDFLAGS := $(LDFLAGS_JDKLIB) \
$(call SET_SHARED_LIBRARY_ORIGIN), \

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2016, 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
@ -35,7 +35,8 @@ import java.util.*;
*
* 1. Adds additional packages to the package.access and
* package.definition security properties.
* 2. Filter out platform-unrelated parts
* 2. Filter out platform-unrelated parts.
* 3. Set the JCE jurisdiction policy directory.
*
* In order to easily maintain platform-related entries, every item
* (including the last line) in package.access and package.definition
@ -50,12 +51,13 @@ public class MakeJavaSecurity {
public static void main(String[] args) throws Exception {
if (args.length < 4) {
if (args.length < 5) {
System.err.println("Usage: java MakeJavaSecurity " +
"[input java.security file name] " +
"[output java.security file name] " +
"[openjdk target os] " +
"[openjdk target cpu architecture]" +
"[JCE jurisdiction policy directory]" +
"[more restricted packages file name?]");
System.exit(1);
@ -63,8 +65,8 @@ public class MakeJavaSecurity {
// more restricted packages
List<String> extraLines;
if (args.length == 5) {
extraLines = Files.readAllLines(Paths.get(args[4]));
if (args.length == 6) {
extraLines = Files.readAllLines(Paths.get(args[5]));
} else {
extraLines = Collections.emptyList();
}
@ -135,6 +137,16 @@ public class MakeJavaSecurity {
}
}
// Set the JCE policy value
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
int index = line.indexOf("crypto.policydir-tbd");
if (index >= 0) {
String prefix = line.substring(0, index);
lines.set(i, prefix + args[4]);
}
}
// Clean up the last line of PKG_ACC and PKG_DEF blocks.
// Not really necessary since a blank line follows.
boolean inBlock = false;

View File

@ -986,8 +986,9 @@ final class CipherCore {
if (padding != null) {
int padStart = padding.unpad(outWithPadding, 0, outLen);
if (padStart < 0) {
throw new BadPaddingException("Given final block not "
+ "properly padded");
throw new BadPaddingException("Given final block not " +
"properly padded. Such issues can arise if a bad key " +
"is used during decryption.");
}
outLen = padStart;
}

View File

@ -331,12 +331,6 @@ public final class Class<T> implements java.io.Serializable,
* Note that this method does not check whether the requested class
* is accessible to its caller.
*
* <p> If the {@code loader} is {@code null}, and a security
* manager is present, and the caller's class loader is not null, then this
* method calls the security manager's {@code checkPermission} method
* with a {@code RuntimePermission("getClassLoader")} permission to
* ensure it's ok to access the bootstrap class loader.
*
* @param name fully qualified name of the desired class
* @param initialize if {@code true} the class will be initialized.
* See Section 12.4 of <em>The Java Language Specification</em>.
@ -348,6 +342,11 @@ public final class Class<T> implements java.io.Serializable,
* by this method fails
* @exception ClassNotFoundException if the class cannot be located by
* the specified class loader
* @exception SecurityException
* if a security manager is present, and the {@code loader} is
* {@code null}, and the caller's class loader is not
* {@code null}, and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
*
* @see java.lang.Class#forName(String)
* @see java.lang.ClassLoader
@ -782,22 +781,17 @@ public final class Class<T> implements java.io.Serializable,
* null in such implementations if this class was loaded by the bootstrap
* class loader.
*
* <p> If a security manager is present, and the caller's class loader is
* not null and the caller's class loader is not the same as or an ancestor of
* the class loader for the class whose class loader is requested, then
* this method calls the security manager's {@code checkPermission}
* method with a {@code RuntimePermission("getClassLoader")}
* permission to ensure it's ok to access the class loader for the class.
*
* <p>If this object
* represents a primitive type or void, null is returned.
*
* @return the class loader that loaded the class or interface
* represented by this object.
* @throws SecurityException
* if a security manager exists and its
* {@code checkPermission} method denies
* access to the class loader for the class.
* @throws SecurityException
* if a security manager is present, and the caller's class loader
* is not {@code null} and is not the same as or an ancestor of the
* class loader for the class whose class loader is requested,
* and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
* @see java.lang.ClassLoader
* @see SecurityManager#checkPermission
* @see java.lang.RuntimePermission

View File

@ -1537,22 +1537,13 @@ public abstract class ClassLoader {
* will return <tt>null</tt> in such implementations if this class loader's
* parent is the bootstrap class loader.
*
* <p> If a security manager is present, and the invoker's class loader is
* not <tt>null</tt> and is not an ancestor of this class loader, then this
* method invokes the security manager's {@link
* SecurityManager#checkPermission(java.security.Permission)
* <tt>checkPermission</tt>} method with a {@link
* RuntimePermission#RuntimePermission(String)
* <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
* access to the parent class loader is permitted. If not, a
* <tt>SecurityException</tt> will be thrown. </p>
*
* @return The parent <tt>ClassLoader</tt>
*
* @throws SecurityException
* If a security manager exists and its <tt>checkPermission</tt>
* method doesn't allow access to this class loader's parent class
* loader.
* If a security manager is present, and the caller's class loader
* is not {@code null} and is not an ancestor of this class loader,
* and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
*
* @since 1.2
*/
@ -1590,12 +1581,11 @@ public abstract class ClassLoader {
* @return The platform {@code ClassLoader}.
*
* @throws SecurityException
* If a security manager exists and the caller's class loader is
* not {@code null} and the caller's class loader is not the same
* If a security manager is present, and the caller's class loader is
* not {@code null}, and the caller's class loader is not the same
* as or an ancestor of the platform class loader,
* and the {@link SecurityManager#checkPermission(java.security.Permission)
* checkPermission} method denies {@code RuntimePermission("getClassLoader")}
* to access the platform class loader.
* and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
*
* @since 9
*/
@ -1636,17 +1626,6 @@ public abstract class ClassLoader {
* If circular initialization of the system class loader is detected then
* an unspecified error or exception is thrown.
*
* <p> If a security manager is present, and the invoker's class loader is
* not <tt>null</tt> and the invoker's class loader is not the same as or
* an ancestor of the system class loader, then this method invokes the
* security manager's {@link
* SecurityManager#checkPermission(java.security.Permission)
* <tt>checkPermission</tt>} method with a {@link
* RuntimePermission#RuntimePermission(String)
* <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
* access to the system class loader. If not, a
* <tt>SecurityException</tt> will be thrown. </p>
*
* @implNote The system property to override the system class loader is not
* examined until the VM is almost fully initialized. Code that executes
* this method during startup should take care not to cache the return
@ -1656,8 +1635,10 @@ public abstract class ClassLoader {
* <tt>null</tt> if none
*
* @throws SecurityException
* If a security manager exists and its <tt>checkPermission</tt>
* method doesn't allow access to the system class loader.
* If a security manager is present, and the caller's class loader
* is not {@code null} and is not the same as or an ancestor of the
* system class loader, and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
*
* @throws IllegalStateException
* If invoked recursively during the construction of the class

View File

@ -1370,8 +1370,13 @@ public final class Math {
* result is positive zero.
* <li>If the argument is infinite, the result is positive infinity.
* <li>If the argument is NaN, the result is NaN.</ul>
* In other words, the result is the same as the value of the expression:
* <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
*
* @apiNote As implied by the above, one valid implementation of
* this method is given by the expression below which computes a
* {@code float} with the same exponent and significand as the
* argument but with a guaranteed zero sign bit indicating a
* positive value:<br>
* {@code Float.intBitsToFloat(0x7fffffff & Float.floatToRawIntBits(a))}
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.
@ -1389,8 +1394,13 @@ public final class Math {
* is positive zero.
* <li>If the argument is infinite, the result is positive infinity.
* <li>If the argument is NaN, the result is NaN.</ul>
* In other words, the result is the same as the value of the expression:
* <p>{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)}
*
* @apiNote As implied by the above, one valid implementation of
* this method is given by the expression below which computes a
* {@code double} with the same exponent and significand as the
* argument but with a guaranteed zero sign bit indicating a
* positive value:<br>
* {@code Double.longBitsToDouble((Double.doubleToRawLongBits(a)<<1)>>>1)}
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.

View File

@ -1070,8 +1070,13 @@ public final class StrictMath {
* result is positive zero.
* <li>If the argument is infinite, the result is positive infinity.
* <li>If the argument is NaN, the result is NaN.</ul>
* In other words, the result is the same as the value of the expression:
* <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
*
* @apiNote As implied by the above, one valid implementation of
* this method is given by the expression below which computes a
* {@code float} with the same exponent and significand as the
* argument but with a guaranteed zero sign bit indicating a
* positive value: <br>
* {@code Float.intBitsToFloat(0x7fffffff & Float.floatToRawIntBits(a))}
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.
@ -1089,8 +1094,13 @@ public final class StrictMath {
* is positive zero.
* <li>If the argument is infinite, the result is positive infinity.
* <li>If the argument is NaN, the result is NaN.</ul>
* In other words, the result is the same as the value of the expression:
* <p>{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)}
*
* @apiNote As implied by the above, one valid implementation of
* this method is given by the expression below which computes a
* {@code double} with the same exponent and significand as the
* argument but with a guaranteed zero sign bit indicating a
* positive value: <br>
* {@code Double.longBitsToDouble((Double.doubleToRawLongBits(a)<<1)>>>1)}
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.

View File

@ -1507,28 +1507,25 @@ class Thread implements Runnable {
}
/**
* Returns the context ClassLoader for this Thread. The context
* ClassLoader is provided by the creator of the thread for use
* Returns the context {@code ClassLoader} for this thread. The context
* {@code ClassLoader} is provided by the creator of the thread for use
* by code running in this thread when loading classes and resources.
* If not {@linkplain #setContextClassLoader set}, the default is the
* ClassLoader context of the parent Thread. The context ClassLoader of the
* {@code ClassLoader} context of the parent thread. The context
* {@code ClassLoader} of the
* primordial thread is typically set to the class loader used to load the
* application.
*
* <p>If a security manager is present, and the invoker's class loader is not
* {@code null} and is not the same as or an ancestor of the context class
* loader, then this method invokes the security manager's {@link
* SecurityManager#checkPermission(java.security.Permission) checkPermission}
* method with a {@link RuntimePermission RuntimePermission}{@code
* ("getClassLoader")} permission to verify that retrieval of the context
* class loader is permitted.
*
* @return the context ClassLoader for this Thread, or {@code null}
* @return the context {@code ClassLoader} for this thread, or {@code null}
* indicating the system class loader (or, failing that, the
* bootstrap class loader)
*
* @throws SecurityException
* if the current thread cannot get the context ClassLoader
* if a security manager is present, and the caller's class loader
* is not {@code null} and is not the same as or an ancestor of the
* context class loader, and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
*
* @since 1.2
*/

View File

@ -497,6 +497,10 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
String shortTypes = LambdaForm.shortenSignature(types);
String className = SPECIES_CLASS_PREFIX + shortTypes;
Class<?> c = BootLoader.loadClassOrNull(className);
if (TRACE_RESOLVE) {
System.out.println("[BMH_RESOLVE] " + shortTypes +
(c != null ? " (success)" : " (fail)") );
}
if (c != null) {
return c.asSubclass(BoundMethodHandle.class);
} else {

View File

@ -492,7 +492,7 @@ class DirectMethodHandle extends MethodHandle {
}
// Caching machinery for field accessors:
private static final byte
static final byte
AF_GETFIELD = 0,
AF_PUTFIELD = 1,
AF_GETSTATIC = 2,
@ -502,7 +502,7 @@ class DirectMethodHandle extends MethodHandle {
AF_LIMIT = 6;
// Enumerate the different field kinds using Wrapper,
// with an extra case added for checked references.
private static final int
static final int
FT_LAST_WRAPPER = Wrapper.COUNT-1,
FT_UNCHECKED_REF = Wrapper.OBJECT.ordinal(),
FT_CHECKED_REF = FT_LAST_WRAPPER+1,
@ -515,7 +515,7 @@ class DirectMethodHandle extends MethodHandle {
@Stable
private static final LambdaForm[] ACCESSOR_FORMS
= new LambdaForm[afIndex(AF_LIMIT, false, 0)];
private static int ftypeKind(Class<?> ftype) {
static int ftypeKind(Class<?> ftype) {
if (ftype.isPrimitive())
return Wrapper.forPrimitiveType(ftype).ordinal();
else if (VerifyType.isNullReferenceConversion(Object.class, ftype))
@ -566,7 +566,64 @@ class DirectMethodHandle extends MethodHandle {
private static final Wrapper[] ALL_WRAPPERS = Wrapper.values();
private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) {
private static Kind getFieldKind(boolean isGetter, boolean isVolatile, Wrapper wrapper) {
if (isGetter) {
if (isVolatile) {
switch (wrapper) {
case BOOLEAN: return GET_BOOLEAN_VOLATILE;
case BYTE: return GET_BYTE_VOLATILE;
case SHORT: return GET_SHORT_VOLATILE;
case CHAR: return GET_CHAR_VOLATILE;
case INT: return GET_INT_VOLATILE;
case LONG: return GET_LONG_VOLATILE;
case FLOAT: return GET_FLOAT_VOLATILE;
case DOUBLE: return GET_DOUBLE_VOLATILE;
case OBJECT: return GET_OBJECT_VOLATILE;
}
} else {
switch (wrapper) {
case BOOLEAN: return GET_BOOLEAN;
case BYTE: return GET_BYTE;
case SHORT: return GET_SHORT;
case CHAR: return GET_CHAR;
case INT: return GET_INT;
case LONG: return GET_LONG;
case FLOAT: return GET_FLOAT;
case DOUBLE: return GET_DOUBLE;
case OBJECT: return GET_OBJECT;
}
}
} else {
if (isVolatile) {
switch (wrapper) {
case BOOLEAN: return PUT_BOOLEAN_VOLATILE;
case BYTE: return PUT_BYTE_VOLATILE;
case SHORT: return PUT_SHORT_VOLATILE;
case CHAR: return PUT_CHAR_VOLATILE;
case INT: return PUT_INT_VOLATILE;
case LONG: return PUT_LONG_VOLATILE;
case FLOAT: return PUT_FLOAT_VOLATILE;
case DOUBLE: return PUT_DOUBLE_VOLATILE;
case OBJECT: return PUT_OBJECT_VOLATILE;
}
} else {
switch (wrapper) {
case BOOLEAN: return PUT_BOOLEAN;
case BYTE: return PUT_BYTE;
case SHORT: return PUT_SHORT;
case CHAR: return PUT_CHAR;
case INT: return PUT_INT;
case LONG: return PUT_LONG;
case FLOAT: return PUT_FLOAT;
case DOUBLE: return PUT_DOUBLE;
case OBJECT: return PUT_OBJECT;
}
}
}
throw new AssertionError("Invalid arguments");
}
static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) {
boolean isGetter = (formOp & 1) == (AF_GETFIELD & 1);
boolean isStatic = (formOp >= AF_GETSTATIC);
boolean needsInit = (formOp >= AF_GETSTATIC_INIT);
@ -576,24 +633,14 @@ class DirectMethodHandle extends MethodHandle {
assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind);
// getObject, putIntVolatile, etc.
StringBuilder nameBuilder = new StringBuilder();
if (isGetter) {
nameBuilder.append("get");
} else {
nameBuilder.append("put");
}
nameBuilder.append(fw.primitiveSimpleName());
nameBuilder.setCharAt(3, Character.toUpperCase(nameBuilder.charAt(3)));
if (isVolatile) {
nameBuilder.append("Volatile");
}
Kind kind = getFieldKind(isGetter, isVolatile, fw);
MethodType linkerType;
if (isGetter)
linkerType = MethodType.methodType(ft, Object.class, long.class);
else
linkerType = MethodType.methodType(void.class, Object.class, long.class, ft);
MemberName linker = new MemberName(Unsafe.class, nameBuilder.toString(), linkerType, REF_invokeVirtual);
MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual);
try {
linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class);
} catch (ReflectiveOperationException ex) {
@ -620,6 +667,7 @@ class DirectMethodHandle extends MethodHandle {
final int F_HOLDER = (isStatic ? nameCursor++ : -1); // static base if any
final int F_OFFSET = nameCursor++; // Either static offset or field offset.
final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1);
final int U_HOLDER = nameCursor++; // UNSAFE holder
final int INIT_BAR = (needsInit ? nameCursor++ : -1);
final int PRE_CAST = (needsCast && !isGetter ? nameCursor++ : -1);
final int LINKER_CALL = nameCursor++;
@ -632,7 +680,7 @@ class DirectMethodHandle extends MethodHandle {
names[PRE_CAST] = new Name(NF_checkCast, names[DMH_THIS], names[SET_VALUE]);
Object[] outArgs = new Object[1 + linkerType.parameterCount()];
assert(outArgs.length == (isGetter ? 3 : 4));
outArgs[0] = UNSAFE;
outArgs[0] = names[U_HOLDER] = new Name(NF_UNSAFE);
if (isStatic) {
outArgs[1] = names[F_HOLDER] = new Name(NF_staticBase, names[DMH_THIS]);
outArgs[2] = names[F_OFFSET] = new Name(NF_staticOffset, names[DMH_THIS]);
@ -650,6 +698,7 @@ class DirectMethodHandle extends MethodHandle {
for (Name n : names) assert(n != null);
// add some detail to the lambdaForm debugname,
// significant only for debugging
StringBuilder nameBuilder = new StringBuilder(kind.methodName);
if (isStatic) {
nameBuilder.append("Static");
} else {
@ -657,7 +706,12 @@ class DirectMethodHandle extends MethodHandle {
}
if (needsCast) nameBuilder.append("Cast");
if (needsInit) nameBuilder.append("Init");
return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT);
if (needsCast || needsInit) {
// can't use the pre-generated form when casting and/or initializing
return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT);
} else {
return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT, kind);
}
}
/**
@ -674,7 +728,8 @@ class DirectMethodHandle extends MethodHandle {
NF_staticOffset,
NF_checkCast,
NF_allocateInstance,
NF_constructorMethod;
NF_constructorMethod,
NF_UNSAFE;
static {
try {
NamedFunction nfs[] = {
@ -697,7 +752,9 @@ class DirectMethodHandle extends MethodHandle {
NF_allocateInstance = new NamedFunction(DirectMethodHandle.class
.getDeclaredMethod("allocateInstance", Object.class)),
NF_constructorMethod = new NamedFunction(DirectMethodHandle.class
.getDeclaredMethod("constructorMethod", Object.class))
.getDeclaredMethod("constructorMethod", Object.class)),
NF_UNSAFE = new NamedFunction(new MemberName(MethodHandleStatics.class
.getDeclaredField("UNSAFE")))
};
// Each nf must be statically invocable or we get tied up in our bootstraps.
assert(InvokerBytecodeGenerator.isStaticallyInvocable(nfs));

View File

@ -28,9 +28,11 @@ package java.lang.invoke;
import java.util.Map;
import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;
import java.util.ArrayList;
import java.util.HashSet;
import sun.invoke.util.Wrapper;
import static java.lang.invoke.MethodHandleNatives.Constants.*;
/**
* Helper class to assist the GenerateJLIClassesPlugin to get access to
@ -66,14 +68,38 @@ class GenerateJLIClassesHelper {
static byte[] generateDirectMethodHandleHolderClassBytes(String className,
MethodType[] methodTypes, int[] types) {
LambdaForm[] forms = new LambdaForm[methodTypes.length];
String[] names = new String[methodTypes.length];
for (int i = 0; i < forms.length; i++) {
forms[i] = DirectMethodHandle.makePreparedLambdaForm(methodTypes[i],
types[i]);
names[i] = forms[i].kind.defaultLambdaName;
ArrayList<LambdaForm> forms = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < methodTypes.length; i++) {
LambdaForm form = DirectMethodHandle
.makePreparedLambdaForm(methodTypes[i], types[i]);
forms.add(form);
names.add(form.kind.defaultLambdaName);
}
return generateCodeBytesForLFs(className, names, forms);
for (Wrapper wrapper : Wrapper.values()) {
if (wrapper == Wrapper.VOID) {
continue;
}
for (byte b = DirectMethodHandle.AF_GETFIELD; b < DirectMethodHandle.AF_LIMIT; b++) {
int ftype = DirectMethodHandle.ftypeKind(wrapper.primitiveType());
LambdaForm form = DirectMethodHandle
.makePreparedFieldLambdaForm(b, /*isVolatile*/false, ftype);
if (form.kind != LambdaForm.Kind.GENERIC) {
forms.add(form);
names.add(form.kind.defaultLambdaName);
}
// volatile
form = DirectMethodHandle
.makePreparedFieldLambdaForm(b, /*isVolatile*/true, ftype);
if (form.kind != LambdaForm.Kind.GENERIC) {
forms.add(form);
names.add(form.kind.defaultLambdaName);
}
}
}
return generateCodeBytesForLFs(className,
names.toArray(new String[0]),
forms.toArray(new LambdaForm[0]));
}
static byte[] generateDelegatingMethodHandleHolderClassBytes(String className,
@ -107,6 +133,34 @@ class GenerateJLIClassesHelper {
forms.toArray(new LambdaForm[0]));
}
static byte[] generateInvokersHolderClassBytes(String className,
MethodType[] methodTypes) {
HashSet<MethodType> dedupSet = new HashSet<>();
ArrayList<LambdaForm> forms = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
int[] types = {
MethodTypeForm.LF_EX_LINKER,
MethodTypeForm.LF_EX_INVOKER,
MethodTypeForm.LF_GEN_LINKER,
MethodTypeForm.LF_GEN_INVOKER
};
for (int i = 0; i < methodTypes.length; i++) {
// generate methods representing invokers of the specified type
if (dedupSet.add(methodTypes[i])) {
for (int type : types) {
LambdaForm invokerForm = Invokers.invokeHandleForm(methodTypes[i],
/*customized*/false, type);
forms.add(invokerForm);
names.add(invokerForm.kind.defaultLambdaName);
}
}
}
return generateCodeBytesForLFs(className,
names.toArray(new String[0]),
forms.toArray(new LambdaForm[0]));
}
/*
* Generate customized code for a set of LambdaForms of specified types into
* a class with a specified name.
@ -166,4 +220,5 @@ class GenerateJLIClassesHelper {
BoundMethodHandle.Factory.generateConcreteBMHClassBytes(
shortTypes, types, className));
}
}

View File

@ -607,7 +607,10 @@ class InvokerBytecodeGenerator {
private static MemberName resolveFrom(String name, MethodType type, Class<?> holder) {
MemberName member = new MemberName(holder, name, type, REF_invokeStatic);
MemberName resolvedMember = MemberName.getFactory().resolveOrNull(REF_invokeStatic, member, holder);
if (TRACE_RESOLVE) {
System.out.println("[LF_RESOLVE] " + holder.getName() + " " + name + " " +
shortenSignature(basicTypeSignature(type)) + (resolvedMember != null ? " (success)" : " (fail)") );
}
return resolvedMember;
}
@ -629,6 +632,28 @@ class InvokerBytecodeGenerator {
name = name + "_" + form.returnType().basicTypeChar();
return resolveFrom(name, invokerType, LambdaForm.Holder.class);
}
case EXACT_INVOKER: // fall-through
case EXACT_LINKER: // fall-through
case GENERIC_INVOKER: // fall-through
case GENERIC_LINKER: return resolveFrom(name, invokerType.basicType(), Invokers.Holder.class);
case GET_OBJECT: // fall-through
case GET_BOOLEAN: // fall-through
case GET_BYTE: // fall-through
case GET_CHAR: // fall-through
case GET_SHORT: // fall-through
case GET_INT: // fall-through
case GET_LONG: // fall-through
case GET_FLOAT: // fall-through
case GET_DOUBLE: // fall-through
case PUT_OBJECT: // fall-through
case PUT_BOOLEAN: // fall-through
case PUT_BYTE: // fall-through
case PUT_CHAR: // fall-through
case PUT_SHORT: // fall-through
case PUT_INT: // fall-through
case PUT_LONG: // fall-through
case PUT_FLOAT: // fall-through
case PUT_DOUBLE: // fall-through
case DIRECT_INVOKE_INTERFACE: // fall-through
case DIRECT_INVOKE_SPECIAL: // fall-through
case DIRECT_INVOKE_STATIC: // fall-through

View File

@ -36,6 +36,7 @@ import static java.lang.invoke.MethodHandleStatics.*;
import static java.lang.invoke.MethodHandleNatives.Constants.*;
import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
import static java.lang.invoke.LambdaForm.*;
import static java.lang.invoke.LambdaForm.Kind.*;
/**
* Construction and caching of often-used invokers.
@ -254,7 +255,7 @@ class Invokers {
* @param which bit-encoded 0x01 whether it is a CP adapter ("linker") or MHs.invoker value ("invoker");
* 0x02 whether it is for invokeExact or generic invoke
*/
private static LambdaForm invokeHandleForm(MethodType mtype, boolean customized, int which) {
static LambdaForm invokeHandleForm(MethodType mtype, boolean customized, int which) {
boolean isCached;
if (!customized) {
mtype = mtype.basicType(); // normalize Z to I, String to Object, etc.
@ -263,12 +264,12 @@ class Invokers {
isCached = false; // maybe cache if mtype == mtype.basicType()
}
boolean isLinker, isGeneric;
String debugName;
Kind kind;
switch (which) {
case MethodTypeForm.LF_EX_LINKER: isLinker = true; isGeneric = false; debugName = "invokeExact_MT"; break;
case MethodTypeForm.LF_EX_INVOKER: isLinker = false; isGeneric = false; debugName = "exactInvoker"; break;
case MethodTypeForm.LF_GEN_LINKER: isLinker = true; isGeneric = true; debugName = "invoke_MT"; break;
case MethodTypeForm.LF_GEN_INVOKER: isLinker = false; isGeneric = true; debugName = "invoker"; break;
case MethodTypeForm.LF_EX_LINKER: isLinker = true; isGeneric = false; kind = EXACT_LINKER; break;
case MethodTypeForm.LF_EX_INVOKER: isLinker = false; isGeneric = false; kind = EXACT_INVOKER; break;
case MethodTypeForm.LF_GEN_LINKER: isLinker = true; isGeneric = true; kind = GENERIC_LINKER; break;
case MethodTypeForm.LF_GEN_INVOKER: isLinker = false; isGeneric = true; kind = GENERIC_INVOKER; break;
default: throw new InternalError();
}
LambdaForm lform;
@ -323,7 +324,11 @@ class Invokers {
names[CHECK_CUSTOM] = new Name(NF_checkCustomized, outArgs[0]);
}
names[LINKER_CALL] = new Name(outCallType, outArgs);
lform = new LambdaForm(debugName, INARG_LIMIT, names);
if (customized) {
lform = new LambdaForm(kind.defaultLambdaName, INARG_LIMIT, names);
} else {
lform = new LambdaForm(kind.defaultLambdaName, INARG_LIMIT, names, kind);
}
if (isLinker)
lform.compileToBytecode(); // JVM needs a real methodOop
if (isCached)
@ -614,4 +619,15 @@ class Invokers {
}
}
}
static {
// The Holder class will contain pre-generated Invokers resolved
// speculatively using MemberName.getFactory().resolveOrNull. However, that
// doesn't initialize the class, which subtly breaks inlining etc. By forcing
// initialization of the Holder class we avoid these issues.
UNSAFE.ensureClassInitialized(Holder.class);
}
/* Placeholder class for Invokers generated ahead of time */
final class Holder {}
}

View File

@ -275,12 +275,52 @@ class LambdaForm {
BOUND_REINVOKER("BMH.reinvoke"),
REINVOKER("MH.reinvoke"),
DELEGATE("MH.delegate"),
EXACT_LINKER("MH.invokeExact_MT"),
EXACT_INVOKER("MH.exactInvoker"),
GENERIC_LINKER("MH.invoke_MT"),
GENERIC_INVOKER("MH.invoker"),
DIRECT_INVOKE_VIRTUAL("DMH.invokeVirtual"),
DIRECT_INVOKE_SPECIAL("DMH.invokeSpecial"),
DIRECT_INVOKE_STATIC("DMH.invokeStatic"),
DIRECT_NEW_INVOKE_SPECIAL("DMH.newInvokeSpecial"),
DIRECT_INVOKE_INTERFACE("DMH.invokeInterface"),
DIRECT_INVOKE_STATIC_INIT("DMH.invokeStaticInit");
DIRECT_INVOKE_STATIC_INIT("DMH.invokeStaticInit"),
GET_OBJECT("getObject"),
PUT_OBJECT("putObject"),
GET_OBJECT_VOLATILE("getObjectVolatile"),
PUT_OBJECT_VOLATILE("putObjectVolatile"),
GET_INT("getInt"),
PUT_INT("putInt"),
GET_INT_VOLATILE("getIntVolatile"),
PUT_INT_VOLATILE("putIntVolatile"),
GET_BOOLEAN("getBoolean"),
PUT_BOOLEAN("putBoolean"),
GET_BOOLEAN_VOLATILE("getBooleanVolatile"),
PUT_BOOLEAN_VOLATILE("putBooleanVolatile"),
GET_BYTE("getByte"),
PUT_BYTE("putByte"),
GET_BYTE_VOLATILE("getByteVolatile"),
PUT_BYTE_VOLATILE("putByteVolatile"),
GET_CHAR("getChar"),
PUT_CHAR("putChar"),
GET_CHAR_VOLATILE("getCharVolatile"),
PUT_CHAR_VOLATILE("putCharVolatile"),
GET_SHORT("getShort"),
PUT_SHORT("putShort"),
GET_SHORT_VOLATILE("getShortVolatile"),
PUT_SHORT_VOLATILE("putShortVolatile"),
GET_LONG("getLong"),
PUT_LONG("putLong"),
GET_LONG_VOLATILE("getLongVolatile"),
PUT_LONG_VOLATILE("putLongVolatile"),
GET_FLOAT("getFloat"),
PUT_FLOAT("putFloat"),
GET_FLOAT_VOLATILE("getFloatVolatile"),
PUT_FLOAT_VOLATILE("putFloatVolatile"),
GET_DOUBLE("getDouble"),
PUT_DOUBLE("putDouble"),
GET_DOUBLE_VOLATILE("getDoubleVolatile"),
PUT_DOUBLE_VOLATILE("putDoubleVolatile");
final String defaultLambdaName;
final String methodName;
@ -329,6 +369,10 @@ class LambdaForm {
int arity, Name[] names) {
this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC);
}
LambdaForm(String debugName,
int arity, Name[] names, Kind kind) {
this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, kind);
}
LambdaForm(String debugName,
int arity, Name[] names, boolean forceInline) {
this(debugName, arity, names, LAST_RESULT, forceInline, /*customized=*/null, Kind.GENERIC);
@ -817,54 +861,6 @@ class LambdaForm {
}
}
private static void computeInitialPreparedForms() {
// Find all predefined invokers and associate them with canonical empty lambda forms.
for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) {
if (!m.isStatic() || !m.isPackage()) continue;
MethodType mt = m.getMethodType();
if (mt.parameterCount() > 0 &&
mt.parameterType(0) == MethodHandle.class &&
m.getName().startsWith("interpret_")) {
String sig = null;
assert((sig = basicTypeSignature(mt)) != null &&
m.getName().equals("interpret" + sig.substring(sig.indexOf('_'))));
LambdaForm form = new LambdaForm(mt);
form.vmentry = m;
form = mt.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, form);
}
}
}
// Set this false to disable use of the interpret_L methods defined in this file.
private static final boolean USE_PREDEFINED_INTERPRET_METHODS = true;
// The following are predefined exact invokers. The system must build
// a separate invoker for each distinct signature.
static Object interpret_L(MethodHandle mh) throws Throwable {
Object[] av = {mh};
String sig = null;
assert(argumentTypesMatch(sig = "L_L", av));
Object res = mh.form.interpretWithArguments(av);
assert(returnTypesMatch(sig, av, res));
return res;
}
static Object interpret_L(MethodHandle mh, Object x1) throws Throwable {
Object[] av = {mh, x1};
String sig = null;
assert(argumentTypesMatch(sig = "LL_L", av));
Object res = mh.form.interpretWithArguments(av);
assert(returnTypesMatch(sig, av, res));
return res;
}
static Object interpret_L(MethodHandle mh, Object x1, Object x2) throws Throwable {
Object[] av = {mh, x1, x2};
String sig = null;
assert(argumentTypesMatch(sig = "LLL_L", av));
Object res = mh.form.interpretWithArguments(av);
assert(returnTypesMatch(sig, av, res));
return res;
}
// The next few routines are called only from assert expressions
// They verify that the built-in invokers process the correct raw data types.
private static boolean argumentTypesMatch(String sig, Object[] av) {
@ -1151,113 +1147,6 @@ class LambdaForm {
return super.hashCode();
}
// Put the predefined NamedFunction invokers into the table.
static void initializeInvokers() {
for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
if (!m.isStatic() || !m.isPackage()) continue;
MethodType type = m.getMethodType();
if (type.equals(INVOKER_METHOD_TYPE) &&
m.getName().startsWith("invoke_")) {
String sig = m.getName().substring("invoke_".length());
int arity = LambdaForm.signatureArity(sig);
MethodType srcType = MethodType.genericMethodType(arity);
if (LambdaForm.signatureReturn(sig) == V_TYPE)
srcType = srcType.changeReturnType(void.class);
MethodTypeForm typeForm = srcType.form();
typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, DirectMethodHandle.make(m));
}
}
}
// The following are predefined NamedFunction invokers. The system must build
// a separate invoker for each distinct signature.
/** void return type invokers. */
@Hidden
static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(0, void.class, mh, a));
mh.invokeBasic();
return null;
}
@Hidden
static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(1, void.class, mh, a));
mh.invokeBasic(a[0]);
return null;
}
@Hidden
static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(2, void.class, mh, a));
mh.invokeBasic(a[0], a[1]);
return null;
}
@Hidden
static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(3, void.class, mh, a));
mh.invokeBasic(a[0], a[1], a[2]);
return null;
}
@Hidden
static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(4, void.class, mh, a));
mh.invokeBasic(a[0], a[1], a[2], a[3]);
return null;
}
@Hidden
static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(5, void.class, mh, a));
mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
return null;
}
/** Object return type invokers. */
@Hidden
static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(0, mh, a));
return mh.invokeBasic();
}
@Hidden
static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(1, mh, a));
return mh.invokeBasic(a[0]);
}
@Hidden
static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(2, mh, a));
return mh.invokeBasic(a[0], a[1]);
}
@Hidden
static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(3, mh, a));
return mh.invokeBasic(a[0], a[1], a[2]);
}
@Hidden
static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(4, mh, a));
return mh.invokeBasic(a[0], a[1], a[2], a[3]);
}
@Hidden
static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
assert(arityCheck(5, mh, a));
return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
}
private static boolean arityCheck(int arity, MethodHandle mh, Object[] a) {
return arityCheck(arity, Object.class, mh, a);
}
private static boolean arityCheck(int arity, Class<?> rtype, MethodHandle mh, Object[] a) {
assert(a.length == arity)
: Arrays.asList(a.length, arity);
assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype))
: Arrays.asList(mh, rtype, arity);
MemberName member = mh.internalMemberName();
if (isInvokeBasic(member)) {
assert(arity > 0);
assert(a[0] instanceof MethodHandle);
MethodHandle mh2 = (MethodHandle) a[0];
assert(mh2.type().basicType() == MethodType.genericMethodType(arity-1).changeReturnType(rtype))
: Arrays.asList(member, mh2, rtype, arity);
}
return true;
}
static final MethodType INVOKER_METHOD_TYPE =
MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
@ -1920,12 +1809,7 @@ class LambdaForm {
DEBUG_NAME_COUNTERS = null;
}
// Put this last, so that previous static inits can run before.
static {
if (USE_PREDEFINED_INTERPRET_METHODS)
computeInitialPreparedForms();
NamedFunction.initializeInvokers();
// The Holder class will contain pre-generated forms resolved
// using MemberName.getFactory(). However, that doesn't initialize the
// class, which subtly breaks inlining etc. By forcing

View File

@ -1745,6 +1745,13 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
return GenerateJLIClassesHelper
.generateBasicFormsClassBytes(className);
}
@Override
public byte[] generateInvokersHolderClassBytes(final String className,
MethodType[] methodTypes) {
return GenerateJLIClassesHelper
.generateInvokersHolderClassBytes(className, methodTypes);
}
});
}

View File

@ -46,6 +46,7 @@ import java.util.Properties;
static final boolean DUMP_CLASS_FILES;
static final boolean TRACE_INTERPRETER;
static final boolean TRACE_METHOD_LINKAGE;
static final boolean TRACE_RESOLVE;
static final int COMPILE_THRESHOLD;
static final boolean LOG_LF_COMPILATION_FAILURE;
static final int DONT_INLINE_THRESHOLD;
@ -65,6 +66,8 @@ import java.util.Properties;
props.getProperty("java.lang.invoke.MethodHandle.TRACE_INTERPRETER"));
TRACE_METHOD_LINKAGE = Boolean.parseBoolean(
props.getProperty("java.lang.invoke.MethodHandle.TRACE_METHOD_LINKAGE"));
TRACE_RESOLVE = Boolean.parseBoolean(
props.getProperty("java.lang.invoke.MethodHandle.TRACE_RESOLVE"));
COMPILE_THRESHOLD = Integer.parseInt(
props.getProperty("java.lang.invoke.MethodHandle.COMPILE_THRESHOLD", "0"));
LOG_LF_COMPILATION_FAILURE = Boolean.parseBoolean(

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2016, 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
@ -233,7 +233,7 @@ public final class HttpCookie implements Cloneable {
// if not specify max-age, this cookie should be
// discarded when user agent is to be closed, but
// it is not expired.
if (maxAge == MAX_AGE_UNSPECIFIED) return false;
if (maxAge < 0) return false;
long deltaSecond = (System.currentTimeMillis() - whenCreated) / 1000;
if (deltaSecond > maxAge)
@ -952,7 +952,8 @@ public final class HttpCookie implements Cloneable {
String attrName,
String attrValue) {
if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED) {
cookie.setMaxAge(cookie.expiryDate2DeltaSeconds(attrValue));
long delta = cookie.expiryDate2DeltaSeconds(attrValue);
cookie.setMaxAge(delta > 0 ? delta : 0);
}
}
});

View File

@ -150,10 +150,12 @@ public final class Duration
/**
* The pattern for parsing.
*/
private static final Pattern PATTERN =
private static class Lazy {
static final Pattern PATTERN =
Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)D)?" +
"(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?",
Pattern.CASE_INSENSITIVE);
}
/**
* The number of seconds in the duration.
@ -387,7 +389,7 @@ public final class Duration
*/
public static Duration parse(CharSequence text) {
Objects.requireNonNull(text, "text");
Matcher matcher = PATTERN.matcher(text);
Matcher matcher = Lazy.PATTERN.matcher(text);
if (matcher.matches()) {
// check for letter T but no time sections
if (!charMatch(text, matcher.start(3), matcher.end(3), 'T')) {

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