This commit is contained in:
Lana Steuck 2016-11-23 19:15:33 +00:00
commit 366e45411f
38 changed files with 1553 additions and 1523 deletions

View File

@ -530,6 +530,10 @@ public class Parser implements Constants, ContentHandler {
XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se); XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se);
} }
// try setting other JDK-impl properties, ignore if not supported
JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE,
_xsltc.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), false);
return(parse(reader, input)); return(parse(reader, input));
} }
catch (ParserConfigurationException e) { catch (ParserConfigurationException e) {
@ -1342,12 +1346,14 @@ public class Parser implements Constants, ContentHandler {
} }
else { else {
SyntaxTreeNode parent = _parentStack.peek(); SyntaxTreeNode parent = _parentStack.peek();
if (element.getClass().isAssignableFrom(Import.class) && if (element.getClass().isAssignableFrom(Import.class) &&
parent.notTypeOf(Import.class)) { parent.notTypeOf(Import.class)) {
ErrorMsg err = new ErrorMsg(ErrorMsg.IMPORT_PRECEDE_OTHERS_ERR, ErrorMsg err = new ErrorMsg(ErrorMsg.IMPORT_PRECEDE_OTHERS_ERR,
prefix+':'+localname); prefix+':'+localname);
throw new SAXException(err.toString()); throw new SAXException(err.toString());
} }
parent.addElement(element); parent.addElement(element);
element.setParent(parent); element.setParent(parent);
} }

View File

@ -43,12 +43,14 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Properties; import java.util.Properties;
import java.util.Vector; import java.util.Vector;
import java.util.jar.Attributes;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream; import java.util.jar.JarOutputStream;
import java.util.jar.Manifest; import java.util.jar.Manifest;
import javax.xml.XMLConstants; import javax.xml.XMLConstants;
import javax.xml.catalog.CatalogFeatures; import javax.xml.catalog.CatalogFeatures;
import jdk.xml.internal.JdkXmlFeatures; import jdk.xml.internal.JdkXmlFeatures;
import jdk.xml.internal.JdkXmlUtils;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
@ -116,8 +118,8 @@ public final class XSLTC {
private File _destDir = null; // -d <directory-name> private File _destDir = null; // -d <directory-name>
private int _outputType = FILE_OUTPUT; // by default private int _outputType = FILE_OUTPUT; // by default
private Vector _classes; private ArrayList<ByteArrayOutputStream> _classes;
private Vector _bcelClasses; private ArrayList<JavaClass> _bcelClasses;
private boolean _callsNodeset = false; private boolean _callsNodeset = false;
private boolean _multiDocument = false; private boolean _multiDocument = false;
private boolean _hasIdCall = false; private boolean _hasIdCall = false;
@ -160,13 +162,18 @@ public final class XSLTC {
/** /**
* HashMap with the loaded classes * HashMap with the loaded classes
*/ */
private final Map<String, Class> _externalExtensionFunctions; private final Map<String, Class<?>> _externalExtensionFunctions;
/** /**
* Catalog features * Catalog features
*/ */
CatalogFeatures _catalogFeatures; CatalogFeatures _catalogFeatures;
/**
* CDATA chunk size
*/
int _cdataChunkSize;
/** /**
* XSLTC compiler constructor * XSLTC compiler constructor
*/ */
@ -230,6 +237,8 @@ public final class XSLTC {
return _extensionClassLoader; return _extensionClassLoader;
} else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) {
return _catalogFeatures; return _catalogFeatures;
} else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) {
return _cdataChunkSize;
} }
return null; return null;
} }
@ -254,6 +263,8 @@ public final class XSLTC {
_externalExtensionFunctions.clear(); _externalExtensionFunctions.clear();
} else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) {
_catalogFeatures = (CatalogFeatures)value; _catalogFeatures = (CatalogFeatures)value;
} else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) {
_cdataChunkSize = Integer.parseInt((String)value);
} }
} }
@ -284,11 +295,11 @@ public final class XSLTC {
public void init() { public void init() {
reset(); reset();
_reader = null; _reader = null;
_classes = new Vector(); _classes = new ArrayList<>();
_bcelClasses = new Vector(); _bcelClasses = new ArrayList<>();
} }
private void setExternalExtensionFunctions(String name, Class clazz) { private void setExternalExtensionFunctions(String name, Class<?> clazz) {
if (_isSecureProcessing && clazz != null && !_externalExtensionFunctions.containsKey(name)) { if (_isSecureProcessing && clazz != null && !_externalExtensionFunctions.containsKey(name)) {
_externalExtensionFunctions.put(name, clazz); _externalExtensionFunctions.put(name, clazz);
} }
@ -319,7 +330,7 @@ public final class XSLTC {
* Returns unmodifiable view of HashMap with loaded external extension * Returns unmodifiable view of HashMap with loaded external extension
* functions - will be needed for the TransformerImpl * functions - will be needed for the TransformerImpl
*/ */
public Map<String, Class> getExternalExtensionFunctions() { public Map<String, Class<?>> getExternalExtensionFunctions() {
return Collections.unmodifiableMap(_externalExtensionFunctions); return Collections.unmodifiableMap(_externalExtensionFunctions);
} }
@ -563,7 +574,7 @@ public final class XSLTC {
final int count = _classes.size(); final int count = _classes.size();
final byte[][] result = new byte[count][1]; final byte[][] result = new byte[count][1];
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
result[i] = (byte[])_classes.elementAt(i); result[i] = _classes.get(i).toByteArray();
return result; return result;
} }
@ -907,7 +918,7 @@ public final class XSLTC {
getOutputFile(clazz.getClassName())))); getOutputFile(clazz.getClassName()))));
break; break;
case JAR_OUTPUT: case JAR_OUTPUT:
_bcelClasses.addElement(clazz); _bcelClasses.add(clazz);
break; break;
case BYTEARRAY_OUTPUT: case BYTEARRAY_OUTPUT:
case BYTEARRAY_AND_FILE_OUTPUT: case BYTEARRAY_AND_FILE_OUTPUT:
@ -915,13 +926,13 @@ public final class XSLTC {
case CLASSLOADER_OUTPUT: case CLASSLOADER_OUTPUT:
ByteArrayOutputStream out = new ByteArrayOutputStream(2048); ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
clazz.dump(out); clazz.dump(out);
_classes.addElement(out.toByteArray()); _classes.add(out);
if (_outputType == BYTEARRAY_AND_FILE_OUTPUT) if (_outputType == BYTEARRAY_AND_FILE_OUTPUT)
clazz.dump(new BufferedOutputStream( clazz.dump(new BufferedOutputStream(
new FileOutputStream(getOutputFile(clazz.getClassName())))); new FileOutputStream(getOutputFile(clazz.getClassName()))));
else if (_outputType == BYTEARRAY_AND_JAR_OUTPUT) else if (_outputType == BYTEARRAY_AND_JAR_OUTPUT)
_bcelClasses.addElement(clazz); _bcelClasses.add(clazz);
break; break;
} }
@ -945,30 +956,24 @@ public final class XSLTC {
// create the manifest // create the manifest
final Manifest manifest = new Manifest(); final Manifest manifest = new Manifest();
final java.util.jar.Attributes atrs = manifest.getMainAttributes(); final java.util.jar.Attributes atrs = manifest.getMainAttributes();
atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION,"1.2"); atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION, "1.2");
final Map map = manifest.getEntries(); final Map<String, Attributes> map = manifest.getEntries();
// create manifest // create manifest
Enumeration classes = _bcelClasses.elements();
final String now = (new Date()).toString(); final String now = (new Date()).toString();
final java.util.jar.Attributes.Name dateAttr = final java.util.jar.Attributes.Name dateAttr =
new java.util.jar.Attributes.Name("Date"); new java.util.jar.Attributes.Name("Date");
while (classes.hasMoreElements()) {
final JavaClass clazz = (JavaClass)classes.nextElement();
final String className = clazz.getClassName().replace('.','/');
final java.util.jar.Attributes attr = new java.util.jar.Attributes();
attr.put(dateAttr, now);
map.put(className+".class", attr);
}
final File jarFile = new File(_destDir, _jarFileName); final File jarFile = new File(_destDir, _jarFileName);
final JarOutputStream jos = final JarOutputStream jos =
new JarOutputStream(new FileOutputStream(jarFile), manifest); new JarOutputStream(new FileOutputStream(jarFile), manifest);
classes = _bcelClasses.elements();
while (classes.hasMoreElements()) { for (JavaClass clazz : _bcelClasses) {
final JavaClass clazz = (JavaClass)classes.nextElement(); final String className = clazz.getClassName().replace('.', '/');
final String className = clazz.getClassName().replace('.','/'); final java.util.jar.Attributes attr = new java.util.jar.Attributes();
jos.putNextEntry(new JarEntry(className+".class")); attr.put(dateAttr, now);
map.put(className + ".class", attr);
jos.putNextEntry(new JarEntry(className + ".class"));
final ByteArrayOutputStream out = new ByteArrayOutputStream(2048); final ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
clazz.dump(out); // dump() closes it's output stream clazz.dump(out); // dump() closes it's output stream
out.writeTo(jos); out.writeTo(jos);

View File

@ -165,14 +165,14 @@ public final class TemplatesImpl implements Templates, Serializable {
}; };
static final class TransletClassLoader extends ClassLoader { static final class TransletClassLoader extends ClassLoader {
private final Map<String,Class> _loadedExternalExtensionFunctions; private final Map<String, Class<?>> _loadedExternalExtensionFunctions;
TransletClassLoader(ClassLoader parent) { TransletClassLoader(ClassLoader parent) {
super(parent); super(parent);
_loadedExternalExtensionFunctions = null; _loadedExternalExtensionFunctions = null;
} }
TransletClassLoader(ClassLoader parent,Map<String, Class> mapEF) { TransletClassLoader(ClassLoader parent, Map<String, Class<?>> mapEF) {
super(parent); super(parent);
_loadedExternalExtensionFunctions = mapEF; _loadedExternalExtensionFunctions = mapEF;
} }
@ -215,7 +215,7 @@ public final class TemplatesImpl implements Templates, Serializable {
/** /**
* Create an XSLTC template object from the translet class definition(s). * Create an XSLTC template object from the translet class definition(s).
*/ */
protected TemplatesImpl(Class[] transletClasses, String transletName, protected TemplatesImpl(Class<?>[] transletClasses, String transletName,
Properties outputProperties, int indentNumber, Properties outputProperties, int indentNumber,
TransformerFactoryImpl tfactory) TransformerFactoryImpl tfactory)
{ {
@ -481,6 +481,7 @@ public final class TemplatesImpl implements Templates, Serializable {
// the module needs access to runtime classes // the module needs access to runtime classes
Module thisModule = TemplatesImpl.class.getModule(); Module thisModule = TemplatesImpl.class.getModule();
Arrays.asList(Constants.PKGS_USED_BY_TRANSLET_CLASSES).forEach(p -> { Arrays.asList(Constants.PKGS_USED_BY_TRANSLET_CLASSES).forEach(p -> {
thisModule.addExports(p, m); thisModule.addExports(p, m);
}); });

View File

@ -222,7 +222,8 @@ public class TransformerFactoryImpl
private boolean _useServicesMechanism; private boolean _useServicesMechanism;
/** /**
* protocols allowed for external references set by the stylesheet processing instruction, Import and Include element. * protocols allowed for external references set by the stylesheet
* processing instruction, Import and Include element.
*/ */
private String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT; private String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
/** /**
@ -240,7 +241,7 @@ public class TransformerFactoryImpl
// Unmodifiable view of external extension function from xslt compiler // Unmodifiable view of external extension function from xslt compiler
// It will be populated by user-specified extension functions during the // It will be populated by user-specified extension functions during the
// type checking // type checking
private Map<String, Class> _xsltcExtensionFunctions; private Map<String, Class<?>> _xsltcExtensionFunctions;
CatalogResolver _catalogUriResolver; CatalogResolver _catalogUriResolver;
CatalogFeatures _catalogFeatures; CatalogFeatures _catalogFeatures;
@ -251,6 +252,8 @@ public class TransformerFactoryImpl
String _catalogPrefer = null; String _catalogPrefer = null;
String _catalogResolve = null; String _catalogResolve = null;
int _cdataChunkSize = JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT;
/** /**
* javax.xml.transform.sax.TransformerFactory implementation. * javax.xml.transform.sax.TransformerFactory implementation.
*/ */
@ -283,7 +286,7 @@ public class TransformerFactoryImpl
_xsltcExtensionFunctions = null; _xsltcExtensionFunctions = null;
} }
public Map<String,Class> getExternalExtensionsMap() { public Map<String, Class<?>> getExternalExtensionsMap() {
return _xsltcExtensionFunctions; return _xsltcExtensionFunctions;
} }
@ -367,6 +370,8 @@ public class TransformerFactoryImpl
return _catalogResolve; return _catalogResolve;
} else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) {
return buildCatalogFeatures(); return buildCatalogFeatures();
} else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) {
return _cdataChunkSize;
} }
/** Check to see if the property is managed by the security manager **/ /** Check to see if the property is managed by the security manager **/
@ -507,6 +512,9 @@ public class TransformerFactoryImpl
_catalogResolve = (String) value; _catalogResolve = (String) value;
cfBuilder = CatalogFeatures.builder().with(Feature.RESOLVE, _catalogResolve); cfBuilder = CatalogFeatures.builder().with(Feature.RESOLVE, _catalogResolve);
return; return;
} else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) {
_cdataChunkSize = JdkXmlUtils.getValue(value, _cdataChunkSize);
return;
} }
if (_xmlSecurityManager != null && if (_xmlSecurityManager != null &&
@ -896,10 +904,10 @@ public class TransformerFactoryImpl
transletName = _packageName + "." + transletName; transletName = _packageName + "." + transletName;
try { try {
final Class clazz = ObjectFactory.findProviderClass(transletName, true); final Class<?> clazz = ObjectFactory.findProviderClass(transletName, true);
resetTransientAttributes(); resetTransientAttributes();
templates = new TemplatesImpl(new Class[]{clazz}, transletName, null, _indentNumber, this); templates = new TemplatesImpl(new Class<?>[]{clazz}, transletName, null, _indentNumber, this);
if (_uriResolver != null) { if (_uriResolver != null) {
templates.setURIResolver(_uriResolver); templates.setURIResolver(_uriResolver);
} }

View File

@ -230,6 +230,7 @@ public final class TransformerImpl extends Transformer
// Catalog is enabled by default // Catalog is enabled by default
boolean _useCatalog = true; boolean _useCatalog = true;
int _cdataChunkSize = JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT;
/** /**
* This class wraps an ErrorListener into a MessageHandler in order to * This class wraps an ErrorListener into a MessageHandler in order to
@ -284,6 +285,9 @@ public final class TransformerImpl extends Transformer
_readerManager.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD); _readerManager.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD);
_readerManager.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _isSecureProcessing); _readerManager.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _isSecureProcessing);
_readerManager.setProperty(XalanConstants.SECURITY_MANAGER, _securityManager); _readerManager.setProperty(XalanConstants.SECURITY_MANAGER, _securityManager);
_cdataChunkSize = JdkXmlUtils.getValue(_tfactory.getAttribute(JdkXmlUtils.CDATA_CHUNK_SIZE),
JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
_readerManager.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, _cdataChunkSize);
_useCatalog = _tfactory.getFeature(XMLConstants.USE_CATALOG); _useCatalog = _tfactory.getFeature(XMLConstants.USE_CATALOG);
if (_useCatalog) { if (_useCatalog) {

View File

@ -137,13 +137,11 @@ public final class Util {
reader.setFeature reader.setFeature
("http://xml.org/sax/features/namespace-prefixes",false); ("http://xml.org/sax/features/namespace-prefixes",false);
try { JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
reader.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true);
xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD));
} catch (SAXNotRecognizedException e) { JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE,
XMLSecurityManager.printWarning(reader.getClass().getName(), xsltc.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), false);
XMLConstants.ACCESS_EXTERNAL_DTD, e);
}
String lastProperty = ""; String lastProperty = "";
try { try {

View File

@ -292,7 +292,8 @@ public class DOMConfigurationImpl extends ParserConfigurationSettings
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
addRecognizedProperties(recognizedProperties); addRecognizedProperties(recognizedProperties);
@ -368,6 +369,8 @@ public class DOMConfigurationImpl extends ParserConfigurationSettings
for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
setProperty(f.getPropertyName(), null); setProperty(f.getPropertyName(), null);
} }
setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
} // <init>(SymbolTable) } // <init>(SymbolTable)

View File

@ -144,6 +144,8 @@ public class PropertyManager {
for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
supportedProps.put(f.getPropertyName(), null); supportedProps.put(f.getPropertyName(), null);
} }
supportedProps.put(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
} }
private void initWriterProps(){ private void initWriterProps(){

View File

@ -1041,14 +1041,14 @@ public class XML11EntityScanner
* *
* @param delimiter The string that signifies the end of the character * @param delimiter The string that signifies the end of the character
* data to be scanned. * data to be scanned.
* @param data The data structure to fill. * @param buffer The data structure to fill.
* @param chunkLimit the size limit of the data to be scanned
* *
* @return Returns true if there is more data to scan, false otherwise. * @return Returns true if there is more data to scan, false otherwise.
* *
* @throws IOException Thrown if i/o error occurs. * @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/ */
protected boolean scanData(String delimiter, XMLStringBuffer buffer) protected boolean scanData(String delimiter, XMLStringBuffer buffer, int chunkLimit)
throws IOException { throws IOException {
boolean done = false; boolean done = false;
@ -1152,82 +1152,50 @@ public class XML11EntityScanner
} }
// iterate over buffer looking for delimiter // iterate over buffer looking for delimiter
if (external) { OUTER: while (fCurrentEntity.position < fCurrentEntity.count) {
OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { c = fCurrentEntity.ch[fCurrentEntity.position++];
c = fCurrentEntity.ch[fCurrentEntity.position++]; if (c == charAt0) {
if (c == charAt0) { // looks like we just hit the delimiter
// looks like we just hit the delimiter int delimOffset = fCurrentEntity.position - 1;
int delimOffset = fCurrentEntity.position - 1; for (int i = 1; i < delimLen; i++) {
for (int i = 1; i < delimLen; i++) { if (fCurrentEntity.position == fCurrentEntity.count) {
if (fCurrentEntity.position == fCurrentEntity.count) { fCurrentEntity.position -= i;
fCurrentEntity.position -= i; break OUTER;
break OUTER;
}
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (delimiter.charAt(i) != c) {
fCurrentEntity.position--;
break;
}
}
if (fCurrentEntity.position == delimOffset + delimLen) {
done = true;
break;
}
}
else if (c == '\n' || c == '\r' || c == 0x85 || c == 0x2028) {
fCurrentEntity.position--;
break;
}
// In external entities control characters cannot appear
// as literals so do not skip over them.
else if (!XML11Char.isXML11ValidLiteral(c)) {
fCurrentEntity.position--;
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
buffer.append(fCurrentEntity.ch, offset, length);
return true;
}
}
}
else {
OUTER: while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == charAt0) {
// looks like we just hit the delimiter
int delimOffset = fCurrentEntity.position - 1;
for (int i = 1; i < delimLen; i++) {
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.position -= i;
break OUTER;
}
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (delimiter.charAt(i) != c) {
fCurrentEntity.position--;
break;
}
} }
if (fCurrentEntity.position == delimOffset + delimLen) { c = fCurrentEntity.ch[fCurrentEntity.position++];
done = true; if (delimiter.charAt(i) != c) {
fCurrentEntity.position--;
break; break;
} }
} }
else if (c == '\n') { if (fCurrentEntity.position == delimOffset + delimLen) {
fCurrentEntity.position--; done = true;
break; break;
} }
// Control characters are allowed to appear as literals }
// in internal entities. else if ((external && (c == '\n' || c == '\r' || c == 0x85 || c == 0x2028))
else if (!XML11Char.isXML11Valid(c)) { || (!external && c == '\n')) {
fCurrentEntity.position--; fCurrentEntity.position--;
int length = fCurrentEntity.position - offset; break;
fCurrentEntity.columnNumber += length - newlines; }
checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); // In external entities control characters cannot appear
buffer.append(fCurrentEntity.ch, offset, length); // as literals so do not skip over them.
return true; else if ((external && !XML11Char.isXML11ValidLiteral(c))
} // Control characters are allowed to appear as literals in internal entities.
|| (!external && !XML11Char.isXML11Valid(c))) {
fCurrentEntity.position--;
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
buffer.append(fCurrentEntity.ch, offset, length);
return true;
}
if (chunkLimit > 0 &&
(buffer.length + fCurrentEntity.position - offset) >= chunkLimit) {
break;
} }
} }
int length = fCurrentEntity.position - offset; int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines; fCurrentEntity.columnNumber += length - newlines;
checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length);
@ -1236,8 +1204,10 @@ public class XML11EntityScanner
} }
buffer.append(fCurrentEntity.ch, offset, length); buffer.append(fCurrentEntity.ch, offset, length);
// return true if string was skipped if (chunkLimit > 0 && buffer.length >= chunkLimit) {
} while (!done); break;
}
} while (!done && chunkLimit == 0);
return !done; return !done;
} // scanData(String,XMLString) } // scanData(String,XMLString)

View File

@ -388,7 +388,7 @@ implements XMLDTDScanner, XMLComponent, XMLEntityHandler {
return false; return false;
fStringBuffer.clear(); fStringBuffer.clear();
while (fEntityScanner.scanData("]", fStringBuffer)) { while (fEntityScanner.scanData("]", fStringBuffer, 0)) {
int c = fEntityScanner.peekChar(); int c = fEntityScanner.peekChar();
if (c != -1) { if (c != -1) {
if (XMLChar.isHighSurrogate(c)) { if (XMLChar.isHighSurrogate(c)) {

View File

@ -200,7 +200,8 @@ public class XMLDocumentFragmentScannerImpl
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
/** Property defaults. */ /** Property defaults. */
@ -212,7 +213,8 @@ public class XMLDocumentFragmentScannerImpl
null, null,
null, null,
null, null,
null null,
JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT
}; };
@ -269,6 +271,9 @@ public class XMLDocumentFragmentScannerImpl
/** SubScanner state: inside scanContent method. */ /** SubScanner state: inside scanContent method. */
protected boolean fInScanContent = false; protected boolean fInScanContent = false;
protected boolean fLastSectionWasCData = false; protected boolean fLastSectionWasCData = false;
protected boolean fCDataStart = false;
protected boolean fInCData = false;
protected boolean fCDataEnd = false;
protected boolean fLastSectionWasEntityReference = false; protected boolean fLastSectionWasEntityReference = false;
protected boolean fLastSectionWasCharacterData = false; protected boolean fLastSectionWasCharacterData = false;
@ -318,6 +323,11 @@ public class XMLDocumentFragmentScannerImpl
/** Xerces Feature: Disallow doctype declaration. */ /** Xerces Feature: Disallow doctype declaration. */
protected boolean fDisallowDoctype = false; protected boolean fDisallowDoctype = false;
/**
* CDATA chunk size limit
*/
private int fChunkSize;
/** /**
* comma-delimited list of protocols that are allowed for the purpose * comma-delimited list of protocols that are allowed for the purpose
* of accessing external dtd or entity references * of accessing external dtd or entity references
@ -490,12 +500,18 @@ public class XMLDocumentFragmentScannerImpl
//therefore we don't need to take care of anything here. So Just break; //therefore we don't need to take care of anything here. So Just break;
break; break;
case XMLStreamConstants.CDATA: case XMLStreamConstants.CDATA:
fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity); fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity);
fDocumentHandler.startCDATA(null); if (fCDataStart) {
//xxx: check if CDATA values comes from getCharacterData() function fDocumentHandler.startCDATA(null);
fCDataStart = false;
fInCData = true;
}
fDocumentHandler.characters(getCharacterData(),null); fDocumentHandler.characters(getCharacterData(),null);
fDocumentHandler.endCDATA(null); if (fCDataEnd) {
//System.out.println(" in CDATA of the XMLNSDocumentScannerImpl"); fDocumentHandler.endCDATA(null);
fCDataEnd = false;
}
break; break;
case XMLStreamConstants.NOTATION_DECLARATION : case XMLStreamConstants.NOTATION_DECLARATION :
break; break;
@ -603,6 +619,8 @@ public class XMLDocumentFragmentScannerImpl
fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD);
fStrictURI = componentManager.getFeature(STANDARD_URI_CONFORMANT, false); fStrictURI = componentManager.getFeature(STANDARD_URI_CONFORMANT, false);
fChunkSize = JdkXmlUtils.getValue(componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE),
JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
resetCommon(); resetCommon();
//fEntityManager.test(); //fEntityManager.test();
@ -647,6 +665,8 @@ public class XMLDocumentFragmentScannerImpl
fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD);
fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(Constants.SECURITY_MANAGER); fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(Constants.SECURITY_MANAGER);
fChunkSize = JdkXmlUtils.getValue(propertyManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE),
JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
resetCommon(); resetCommon();
} // reset(XMLComponentManager) } // reset(XMLComponentManager)
@ -1665,34 +1685,11 @@ public class XMLDocumentFragmentScannerImpl
while (true) { while (true) {
//scanData will fill the contentBuffer //scanData will fill the contentBuffer
if (!fEntityScanner.scanData("]]>", contentBuffer)) { if (!fEntityScanner.scanData("]]>", contentBuffer, fChunkSize)) {
fInCData = false;
fCDataEnd = true;
fMarkupDepth--;
break ; break ;
/** We dont need all this code if we pass ']]>' as delimeter..
* int brackets = 2;
* while (fEntityScanner.skipChar(']')) {
* brackets++;
* }
*
* //When we find more than 2 square brackets
* if (fDocumentHandler != null && brackets > 2) {
* //we dont need to clear the buffer..
* //contentBuffer.clear();
* for (int i = 2; i < brackets; i++) {
* contentBuffer.append(']');
* }
* fDocumentHandler.characters(contentBuffer, null);
* }
*
* if (fEntityScanner.skipChar('>')) {
* break;
* }
* if (fDocumentHandler != null) {
* //we dont need to clear the buffer now..
* //contentBuffer.clear();
* contentBuffer.append("]]");
* fDocumentHandler.characters(contentBuffer, null);
* }
**/
} else { } else {
int c = fEntityScanner.peekChar(); int c = fEntityScanner.peekChar();
if (c != -1 && isInvalidLiteral(c)) { if (c != -1 && isInvalidLiteral(c)) {
@ -1705,6 +1702,9 @@ public class XMLDocumentFragmentScannerImpl
new Object[]{Integer.toString(c,16)}); new Object[]{Integer.toString(c,16)});
fEntityScanner.scanChar(null); fEntityScanner.scanChar(null);
} }
} else {
//CData partially returned due to the size limit
break;
} }
//by this time we have also read surrogate contents if any... //by this time we have also read surrogate contents if any...
if (fDocumentHandler != null) { if (fDocumentHandler != null) {
@ -1712,16 +1712,6 @@ public class XMLDocumentFragmentScannerImpl
} }
} }
} }
fMarkupDepth--;
if (fDocumentHandler != null && contentBuffer.length > 0) {
//fDocumentHandler.characters(contentBuffer, null);
}
// call handler
if (fDocumentHandler != null) {
//fDocumentHandler.endCDATA(null);
}
return true; return true;
@ -2635,6 +2625,7 @@ public class XMLDocumentFragmentScannerImpl
} }
setScannerState(SCANNER_STATE_COMMENT); setScannerState(SCANNER_STATE_COMMENT);
} else if (fEntityScanner.skipString(cdata)) { } else if (fEntityScanner.skipString(cdata)) {
fCDataStart = true;
setScannerState(SCANNER_STATE_CDATA ); setScannerState(SCANNER_STATE_CDATA );
} else if (!scanForDoctypeHook()) { } else if (!scanForDoctypeHook()) {
reportFatalError("MarkupNotRecognizedInContent", reportFatalError("MarkupNotRecognizedInContent",
@ -3015,9 +3006,11 @@ public class XMLDocumentFragmentScannerImpl
//xxx: What if CDATA is the first event //xxx: What if CDATA is the first event
//<foo><![CDATA[hello<><>]]>append</foo> //<foo><![CDATA[hello<><>]]>append</foo>
//we should not clear the buffer only when the last state was either SCANNER_STATE_REFERENCE or //we should not clear the buffer only when the last state was
//either SCANNER_STATE_REFERENCE or
//SCANNER_STATE_CHARACTER_DATA or SCANNER_STATE_REFERENCE //SCANNER_STATE_CHARACTER_DATA or SCANNER_STATE_REFERENCE
if(fIsCoalesce && ( fLastSectionWasEntityReference || fLastSectionWasCData || fLastSectionWasCharacterData)){ if(fIsCoalesce && ( fLastSectionWasEntityReference ||
fLastSectionWasCData || fLastSectionWasCharacterData)){
fLastSectionWasCData = true ; fLastSectionWasCData = true ;
fLastSectionWasEntityReference = false; fLastSectionWasEntityReference = false;
fLastSectionWasCharacterData = false; fLastSectionWasCharacterData = false;
@ -3026,7 +3019,7 @@ public class XMLDocumentFragmentScannerImpl
fContentBuffer.clear(); fContentBuffer.clear();
} }
fUsebuffer = true; fUsebuffer = true;
//CDATA section is completely read in all the case. //CDATA section is read up to the chunk size limit
scanCDATASection(fContentBuffer , true); scanCDATASection(fContentBuffer , true);
setScannerState(SCANNER_STATE_CONTENT); setScannerState(SCANNER_STATE_CONTENT);
//1. if fIsCoalesce is set to true we set the variable fLastSectionWasCData to true //1. if fIsCoalesce is set to true we set the variable fLastSectionWasCData to true
@ -3036,13 +3029,16 @@ public class XMLDocumentFragmentScannerImpl
//2. Check if application has set for reporting CDATA event //2. Check if application has set for reporting CDATA event
//3. if the application has neither set the fIsCoalesce to true nor fReportCdataEvent //3. if the application has neither set the fIsCoalesce to true nor fReportCdataEvent
//return the cdata event as characters. //return the cdata event as characters.
if(fIsCoalesce){ if (fIsCoalesce) {
fLastSectionWasCData = true ; fLastSectionWasCData = true ;
//there might be more data to coalesce. //there might be more data to coalesce.
continue; continue;
}else if(fReportCdataEvent){ } else if(fReportCdataEvent) {
if (!fCDataEnd) {
setScannerState(SCANNER_STATE_CDATA);
}
return XMLEvent.CDATA; return XMLEvent.CDATA;
} else{ } else {
return XMLEvent.CHARACTERS; return XMLEvent.CHARACTERS;
} }
} }
@ -3051,9 +3047,11 @@ public class XMLDocumentFragmentScannerImpl
fMarkupDepth++; fMarkupDepth++;
foundBuiltInRefs = false; foundBuiltInRefs = false;
//we should not clear the buffer only when the last state was either CDATA or //we should not clear the buffer only when the last state was
//either CDATA or
//SCANNER_STATE_CHARACTER_DATA or SCANNER_STATE_REFERENCE //SCANNER_STATE_CHARACTER_DATA or SCANNER_STATE_REFERENCE
if(fIsCoalesce && ( fLastSectionWasEntityReference || fLastSectionWasCData || fLastSectionWasCharacterData)){ if(fIsCoalesce && ( fLastSectionWasEntityReference ||
fLastSectionWasCData || fLastSectionWasCharacterData)){
//fLastSectionWasEntityReference or fLastSectionWasCData are only //fLastSectionWasEntityReference or fLastSectionWasCData are only
//used when fIsCoalesce is set to true. //used when fIsCoalesce is set to true.
fLastSectionWasEntityReference = true ; fLastSectionWasEntityReference = true ;

View File

@ -968,9 +968,11 @@ public class XMLDocumentScannerImpl
case SCANNER_STATE_CONTENT: { case SCANNER_STATE_CONTENT: {
reportFatalError("ContentIllegalInProlog", null); reportFatalError("ContentIllegalInProlog", null);
fEntityScanner.scanChar(null); fEntityScanner.scanChar(null);
return -1;
} }
case SCANNER_STATE_REFERENCE: { case SCANNER_STATE_REFERENCE: {
reportFatalError("ReferenceIllegalInProlog", null); reportFatalError("ReferenceIllegalInProlog", null);
return -1;
} }
/** /**

View File

@ -217,7 +217,8 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
/** Property defaults. */ /** Property defaults. */
@ -232,7 +233,8 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver {
null, null,
null, null,
null, null,
null null,
JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT
}; };
private static final String XMLEntity = "[xml]".intern(); private static final String XMLEntity = "[xml]".intern();

View File

@ -1350,13 +1350,15 @@ public class XMLEntityScanner implements XMLLocator {
* @param delimiter The string that signifies the end of the character * @param delimiter The string that signifies the end of the character
* data to be scanned. * data to be scanned.
* @param buffer The XMLStringBuffer to fill. * @param buffer The XMLStringBuffer to fill.
* @param chunkLimit the size limit of the data to be scanned. Zero by default
* indicating no limit.
* *
* @return Returns true if there is more data to scan, false otherwise. * @return Returns true if there is more data to scan, false otherwise.
* *
* @throws IOException Thrown if i/o error occurs. * @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file. * @throws EOFException Thrown on end of file.
*/ */
protected boolean scanData(String delimiter, XMLStringBuffer buffer) protected boolean scanData(String delimiter, XMLStringBuffer buffer, int chunkLimit)
throws IOException { throws IOException {
boolean done = false; boolean done = false;
@ -1505,6 +1507,10 @@ public class XMLEntityScanner implements XMLLocator {
buffer.append(fCurrentEntity.ch, offset, length); buffer.append(fCurrentEntity.ch, offset, length);
return true; return true;
} }
if (chunkLimit > 0 &&
(buffer.length + fCurrentEntity.position - offset) >= chunkLimit) {
break;
}
} }
int length = fCurrentEntity.position - offset; int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines; fCurrentEntity.columnNumber += length - newlines;
@ -1520,7 +1526,10 @@ public class XMLEntityScanner implements XMLLocator {
print(); print();
System.out.println(" -> " + done); System.out.println(" -> " + done);
} }
} while (!done); if (chunkLimit > 0 && buffer.length >= chunkLimit) {
break;
}
} while (!done && chunkLimit == 0);
return !done; return !done;
} // scanData(String, XMLStringBuffer) } // scanData(String, XMLStringBuffer)

View File

@ -760,7 +760,7 @@ public abstract class XMLScanner
// since scanData appends the parsed data to the buffer passed // since scanData appends the parsed data to the buffer passed
// a while loop would append the whole of parsed data to the buffer(data:XMLStringBuffer) // a while loop would append the whole of parsed data to the buffer(data:XMLStringBuffer)
//until all of the data is buffered. //until all of the data is buffered.
if (fEntityScanner.scanData("?>", data)) { if (fEntityScanner.scanData("?>", data, 0)) {
do { do {
int c = fEntityScanner.peekChar(); int c = fEntityScanner.peekChar();
if (c != -1) { if (c != -1) {
@ -772,7 +772,7 @@ public abstract class XMLScanner
fEntityScanner.scanChar(null); fEntityScanner.scanChar(null);
} }
} }
} while (fEntityScanner.scanData("?>", data)); } while (fEntityScanner.scanData("?>", data, 0));
} }
} // scanPIData(String,XMLString) } // scanPIData(String,XMLString)
@ -797,7 +797,7 @@ public abstract class XMLScanner
// text // text
// REVISIT: handle invalid character, eof // REVISIT: handle invalid character, eof
text.clear(); text.clear();
while (fEntityScanner.scanData("--", text)) { while (fEntityScanner.scanData("--", text, 0)) {
int c = fEntityScanner.peekChar(); int c = fEntityScanner.peekChar();
//System.out.println( "XMLScanner#scanComment#text.toString() == " + text.toString() ); //System.out.println( "XMLScanner#scanComment#text.toString() == " + text.toString() );

View File

@ -250,7 +250,8 @@ XSLoader, DOMConfiguration {
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
// Data // Data
@ -282,7 +283,7 @@ XSLoader, DOMConfiguration {
private XSDDescription fXSDDescription = new XSDDescription(); private XSDDescription fXSDDescription = new XSDDescription();
private String faccessExternalSchema = Constants.EXTERNAL_ACCESS_DEFAULT; private String faccessExternalSchema = Constants.EXTERNAL_ACCESS_DEFAULT;
private WeakHashMap fJAXPCache; private WeakHashMap<Object, SchemaGrammar> fJAXPCache;
private Locale fLocale = Locale.getDefault(); private Locale fLocale = Locale.getDefault();
// XSLoader attributes // XSLoader attributes
@ -366,7 +367,7 @@ XSLoader, DOMConfiguration {
} }
fCMBuilder = builder; fCMBuilder = builder;
fSchemaHandler = new XSDHandler(fGrammarBucket); fSchemaHandler = new XSDHandler(fGrammarBucket);
fJAXPCache = new WeakHashMap(); fJAXPCache = new WeakHashMap<>();
fSettingsChanged = true; fSettingsChanged = true;
} }
@ -377,7 +378,7 @@ XSLoader, DOMConfiguration {
* are recognized. * are recognized.
*/ */
public String[] getRecognizedFeatures() { public String[] getRecognizedFeatures() {
return (String[])(RECOGNIZED_FEATURES.clone()); return RECOGNIZED_FEATURES.clone();
} // getRecognizedFeatures(): String[] } // getRecognizedFeatures(): String[]
/** /**
@ -419,7 +420,7 @@ XSLoader, DOMConfiguration {
* are recognized. * are recognized.
*/ */
public String[] getRecognizedProperties() { public String[] getRecognizedProperties() {
return (String[])(RECOGNIZED_PROPERTIES.clone()); return RECOGNIZED_PROPERTIES.clone();
} // getRecognizedProperties(): String[] } // getRecognizedProperties(): String[]
/** /**
@ -568,7 +569,7 @@ XSLoader, DOMConfiguration {
desc.setBaseSystemId(source.getBaseSystemId()); desc.setBaseSystemId(source.getBaseSystemId());
desc.setLiteralSystemId( source.getSystemId()); desc.setLiteralSystemId( source.getSystemId());
// none of the other fields make sense for preparsing // none of the other fields make sense for preparsing
Map locationPairs = new HashMap(); Map<String, LocationArray> locationPairs = new HashMap<>();
// Process external schema location properties. // Process external schema location properties.
// We don't call tokenizeSchemaLocationStr here, because we also want // We don't call tokenizeSchemaLocationStr here, because we also want
// to check whether the values are valid URI. // to check whether the values are valid URI.
@ -665,7 +666,7 @@ XSLoader, DOMConfiguration {
// add external schema locations to the location pairs // add external schema locations to the location pairs
public static void processExternalHints(String sl, String nsl, public static void processExternalHints(String sl, String nsl,
Map<String, XMLSchemaLoader.LocationArray> locations, Map<String, LocationArray> locations,
XMLErrorReporter er) { XMLErrorReporter er) {
if (sl != null) { if (sl != null) {
try { try {
@ -694,9 +695,10 @@ XSLoader, DOMConfiguration {
if (nsl != null) { if (nsl != null) {
try { try {
// similarly for no ns schema location property // similarly for no ns schema location property
XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(
SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
attrDecl.fType.validate(nsl, null, null); attrDecl.fType.validate(nsl, null, null);
LocationArray la = ((LocationArray)locations.get(XMLSymbols.EMPTY_STRING)); LocationArray la = locations.get(XMLSymbols.EMPTY_STRING);
if(la == null) { if(la == null) {
la = new LocationArray(); la = new LocationArray();
locations.put(XMLSymbols.EMPTY_STRING, la); locations.put(XMLSymbols.EMPTY_STRING, la);
@ -763,14 +765,14 @@ XSLoader, DOMConfiguration {
return; return;
} }
Class componentType = fJAXPSource.getClass().getComponentType(); Class<?> componentType = fJAXPSource.getClass().getComponentType();
XMLInputSource xis = null; XMLInputSource xis = null;
String sid = null; String sid = null;
if (componentType == null) { if (componentType == null) {
// Not an array // Not an array
if (fJAXPSource instanceof InputStream || if (fJAXPSource instanceof InputStream ||
fJAXPSource instanceof InputSource) { fJAXPSource instanceof InputSource) {
SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(fJAXPSource); SchemaGrammar g = fJAXPCache.get(fJAXPSource);
if (g != null) { if (g != null) {
fGrammarBucket.putGrammar(g); fGrammarBucket.putGrammar(g);
return; return;
@ -823,7 +825,7 @@ XSLoader, DOMConfiguration {
for (int i = 0; i < objArr.length; i++) { for (int i = 0; i < objArr.length; i++) {
if (objArr[i] instanceof InputStream || if (objArr[i] instanceof InputStream ||
objArr[i] instanceof InputSource) { objArr[i] instanceof InputSource) {
SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(objArr[i]); SchemaGrammar g = fJAXPCache.get(objArr[i]);
if (g != null) { if (g != null) {
fGrammarBucket.putGrammar(g); fGrammarBucket.putGrammar(g);
continue; continue;

View File

@ -344,13 +344,14 @@ public class XMLSchemaValidator
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
/** Property defaults. */ /** Property defaults. */
private static final Object[] PROPERTY_DEFAULTS = private static final Object[] PROPERTY_DEFAULTS =
{ null, null, null, null, null, null, null, null, null, null, null, null, { null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null}; null, null, null, null, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT };
// this is the number of valuestores of each kind // this is the number of valuestores of each kind
// we expect an element to have. It's almost // we expect an element to have. It's almost
@ -358,10 +359,14 @@ public class XMLSchemaValidator
protected static final int ID_CONSTRAINT_NUM = 1; protected static final int ID_CONSTRAINT_NUM = 1;
// xsi:* attribute declarations // xsi:* attribute declarations
static final XSAttributeDecl XSI_TYPE = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); static final XSAttributeDecl XSI_TYPE =
static final XSAttributeDecl XSI_NIL = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE);
static final XSAttributeDecl XSI_SCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); static final XSAttributeDecl XSI_NIL =
static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL);
static final XSAttributeDecl XSI_SCHEMALOCATION =
SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION);
static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION =
SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION);
// //
// Data // Data

View File

@ -336,7 +336,8 @@ public class SchemaParsingConfig extends BasicParserConfiguration
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
addRecognizedProperties(recognizedProperties); addRecognizedProperties(recognizedProperties);
@ -368,6 +369,7 @@ public class SchemaParsingConfig extends BasicParserConfiguration
fValidationManager = new ValidationManager(); fValidationManager = new ValidationManager();
fProperties.put(VALIDATION_MANAGER, fValidationManager); fProperties.put(VALIDATION_MANAGER, fValidationManager);
fProperties.put(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
fVersionDetector = new XMLVersionDetector(); fVersionDetector = new XMLVersionDetector();

View File

@ -350,7 +350,7 @@ public class XSDHandler {
// This map's job is to act as a link between the Schema Element and its // This map's job is to act as a link between the Schema Element and its
// XSDocumentInfo object. // XSDocumentInfo object.
private Map fDoc2XSDocumentMap = new HashMap(); private Map<Element, XSDocumentInfo> fDoc2XSDocumentMap = new HashMap<>();
// map between <redefine> elements and the XSDocumentInfo // map between <redefine> elements and the XSDocumentInfo
// objects that correspond to the documents being redefined. // objects that correspond to the documents being redefined.
@ -1104,10 +1104,12 @@ public class XSDHandler {
fSchemaGrammarDescription.setTargetNamespace(callerTNS); fSchemaGrammarDescription.setTargetNamespace(callerTNS);
boolean alreadyTraversed = false; boolean alreadyTraversed = false;
XMLInputSource schemaSource = resolveSchemaSource(fSchemaGrammarDescription, mustResolve, child, true); XMLInputSource schemaSource =
resolveSchemaSource(fSchemaGrammarDescription, mustResolve, child, true);
if (fNamespaceGrowth && refType == XSDDescription.CONTEXT_INCLUDE) { if (fNamespaceGrowth && refType == XSDDescription.CONTEXT_INCLUDE) {
try { try {
final String schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); final String schemaId = XMLEntityManager.expandSystemId(
schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false);
alreadyTraversed = sg.getDocumentLocations().contains(schemaId); alreadyTraversed = sg.getDocumentLocations().contains(schemaId);
} }
catch(MalformedURIException e) { catch(MalformedURIException e) {
@ -1133,10 +1135,11 @@ public class XSDHandler {
// To handle mutual <include>s // To handle mutual <include>s
XSDocumentInfo newSchemaInfo = null; XSDocumentInfo newSchemaInfo = null;
if (fLastSchemaWasDuplicate) { if (fLastSchemaWasDuplicate) {
newSchemaInfo = newSchemaRoot == null ? null : (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); newSchemaInfo = newSchemaRoot == null ? null : fDoc2XSDocumentMap.get(newSchemaRoot);
} }
else { else {
newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription, importCollision); newSchemaInfo = constructTrees(newSchemaRoot, schemaHint,
fSchemaGrammarDescription, importCollision);
} }
if (localName.equals(SchemaSymbols.ELT_REDEFINE) && if (localName.equals(SchemaSymbols.ELT_REDEFINE) &&
@ -3552,9 +3555,11 @@ public class XSDHandler {
// than checking its value. Don't set the ERROR_HANDLER // than checking its value. Don't set the ERROR_HANDLER
// or LOCALE properties unless they've actually changed. // or LOCALE properties unless they've actually changed.
if (fErrorHandler != fSchemaParser.getProperty(ERROR_HANDLER)) { if (fErrorHandler != fSchemaParser.getProperty(ERROR_HANDLER)) {
fSchemaParser.setProperty(ERROR_HANDLER, (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); fSchemaParser.setProperty(ERROR_HANDLER,
(fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler());
if (fAnnotationValidator != null) { if (fAnnotationValidator != null) {
fAnnotationValidator.setProperty(ERROR_HANDLER, (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); fAnnotationValidator.setProperty(ERROR_HANDLER,
(fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler());
} }
} }
if (fLocale != fSchemaParser.getProperty(LOCALE)) { if (fLocale != fSchemaParser.getProperty(LOCALE)) {
@ -3567,7 +3572,8 @@ public class XSDHandler {
catch (XMLConfigurationException e) {} catch (XMLConfigurationException e) {}
try { try {
fSchemaParser.setFeature(CONTINUE_AFTER_FATAL_ERROR, fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR)); fSchemaParser.setFeature(CONTINUE_AFTER_FATAL_ERROR,
fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR));
} catch (XMLConfigurationException e) {} } catch (XMLConfigurationException e) {}
try { try {
@ -3601,13 +3607,16 @@ public class XSDHandler {
} }
} catch (XMLConfigurationException e) {} } catch (XMLConfigurationException e) {}
fSecurityPropertyMgr = (XMLSecurityPropertyManager) componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); fSecurityPropertyMgr = (XMLSecurityPropertyManager)
componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER);
//Passing on the setting to the parser //Passing on the setting to the parser
fSchemaParser.setProperty(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr); fSchemaParser.setProperty(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);
fAccessExternalDTD = fSecurityPropertyMgr.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); fAccessExternalDTD = fSecurityPropertyMgr.getValue(
fAccessExternalSchema = fSecurityPropertyMgr.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD);
fAccessExternalSchema = fSecurityPropertyMgr.getValue(
XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA);
// Passing the Catalog settings to the parser // Passing the Catalog settings to the parser
fUseCatalog = componentManager.getFeature(XMLConstants.USE_CATALOG); fUseCatalog = componentManager.getFeature(XMLConstants.USE_CATALOG);
@ -3620,9 +3629,16 @@ public class XSDHandler {
fResolve = (String)componentManager.getProperty(JdkXmlUtils.CATALOG_RESOLVE); fResolve = (String)componentManager.getProperty(JdkXmlUtils.CATALOG_RESOLVE);
for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
fSchemaParser.setProperty(f.getPropertyName(), componentManager.getProperty(f.getPropertyName())); fSchemaParser.setProperty(f.getPropertyName(),
fEntityManager.setProperty(f.getPropertyName(), componentManager.getProperty(f.getPropertyName())); componentManager.getProperty(f.getPropertyName()));
fEntityManager.setProperty(f.getPropertyName(),
componentManager.getProperty(f.getPropertyName()));
} }
fSchemaParser.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE,
componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE));
fEntityManager.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE,
componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE));
} // reset(XMLComponentManager) } // reset(XMLComponentManager)
@ -3635,11 +3651,10 @@ public class XSDHandler {
for (int i = 0; i < fLocalElemStackPos; i++) { for (int i = 0; i < fLocalElemStackPos; i++) {
Element currElem = fLocalElementDecl[i]; Element currElem = fLocalElementDecl[i];
//XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getDocument(currElem));
//XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getRoot(DOMUtil.getDocument(currElem)));
XSDocumentInfo currSchema = fLocalElementDecl_schema[i]; XSDocumentInfo currSchema = fLocalElementDecl_schema[i];
SchemaGrammar currGrammar = fGrammarBucket.getGrammar(currSchema.fTargetNamespace); SchemaGrammar currGrammar = fGrammarBucket.getGrammar(currSchema.fTargetNamespace);
fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, currGrammar, fAllContext[i], fParent[i], fLocalElemNamespaceContext[i]); fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema,
currGrammar, fAllContext[i], fParent[i], fLocalElemNamespaceContext[i]);
// If it's an empty particle, remove it from the containing component. // If it's an empty particle, remove it from the containing component.
if (fParticle[i].fType == XSParticleDecl.PARTICLE_EMPTY) { if (fParticle[i].fType == XSParticleDecl.PARTICLE_EMPTY) {
XSModelGroupImpl group = null; XSModelGroupImpl group = null;
@ -4065,7 +4080,8 @@ public class XSDHandler {
Element decl, XSDocumentInfo decl_Doc) { Element decl, XSDocumentInfo decl_Doc) {
if (DEBUG_NODE_POOL) { if (DEBUG_NODE_POOL) {
System.out.println("DOCUMENT NS:"+ currSchema.fTargetNamespace+" hashcode:"+ ((Object)currSchema.fSchemaElement).hashCode()); System.out.println("DOCUMENT NS:" + currSchema.fTargetNamespace + " hashcode:" +
((Object)currSchema.fSchemaElement).hashCode());
} }
Object temp = decl_Doc; Object temp = decl_Doc;
if (temp == null) { if (temp == null) {
@ -4091,7 +4107,8 @@ public class XSDHandler {
// returns whether more than <annotation>s occur in children of elem // returns whether more than <annotation>s occur in children of elem
private boolean nonAnnotationContent(Element elem) { private boolean nonAnnotationContent(Element elem) {
for(Element child = DOMUtil.getFirstChildElement(elem); child != null; child = DOMUtil.getNextSiblingElement(child)) { for(Element child = DOMUtil.getFirstChildElement(elem); child != null;
child = DOMUtil.getNextSiblingElement(child)) {
if(!(DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION))) return true; if(!(DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION))) return true;
} }
return false; return false;

View File

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
*/ */
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
@ -17,7 +17,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.sun.org.apache.xerces.internal.jaxp.validation; package com.sun.org.apache.xerces.internal.jaxp.validation;
import com.sun.org.apache.xerces.internal.impl.Constants; import com.sun.org.apache.xerces.internal.impl.Constants;
@ -47,7 +46,8 @@ import jdk.xml.internal.JdkXmlUtils;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
/** /**
* <p>A validator helper for <code>StreamSource</code>s.</p> * <p>
* A validator helper for <code>StreamSource</code>s.</p>
* *
* @author Michael Glavassevich, IBM * @author Michael Glavassevich, IBM
* @author <a href="mailto:Sunitha.Reddy@Sun.com">Sunitha Reddy</a> * @author <a href="mailto:Sunitha.Reddy@Sun.com">Sunitha Reddy</a>
@ -55,74 +55,98 @@ import org.xml.sax.SAXException;
final class StreamValidatorHelper implements ValidatorHelper { final class StreamValidatorHelper implements ValidatorHelper {
// feature identifiers // feature identifiers
/**
/** Feature identifier: parser settings. */ * Feature identifier: parser settings.
private static final String PARSER_SETTINGS = */
Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; private static final String PARSER_SETTINGS
= Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS;
// property identifiers // property identifiers
/**
* Property identifier: entity resolver.
*/
private static final String ENTITY_RESOLVER
= Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
/** Property identifier: entity resolver. */ /**
private static final String ENTITY_RESOLVER = * Property identifier: error handler.
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; */
private static final String ERROR_HANDLER
= Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY;
/** Property identifier: error handler. */ /**
private static final String ERROR_HANDLER = * Property identifier: error reporter.
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; */
private static final String ERROR_REPORTER
= Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: error reporter. */ /**
private static final String ERROR_REPORTER = * Property identifier: XML Schema validator.
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; */
private static final String SCHEMA_VALIDATOR
= Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY;
/** Property identifier: XML Schema validator. */ /**
private static final String SCHEMA_VALIDATOR = * Property identifier: symbol table.
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY; */
private static final String SYMBOL_TABLE
= Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: symbol table. */ /**
private static final String SYMBOL_TABLE = * Property identifier: validation manager.
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; */
private static final String VALIDATION_MANAGER
= Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
/** Property identifier: validation manager. */ private static final String DEFAULT_TRANSFORMER_IMPL
private static final String VALIDATION_MANAGER = = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
private static final String DEFAULT_TRANSFORMER_IMPL = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; /**
* Property id: security manager.
/** Property id: security manager. */ */
private static final String SECURITY_MANAGER = private static final String SECURITY_MANAGER
Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; = Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;
// //
// Data // Data
// //
/**
* SoftReference to parser configuration. *
*/
private SoftReference<XMLParserConfiguration> fConfiguration = new SoftReference<>(null);
/** SoftReference to parser configuration. **/ /**
private SoftReference fConfiguration = new SoftReference(null); * Schema validator. *
*/
/** Schema validator. **/
private com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator fSchemaValidator; private com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator fSchemaValidator;
/** Component manager. **/ /**
* Component manager. *
*/
private XMLSchemaValidatorComponentManager fComponentManager; private XMLSchemaValidatorComponentManager fComponentManager;
private ValidatorHandlerImpl handler = null; private ValidatorHandlerImpl handler = null;
public StreamValidatorHelper(XMLSchemaValidatorComponentManager componentManager) { public StreamValidatorHelper(XMLSchemaValidatorComponentManager componentManager) {
fComponentManager = componentManager; fComponentManager = componentManager;
fSchemaValidator = (com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator) fComponentManager.getProperty(SCHEMA_VALIDATOR); fSchemaValidator = (com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator)
fComponentManager.getProperty(SCHEMA_VALIDATOR);
} }
public void validate(Source source, Result result) public void validate(Source source, Result result)
throws SAXException, IOException { throws SAXException, IOException {
if (result == null || result instanceof StreamResult) { if (result == null || result instanceof StreamResult) {
final StreamSource streamSource = (StreamSource) source; final StreamSource streamSource = (StreamSource) source;
TransformerHandler identityTransformerHandler ; TransformerHandler identityTransformerHandler;
if( result!=null ) { if (result != null) {
try { try {
SAXTransformerFactory tf = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ? SAXTransformerFactory tf = fComponentManager.getFeature(
(SAXTransformerFactory)SAXTransformerFactory.newInstance() Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
: (SAXTransformerFactory) TransformerFactory.newInstance(DEFAULT_TRANSFORMER_IMPL, StreamValidatorHelper.class.getClassLoader()); (SAXTransformerFactory) SAXTransformerFactory.newInstance() :
(SAXTransformerFactory) TransformerFactory.newInstance(
DEFAULT_TRANSFORMER_IMPL,
StreamValidatorHelper.class.getClassLoader());
identityTransformerHandler = tf.newTransformerHandler(); identityTransformerHandler = tf.newTransformerHandler();
} catch (TransformerConfigurationException e) { } catch (TransformerConfigurationException e) {
throw new TransformerFactoryConfigurationError(e); throw new TransformerFactoryConfigurationError(e);
@ -133,13 +157,14 @@ final class StreamValidatorHelper implements ValidatorHelper {
identityTransformerHandler.setResult(result); identityTransformerHandler.setResult(result);
} }
XMLInputSource input = new XMLInputSource(streamSource.getPublicId(), streamSource.getSystemId(), null, false); XMLInputSource input = new XMLInputSource(streamSource.getPublicId(),
streamSource.getSystemId(), null, false);
input.setByteStream(streamSource.getInputStream()); input.setByteStream(streamSource.getInputStream());
input.setCharacterStream(streamSource.getReader()); input.setCharacterStream(streamSource.getReader());
// Gets the parser configuration. We'll create and initialize a new one, if we // Gets the parser configuration. We'll create and initialize a new one, if we
// haven't created one before or if the previous one was garbage collected. // haven't created one before or if the previous one was garbage collected.
XMLParserConfiguration config = (XMLParserConfiguration) fConfiguration.get(); XMLParserConfiguration config = fConfiguration.get();
if (config == null) { if (config == null) {
config = initialize(); config = initialize();
} }
@ -155,18 +180,17 @@ final class StreamValidatorHelper implements ValidatorHelper {
try { try {
config.parse(input); config.parse(input);
} } catch (XMLParseException e) {
catch (XMLParseException e) {
throw Util.toSAXParseException(e); throw Util.toSAXParseException(e);
} } catch (XNIException e) {
catch (XNIException e) {
throw Util.toSAXException(e); throw Util.toSAXException(e);
} }
return; return;
} }
throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(
fComponentManager.getLocale(),
"SourceResultMismatch", "SourceResultMismatch",
new Object [] {source.getClass().getName(), result.getClass().getName()})); new Object[]{source.getClass().getName(), result.getClass().getName()}));
} }
private XMLParserConfiguration initialize() { private XMLParserConfiguration initialize() {
@ -197,7 +221,10 @@ final class StreamValidatorHelper implements ValidatorHelper {
// Passing on the CatalogFeatures settings // Passing on the CatalogFeatures settings
JdkXmlUtils.catalogFeaturesConfig2Config(fComponentManager, config); JdkXmlUtils.catalogFeaturesConfig2Config(fComponentManager, config);
fConfiguration = new SoftReference(config); config.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE,
fComponentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE));
fConfiguration = new SoftReference<>(config);
return config; return config;
} }

View File

@ -165,6 +165,8 @@ public final class XMLSchemaFactory extends SchemaFactory {
for (Feature f : Feature.values()) { for (Feature f : Feature.values()) {
fXMLSchemaLoader.setProperty(f.getPropertyName(), null); fXMLSchemaLoader.setProperty(f.getPropertyName(), null);
} }
fXMLSchemaLoader.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
} }
/** /**

View File

@ -48,6 +48,7 @@ import com.sun.org.apache.xerces.internal.xni.parser.XMLComponent;
import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager; import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException; import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
import javax.xml.catalog.CatalogFeatures; import javax.xml.catalog.CatalogFeatures;
import jdk.xml.internal.JdkXmlUtils;
import org.w3c.dom.ls.LSResourceResolver; import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.ErrorHandler; import org.xml.sax.ErrorHandler;
@ -311,6 +312,9 @@ final class XMLSchemaValidatorComponentManager extends ParserConfigurationSettin
for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
setProperty(f.getPropertyName(), grammarContainer.getProperty(f.getPropertyName())); setProperty(f.getPropertyName(), grammarContainer.getProperty(f.getPropertyName()));
} }
setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE,
grammarContainer.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE));
} }
/** /**

View File

@ -345,7 +345,8 @@ public class DTDConfiguration
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
addRecognizedProperties(recognizedProperties); addRecognizedProperties(recognizedProperties);
@ -429,6 +430,8 @@ public class DTDConfiguration
for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
setProperty(f.getPropertyName(), null); setProperty(f.getPropertyName(), null);
} }
setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
} // <init>(SymbolTable,XMLGrammarPool) } // <init>(SymbolTable,XMLGrammarPool)
// //

View File

@ -328,7 +328,8 @@ public class NonValidatingConfiguration
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
addRecognizedProperties(recognizedProperties); addRecognizedProperties(recognizedProperties);
@ -391,6 +392,8 @@ public class NonValidatingConfiguration
for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
setProperty(f.getPropertyName(), null); setProperty(f.getPropertyName(), null);
} }
setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
} // <init>(SymbolTable,XMLGrammarPool) } // <init>(SymbolTable,XMLGrammarPool)
// //

View File

@ -561,7 +561,8 @@ public class XML11Configuration extends ParserConfigurationSettings
JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_DEFER,
JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_FILES,
JdkXmlUtils.CATALOG_PREFER, JdkXmlUtils.CATALOG_PREFER,
JdkXmlUtils.CATALOG_RESOLVE JdkXmlUtils.CATALOG_RESOLVE,
JdkXmlUtils.CDATA_CHUNK_SIZE
}; };
addRecognizedProperties(recognizedProperties); addRecognizedProperties(recognizedProperties);
@ -629,6 +630,8 @@ public class XML11Configuration extends ParserConfigurationSettings
fProperties.put(f.getPropertyName(), null); fProperties.put(f.getPropertyName(), null);
} }
setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
fConfigUpdated = false; fConfigUpdated = false;
} // <init>(SymbolTable,XMLGrammarPool) } // <init>(SymbolTable,XMLGrammarPool)

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
*/ */
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
@ -17,9 +17,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/*
* $Id: EmptySerializer.java,v 1.2.4.1 2005/09/15 08:15:16 suresh_emailid Exp $
*/
package com.sun.org.apache.xml.internal.serializer; package com.sun.org.apache.xml.internal.serializer;
import java.io.IOException; import java.io.IOException;
@ -48,235 +46,224 @@ import org.xml.sax.SAXParseException;
public class EmptySerializer implements SerializationHandler public class EmptySerializer implements SerializationHandler
{ {
protected static final String ERR = "EmptySerializer method not over-ridden"; protected static final String ERR = "EmptySerializer method not over-ridden";
/**
* @see SerializationHandler#asContentHandler()
*/
protected void couldThrowIOException() throws IOException protected void couldThrowIOException() throws IOException {
return; // don't do anything.
}
protected void couldThrowSAXException() throws SAXException {
return; // don't do anything.
}
protected void couldThrowSAXException(char[] chars, int off, int len)
throws SAXException
{ {
return; // don't do anything. return; // don't do anything.
} }
protected void couldThrowSAXException() throws SAXException protected void couldThrowSAXException(String elemQName)
throws SAXException
{ {
return; // don't do anything. return; // don't do anything.
} }
protected void couldThrowSAXException(char[] chars, int off, int len) throws SAXException void aMethodIsCalled() {
{
return; // don't do anything.
}
protected void couldThrowSAXException(String elemQName) throws SAXException
{
return; // don't do anything.
}
void aMethodIsCalled()
{
// throw new RuntimeException(err); // throw new RuntimeException(err);
return; return;
} }
/** /**
* @see SerializationHandler#asContentHandler() * @see SerializationHandler#asContentHandler()
*/ */
public ContentHandler asContentHandler() throws IOException public ContentHandler asContentHandler() throws IOException {
{
couldThrowIOException(); couldThrowIOException();
return null; return null;
} }
/** /**
* @see SerializationHandler#setContentHandler(org.xml.sax.ContentHandler) * @see SerializationHandler#setContentHandler(org.xml.sax.ContentHandler)
*/ */
public void setContentHandler(ContentHandler ch) public void setContentHandler(ContentHandler ch) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#close() * @see SerializationHandler#close()
*/ */
public void close() public void close() {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#getOutputFormat() * @see SerializationHandler#getOutputFormat()
*/ */
public Properties getOutputFormat() public Properties getOutputFormat() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see SerializationHandler#getOutputStream() * @see SerializationHandler#getOutputStream()
*/ */
public OutputStream getOutputStream() public OutputStream getOutputStream() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see SerializationHandler#getWriter() * @see SerializationHandler#getWriter()
*/ */
public Writer getWriter() public Writer getWriter() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see SerializationHandler#reset() * @see SerializationHandler#reset()
*/ */
public boolean reset() public boolean reset() {
{
aMethodIsCalled(); aMethodIsCalled();
return false; return false;
} }
/** /**
* @see SerializationHandler#serialize(org.w3c.dom.Node) * @see SerializationHandler#serialize(org.w3c.dom.Node)
*/ */
public void serialize(Node node) throws IOException public void serialize(Node node) throws IOException {
{
couldThrowIOException(); couldThrowIOException();
} }
/** /**
* @see SerializationHandler#setCdataSectionElements(java.util.ArrayList<String>) * @see SerializationHandler#setCdataSectionElements(java.util.ArrayList<String>)
*/ */
public void setCdataSectionElements(ArrayList<String> URI_and_localNames) public void setCdataSectionElements(ArrayList<String> URI_and_localNames) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#setEscaping(boolean) * @see SerializationHandler#setEscaping(boolean)
*/ */
public boolean setEscaping(boolean escape) throws SAXException public boolean setEscaping(boolean escape) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
return false; return false;
} }
/** /**
* @see SerializationHandler#setIndent(boolean) * @see SerializationHandler#setIndent(boolean)
*/ */
public void setIndent(boolean indent) public void setIndent(boolean indent) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#setIndentAmount(int) * @see SerializationHandler#setIndentAmount(int)
*/ */
public void setIndentAmount(int spaces) public void setIndentAmount(int spaces) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#setIsStandalone(boolean) * @see SerializationHandler#setIsStandalone(boolean)
*/ */
public void setIsStandalone(boolean isStandalone) public void setIsStandalone(boolean isStandalone) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#setOutputFormat(java.util.Properties) * @see SerializationHandler#setOutputFormat(java.util.Properties)
*/ */
public void setOutputFormat(Properties format) public void setOutputFormat(Properties format) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#setOutputStream(java.io.OutputStream) * @see SerializationHandler#setOutputStream(java.io.OutputStream)
*/ */
public void setOutputStream(OutputStream output) public void setOutputStream(OutputStream output) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#setVersion(java.lang.String) * @see SerializationHandler#setVersion(java.lang.String)
*/ */
public void setVersion(String version) public void setVersion(String version) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#setWriter(java.io.Writer) * @see SerializationHandler#setWriter(java.io.Writer)
*/ */
public void setWriter(Writer writer) public void setWriter(Writer writer) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#setTransformer(javax.xml.transform.Transformer) * @see SerializationHandler#setTransformer(javax.xml.transform.Transformer)
*/ */
public void setTransformer(Transformer transformer) public void setTransformer(Transformer transformer) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see SerializationHandler#getTransformer() * @see SerializationHandler#getTransformer()
*/ */
public Transformer getTransformer() public Transformer getTransformer() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see SerializationHandler#flushPending() * @see SerializationHandler#flushPending()
*/ */
public void flushPending() throws SAXException public void flushPending() throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/ */
public void addAttribute( public void addAttribute(String uri, String localName, String rawName,
String uri, String type, String value, boolean XSLAttribute)
String localName,
String rawName,
String type,
String value,
boolean XSLAttribute)
throws SAXException throws SAXException
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedContentHandler#addAttributes(org.xml.sax.Attributes) * @see ExtendedContentHandler#addAttributes(org.xml.sax.Attributes)
*/ */
public void addAttributes(Attributes atts) throws SAXException public void addAttributes(Attributes atts) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String) * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String)
*/ */
public void addAttribute(String name, String value) public void addAttribute(String name, String value) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see ExtendedContentHandler#characters(java.lang.String) * @see ExtendedContentHandler#characters(java.lang.String)
*/ */
public void characters(String chars) throws SAXException public void characters(String chars) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedContentHandler#endElement(java.lang.String) * @see ExtendedContentHandler#endElement(java.lang.String)
*/ */
public void endElement(String elemName) throws SAXException public void endElement(String elemName) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedContentHandler#startDocument() * @see ExtendedContentHandler#startDocument()
*/ */
public void startDocument() throws SAXException public void startDocument() throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String) * @see ExtendedContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String)
*/ */
@ -285,13 +272,14 @@ public class EmptySerializer implements SerializationHandler
{ {
couldThrowSAXException(qName); couldThrowSAXException(qName);
} }
/** /**
* @see ExtendedContentHandler#startElement(java.lang.String) * @see ExtendedContentHandler#startElement(java.lang.String)
*/ */
public void startElement(String qName) throws SAXException public void startElement(String qName) throws SAXException {
{
couldThrowSAXException(qName); couldThrowSAXException(qName);
} }
/** /**
* @see ExtendedContentHandler#namespaceAfterStartElement(java.lang.String, java.lang.String) * @see ExtendedContentHandler#namespaceAfterStartElement(java.lang.String, java.lang.String)
*/ */
@ -303,68 +291,67 @@ public class EmptySerializer implements SerializationHandler
/** /**
* @see ExtendedContentHandler#startPrefixMapping(java.lang.String, java.lang.String, boolean) * @see ExtendedContentHandler#startPrefixMapping(java.lang.String, java.lang.String, boolean)
*/ */
public boolean startPrefixMapping( public boolean startPrefixMapping(String prefix, String uri,
String prefix, boolean shouldFlush)
String uri,
boolean shouldFlush)
throws SAXException throws SAXException
{ {
couldThrowSAXException(); couldThrowSAXException();
return false; return false;
} }
/** /**
* @see ExtendedContentHandler#entityReference(java.lang.String) * @see ExtendedContentHandler#entityReference(java.lang.String)
*/ */
public void entityReference(String entityName) throws SAXException public void entityReference(String entityName) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedContentHandler#getNamespaceMappings() * @see ExtendedContentHandler#getNamespaceMappings()
*/ */
public NamespaceMappings getNamespaceMappings() public NamespaceMappings getNamespaceMappings() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see ExtendedContentHandler#getPrefix(java.lang.String) * @see ExtendedContentHandler#getPrefix(java.lang.String)
*/ */
public String getPrefix(String uri) public String getPrefix(String uri) {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see ExtendedContentHandler#getNamespaceURI(java.lang.String, boolean) * @see ExtendedContentHandler#getNamespaceURI(java.lang.String, boolean)
*/ */
public String getNamespaceURI(String name, boolean isElement) public String getNamespaceURI(String name, boolean isElement) {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see ExtendedContentHandler#getNamespaceURIFromPrefix(java.lang.String) * @see ExtendedContentHandler#getNamespaceURIFromPrefix(java.lang.String)
*/ */
public String getNamespaceURIFromPrefix(String prefix) public String getNamespaceURIFromPrefix(String prefix) {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator)
*/ */
public void setDocumentLocator(Locator arg0) public void setDocumentLocator(Locator arg0) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see org.xml.sax.ContentHandler#endDocument() * @see org.xml.sax.ContentHandler#endDocument()
*/ */
public void endDocument() throws SAXException public void endDocument() throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String)
*/ */
@ -373,25 +360,24 @@ public class EmptySerializer implements SerializationHandler
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)
*/ */
public void endPrefixMapping(String arg0) throws SAXException public void endPrefixMapping(String arg0) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/ */
public void startElement( public void startElement(String arg0, String arg1, String arg2,
String arg0, Attributes arg3)
String arg1,
String arg2,
Attributes arg3)
throws SAXException throws SAXException
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/ */
@ -400,13 +386,14 @@ public class EmptySerializer implements SerializationHandler
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ContentHandler#characters(char[], int, int) * @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/ */
public void characters(char[] arg0, int arg1, int arg2) throws SAXException public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
{
couldThrowSAXException(arg0, arg1, arg2); couldThrowSAXException(arg0, arg1, arg2);
} }
/** /**
* @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
*/ */
@ -415,6 +402,7 @@ public class EmptySerializer implements SerializationHandler
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String)
*/ */
@ -423,20 +411,21 @@ public class EmptySerializer implements SerializationHandler
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)
*/ */
public void skippedEntity(String arg0) throws SAXException public void skippedEntity(String arg0) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedLexicalHandler#comment(java.lang.String) * @see ExtendedLexicalHandler#comment(java.lang.String)
*/ */
public void comment(String comment) throws SAXException public void comment(String comment) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String) * @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String)
*/ */
@ -445,189 +434,187 @@ public class EmptySerializer implements SerializationHandler
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.LexicalHandler#endDTD() * @see org.xml.sax.ext.LexicalHandler#endDTD()
*/ */
public void endDTD() throws SAXException public void endDTD() throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String) * @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String)
*/ */
public void startEntity(String arg0) throws SAXException public void startEntity(String arg0) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String) * @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String)
*/ */
public void endEntity(String arg0) throws SAXException public void endEntity(String arg0) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.LexicalHandler#startCDATA() * @see org.xml.sax.ext.LexicalHandler#startCDATA()
*/ */
public void startCDATA() throws SAXException public void startCDATA() throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.LexicalHandler#endCDATA() * @see org.xml.sax.ext.LexicalHandler#endCDATA()
*/ */
public void endCDATA() throws SAXException public void endCDATA() throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int) * @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int)
*/ */
public void comment(char[] arg0, int arg1, int arg2) throws SAXException public void comment(char[] arg0, int arg1, int arg2) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see XSLOutputAttributes#getDoctypePublic() * @see XSLOutputAttributes#getDoctypePublic()
*/ */
public String getDoctypePublic() public String getDoctypePublic() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see XSLOutputAttributes#getDoctypeSystem() * @see XSLOutputAttributes#getDoctypeSystem()
*/ */
public String getDoctypeSystem() public String getDoctypeSystem() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see XSLOutputAttributes#getEncoding() * @see XSLOutputAttributes#getEncoding()
*/ */
public String getEncoding() public String getEncoding() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see XSLOutputAttributes#getIndent() * @see XSLOutputAttributes#getIndent()
*/ */
public boolean getIndent() public boolean getIndent() {
{
aMethodIsCalled(); aMethodIsCalled();
return false; return false;
} }
/** /**
* @see XSLOutputAttributes#getIndentAmount() * @see XSLOutputAttributes#getIndentAmount()
*/ */
public int getIndentAmount() public int getIndentAmount() {
{
aMethodIsCalled(); aMethodIsCalled();
return 0; return 0;
} }
/** /**
* @see XSLOutputAttributes#getMediaType() * @see XSLOutputAttributes#getMediaType()
*/ */
public String getMediaType() public String getMediaType() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see XSLOutputAttributes#getOmitXMLDeclaration() * @see XSLOutputAttributes#getOmitXMLDeclaration()
*/ */
public boolean getOmitXMLDeclaration() public boolean getOmitXMLDeclaration() {
{
aMethodIsCalled(); aMethodIsCalled();
return false; return false;
} }
/** /**
* @see XSLOutputAttributes#getStandalone() * @see XSLOutputAttributes#getStandalone()
*/ */
public String getStandalone() public String getStandalone() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see XSLOutputAttributes#getVersion() * @see XSLOutputAttributes#getVersion()
*/ */
public String getVersion() public String getVersion() {
{
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
} }
/** /**
* @see XSLOutputAttributes#setDoctype(java.lang.String, java.lang.String) * @see XSLOutputAttributes#setDoctype(java.lang.String, java.lang.String)
*/ */
public void setDoctype(String system, String pub) public void setDoctype(String system, String pub) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see XSLOutputAttributes#setDoctypePublic(java.lang.String) * @see XSLOutputAttributes#setDoctypePublic(java.lang.String)
*/ */
public void setDoctypePublic(String doctype) public void setDoctypePublic(String doctype) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see XSLOutputAttributes#setDoctypeSystem(java.lang.String) * @see XSLOutputAttributes#setDoctypeSystem(java.lang.String)
*/ */
public void setDoctypeSystem(String doctype) public void setDoctypeSystem(String doctype) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see XSLOutputAttributes#setEncoding(java.lang.String) * @see XSLOutputAttributes#setEncoding(java.lang.String)
*/ */
public void setEncoding(String encoding) public void setEncoding(String encoding) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see XSLOutputAttributes#setMediaType(java.lang.String) * @see XSLOutputAttributes#setMediaType(java.lang.String)
*/ */
public void setMediaType(String mediatype) public void setMediaType(String mediatype) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see XSLOutputAttributes#setOmitXMLDeclaration(boolean) * @see XSLOutputAttributes#setOmitXMLDeclaration(boolean)
*/ */
public void setOmitXMLDeclaration(boolean b) public void setOmitXMLDeclaration(boolean b) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see XSLOutputAttributes#setStandalone(java.lang.String) * @see XSLOutputAttributes#setStandalone(java.lang.String)
*/ */
public void setStandalone(String standalone) public void setStandalone(String standalone) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see org.xml.sax.ext.DeclHandler#elementDecl(java.lang.String, java.lang.String) * @see org.xml.sax.ext.DeclHandler#elementDecl(java.lang.String, java.lang.String)
*/ */
public void elementDecl(String arg0, String arg1) throws SAXException public void elementDecl(String arg0, String arg1) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.DeclHandler#attributeDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) * @see org.xml.sax.ext.DeclHandler#attributeDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/ */
public void attributeDecl( public void attributeDecl(String arg0, String arg1, String arg2,
String arg0, String arg3, String arg4)
String arg1,
String arg2,
String arg3,
String arg4)
throws SAXException throws SAXException
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.DeclHandler#internalEntityDecl(java.lang.String, java.lang.String) * @see org.xml.sax.ext.DeclHandler#internalEntityDecl(java.lang.String, java.lang.String)
*/ */
@ -636,6 +623,7 @@ public class EmptySerializer implements SerializationHandler
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ext.DeclHandler#externalEntityDecl(java.lang.String, java.lang.String, java.lang.String) * @see org.xml.sax.ext.DeclHandler#externalEntityDecl(java.lang.String, java.lang.String, java.lang.String)
*/ */
@ -644,32 +632,32 @@ public class EmptySerializer implements SerializationHandler
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
*/ */
public void warning(SAXParseException arg0) throws SAXException public void warning(SAXParseException arg0) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
*/ */
public void error(SAXParseException arg0) throws SAXException public void error(SAXParseException arg0) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
*/ */
public void fatalError(SAXParseException arg0) throws SAXException public void fatalError(SAXParseException arg0) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see Serializer#asDOMSerializer() * @see Serializer#asDOMSerializer()
*/ */
public DOMSerializer asDOMSerializer() throws IOException public DOMSerializer asDOMSerializer() throws IOException {
{
couldThrowIOException(); couldThrowIOException();
return null; return null;
} }
@ -684,8 +672,7 @@ public class EmptySerializer implements SerializationHandler
/** /**
* @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator)
*/ */
public void setSourceLocator(SourceLocator locator) public void setSourceLocator(SourceLocator locator) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
@ -701,30 +688,30 @@ public class EmptySerializer implements SerializationHandler
/** /**
* @see ExtendedContentHandler#characters(org.w3c.dom.Node) * @see ExtendedContentHandler#characters(org.w3c.dom.Node)
*/ */
public void characters(Node node) throws SAXException public void characters(Node node) throws SAXException {
{
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see ExtendedContentHandler#addXSLAttribute(java.lang.String, java.lang.String, java.lang.String) * @see ExtendedContentHandler#addXSLAttribute(java.lang.String, java.lang.String, java.lang.String)
*/ */
public void addXSLAttribute(String qName, String value, String uri) public void addXSLAttribute(String qName, String value, String uri) {
{
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/ */
public void addAttribute(String uri, String localName, String rawName, String type, String value) throws SAXException public void addAttribute(String uri, String localName, String rawName,
{ String type, String value) throws SAXException {
couldThrowSAXException(); couldThrowSAXException();
} }
/** /**
* @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String) * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String)
*/ */
public void notationDecl(String arg0, String arg1, String arg2) throws SAXException public void notationDecl(String arg0, String arg1, String arg2)
throws SAXException
{ {
couldThrowSAXException(); couldThrowSAXException();
} }
@ -732,12 +719,8 @@ public class EmptySerializer implements SerializationHandler
/** /**
* @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/ */
public void unparsedEntityDecl( public void unparsedEntityDecl(String arg0, String arg1, String arg2,
String arg0, String arg3) throws SAXException {
String arg1,
String arg2,
String arg3)
throws SAXException {
couldThrowSAXException(); couldThrowSAXException();
} }
@ -746,10 +729,8 @@ public class EmptySerializer implements SerializationHandler
*/ */
public void setDTDEntityExpansion(boolean expand) { public void setDTDEntityExpansion(boolean expand) {
aMethodIsCalled(); aMethodIsCalled();
} }
public String getOutputProperty(String name) { public String getOutputProperty(String name) {
aMethodIsCalled(); aMethodIsCalled();
return null; return null;
@ -762,19 +743,16 @@ public class EmptySerializer implements SerializationHandler
public void setOutputProperty(String name, String val) { public void setOutputProperty(String name, String val) {
aMethodIsCalled(); aMethodIsCalled();
} }
public void setOutputPropertyDefault(String name, String val) { public void setOutputPropertyDefault(String name, String val) {
aMethodIsCalled(); aMethodIsCalled();
} }
/** /**
* @see org.apache.xml.serializer.Serializer#asDOM3Serializer() * @see org.apache.xml.serializer.Serializer#asDOM3Serializer()
*/ */
public Object asDOM3Serializer() throws IOException public Object asDOM3Serializer() throws IOException {
{
couldThrowIOException(); couldThrowIOException();
return null; return null;
} }

View File

@ -1,15 +1,13 @@
/* /*
* reserved comment block * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Licensed to the Apache Software Foundation (ASF) under one * Licensed to the Apache Software Foundation (ASF) under one or more
* or more contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file distributed with
* distributed with this work for additional information * this work for additional information regarding copyright ownership.
* regarding copyright ownership. The ASF licenses this file * The ASF licenses this file to You under the Apache License, Version 2.0
* to you under the Apache License, Version 2.0 (the "License"); * (the "License"); you may not use this file except in compliance with
* you may not use this file except in compliance with the License. * the License. You may obtain a copy of the License at
* 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
* *
@ -19,22 +17,18 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/*
* $Id: SerializerBase.java,v 1.5 2006/04/14 12:09:19 sunithareddy Exp $
*/
package com.sun.org.apache.xml.internal.serializer; package com.sun.org.apache.xml.internal.serializer;
import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
import com.sun.org.apache.xml.internal.serializer.utils.Utils;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Set; import java.util.Set;
import java.util.ArrayList; import java.util.ArrayList;
import javax.xml.transform.OutputKeys; import javax.xml.transform.OutputKeys;
import javax.xml.transform.SourceLocator; import javax.xml.transform.SourceLocator;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
import com.sun.org.apache.xml.internal.serializer.utils.Utils;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.Locator; import org.xml.sax.Locator;
@ -42,7 +36,6 @@ import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; import org.xml.sax.SAXParseException;
import org.xml.sax.ext.Locator2; import org.xml.sax.ext.Locator2;
/** /**
* This class acts as a base class for the XML "serializers" * This class acts as a base class for the XML "serializers"
* and the stream serializers. * and the stream serializers.
@ -54,7 +47,6 @@ public abstract class SerializerBase
implements SerializationHandler, SerializerConstants implements SerializationHandler, SerializerConstants
{ {
/** /**
* To fire off the end element trace event * To fire off the end element trace event
* @param name Name of element * @param name Name of element
@ -62,8 +54,7 @@ public abstract class SerializerBase
protected void fireEndElem(String name) protected void fireEndElem(String name)
throws org.xml.sax.SAXException throws org.xml.sax.SAXException
{ {
if (m_tracer != null) if (m_tracer != null) {
{
flushMyWriter(); flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENDELEMENT,name, (Attributes)null); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENDELEMENT,name, (Attributes)null);
} }
@ -78,8 +69,7 @@ public abstract class SerializerBase
protected void fireCharEvent(char[] chars, int start, int length) protected void fireCharEvent(char[] chars, int start, int length)
throws org.xml.sax.SAXException throws org.xml.sax.SAXException
{ {
if (m_tracer != null) if (m_tracer != null) {
{
flushMyWriter(); flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length);
} }
@ -87,7 +77,7 @@ public abstract class SerializerBase
/** /**
* true if we still need to call startDocumentInternal() * true if we still need to call startDocumentInternal()
*/ */
protected boolean m_needToCallStartDocument = true; protected boolean m_needToCallStartDocument = true;
/** True if a trailing "]]>" still needs to be written to be /** True if a trailing "]]>" still needs to be written to be
@ -150,6 +140,7 @@ public abstract class SerializerBase
* Flag to tell if indenting (pretty-printing) is on. * Flag to tell if indenting (pretty-printing) is on.
*/ */
protected boolean m_doIndent = false; protected boolean m_doIndent = false;
/** /**
* Amount to indent. * Amount to indent.
*/ */
@ -186,7 +177,6 @@ public abstract class SerializerBase
protected SourceLocator m_sourceLocator; protected SourceLocator m_sourceLocator;
/** /**
* The writer to send output to. This field is only used in the ToStream * The writer to send output to. This field is only used in the ToStream
* serializers, but exists here just so that the fireStartDoc() and * serializers, but exists here just so that the fireStartDoc() and
@ -227,11 +217,9 @@ public abstract class SerializerBase
* *
* @see ExtendedLexicalHandler#comment(String) * @see ExtendedLexicalHandler#comment(String)
*/ */
public void comment(String data) throws SAXException public void comment(String data) throws SAXException {
{
final int length = data.length(); final int length = data.length();
if (length > m_charsBuff.length) if (length > m_charsBuff.length) {
{
m_charsBuff = new char[length * 2 + 1]; m_charsBuff = new char[length * 2 + 1];
} }
data.getChars(0, length, m_charsBuff, 0); data.getChars(0, length, m_charsBuff, 0);
@ -248,10 +236,7 @@ public abstract class SerializerBase
* XML file, it sometimes generates a NS prefix of the form "ns?" for * XML file, it sometimes generates a NS prefix of the form "ns?" for
* an attribute. * an attribute.
*/ */
protected String patchName(String qname) protected String patchName(String qname) {
{
final int lastColon = qname.lastIndexOf(':'); final int lastColon = qname.lastIndexOf(':');
if (lastColon > 0) { if (lastColon > 0) {
@ -259,12 +244,11 @@ public abstract class SerializerBase
final String prefix = qname.substring(0, firstColon); final String prefix = qname.substring(0, firstColon);
final String localName = qname.substring(lastColon + 1); final String localName = qname.substring(lastColon + 1);
// If uri is "" then ignore prefix // If uri is "" then ignore prefix
final String uri = m_prefixMap.lookupNamespace(prefix); final String uri = m_prefixMap.lookupNamespace(prefix);
if (uri != null && uri.length() == 0) { if (uri != null && uri.length() == 0) {
return localName; return localName;
} } else if (firstColon != lastColon) {
else if (firstColon != lastColon) {
return prefix + ':' + localName; return prefix + ':' + localName;
} }
} }
@ -277,8 +261,7 @@ public abstract class SerializerBase
* @param qname the qualified name * @param qname the qualified name
* @return the name, but excluding any prefix and colon. * @return the name, but excluding any prefix and colon.
*/ */
protected static String getLocalName(String qname) protected static String getLocalName(String qname) {
{
final int col = qname.lastIndexOf(':'); final int col = qname.lastIndexOf(':');
return (col > 0) ? qname.substring(col + 1) : qname; return (col > 0) ? qname.substring(col + 1) : qname;
} }
@ -309,8 +292,7 @@ public abstract class SerializerBase
* during the invocation of the events in this interface. The * during the invocation of the events in this interface. The
* application should not attempt to use it at any other time.</p> * application should not attempt to use it at any other time.</p>
*/ */
public void setDocumentLocator(Locator locator) public void setDocumentLocator(Locator locator) {
{
m_locator = locator; m_locator = locator;
} }
@ -332,20 +314,13 @@ public abstract class SerializerBase
* @param XSLAttribute true if this attribute is coming from an xsl:attriute element * @param XSLAttribute true if this attribute is coming from an xsl:attriute element
* @see ExtendedContentHandler#addAttribute(String, String, String, String, String) * @see ExtendedContentHandler#addAttribute(String, String, String, String, String)
*/ */
public void addAttribute( public void addAttribute(String uri, String localName, String rawName,
String uri, String type, String value, boolean XSLAttribute)
String localName,
String rawName,
String type,
String value,
boolean XSLAttribute)
throws SAXException throws SAXException
{ {
if (m_elemContext.m_startTagOpen) if (m_elemContext.m_startTagOpen) {
{
addAttributeAlways(uri, localName, rawName, type, value, XSLAttribute); addAttributeAlways(uri, localName, rawName, type, value, XSLAttribute);
} }
} }
/** /**
@ -362,51 +337,32 @@ public abstract class SerializerBase
* @return true if the attribute was added, * @return true if the attribute was added,
* false if an existing value was replaced. * false if an existing value was replaced.
*/ */
public boolean addAttributeAlways( public boolean addAttributeAlways(String uri, String localName, String rawName,
String uri, String type, String value, boolean XSLAttribute)
String localName,
String rawName,
String type,
String value,
boolean XSLAttribute)
{ {
boolean was_added; boolean was_added;
// final int index = int index;
// (localName == null || uri == null) ?
// m_attributes.getIndex(rawName):m_attributes.getIndex(uri, localName);
int index;
// if (localName == null || uri == null){
// index = m_attributes.getIndex(rawName);
// }
// else {
// index = m_attributes.getIndex(uri, localName);
// }
if (localName == null || uri == null || uri.length() == 0)
index = m_attributes.getIndex(rawName);
else {
index = m_attributes.getIndex(uri,localName);
}
if (index >= 0)
{
/* We've seen the attribute before.
* We may have a null uri or localName, but all
* we really want to re-set is the value anyway.
*/
m_attributes.setValue(index,value);
was_added = false;
}
else
{
// the attribute doesn't exist yet, create it
m_attributes.addAttribute(uri, localName, rawName, type, value);
was_added = true;
}
return was_added;
if (localName == null || uri == null || uri.length() == 0)
index = m_attributes.getIndex(rawName);
else {
index = m_attributes.getIndex(uri,localName);
}
if (index >= 0) {
/* We've seen the attribute before.
* We may have a null uri or localName, but all
* we really want to re-set is the value anyway.
*/
m_attributes.setValue(index,value);
was_added = false;
} else {
// the attribute doesn't exist yet, create it
m_attributes.addAttribute(uri, localName, rawName, type, value);
was_added = true;
}
return was_added;
} }
/** /**
* Adds the given attribute to the set of collected attributes, * Adds the given attribute to the set of collected attributes,
* but only if there is a currently open element. * but only if there is a currently open element.
@ -414,16 +370,14 @@ public abstract class SerializerBase
* @param name the attribute's qualified name * @param name the attribute's qualified name
* @param value the value of the attribute * @param value the value of the attribute
*/ */
public void addAttribute(String name, final String value) public void addAttribute(String name, final String value) {
{ if (m_elemContext.m_startTagOpen) {
if (m_elemContext.m_startTagOpen)
{
final String patchedName = patchName(name); final String patchedName = patchName(name);
final String localName = getLocalName(patchedName); final String localName = getLocalName(patchedName);
final String uri = getNamespaceURI(patchedName, false); final String uri = getNamespaceURI(patchedName, false);
addAttributeAlways(uri,localName, patchedName, "CDATA", value, false); addAttributeAlways(uri,localName, patchedName, "CDATA", value, false);
} }
} }
/** /**
@ -434,15 +388,13 @@ public abstract class SerializerBase
* @param value the value of the attribute * @param value the value of the attribute
* @param uri the URI that the prefix of the name points to * @param uri the URI that the prefix of the name points to
*/ */
public void addXSLAttribute(String name, final String value, final String uri) public void addXSLAttribute(String name, final String value, final String uri) {
{ if (m_elemContext.m_startTagOpen) {
if (m_elemContext.m_startTagOpen)
{
final String patchedName = patchName(name); final String patchedName = patchName(name);
final String localName = getLocalName(patchedName); final String localName = getLocalName(patchedName);
addAttributeAlways(uri,localName, patchedName, "CDATA", value, true); addAttributeAlways(uri,localName, patchedName, "CDATA", value, true);
} }
} }
/** /**
@ -451,12 +403,9 @@ public abstract class SerializerBase
* is currently open. * is currently open.
* @param atts List of attributes to add to this list * @param atts List of attributes to add to this list
*/ */
public void addAttributes(Attributes atts) throws SAXException public void addAttributes(Attributes atts) throws SAXException {
{
int nAtts = atts.getLength(); int nAtts = atts.getLength();
for (int i = 0; i < nAtts; i++) for (int i = 0; i < nAtts; i++) {
{
String uri = atts.getURI(i); String uri = atts.getURI(i);
if (null == uri) if (null == uri)
@ -469,7 +418,6 @@ public abstract class SerializerBase
atts.getType(i), atts.getType(i),
atts.getValue(i), atts.getValue(i),
false); false);
} }
} }
@ -482,8 +430,7 @@ public abstract class SerializerBase
* or null if the serializer is not SAX 2 capable * or null if the serializer is not SAX 2 capable
* @throws IOException An I/O exception occured * @throws IOException An I/O exception occured
*/ */
public ContentHandler asContentHandler() throws IOException public ContentHandler asContentHandler() throws IOException {
{
return this; return this;
} }
@ -494,8 +441,7 @@ public abstract class SerializerBase
* @throws org.xml.sax.SAXException The application may raise an exception. * @throws org.xml.sax.SAXException The application may raise an exception.
* @see #startEntity * @see #startEntity
*/ */
public void endEntity(String name) throws org.xml.sax.SAXException public void endEntity(String name) throws org.xml.sax.SAXException {
{
if (name.equals("[dtd]")) if (name.equals("[dtd]"))
m_inExternalDTD = false; m_inExternalDTD = false;
m_inEntityRef = false; m_inEntityRef = false;
@ -509,27 +455,24 @@ public abstract class SerializerBase
* ToStream serializers, not ToSAXHandler serializers. * ToStream serializers, not ToSAXHandler serializers.
* @see ToStream * @see ToStream
*/ */
public void close() public void close() {
{
// do nothing (base behavior) // do nothing (base behavior)
} }
/** /**
* Initialize global variables * Initialize global variables
*/ */
protected void initCDATA() protected void initCDATA() {
{
// CDATA stack // CDATA stack
// _cdataStack = new Stack(); // _cdataStack = new Stack();
// _cdataStack.push(new Integer(-1)); // push dummy value // _cdataStack.push(new Integer(-1)); // push dummy value
} }
/** /**
* Returns the character encoding to be used in the output document. * Returns the character encoding to be used in the output document.
* @return the character encoding to be used in the output document. * @return the character encoding to be used in the output document.
*/ */
public String getEncoding() public String getEncoding() {
{
return getOutputProperty(OutputKeys.ENCODING); return getOutputProperty(OutputKeys.ENCODING);
} }
@ -537,8 +480,7 @@ public abstract class SerializerBase
* Sets the character encoding coming from the xsl:output encoding stylesheet attribute. * Sets the character encoding coming from the xsl:output encoding stylesheet attribute.
* @param m_encoding the character encoding * @param m_encoding the character encoding
*/ */
public void setEncoding(String encoding) public void setEncoding(String encoding) {
{
setOutputProperty(OutputKeys.ENCODING,encoding); setOutputProperty(OutputKeys.ENCODING,encoding);
} }
@ -547,19 +489,16 @@ public abstract class SerializerBase
* @param b true if the XML declaration is to be omitted from the output * @param b true if the XML declaration is to be omitted from the output
* document. * document.
*/ */
public void setOmitXMLDeclaration(boolean b) public void setOmitXMLDeclaration(boolean b) {
{
String val = b ? "yes":"no"; String val = b ? "yes":"no";
setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,val); setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,val);
} }
/** /**
* @return true if the XML declaration is to be omitted from the output * @return true if the XML declaration is to be omitted from the output
* document. * document.
*/ */
public boolean getOmitXMLDeclaration() public boolean getOmitXMLDeclaration() {
{
return m_shouldNotWriteXMLHeader; return m_shouldNotWriteXMLHeader;
} }
@ -625,8 +564,7 @@ public abstract class SerializerBase
* document. This method remembers if the value was explicitly set using * document. This method remembers if the value was explicitly set using
* this method, verses if the value is the default value. * this method, verses if the value is the default value.
*/ */
public void setStandalone(String standalone) public void setStandalone(String standalone) {
{
setOutputProperty(OutputKeys.STANDALONE, standalone); setOutputProperty(OutputKeys.STANDALONE, standalone);
} }
@ -635,8 +573,7 @@ public abstract class SerializerBase
* default or explicite setting. * default or explicite setting.
* @param standalone "yes" | "no" * @param standalone "yes" | "no"
*/ */
protected void setStandaloneInternal(String standalone) protected void setStandaloneInternal(String standalone) {
{
if ("yes".equals(standalone)) if ("yes".equals(standalone))
m_standalone = "yes"; m_standalone = "yes";
else else
@ -650,8 +587,7 @@ public abstract class SerializerBase
* be included in the output document. * be included in the output document.
* @see XSLOutputAttributes#getStandalone() * @see XSLOutputAttributes#getStandalone()
*/ */
public String getStandalone() public String getStandalone() {
{
return m_standalone; return m_standalone;
} }
@ -659,8 +595,7 @@ public abstract class SerializerBase
* @return true if the output document should be indented to visually * @return true if the output document should be indented to visually
* indicate its structure. * indicate its structure.
*/ */
public boolean getIndent() public boolean getIndent() {
{
return m_doIndent; return m_doIndent;
} }
/** /**
@ -669,8 +604,7 @@ public abstract class SerializerBase
* @return the mediatype the media-type or MIME type associated with the * @return the mediatype the media-type or MIME type associated with the
* output document. * output document.
*/ */
public String getMediaType() public String getMediaType() {
{
return m_mediatype; return m_mediatype;
} }
@ -678,8 +612,7 @@ public abstract class SerializerBase
* Gets the version of the output format. * Gets the version of the output format.
* @return the version of the output format. * @return the version of the output format.
*/ */
public String getVersion() public String getVersion() {
{
return m_version; return m_version;
} }
@ -688,8 +621,7 @@ public abstract class SerializerBase
* @param version the version of the output format. * @param version the version of the output format.
* @see SerializationHandler#setVersion(String) * @see SerializationHandler#setVersion(String)
*/ */
public void setVersion(String version) public void setVersion(String version) {
{
setOutputProperty(OutputKeys.VERSION, version); setOutputProperty(OutputKeys.VERSION, version);
} }
@ -700,16 +632,14 @@ public abstract class SerializerBase
* @see javax.xml.transform.OutputKeys#MEDIA_TYPE * @see javax.xml.transform.OutputKeys#MEDIA_TYPE
* @see SerializationHandler#setMediaType(String) * @see SerializationHandler#setMediaType(String)
*/ */
public void setMediaType(String mediaType) public void setMediaType(String mediaType) {
{
setOutputProperty(OutputKeys.MEDIA_TYPE,mediaType); setOutputProperty(OutputKeys.MEDIA_TYPE,mediaType);
} }
/** /**
* @return the number of spaces to indent for each indentation level. * @return the number of spaces to indent for each indentation level.
*/ */
public int getIndentAmount() public int getIndentAmount() {
{
return m_indentAmount; return m_indentAmount;
} }
@ -717,8 +647,7 @@ public abstract class SerializerBase
* Sets the indentation amount. * Sets the indentation amount.
* @param m_indentAmount The m_indentAmount to set * @param m_indentAmount The m_indentAmount to set
*/ */
public void setIndentAmount(int m_indentAmount) public void setIndentAmount(int m_indentAmount) {
{
this.m_indentAmount = m_indentAmount; this.m_indentAmount = m_indentAmount;
} }
@ -729,8 +658,7 @@ public abstract class SerializerBase
* visually indicate its structure. * visually indicate its structure.
* @see XSLOutputAttributes#setIndent(boolean) * @see XSLOutputAttributes#setIndent(boolean)
*/ */
public void setIndent(boolean doIndent) public void setIndent(boolean doIndent) {
{
String val = doIndent ? "yes":"no"; String val = doIndent ? "yes":"no";
setOutputProperty(OutputKeys.INDENT,val); setOutputProperty(OutputKeys.INDENT,val);
} }
@ -740,8 +668,7 @@ public abstract class SerializerBase
* @param isStandalone true if the ORACLE_IS_STANDALONE is set to yes * @param isStandalone true if the ORACLE_IS_STANDALONE is set to yes
* @see OutputPropertiesFactory ORACLE_IS_STANDALONE * @see OutputPropertiesFactory ORACLE_IS_STANDALONE
*/ */
public void setIsStandalone(boolean isStandalone) public void setIsStandalone(boolean isStandalone) {
{
m_isStandalone = isStandalone; m_isStandalone = isStandalone;
} }
@ -772,8 +699,7 @@ public abstract class SerializerBase
* @throws IOException An I/O exception occured * @throws IOException An I/O exception occured
* @see Serializer#asDOMSerializer() * @see Serializer#asDOMSerializer()
*/ */
public DOMSerializer asDOMSerializer() throws IOException public DOMSerializer asDOMSerializer() throws IOException {
{
return this; return this;
} }
@ -785,8 +711,7 @@ public abstract class SerializerBase
* *
* @return true if strings are equal. * @return true if strings are equal.
*/ */
private static final boolean subPartMatch(String p, String t) private static final boolean subPartMatch(String p, String t) {
{
return (p == t) || ((null != p) && (p.equals(t))); return (p == t) || ((null != p) && (p.equals(t)));
} }
@ -799,8 +724,7 @@ public abstract class SerializerBase
* @return returns the prefix of the qualified name, * @return returns the prefix of the qualified name,
* or null if there is no prefix. * or null if there is no prefix.
*/ */
protected static final String getPrefixPart(String qname) protected static final String getPrefixPart(String qname) {
{
final int col = qname.indexOf(':'); final int col = qname.indexOf(':');
return (col > 0) ? qname.substring(0, col) : null; return (col > 0) ? qname.substring(0, col) : null;
//return (col > 0) ? qname.substring(0,col) : ""; //return (col > 0) ? qname.substring(0,col) : "";
@ -811,8 +735,7 @@ public abstract class SerializerBase
* @return the current namespace mappings (prefix/uri) * @return the current namespace mappings (prefix/uri)
* @see ExtendedContentHandler#getNamespaceMappings() * @see ExtendedContentHandler#getNamespaceMappings()
*/ */
public NamespaceMappings getNamespaceMappings() public NamespaceMappings getNamespaceMappings() {
{
return m_prefixMap; return m_prefixMap;
} }
@ -822,8 +745,7 @@ public abstract class SerializerBase
* @return a prefix pointing to the given URI (if any). * @return a prefix pointing to the given URI (if any).
* @see ExtendedContentHandler#getPrefix(String) * @see ExtendedContentHandler#getPrefix(String)
*/ */
public String getPrefix(String namespaceURI) public String getPrefix(String namespaceURI) {
{
String prefix = m_prefixMap.lookupPrefix(namespaceURI); String prefix = m_prefixMap.lookupPrefix(namespaceURI);
return prefix; return prefix;
} }
@ -836,19 +758,15 @@ public abstract class SerializerBase
* an element. * an element.
* @return returns the namespace URI associated with the qualified name. * @return returns the namespace URI associated with the qualified name.
*/ */
public String getNamespaceURI(String qname, boolean isElement) public String getNamespaceURI(String qname, boolean isElement) {
{
String uri = EMPTYSTRING; String uri = EMPTYSTRING;
int col = qname.lastIndexOf(':'); int col = qname.lastIndexOf(':');
final String prefix = (col > 0) ? qname.substring(0, col) : EMPTYSTRING; final String prefix = (col > 0) ? qname.substring(0, col) : EMPTYSTRING;
if (!EMPTYSTRING.equals(prefix) || isElement) if (!EMPTYSTRING.equals(prefix) || isElement) {
{ if (m_prefixMap != null) {
if (m_prefixMap != null)
{
uri = m_prefixMap.lookupNamespace(prefix); uri = m_prefixMap.lookupNamespace(prefix);
if (uri == null && !prefix.equals(XMLNS_PREFIX)) if (uri == null && !prefix.equals(XMLNS_PREFIX)) {
{
throw new RuntimeException( throw new RuntimeException(
Utils.messages.createMessage( Utils.messages.createMessage(
MsgKey.ER_NAMESPACE_PREFIX, MsgKey.ER_NAMESPACE_PREFIX,
@ -866,8 +784,7 @@ public abstract class SerializerBase
* @return the namespace URI currently associated with the * @return the namespace URI currently associated with the
* prefix, null if the prefix is undefined. * prefix, null if the prefix is undefined.
*/ */
public String getNamespaceURIFromPrefix(String prefix) public String getNamespaceURIFromPrefix(String prefix) {
{
String uri = null; String uri = null;
if (m_prefixMap != null) if (m_prefixMap != null)
uri = m_prefixMap.lookupNamespace(prefix); uri = m_prefixMap.lookupNamespace(prefix);
@ -881,16 +798,14 @@ public abstract class SerializerBase
* *
* @throws org.xml.sax.SAXException * @throws org.xml.sax.SAXException
*/ */
public void entityReference(String name) throws org.xml.sax.SAXException public void entityReference(String name) throws org.xml.sax.SAXException {
{
flushPending(); flushPending();
startEntity(name); startEntity(name);
endEntity(name); endEntity(name);
if (m_tracer != null) if (m_tracer != null)
fireEntityReference(name); fireEntityReference(name);
} }
/** /**
@ -898,8 +813,7 @@ public abstract class SerializerBase
* @param t the transformer associated with this serializer. * @param t the transformer associated with this serializer.
* @see SerializationHandler#setTransformer(Transformer) * @see SerializationHandler#setTransformer(Transformer)
*/ */
public void setTransformer(Transformer t) public void setTransformer(Transformer t) {
{
m_transformer = t; m_transformer = t;
// If this transformer object implements the SerializerTrace interface // If this transformer object implements the SerializerTrace interface
@ -912,13 +826,13 @@ public abstract class SerializerBase
m_tracer = null; m_tracer = null;
} }
} }
/** /**
* Gets the transformer associated with this serializer * Gets the transformer associated with this serializer
* @return returns the transformer associated with this serializer. * @return returns the transformer associated with this serializer.
* @see SerializationHandler#getTransformer() * @see SerializationHandler#getTransformer()
*/ */
public Transformer getTransformer() public Transformer getTransformer() {
{
return m_transformer; return m_transformer;
} }
@ -933,11 +847,9 @@ public abstract class SerializerBase
{ {
flushPending(); flushPending();
String data = node.getNodeValue(); String data = node.getNodeValue();
if (data != null) if (data != null) {
{
final int length = data.length(); final int length = data.length();
if (length > m_charsBuff.length) if (length > m_charsBuff.length) {
{
m_charsBuff = new char[length * 2 + 1]; m_charsBuff = new char[length * 2 + 1];
} }
data.getChars(0, length, m_charsBuff, 0); data.getChars(0, length, m_charsBuff, 0);
@ -956,16 +868,13 @@ public abstract class SerializerBase
* @see org.xml.sax.ErrorHandler#fatalError(SAXParseException) * @see org.xml.sax.ErrorHandler#fatalError(SAXParseException)
*/ */
public void fatalError(SAXParseException exc) throws SAXException { public void fatalError(SAXParseException exc) throws SAXException {
m_elemContext.m_startTagOpen = false;
m_elemContext.m_startTagOpen = false;
} }
/** /**
* @see org.xml.sax.ErrorHandler#warning(SAXParseException) * @see org.xml.sax.ErrorHandler#warning(SAXParseException)
*/ */
public void warning(SAXParseException exc) throws SAXException public void warning(SAXParseException exc) throws SAXException {
{
} }
/** /**
@ -982,20 +891,6 @@ public abstract class SerializerBase
} }
} }
/**
* Report the characters event
* @param chars content of characters
* @param start starting index of characters to output
* @param length number of characters to output
*/
// protected void fireCharEvent(char[] chars, int start, int length)
// throws org.xml.sax.SAXException
// {
// if (m_tracer != null)
// m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length);
// }
//
/** /**
* This method is only used internally when flushing the writer from the * This method is only used internally when flushing the writer from the
* various fire...() trace events. Due to the writer being wrapped with * various fire...() trace events. Due to the writer being wrapped with
@ -1005,20 +900,15 @@ public abstract class SerializerBase
* which trace the output written to the output stream. * which trace the output written to the output stream.
* *
*/ */
private void flushMyWriter() private void flushMyWriter() {
{ if (m_writer != null) {
if (m_writer != null) try {
{
try
{
m_writer.flush(); m_writer.flush();
} } catch(IOException ioe) {
catch(IOException ioe)
{
} }
} }
} }
/** /**
* Report the CDATA trace event * Report the CDATA trace event
* @param chars content of CDATA * @param chars content of CDATA
@ -1028,10 +918,9 @@ public abstract class SerializerBase
protected void fireCDATAEvent(char[] chars, int start, int length) protected void fireCDATAEvent(char[] chars, int start, int length)
throws org.xml.sax.SAXException throws org.xml.sax.SAXException
{ {
if (m_tracer != null) if (m_tracer != null) {
{
flushMyWriter(); flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CDATA, chars, start,length); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CDATA, chars, start,length);
} }
} }
@ -1044,10 +933,9 @@ public abstract class SerializerBase
protected void fireCommentEvent(char[] chars, int start, int length) protected void fireCommentEvent(char[] chars, int start, int length)
throws org.xml.sax.SAXException throws org.xml.sax.SAXException
{ {
if (m_tracer != null) if (m_tracer != null) {
{
flushMyWriter(); flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT, new String(chars, start, length)); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT, new String(chars, start, length));
} }
} }
@ -1221,12 +1109,10 @@ public abstract class SerializerBase
* *
* @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator)
*/ */
public void setSourceLocator(SourceLocator locator) public void setSourceLocator(SourceLocator locator) {
{
m_sourceLocator = locator; m_sourceLocator = locator;
} }
/** /**
* Used only by TransformerSnapshotImpl to restore the serialization * Used only by TransformerSnapshotImpl to restore the serialization
* to a previous state. * to a previous state.
@ -1237,8 +1123,7 @@ public abstract class SerializerBase
m_prefixMap = mappings; m_prefixMap = mappings;
} }
public boolean reset() public boolean reset() {
{
resetSerializerBase(); resetSerializerBase();
return true; return true;
} }
@ -1247,8 +1132,7 @@ public abstract class SerializerBase
* Reset all of the fields owned by SerializerBase * Reset all of the fields owned by SerializerBase
* *
*/ */
private void resetSerializerBase() private void resetSerializerBase() {
{
this.m_attributes.clear(); this.m_attributes.clear();
this.m_StringOfCDATASections = null; this.m_StringOfCDATASections = null;
this.m_elemContext = new ElemContext(); this.m_elemContext = new ElemContext();
@ -1280,13 +1164,12 @@ public abstract class SerializerBase
* *
* This concept is made clear in the XSLT 2.0 draft. * This concept is made clear in the XSLT 2.0 draft.
*/ */
final boolean inTemporaryOutputState() final boolean inTemporaryOutputState() {
{
/* This is a hack. We should really be letting the serializer know /* This is a hack. We should really be letting the serializer know
* that it is in temporary output state with an explicit call, but * that it is in temporary output state with an explicit call, but
* from a pragmatic point of view (for now anyways) having no output * from a pragmatic point of view (for now anyways) having no output
* encoding at all, not even the default UTF-8 indicates that the serializer * encoding at all, not even the default UTF-8 indicates that the
* is being used for temporary RTF. * serializer is being used for temporary RTF.
*/ */
return (getEncoding() == null); return (getEncoding() == null);
@ -1295,36 +1178,38 @@ public abstract class SerializerBase
/** /**
* This method adds an attribute the the current element, * This method adds an attribute the the current element,
* but should not be used for an xsl:attribute child. * but should not be used for an xsl:attribute child.
* @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String,
* java.lang.String, java.lang.String, java.lang.String)
*/ */
public void addAttribute(String uri, String localName, String rawName, String type, String value) throws SAXException public void addAttribute(String uri, String localName, String rawName,
String type, String value) throws SAXException
{ {
if (m_elemContext.m_startTagOpen) if (m_elemContext.m_startTagOpen) {
{
addAttributeAlways(uri, localName, rawName, type, value, false); addAttributeAlways(uri, localName, rawName, type, value, false);
} }
} }
/** /**
* @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String) * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String,
* java.lang.String, java.lang.String)
*/ */
public void notationDecl(String arg0, String arg1, String arg2) public void notationDecl(String arg0, String arg1, String arg2)
throws SAXException { throws SAXException
{
// This method just provides a definition to satisfy the interface // This method just provides a definition to satisfy the interface
// A particular sub-class of SerializerBase provides the implementation (if desired) // A particular sub-class of SerializerBase provides the implementation
// (if desired)
} }
/** /**
* @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String,
* java.lang.String, java.lang.String, java.lang.String)
*/ */
public void unparsedEntityDecl( public void unparsedEntityDecl(String arg0, String arg1, String arg2,
String arg0, String arg3) throws SAXException {
String arg1,
String arg2,
String arg3)
throws SAXException {
// This method just provides a definition to satisfy the interface // This method just provides a definition to satisfy the interface
// A particular sub-class of SerializerBase provides the implementation (if desired) // A particular sub-class of SerializerBase provides the implementation
// (if desired)
} }
/** /**
@ -1606,6 +1491,7 @@ public abstract class SerializerBase
* map will have what that attribute maps to. * map will have what that attribute maps to.
*/ */
private HashMap<String, String> m_OutputProps; private HashMap<String, String> m_OutputProps;
/** /**
* A mapping of keys to default values, for example if * A mapping of keys to default values, for example if
* the default value of the encoding is "UTF-8" then this * the default value of the encoding is "UTF-8" then this
@ -1616,6 +1502,7 @@ public abstract class SerializerBase
Set<String> getOutputPropDefaultKeys() { Set<String> getOutputPropDefaultKeys() {
return m_OutputPropsDefault.keySet(); return m_OutputPropsDefault.keySet();
} }
Set<String> getOutputPropKeys() { Set<String> getOutputPropKeys() {
return m_OutputProps.keySet(); return m_OutputProps.keySet();
} }
@ -1634,6 +1521,7 @@ public abstract class SerializerBase
return val; return val;
} }
/** /**
* *
* @param name The name of the property, e.g. "{http://myprop}indent-tabs" or "indent". * @param name The name of the property, e.g. "{http://myprop}indent-tabs" or "indent".

View File

@ -1,13 +1,13 @@
/* /*
* reserved comment block * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT REMOVE OR ALTER!
*/ */
/* /*
* 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
* Licensed under the Apache License, Version 2.0 (the "License"); * this work for additional information regarding copyright ownership.
* you may not use this file except in compliance with the License. * The ASF licenses this file to You under the Apache License, Version 2.0
* You may obtain a copy of the License at * (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
* *
@ -17,13 +17,10 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/*
* $Id: ToSAXHandler.java,v 1.2.4.1 2005/09/22 11:03:15 pvedula Exp $
*/
package com.sun.org.apache.xml.internal.serializer; package com.sun.org.apache.xml.internal.serializer;
import java.util.ArrayList; import java.util.ArrayList;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler; import org.xml.sax.ErrorHandler;
@ -39,23 +36,16 @@ import org.xml.sax.ext.LexicalHandler;
* *
* @xsl.usage internal * @xsl.usage internal
*/ */
public abstract class ToSAXHandler extends SerializerBase public abstract class ToSAXHandler extends SerializerBase {
{ public ToSAXHandler() { }
public ToSAXHandler()
{
}
public ToSAXHandler( public ToSAXHandler(ContentHandler hdlr, LexicalHandler lex, String encoding) {
ContentHandler hdlr,
LexicalHandler lex,
String encoding)
{
setContentHandler(hdlr); setContentHandler(hdlr);
setLexHandler(lex); setLexHandler(lex);
setEncoding(encoding); setEncoding(encoding);
} }
public ToSAXHandler(ContentHandler handler, String encoding)
{ public ToSAXHandler(ContentHandler handler, String encoding) {
setContentHandler(handler); setContentHandler(handler);
setEncoding(encoding); setEncoding(encoding);
} }
@ -90,16 +80,14 @@ public abstract class ToSAXHandler extends SerializerBase
/** /**
* Pass callback to the SAX Handler * Pass callback to the SAX Handler
*/ */
protected void startDocumentInternal() throws SAXException protected void startDocumentInternal() throws SAXException {
{ if (m_needToCallStartDocument) {
if (m_needToCallStartDocument)
{
super.startDocumentInternal(); super.startDocumentInternal();
m_saxHandler.startDocument(); m_saxHandler.startDocument();
m_needToCallStartDocument = false; m_needToCallStartDocument = false;
} }
} }
/** /**
* Do nothing. * Do nothing.
* @see org.xml.sax.ext.LexicalHandler#startDTD(String, String, String) * @see org.xml.sax.ext.LexicalHandler#startDTD(String, String, String)
@ -113,20 +101,20 @@ public abstract class ToSAXHandler extends SerializerBase
/** /**
* Receive notification of character data. * Receive notification of character data.
* *
* @param characters The string of characters to process. * @param chars The string of characters to process.
* *
* @throws org.xml.sax.SAXException * @throws org.xml.sax.SAXException
* *
* @see ExtendedContentHandler#characters(String) * @see ExtendedContentHandler#characters(String)
*/ */
public void characters(String characters) throws SAXException public void characters(String chars) throws SAXException {
{ final int len = (chars == null) ? 0 : chars.length();
final int len = characters.length(); if (len > m_charsBuff.length) {
if (len > m_charsBuff.length) m_charsBuff = new char[len * 2 + 1];
{ }
m_charsBuff = new char[len*2 + 1]; if (len > 0) {
chars.getChars(0, len, m_charsBuff, 0);
} }
characters.getChars(0,len, m_charsBuff, 0);
characters(m_charsBuff, 0, len); characters(m_charsBuff, 0, len);
} }
@ -135,16 +123,13 @@ public abstract class ToSAXHandler extends SerializerBase
* *
* @see ExtendedLexicalHandler#comment(String) * @see ExtendedLexicalHandler#comment(String)
*/ */
public void comment(String comment) throws SAXException public void comment(String comment) throws SAXException {
{
flushPending(); flushPending();
// Ignore if a lexical handler has not been set // Ignore if a lexical handler has not been set
if (m_lexHandler != null) if (m_lexHandler != null) {
{
final int len = comment.length(); final int len = comment.length();
if (len > m_charsBuff.length) if (len > m_charsBuff.length) {
{
m_charsBuff = new char[len*2 + 1]; m_charsBuff = new char[len*2 + 1];
} }
comment.getChars(0,len, m_charsBuff, 0); comment.getChars(0,len, m_charsBuff, 0);
@ -153,7 +138,6 @@ public abstract class ToSAXHandler extends SerializerBase
if (m_tracer != null) if (m_tracer != null)
super.fireCommentEvent(m_charsBuff, 0, len); super.fireCommentEvent(m_charsBuff, 0, len);
} }
} }
/** /**
@ -167,12 +151,10 @@ public abstract class ToSAXHandler extends SerializerBase
// Redefined in SAXXMLOutput // Redefined in SAXXMLOutput
} }
protected void closeStartTag() throws SAXException protected void closeStartTag() throws SAXException {
{
} }
protected void closeCDATA() throws SAXException protected void closeCDATA() throws SAXException {
{
// Redefined in SAXXMLOutput // Redefined in SAXXMLOutput
} }
@ -191,12 +173,8 @@ public abstract class ToSAXHandler extends SerializerBase
* *
* @see org.xml.sax.ContentHandler#startElement(String,String,String,Attributes) * @see org.xml.sax.ContentHandler#startElement(String,String,String,Attributes)
*/ */
public void startElement( public void startElement(String arg0, String arg1, String arg2,
String arg0, Attributes arg3) throws SAXException
String arg1,
String arg2,
Attributes arg3)
throws SAXException
{ {
if (m_state != null) { if (m_state != null) {
m_state.resetState(getTransformer()); m_state.resetState(getTransformer());
@ -211,8 +189,7 @@ public abstract class ToSAXHandler extends SerializerBase
* Sets the LexicalHandler. * Sets the LexicalHandler.
* @param _lexHandler The LexicalHandler to set * @param _lexHandler The LexicalHandler to set
*/ */
public void setLexHandler(LexicalHandler _lexHandler) public void setLexHandler(LexicalHandler _lexHandler) {
{
this.m_lexHandler = _lexHandler; this.m_lexHandler = _lexHandler;
} }
@ -220,11 +197,9 @@ public abstract class ToSAXHandler extends SerializerBase
* Sets the SAX ContentHandler. * Sets the SAX ContentHandler.
* @param _saxHandler The ContentHandler to set * @param _saxHandler The ContentHandler to set
*/ */
public void setContentHandler(ContentHandler _saxHandler) public void setContentHandler(ContentHandler _saxHandler) {
{
this.m_saxHandler = _saxHandler; this.m_saxHandler = _saxHandler;
if (m_lexHandler == null && _saxHandler instanceof LexicalHandler) if (m_lexHandler == null && _saxHandler instanceof LexicalHandler) {
{
// we are not overwriting an existing LexicalHandler, and _saxHandler // we are not overwriting an existing LexicalHandler, and _saxHandler
// is also implements LexicalHandler, so lets use it // is also implements LexicalHandler, so lets use it
m_lexHandler = (LexicalHandler) _saxHandler; m_lexHandler = (LexicalHandler) _saxHandler;
@ -236,8 +211,7 @@ public abstract class ToSAXHandler extends SerializerBase
* stream serializers. * stream serializers.
* @see SerializationHandler#setCdataSectionElements(java.util.ArrayList<String>) * @see SerializationHandler#setCdataSectionElements(java.util.ArrayList<String>)
*/ */
public void setCdataSectionElements(ArrayList<String> URI_and_localNames) public void setCdataSectionElements(ArrayList<String> URI_and_localNames) {
{
// do nothing // do nothing
} }
@ -247,8 +221,7 @@ public abstract class ToSAXHandler extends SerializerBase
* @param doOutputNSAttr whether or not namespace declarations * @param doOutputNSAttr whether or not namespace declarations
* should appear as attributes * should appear as attributes
*/ */
public void setShouldOutputNSAttr(boolean doOutputNSAttr) public void setShouldOutputNSAttr(boolean doOutputNSAttr) {
{
m_shouldGenerateNSAttribute = doOutputNSAttr; m_shouldGenerateNSAttribute = doOutputNSAttr;
} }
@ -258,8 +231,7 @@ public abstract class ToSAXHandler extends SerializerBase
* also be mirrored with self generated additional attributes of elements * also be mirrored with self generated additional attributes of elements
* that declare the namespace, for example the attribute xmlns:prefix1="uri1" * that declare the namespace, for example the attribute xmlns:prefix1="uri1"
*/ */
boolean getShouldOutputNSAttr() boolean getShouldOutputNSAttr() {
{
return m_shouldGenerateNSAttribute; return m_shouldGenerateNSAttribute;
} }
@ -267,27 +239,21 @@ public abstract class ToSAXHandler extends SerializerBase
* This method flushes any pending events, which can be startDocument() * This method flushes any pending events, which can be startDocument()
* closing the opening tag of an element, or closing an open CDATA section. * closing the opening tag of an element, or closing an open CDATA section.
*/ */
public void flushPending() throws SAXException public void flushPending() throws SAXException {
{ if (m_needToCallStartDocument) {
if (m_needToCallStartDocument)
{
startDocumentInternal(); startDocumentInternal();
m_needToCallStartDocument = false; m_needToCallStartDocument = false;
} }
if (m_elemContext.m_startTagOpen) if (m_elemContext.m_startTagOpen) {
{
closeStartTag(); closeStartTag();
m_elemContext.m_startTagOpen = false; m_elemContext.m_startTagOpen = false;
} }
if (m_cdataTagOpen) if (m_cdataTagOpen) {
{
closeCDATA(); closeCDATA();
m_cdataTagOpen = false; m_cdataTagOpen = false;
} }
} }
/** /**
@ -350,8 +316,7 @@ public abstract class ToSAXHandler extends SerializerBase
throws org.xml.sax.SAXException throws org.xml.sax.SAXException
{ {
// remember the current node // remember the current node
if (m_state != null) if (m_state != null) {
{
m_state.setCurrentNode(node); m_state.setCurrentNode(node);
} }
@ -392,12 +357,10 @@ public abstract class ToSAXHandler extends SerializerBase
*/ */
public void warning(SAXParseException exc) throws SAXException { public void warning(SAXParseException exc) throws SAXException {
super.warning(exc); super.warning(exc);
if (m_saxHandler instanceof ErrorHandler) if (m_saxHandler instanceof ErrorHandler)
((ErrorHandler)m_saxHandler).warning(exc); ((ErrorHandler)m_saxHandler).warning(exc);
} }
/** /**
* Try's to reset the super class and reset this class for * Try's to reset the super class and reset this class for
* re-use, so that you don't need to create a new serializer * re-use, so that you don't need to create a new serializer
@ -406,11 +369,9 @@ public abstract class ToSAXHandler extends SerializerBase
* @return true if the class was successfuly reset. * @return true if the class was successfuly reset.
* @see Serializer#reset() * @see Serializer#reset()
*/ */
public boolean reset() public boolean reset() {
{
boolean wasReset = false; boolean wasReset = false;
if (super.reset()) if (super.reset()) {
{
resetToSAXHandler(); resetToSAXHandler();
wasReset = true; wasReset = true;
} }
@ -421,8 +382,7 @@ public abstract class ToSAXHandler extends SerializerBase
* Reset all of the fields owned by ToSAXHandler class * Reset all of the fields owned by ToSAXHandler class
* *
*/ */
private void resetToSAXHandler() private void resetToSAXHandler() {
{
this.m_lexHandler = null; this.m_lexHandler = null;
this.m_saxHandler = null; this.m_saxHandler = null;
this.m_state = null; this.m_state = null;

View File

@ -1,15 +1,13 @@
/* /*
* reserved comment block * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Licensed to the Apache Software Foundation (ASF) under one * Licensed to the Apache Software Foundation (ASF) under one or more
* or more contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file distributed with
* distributed with this work for additional information * this work for additional information regarding copyright ownership.
* regarding copyright ownership. The ASF licenses this file * The ASF licenses this file to You under the Apache License, Version 2.0
* to you under the Apache License, Version 2.0 (the "License"); * (the "License"); you may not use this file except in compliance with
* you may not use this file except in compliance with the License. * the License. You may obtain a copy of the License at
* 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
* *
@ -19,12 +17,13 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/*
* $Id: ToStream.java,v 1.4 2005/11/10 06:43:26 suresh_emailid Exp $
*/
package com.sun.org.apache.xml.internal.serializer; package com.sun.org.apache.xml.internal.serializer;
import com.sun.org.apache.xalan.internal.utils.SecuritySupport; import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
import com.sun.org.apache.xml.internal.serializer.utils.Utils;
import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
@ -36,30 +35,22 @@ import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.ArrayList; import java.util.ArrayList;
import javax.xml.transform.ErrorListener; import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys; import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
import com.sun.org.apache.xml.internal.serializer.utils.Utils;
import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
//import com.sun.media.sound.IESecurity;
/** /**
* This abstract class is a base class for other stream * This abstract class is a base class for other stream
* serializers (xml, html, text ...) that write output to a stream. * serializers (xml, html, text ...) that write output to a stream.
* *
* @xsl.usage internal * @xsl.usage internal
*/ */
abstract public class ToStream extends SerializerBase abstract public class ToStream extends SerializerBase {
{
private static final String COMMENT_BEGIN = "<!--"; private static final String COMMENT_BEGIN = "<!--";
private static final String COMMENT_END = "-->"; private static final String COMMENT_END = "-->";
@ -67,7 +58,6 @@ abstract public class ToStream extends SerializerBase
/** Stack to keep track of disabling output escaping. */ /** Stack to keep track of disabling output escaping. */
protected BoolStack m_disableOutputEscapingStates = new BoolStack(); protected BoolStack m_disableOutputEscapingStates = new BoolStack();
/** /**
* The encoding information associated with this serializer. * The encoding information associated with this serializer.
* Although initially there is no encoding, * Although initially there is no encoding,
@ -87,21 +77,17 @@ abstract public class ToStream extends SerializerBase
*/ */
java.lang.reflect.Method m_canConvertMeth; java.lang.reflect.Method m_canConvertMeth;
/** /**
* Boolean that tells if we already tried to get the converter. * Boolean that tells if we already tried to get the converter.
*/ */
boolean m_triedToGetConverter = false; boolean m_triedToGetConverter = false;
/** /**
* Opaque reference to the sun.io.CharToByteConverter for this * Opaque reference to the sun.io.CharToByteConverter for this
* encoding. * encoding.
*/ */
Object m_charToByteConverter = null; Object m_charToByteConverter = null;
/** /**
* Stack to keep track of whether or not we need to * Stack to keep track of whether or not we need to
* preserve whitespace. * preserve whitespace.
@ -139,7 +125,6 @@ abstract public class ToStream extends SerializerBase
*/ */
protected int m_maxCharacter = Encodings.getLastPrintable(); protected int m_maxCharacter = Encodings.getLastPrintable();
/** /**
* The system line separator for writing out line breaks. * The system line separator for writing out line breaks.
* The default value is from the system property, * The default value is from the system property,
@ -188,8 +173,8 @@ abstract public class ToStream extends SerializerBase
protected boolean m_inDoctype = false; protected boolean m_inDoctype = false;
/** /**
* Flag to quickly tell if the encoding is UTF8. * Flag to quickly tell if the encoding is UTF8.
*/ */
boolean m_isUTF8 = false; boolean m_isUTF8 = false;
/** /**
@ -203,29 +188,23 @@ abstract public class ToStream extends SerializerBase
*/ */
private boolean m_expandDTDEntities = true; private boolean m_expandDTDEntities = true;
/** /**
* Default constructor * Default constructor
*/ */
public ToStream() public ToStream() { }
{
}
/** /**
* This helper method to writes out "]]>" when closing a CDATA section. * This helper method to writes out "]]>" when closing a CDATA section.
* *
* @throws org.xml.sax.SAXException * @throws org.xml.sax.SAXException
*/ */
protected void closeCDATA() throws org.xml.sax.SAXException protected void closeCDATA() throws org.xml.sax.SAXException {
{ try {
try
{
m_writer.write(CDATA_DELIMITER_CLOSE); m_writer.write(CDATA_DELIMITER_CLOSE);
// write out a CDATA section closing "]]>" // write out a CDATA section closing "]]>"
m_cdataTagOpen = false; // Remember that we have done so. m_cdataTagOpen = false; // Remember that we have done so.
} }
catch (IOException e) catch (IOException e) {
{
throw new SAXException(e); throw new SAXException(e);
} }
} }
@ -237,18 +216,11 @@ abstract public class ToStream extends SerializerBase
* @param node Node to serialize. * @param node Node to serialize.
* @throws IOException An I/O exception occured while serializing * @throws IOException An I/O exception occured while serializing
*/ */
public void serialize(Node node) throws IOException public void serialize(Node node) throws IOException {
{ try {
TreeWalker walker = new TreeWalker(this);
try
{
TreeWalker walker =
new TreeWalker(this);
walker.traverse(node); walker.traverse(node);
} } catch (org.xml.sax.SAXException se) {
catch (org.xml.sax.SAXException se)
{
throw new WrappedRuntimeException(se); throw new WrappedRuntimeException(se);
} }
} }
@ -260,8 +232,7 @@ abstract public class ToStream extends SerializerBase
* *
* NEEDSDOC ($objectName$) @return * NEEDSDOC ($objectName$) @return
*/ */
static final boolean isUTF16Surrogate(char c) static final boolean isUTF16Surrogate(char c) {
{
return (c & 0xFC00) == 0xD800; return (c & 0xFC00) == 0xD800;
} }
@ -275,49 +246,40 @@ abstract public class ToStream extends SerializerBase
* *
* @throws org.xml.sax.SAXException * @throws org.xml.sax.SAXException
*/ */
protected final void flushWriter() throws org.xml.sax.SAXException protected final void flushWriter() throws org.xml.sax.SAXException {
{ final Writer writer = m_writer;
final java.io.Writer writer = m_writer; if (null != writer) {
if (null != writer) try {
{ if (writer instanceof WriterToUTF8Buffered) {
try
{
if (writer instanceof WriterToUTF8Buffered)
{
if (m_shouldFlush) if (m_shouldFlush)
((WriterToUTF8Buffered) writer).flush(); ((WriterToUTF8Buffered)writer).flush();
else else
((WriterToUTF8Buffered) writer).flushBuffer(); ((WriterToUTF8Buffered)writer).flushBuffer();
} }
if (writer instanceof WriterToASCI) if (writer instanceof WriterToASCI) {
{
if (m_shouldFlush) if (m_shouldFlush)
writer.flush(); writer.flush();
} } else {
else
{
// Flush always. // Flush always.
// Not a great thing if the writer was created // Not a great thing if the writer was created
// by this class, but don't have a choice. // by this class, but don't have a choice.
writer.flush(); writer.flush();
} }
} } catch (IOException ioe) {
catch (IOException ioe)
{
throw new org.xml.sax.SAXException(ioe); throw new org.xml.sax.SAXException(ioe);
} }
} }
} }
OutputStream m_outputStream; OutputStream m_outputStream;
/** /**
* Get the output stream where the events will be serialized to. * Get the output stream where the events will be serialized to.
* *
* @return reference to the result stream, or null of only a writer was * @return reference to the result stream, or null of only a writer was
* set. * set.
*/ */
public OutputStream getOutputStream() public OutputStream getOutputStream() {
{
return m_outputStream; return m_outputStream;
} }
@ -341,9 +303,8 @@ abstract public class ToStream extends SerializerBase
// Do not inline external DTD // Do not inline external DTD
if (m_inExternalDTD) if (m_inExternalDTD)
return; return;
try try {
{ final Writer writer = m_writer;
final java.io.Writer writer = m_writer;
DTDprolog(); DTDprolog();
writer.write("<!ELEMENT "); writer.write("<!ELEMENT ");
@ -379,13 +340,10 @@ abstract public class ToStream extends SerializerBase
// Do not inline external DTD // Do not inline external DTD
if (m_inExternalDTD) if (m_inExternalDTD)
return; return;
try try {
{
DTDprolog(); DTDprolog();
outputEntityDecl(name, value); outputEntityDecl(name, value);
} } catch (IOException e) {
catch (IOException e)
{
throw new SAXException(e); throw new SAXException(e);
} }
@ -401,7 +359,7 @@ abstract public class ToStream extends SerializerBase
*/ */
void outputEntityDecl(String name, String value) throws IOException void outputEntityDecl(String name, String value) throws IOException
{ {
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
writer.write("<!ENTITY "); writer.write("<!ENTITY ");
writer.write(name); writer.write(name);
writer.write(" \""); writer.write(" \"");
@ -415,8 +373,7 @@ abstract public class ToStream extends SerializerBase
* *
* @throws org.xml.sax.SAXException * @throws org.xml.sax.SAXException
*/ */
protected final void outputLineSep() throws IOException protected final void outputLineSep() throws IOException {
{
m_writer.write(m_lineSep, 0, m_lineSepLen); m_writer.write(m_lineSep, 0, m_lineSepLen);
} }
@ -594,20 +551,17 @@ abstract public class ToStream extends SerializerBase
* *
* @param format The output format to use * @param format The output format to use
*/ */
public void setOutputFormat(Properties format) public void setOutputFormat(Properties format) {
{
boolean shouldFlush = m_shouldFlush; boolean shouldFlush = m_shouldFlush;
if (format != null) if (format != null) {
{
// Set the default values first, // Set the default values first,
// and the non-default values after that, // and the non-default values after that,
// just in case there is some unexpected // just in case there is some unexpected
// residual values left over from over-ridden default values // residual values left over from over-ridden default values
Enumeration propNames; Enumeration propNames;
propNames = format.propertyNames(); propNames = format.propertyNames();
while (propNames.hasMoreElements()) while (propNames.hasMoreElements()) {
{
String key = (String) propNames.nextElement(); String key = (String) propNames.nextElement();
// Get the value, possibly a default value // Get the value, possibly a default value
String value = format.getProperty(key); String value = format.getProperty(key);
@ -629,18 +583,11 @@ abstract public class ToStream extends SerializerBase
String entitiesFileName = String entitiesFileName =
(String) format.get(OutputPropertiesFactory.S_KEY_ENTITIES); (String) format.get(OutputPropertiesFactory.S_KEY_ENTITIES);
if (null != entitiesFileName) if (null != entitiesFileName) {
{ String method = (String) format.get(OutputKeys.METHOD);
String method =
(String) format.get(OutputKeys.METHOD);
m_charInfo = CharInfo.getCharInfo(entitiesFileName, method); m_charInfo = CharInfo.getCharInfo(entitiesFileName, method);
} }
m_shouldFlush = shouldFlush; m_shouldFlush = shouldFlush;
} }
@ -678,8 +625,7 @@ abstract public class ToStream extends SerializerBase
* *
* @param writer The output writer stream * @param writer The output writer stream
*/ */
public void setWriter(Writer writer) public void setWriter(Writer writer) {
{
setWriterInternal(writer, true); setWriterInternal(writer, true);
} }
@ -716,8 +662,7 @@ abstract public class ToStream extends SerializerBase
* operating systems end-of-line separator. * operating systems end-of-line separator.
* @return The previously set value of the serializer. * @return The previously set value of the serializer.
*/ */
public boolean setLineSepUse(boolean use_sytem_line_break) public boolean setLineSepUse(boolean use_sytem_line_break) {
{
boolean oldValue = m_lineSepUse; boolean oldValue = m_lineSepUse;
m_lineSepUse = use_sytem_line_break; m_lineSepUse = use_sytem_line_break;
return oldValue; return oldValue;
@ -734,8 +679,7 @@ abstract public class ToStream extends SerializerBase
* *
* @param output The output stream * @param output The output stream
*/ */
public void setOutputStream(OutputStream output) public void setOutputStream(OutputStream output) {
{
setOutputStreamInternal(output, true); setOutputStreamInternal(output, true);
} }
@ -848,7 +792,7 @@ abstract public class ToStream extends SerializerBase
*/ */
private void printSpace(int n) throws IOException private void printSpace(int n) throws IOException
{ {
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
{ {
writer.write(' '); writer.write(' ');
@ -888,7 +832,7 @@ abstract public class ToStream extends SerializerBase
return; return;
try try
{ {
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
DTDprolog(); DTDprolog();
writer.write("<!ATTLIST "); writer.write("<!ATTLIST ");
@ -1038,7 +982,7 @@ abstract public class ToStream extends SerializerBase
+ Integer.toHexString(low)})); + Integer.toHexString(low)}));
} }
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
// If we make it to here we have a valid high, low surrogate pair // If we make it to here we have a valid high, low surrogate pair
if (m_encodingInfo.isInEncoding(c,low)) { if (m_encodingInfo.isInEncoding(c,low)) {
@ -1089,7 +1033,7 @@ abstract public class ToStream extends SerializerBase
* @throws java.io.IOException * @throws java.io.IOException
*/ */
protected int accumDefaultEntity( protected int accumDefaultEntity(
java.io.Writer writer, Writer writer,
char ch, char ch,
int i, int i,
char[] chars, char[] chars,
@ -1146,7 +1090,7 @@ abstract public class ToStream extends SerializerBase
boolean useSystemLineSeparator) boolean useSystemLineSeparator)
throws IOException, org.xml.sax.SAXException throws IOException, org.xml.sax.SAXException
{ {
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
int end = start + length; int end = start + length;
for (int i = start; i < end; i++) for (int i = start; i < end; i++)
@ -1855,7 +1799,7 @@ abstract public class ToStream extends SerializerBase
m_startNewLine = true; m_startNewLine = true;
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
writer.write('<'); writer.write('<');
writer.write(name); writer.write(name);
} }
@ -1926,7 +1870,7 @@ abstract public class ToStream extends SerializerBase
closeCDATA(); closeCDATA();
try try
{ {
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
writer.write("<!DOCTYPE "); writer.write("<!DOCTYPE ");
writer.write(name); writer.write(name);
@ -1987,7 +1931,7 @@ abstract public class ToStream extends SerializerBase
* @throws java.io.IOException * @throws java.io.IOException
* @throws org.xml.sax.SAXException * @throws org.xml.sax.SAXException
*/ */
public void processAttributes(java.io.Writer writer, int nAttrs) throws IOException, SAXException public void processAttributes(Writer writer, int nAttrs) throws IOException, SAXException
{ {
/* real SAX attributes are not passed in, so process the /* real SAX attributes are not passed in, so process the
* attributes that were collected after the startElement call. * attributes that were collected after the startElement call.
@ -2084,7 +2028,7 @@ abstract public class ToStream extends SerializerBase
try try
{ {
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
if (m_elemContext.m_startTagOpen) if (m_elemContext.m_startTagOpen)
{ {
if (m_tracer != null) if (m_tracer != null)
@ -2290,7 +2234,7 @@ abstract public class ToStream extends SerializerBase
if (shouldIndent() && !m_isStandalone) if (shouldIndent() && !m_isStandalone)
indent(); indent();
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
writer.write(COMMENT_BEGIN); writer.write(COMMENT_BEGIN);
// Detect occurrences of two consecutive dashes, handle as necessary. // Detect occurrences of two consecutive dashes, handle as necessary.
for (int i = start; i < limit; i++) for (int i = start; i < limit; i++)
@ -2370,7 +2314,7 @@ abstract public class ToStream extends SerializerBase
outputDocTypeDecl(m_elemContext.m_elementName, false); outputDocTypeDecl(m_elemContext.m_elementName, false);
m_needToOutputDocTypeDecl = false; m_needToOutputDocTypeDecl = false;
} }
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
if (!m_inDoctype) if (!m_inDoctype)
writer.write("]>"); writer.write("]>");
else else
@ -2598,15 +2542,12 @@ abstract public class ToStream extends SerializerBase
* OutputProperties. Eventually this method should go away and a call * OutputProperties. Eventually this method should go away and a call
* to setCdataSectionElements(ArrayList<String> v) should be made directly. * to setCdataSectionElements(ArrayList<String> v) should be made directly.
*/ */
private void setCdataSectionElements(String key, Properties props) private void setCdataSectionElements(String key, Properties props) {
{
String s = props.getProperty(key); String s = props.getProperty(key);
if (null != s) if (null != s) {
{
// ArrayList<String> of URI/LocalName pairs // ArrayList<String> of URI/LocalName pairs
ArrayList<String> v = new ArrayList<>(); ArrayList<String> al = new ArrayList<>();
int l = s.length(); int l = s.length();
boolean inCurly = false; boolean inCurly = false;
StringBuilder buf = new StringBuilder(); StringBuilder buf = new StringBuilder();
@ -2624,7 +2565,7 @@ abstract public class ToStream extends SerializerBase
{ {
if (buf.length() > 0) if (buf.length() > 0)
{ {
addCdataSectionElement(buf.toString(), v); addCdataSectionElement(buf.toString(), al);
buf.setLength(0); buf.setLength(0);
} }
continue; continue;
@ -2640,11 +2581,11 @@ abstract public class ToStream extends SerializerBase
if (buf.length() > 0) if (buf.length() > 0)
{ {
addCdataSectionElement(buf.toString(), v); addCdataSectionElement(buf.toString(), al);
buf.setLength(0); buf.setLength(0);
} }
// call the official, public method to set the collected names // call the official, public method to set the collected names
setCdataSectionElements(v); setCdataSectionElements(al);
} }
} }
@ -2656,25 +2597,19 @@ abstract public class ToStream extends SerializerBase
* *
* @return a QName object * @return a QName object
*/ */
private void addCdataSectionElement(String URI_and_localName, ArrayList<String> v) private void addCdataSectionElement(String URI_and_localName, ArrayList<String> al) {
{ StringTokenizer tokenizer = new StringTokenizer(URI_and_localName, "{}", false);
StringTokenizer tokenizer =
new StringTokenizer(URI_and_localName, "{}", false);
String s1 = tokenizer.nextToken(); String s1 = tokenizer.nextToken();
String s2 = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; String s2 = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (null == s2) if (null == s2) {
{
// add null URI and the local name // add null URI and the local name
v.add(null); al.add(null);
v.add(s1); al.add(s1);
} } else {
else
{
// add URI, then local name // add URI, then local name
v.add(s1); al.add(s1);
v.add(s2); al.add(s2);
} }
} }
@ -2685,25 +2620,20 @@ abstract public class ToStream extends SerializerBase
* *
* @param URI_and_localNames an ArrayList of pairs of Strings (URI/local) * @param URI_and_localNames an ArrayList of pairs of Strings (URI/local)
*/ */
public void setCdataSectionElements(ArrayList<String> URI_and_localNames) public void setCdataSectionElements(ArrayList<String> URI_and_localNames) {
{
// convert to the new way. // convert to the new way.
if (URI_and_localNames != null) if (URI_and_localNames != null) {
{
final int len = URI_and_localNames.size() - 1; final int len = URI_and_localNames.size() - 1;
if (len > 0) if (len > 0) {
{
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i += 2) for (int i = 0; i < len; i += 2) {
{
// whitspace separated "{uri1}local1 {uri2}local2 ..." // whitspace separated "{uri1}local1 {uri2}local2 ..."
if (i != 0) if (i != 0)
sb.append(' '); sb.append(' ');
final String uri = (String) URI_and_localNames.get(i); final String uri = (String) URI_and_localNames.get(i);
final String localName = final String localName =
(String) URI_and_localNames.get(i + 1); (String) URI_and_localNames.get(i + 1);
if (uri != null) if (uri != null) {
{
// If there is no URI don't put this in, just the localName then. // If there is no URI don't put this in, just the localName then.
sb.append('{'); sb.append('{');
sb.append(uri); sb.append(uri);
@ -3007,25 +2937,19 @@ abstract public class ToStream extends SerializerBase
* exist. This method should be called everytime an attribute is added, * exist. This method should be called everytime an attribute is added,
* or when an attribute value is changed, or an element is created. * or when an attribute value is changed, or an element is created.
*/ */
protected void firePseudoAttributes() {
protected void firePseudoAttributes() if (m_tracer != null) {
{ try {
if (m_tracer != null)
{
try
{
// flush out the "<elemName" if not already flushed // flush out the "<elemName" if not already flushed
m_writer.flush(); m_writer.flush();
// make a StringBuffer to write the name="value" pairs to. // make a StringBuffer to write the name="value" pairs to.
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
int nAttrs = m_attributes.getLength(); int nAttrs = m_attributes.getLength();
if (nAttrs > 0) if (nAttrs > 0) {
{
// make a writer that internally appends to the same // make a writer that internally appends to the same
// StringBuffer // StringBuffer
java.io.Writer writer = Writer writer = new ToStream.WritertoStringBuffer(sb);
new ToStream.WritertoStringBuffer(sb);
processAttributes(writer, nAttrs); processAttributes(writer, nAttrs);
// Don't clear the attributes! // Don't clear the attributes!
@ -3042,13 +2966,9 @@ abstract public class ToStream extends SerializerBase
ch, ch,
0, 0,
ch.length); ch.length);
} } catch (IOException ioe) {
catch (IOException ioe)
{
// ignore ? // ignore ?
} } catch (SAXException se) {
catch (SAXException se)
{
// ignore ? // ignore ?
} }
} }
@ -3060,41 +2980,35 @@ abstract public class ToStream extends SerializerBase
* In this manner trace events, and the real writing of attributes will use * In this manner trace events, and the real writing of attributes will use
* the same code. * the same code.
*/ */
private class WritertoStringBuffer extends java.io.Writer private class WritertoStringBuffer extends Writer {
{
final private StringBuffer m_stringbuf; final private StringBuffer m_stringbuf;
/** /**
* @see java.io.Writer#write(char[], int, int) * @see java.io.Writer#write(char[], int, int)
*/ */
WritertoStringBuffer(StringBuffer sb) WritertoStringBuffer(StringBuffer sb) {
{
m_stringbuf = sb; m_stringbuf = sb;
} }
public void write(char[] arg0, int arg1, int arg2) throws IOException public void write(char[] arg0, int arg1, int arg2) throws IOException {
{
m_stringbuf.append(arg0, arg1, arg2); m_stringbuf.append(arg0, arg1, arg2);
} }
/** /**
* @see java.io.Writer#flush() * @see java.io.Writer#flush()
*/ */
public void flush() throws IOException public void flush() throws IOException {}
{
}
/** /**
* @see java.io.Writer#close() * @see java.io.Writer#close()
*/ */
public void close() throws IOException public void close() throws IOException {}
{
}
public void write(int i) public void write(int i) {
{
m_stringbuf.append((char) i); m_stringbuf.append((char) i);
} }
public void write(String s) public void write(String s) {
{
m_stringbuf.append(s); m_stringbuf.append(s);
} }
} }
@ -3104,12 +3018,11 @@ abstract public class ToStream extends SerializerBase
*/ */
public void setTransformer(Transformer transformer) { public void setTransformer(Transformer transformer) {
super.setTransformer(transformer); super.setTransformer(transformer);
if (m_tracer != null if (m_tracer != null && !(m_writer instanceof SerializerTraceWriter)) {
&& !(m_writer instanceof SerializerTraceWriter) )
m_writer = new SerializerTraceWriter(m_writer, m_tracer); m_writer = new SerializerTraceWriter(m_writer, m_tracer);
}
} }
/** /**
* Try's to reset the super class and reset this class for * Try's to reset the super class and reset this class for
* re-use, so that you don't need to create a new serializer * re-use, so that you don't need to create a new serializer
@ -3117,11 +3030,9 @@ abstract public class ToStream extends SerializerBase
* *
* @return true if the class was successfuly reset. * @return true if the class was successfuly reset.
*/ */
public boolean reset() public boolean reset() {
{
boolean wasReset = false; boolean wasReset = false;
if (super.reset()) if (super.reset()) {
{
resetToStream(); resetToStream();
wasReset = true; wasReset = true;
} }
@ -3132,14 +3043,12 @@ abstract public class ToStream extends SerializerBase
* Reset all of the fields owned by ToStream class * Reset all of the fields owned by ToStream class
* *
*/ */
private void resetToStream() private void resetToStream() {
{
this.m_cdataStartCalled = false; this.m_cdataStartCalled = false;
/* The stream is being reset. It is one of /* The stream is being reset. It is one of
* ToXMLStream, ToHTMLStream ... and this type can't be changed * ToXMLStream, ToHTMLStream ... and this type can't be changed
* so neither should m_charInfo which is associated with the * so neither should m_charInfo which is associated with the
* type of Stream. Just leave m_charInfo as-is for the next re-use. * type of Stream. Just leave m_charInfo as-is for the next re-use.
*
*/ */
// this.m_charInfo = null; // don't set to null // this.m_charInfo = null; // don't set to null
@ -3183,173 +3092,150 @@ abstract public class ToStream extends SerializerBase
* *
* @xsl.usage internal * @xsl.usage internal
*/ */
static final class BoolStack static final class BoolStack {
{ /** Array of boolean values */
private boolean m_values[];
/** Array of boolean values */ /** Array size allocated */
private boolean m_values[]; private int m_allocatedSize;
/** Array size allocated */ /** Index into the array of booleans */
private int m_allocatedSize; private int m_index;
/** Index into the array of booleans */ /**
private int m_index; * Default constructor. Note that the default
* block size is very small, for small lists.
*/
public BoolStack() {
this(32);
}
/** /**
* Default constructor. Note that the default * Construct a IntVector, using the given block size.
* block size is very small, for small lists. *
*/ * @param size array size to allocate
public BoolStack() */
{ public BoolStack(int size) {
this(32); m_allocatedSize = size;
} m_values = new boolean[size];
m_index = -1;
}
/** /**
* Construct a IntVector, using the given block size. * Get the length of the list.
* *
* @param size array size to allocate * @return Current length of the list
*/ */
public BoolStack(int size) public final int size() {
{ return m_index + 1;
}
m_allocatedSize = size; /**
m_values = new boolean[size]; * Clears the stack.
m_index = -1; *
} */
public final void clear() {
m_index = -1;
}
/** /**
* Get the length of the list. * Pushes an item onto the top of this stack.
* *
* @return Current length of the list *
*/ * @param val the boolean to be pushed onto this stack.
public final int size() * @return the <code>item</code> argument.
{ */
return m_index + 1; public final boolean push(boolean val) {
} if (m_index == m_allocatedSize - 1)
grow();
/** return (m_values[++m_index] = val);
* Clears the stack. }
*
*/
public final void clear()
{
m_index = -1;
}
/** /**
* Pushes an item onto the top of this stack. * Removes the object at the top of this stack and returns that
* * object as the value of this function.
* *
* @param val the boolean to be pushed onto this stack. * @return The object at the top of this stack.
* @return the <code>item</code> argument. * @throws EmptyStackException if this stack is empty.
*/ */
public final boolean push(boolean val) public final boolean pop() {
{ return m_values[m_index--];
}
if (m_index == m_allocatedSize - 1) /**
grow(); * Removes the object at the top of this stack and returns the
* next object at the top as the value of this function.
*
*
* @return Next object to the top or false if none there
*/
public final boolean popAndTop() {
m_index--;
return (m_index >= 0) ? m_values[m_index] : false;
}
return (m_values[++m_index] = val); /**
} * Set the item at the top of this stack
*
*
* @param b Object to set at the top of this stack
*/
public final void setTop(boolean b) {
m_values[m_index] = b;
}
/** /**
* Removes the object at the top of this stack and returns that * Looks at the object at the top of this stack without removing it
* object as the value of this function. * from the stack.
* *
* @return The object at the top of this stack. * @return the object at the top of this stack.
* @throws EmptyStackException if this stack is empty. * @throws EmptyStackException if this stack is empty.
*/ */
public final boolean pop() public final boolean peek() {
{ return m_values[m_index];
return m_values[m_index--]; }
}
/** /**
* Removes the object at the top of this stack and returns the * Looks at the object at the top of this stack without removing it
* next object at the top as the value of this function. * from the stack. If the stack is empty, it returns false.
* *
* * @return the object at the top of this stack.
* @return Next object to the top or false if none there */
*/ public final boolean peekOrFalse() {
public final boolean popAndTop() return (m_index > -1) ? m_values[m_index] : false;
{ }
m_index--; /**
* Looks at the object at the top of this stack without removing it
* from the stack. If the stack is empty, it returns true.
*
* @return the object at the top of this stack.
*/
public final boolean peekOrTrue() {
return (m_index > -1) ? m_values[m_index] : true;
}
return (m_index >= 0) ? m_values[m_index] : false; /**
} * Tests if this stack is empty.
*
* @return <code>true</code> if this stack is empty;
* <code>false</code> otherwise.
*/
public boolean isEmpty() {
return (m_index == -1);
}
/** /**
* Set the item at the top of this stack * Grows the size of the stack
* *
* */
* @param b Object to set at the top of this stack private void grow() {
*/ m_allocatedSize *= 2;
public final void setTop(boolean b) boolean newVector[] = new boolean[m_allocatedSize];
{ System.arraycopy(m_values, 0, newVector, 0, m_index + 1);
m_values[m_index] = b; m_values = newVector;
} }
/**
* Looks at the object at the top of this stack without removing it
* from the stack.
*
* @return the object at the top of this stack.
* @throws EmptyStackException if this stack is empty.
*/
public final boolean peek()
{
return m_values[m_index];
}
/**
* Looks at the object at the top of this stack without removing it
* from the stack. If the stack is empty, it returns false.
*
* @return the object at the top of this stack.
*/
public final boolean peekOrFalse()
{
return (m_index > -1) ? m_values[m_index] : false;
}
/**
* Looks at the object at the top of this stack without removing it
* from the stack. If the stack is empty, it returns true.
*
* @return the object at the top of this stack.
*/
public final boolean peekOrTrue()
{
return (m_index > -1) ? m_values[m_index] : true;
}
/**
* Tests if this stack is empty.
*
* @return <code>true</code> if this stack is empty;
* <code>false</code> otherwise.
*/
public boolean isEmpty()
{
return (m_index == -1);
}
/**
* Grows the size of the stack
*
*/
private void grow()
{
m_allocatedSize *= 2;
boolean newVector[] = new boolean[m_allocatedSize];
System.arraycopy(m_values, 0, newVector, 0, m_index + 1);
m_values = newVector;
}
} }
// Implement DTDHandler // Implement DTDHandler
@ -3421,14 +3307,12 @@ abstract public class ToStream extends SerializerBase
* @throws IOException * @throws IOException
*/ */
private void DTDprolog() throws SAXException, IOException { private void DTDprolog() throws SAXException, IOException {
final java.io.Writer writer = m_writer; final Writer writer = m_writer;
if (m_needToOutputDocTypeDecl) if (m_needToOutputDocTypeDecl) {
{
outputDocTypeDecl(m_elemContext.m_elementName, false); outputDocTypeDecl(m_elemContext.m_elementName, false);
m_needToOutputDocTypeDecl = false; m_needToOutputDocTypeDecl = false;
} }
if (m_inDoctype) if (m_inDoctype) {
{
writer.write(" ["); writer.write(" [");
writer.write(m_lineSep, 0, m_lineSepLen); writer.write(m_lineSep, 0, m_lineSepLen);
m_inDoctype = false; m_inDoctype = false;

View File

@ -1,13 +1,13 @@
/* /*
* reserved comment block * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Copyright 1999-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
* Licensed under the Apache License, Version 2.0 (the "License"); * this work for additional information regarding copyright ownership.
* you may not use this file except in compliance with the License. * The ASF licenses this file to You under the Apache License, Version 2.0
* You may obtain a copy of the License at * (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
* *
@ -17,9 +17,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/*
* $Id: ToUnknownStream.java,v 1.3 2005/09/28 13:49:08 pvedula Exp $
*/
package com.sun.org.apache.xml.internal.serializer; package com.sun.org.apache.xml.internal.serializer;
import java.io.IOException; import java.io.IOException;
@ -27,17 +25,14 @@ import java.io.OutputStream;
import java.io.Writer; import java.io.Writer;
import java.util.Properties; import java.util.Properties;
import java.util.ArrayList; import java.util.ArrayList;
import javax.xml.transform.SourceLocator; import javax.xml.transform.SourceLocator;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.Locator; import org.xml.sax.Locator;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
/** /**
*This class wraps another SerializationHandler. The wrapped object will either *This class wraps another SerializationHandler. The wrapped object will either
* handler XML or HTML, which is not known until a little later when the first XML * handler XML or HTML, which is not known until a little later when the first XML
@ -55,7 +50,6 @@ import org.xml.sax.SAXException;
*/ */
public final class ToUnknownStream extends SerializerBase public final class ToUnknownStream extends SerializerBase
{ {
/** /**
* The wrapped handler, initially XML but possibly switched to HTML * The wrapped handler, initially XML but possibly switched to HTML
*/ */
@ -71,11 +65,11 @@ public final class ToUnknownStream extends SerializerBase
*/ */
private boolean m_wrapped_handler_not_initialized = false; private boolean m_wrapped_handler_not_initialized = false;
/** /**
* the prefix of the very first tag in the document * the prefix of the very first tag in the document
*/ */
private String m_firstElementPrefix; private String m_firstElementPrefix;
/** /**
* the element name (including any prefix) of the very first tag in the document * the element name (including any prefix) of the very first tag in the document
*/ */
@ -101,6 +95,7 @@ public final class ToUnknownStream extends SerializerBase
* _namespacePrefix has the matching prefix for these URI's * _namespacePrefix has the matching prefix for these URI's
*/ */
private ArrayList<String> m_namespaceURI = null; private ArrayList<String> m_namespaceURI = null;
/** /**
* A collection of namespace Prefix (only for first element) * A collection of namespace Prefix (only for first element)
* _namespaceURI has the matching URIs for these prefix' * _namespaceURI has the matching URIs for these prefix'
@ -112,34 +107,13 @@ public final class ToUnknownStream extends SerializerBase
* was initialized * was initialized
*/ */
private boolean m_needToCallStartDocument = false; private boolean m_needToCallStartDocument = false;
/**
* true if setVersion() was called before the underlying handler
* was initialized
*/
private boolean m_setVersion_called = false;
/**
* true if setDoctypeSystem() was called before the underlying handler
* was initialized
*/
private boolean m_setDoctypeSystem_called = false;
/**
* true if setDoctypePublic() was called before the underlying handler
* was initialized
*/
private boolean m_setDoctypePublic_called = false;
/**
* true if setMediaType() was called before the underlying handler
* was initialized
*/
private boolean m_setMediaType_called = false;
/** /**
* Default constructor. * Default constructor.
* Initially this object wraps an XML Stream object, so _handler is never null. * Initially this object wraps an XML Stream object, so _handler is never null.
* That may change later to an HTML Stream object. * That may change later to an HTML Stream object.
*/ */
public ToUnknownStream() public ToUnknownStream() {
{
m_handler = new ToXMLStream(); m_handler = new ToXMLStream();
} }
@ -147,8 +121,7 @@ public final class ToUnknownStream extends SerializerBase
* @see Serializer#asContentHandler() * @see Serializer#asContentHandler()
* @return the wrapped XML or HTML handler * @return the wrapped XML or HTML handler
*/ */
public ContentHandler asContentHandler() throws IOException public ContentHandler asContentHandler() throws IOException {
{
/* don't return the real handler ( m_handler ) because /* don't return the real handler ( m_handler ) because
* that would expose the real handler to the outside. * that would expose the real handler to the outside.
* Keep m_handler private so it can be internally swapped * Keep m_handler private so it can be internally swapped
@ -160,8 +133,7 @@ public final class ToUnknownStream extends SerializerBase
/** /**
* @see SerializationHandler#close() * @see SerializationHandler#close()
*/ */
public void close() public void close() {
{
m_handler.close(); m_handler.close();
} }
@ -169,8 +141,7 @@ public final class ToUnknownStream extends SerializerBase
* @see Serializer#getOutputFormat() * @see Serializer#getOutputFormat()
* @return the properties of the underlying handler * @return the properties of the underlying handler
*/ */
public Properties getOutputFormat() public Properties getOutputFormat() {
{
return m_handler.getOutputFormat(); return m_handler.getOutputFormat();
} }
@ -178,8 +149,7 @@ public final class ToUnknownStream extends SerializerBase
* @see Serializer#getOutputStream() * @see Serializer#getOutputStream()
* @return the OutputStream of the underlying XML or HTML handler * @return the OutputStream of the underlying XML or HTML handler
*/ */
public OutputStream getOutputStream() public OutputStream getOutputStream() {
{
return m_handler.getOutputStream(); return m_handler.getOutputStream();
} }
@ -187,8 +157,7 @@ public final class ToUnknownStream extends SerializerBase
* @see Serializer#getWriter() * @see Serializer#getWriter()
* @return the Writer of the underlying XML or HTML handler * @return the Writer of the underlying XML or HTML handler
*/ */
public Writer getWriter() public Writer getWriter() {
{
return m_handler.getWriter(); return m_handler.getWriter();
} }
@ -197,8 +166,7 @@ public final class ToUnknownStream extends SerializerBase
* @see Serializer#reset() * @see Serializer#reset()
* @return ??? * @return ???
*/ */
public boolean reset() public boolean reset() {
{
return m_handler.reset(); return m_handler.reset();
} }
@ -208,10 +176,8 @@ public final class ToUnknownStream extends SerializerBase
* @see DOMSerializer#serialize(Node) * @see DOMSerializer#serialize(Node)
* *
*/ */
public void serialize(Node node) throws IOException public void serialize(Node node) throws IOException {
{ if (m_firstTagNotEmitted) {
if (m_firstTagNotEmitted)
{
flush(); flush();
} }
m_handler.serialize(node); m_handler.serialize(node);
@ -220,8 +186,7 @@ public final class ToUnknownStream extends SerializerBase
/** /**
* @see SerializationHandler#setEscaping(boolean) * @see SerializationHandler#setEscaping(boolean)
*/ */
public boolean setEscaping(boolean escape) throws SAXException public boolean setEscaping(boolean escape) throws SAXException {
{
return m_handler.setEscaping(escape); return m_handler.setEscaping(escape);
} }
@ -230,8 +195,7 @@ public final class ToUnknownStream extends SerializerBase
* @param format the output properties to set * @param format the output properties to set
* @see Serializer#setOutputFormat(Properties) * @see Serializer#setOutputFormat(Properties)
*/ */
public void setOutputFormat(Properties format) public void setOutputFormat(Properties format) {
{
m_handler.setOutputFormat(format); m_handler.setOutputFormat(format);
} }
@ -240,8 +204,7 @@ public final class ToUnknownStream extends SerializerBase
* @param output the OutputStream to write to * @param output the OutputStream to write to
* @see Serializer#setOutputStream(OutputStream) * @see Serializer#setOutputStream(OutputStream)
*/ */
public void setOutputStream(OutputStream output) public void setOutputStream(OutputStream output) {
{
m_handler.setOutputStream(output); m_handler.setOutputStream(output);
} }
@ -250,8 +213,7 @@ public final class ToUnknownStream extends SerializerBase
* @param writer the writer to write to * @param writer the writer to write to
* @see Serializer#setWriter(Writer) * @see Serializer#setWriter(Writer)
*/ */
public void setWriter(Writer writer) public void setWriter(Writer writer) {
{
m_handler.setWriter(writer); m_handler.setWriter(writer);
} }
@ -265,12 +227,8 @@ public final class ToUnknownStream extends SerializerBase
* @param XSLAttribute true if this attribute is coming from an xsl:attribute element * @param XSLAttribute true if this attribute is coming from an xsl:attribute element
* @see ExtendedContentHandler#addAttribute(String, String, String, String, String) * @see ExtendedContentHandler#addAttribute(String, String, String, String, String)
*/ */
public void addAttribute( public void addAttribute(String uri, String localName, String rawName,
String uri, String type, String value)
String localName,
String rawName,
String type,
String value)
throws SAXException throws SAXException
{ {
addAttribute(uri, localName, rawName, type, value, false); addAttribute(uri, localName, rawName, type, value, false);
@ -286,35 +244,27 @@ public final class ToUnknownStream extends SerializerBase
* @param XSLAttribute true if this attribute is coming from an xsl:attribute element * @param XSLAttribute true if this attribute is coming from an xsl:attribute element
* @see ExtendedContentHandler#addAttribute(String, String, String, String, String) * @see ExtendedContentHandler#addAttribute(String, String, String, String, String)
*/ */
public void addAttribute( public void addAttribute(String uri, String localName, String rawName,
String uri, String type, String value, boolean XSLAttribute)
String localName,
String rawName,
String type,
String value,
boolean XSLAttribute)
throws SAXException throws SAXException
{ {
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{
flush(); flush();
} }
m_handler.addAttribute(uri, localName, rawName, type, value, XSLAttribute); m_handler.addAttribute(uri, localName, rawName, type, value, XSLAttribute);
} }
/** /**
* Adds an attribute to the currenly open tag * Adds an attribute to the currenly open tag
* @param rawName the attribute name, with prefix (if any) * @param rawName the attribute name, with prefix (if any)
* @param value the value of the parameter * @param value the value of the parameter
* @see ExtendedContentHandler#addAttribute(String, String) * @see ExtendedContentHandler#addAttribute(String, String)
*/ */
public void addAttribute(String rawName, String value) public void addAttribute(String rawName, String value) {
{ if (m_firstTagNotEmitted) {
if (m_firstTagNotEmitted)
{
flush(); flush();
} }
m_handler.addAttribute(rawName, value); m_handler.addAttribute(rawName, value);
} }
/** /**
@ -323,52 +273,50 @@ public final class ToUnknownStream extends SerializerBase
public void addUniqueAttribute(String rawName, String value, int flags) public void addUniqueAttribute(String rawName, String value, int flags)
throws SAXException throws SAXException
{ {
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{
flush(); flush();
} }
m_handler.addUniqueAttribute(rawName, value, flags); m_handler.addUniqueAttribute(rawName, value, flags);
} }
/** /**
* Converts the String to a character array and calls the SAX method * Converts the String to a character array and calls the SAX method
* characters(char[],int,int); * characters(char[],int,int);
* *
* @param chars The string of characters to process.
*
* @throws org.xml.sax.SAXException
*
* @see ExtendedContentHandler#characters(String) * @see ExtendedContentHandler#characters(String)
*/ */
public void characters(String chars) throws SAXException public void characters(String chars) throws SAXException {
{ final int len = (chars == null) ? 0 : chars.length();
final int length = chars.length(); if (len > m_charsBuff.length) {
if (length > m_charsBuff.length) m_charsBuff = new char[len * 2 + 1];
{
m_charsBuff = new char[length*2 + 1];
} }
chars.getChars(0, length, m_charsBuff, 0); if (len > 0) {
this.characters(m_charsBuff, 0, length); chars.getChars(0, len, m_charsBuff, 0);
}
this.characters(m_charsBuff, 0, len);
} }
/** /**
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see ExtendedContentHandler#endElement(String) * @see ExtendedContentHandler#endElement(String)
*/ */
public void endElement(String elementName) throws SAXException public void endElement(String elementName) throws SAXException {
{ if (m_firstTagNotEmitted) {
if (m_firstTagNotEmitted)
{
flush(); flush();
} }
m_handler.endElement(elementName); m_handler.endElement(elementName);
} }
/** /**
* @see org.xml.sax.ContentHandler#startPrefixMapping(String, String) * @see org.xml.sax.ContentHandler#startPrefixMapping(String, String)
* @param prefix The prefix that maps to the URI * @param prefix The prefix that maps to the URI
* @param uri The URI for the namespace * @param uri The URI for the namespace
*/ */
public void startPrefixMapping(String prefix, String uri) throws SAXException public void startPrefixMapping(String prefix, String uri) throws SAXException {
{
this.startPrefixMapping(prefix,uri, true); this.startPrefixMapping(prefix,uri, true);
} }
@ -387,11 +335,12 @@ public final class ToUnknownStream extends SerializerBase
throws SAXException throws SAXException
{ {
// hack for XSLTC with finding URI for default namespace // hack for XSLTC with finding URI for default namespace
if (m_firstTagNotEmitted && m_firstElementURI == null && m_firstElementName != null) if (m_firstTagNotEmitted &&
m_firstElementURI == null &&
m_firstElementName != null)
{ {
String prefix1 = getPrefixPart(m_firstElementName); String prefix1 = getPrefixPart(m_firstElementName);
if (prefix1 == null && EMPTYSTRING.equals(prefix)) if (prefix1 == null && EMPTYSTRING.equals(prefix)) {
{
// the elements URI is not known yet, and it // the elements URI is not known yet, and it
// doesn't have a prefix, and we are currently // doesn't have a prefix, and we are currently
// setting the uri for prefix "", so we have // setting the uri for prefix "", so we have
@ -399,45 +348,36 @@ public final class ToUnknownStream extends SerializerBase
m_firstElementURI = uri; m_firstElementURI = uri;
} }
} }
startPrefixMapping(prefix,uri, false); startPrefixMapping(prefix, uri, false);
} }
public boolean startPrefixMapping(String prefix, String uri, boolean shouldFlush) public boolean startPrefixMapping(String prefix, String uri, boolean shouldFlush)
throws SAXException throws SAXException
{ {
boolean pushed = false; boolean pushed = false;
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{ if (m_firstElementName != null && shouldFlush) {
if (m_firstElementName != null && shouldFlush)
{
/* we've already seen a startElement, and this is a prefix mapping /* we've already seen a startElement, and this is a prefix mapping
* for the up coming element, so flush the old element * for the up coming element, so flush the old element
* then send this event on its way. * then send this event on its way.
*/ */
flush(); flush();
pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush); pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush);
} } else {
else if (m_namespacePrefix == null) {
{
if (m_namespacePrefix == null)
{
m_namespacePrefix = new ArrayList<>(); m_namespacePrefix = new ArrayList<>();
m_namespaceURI = new ArrayList<>(); m_namespaceURI = new ArrayList<>();
} }
m_namespacePrefix.add(prefix); m_namespacePrefix.add(prefix);
m_namespaceURI.add(uri); m_namespaceURI.add(uri);
if (m_firstElementURI == null) if (m_firstElementURI == null) {
{
if (prefix.equals(m_firstElementPrefix)) if (prefix.equals(m_firstElementPrefix))
m_firstElementURI = uri; m_firstElementURI = uri;
} }
} }
} else {
} pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush);
else
{
pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush);
} }
return pushed; return pushed;
} }
@ -446,54 +386,39 @@ public final class ToUnknownStream extends SerializerBase
* This method cannot be cached because default is different in * This method cannot be cached because default is different in
* HTML and XML (we need more than a boolean). * HTML and XML (we need more than a boolean).
*/ */
public void setVersion(String version) {
public void setVersion(String version)
{
m_handler.setVersion(version); m_handler.setVersion(version);
// Cache call to setVersion()
// super.setVersion(version);
m_setVersion_called = true;
} }
/** /**
* @see org.xml.sax.ContentHandler#startDocument() * @see org.xml.sax.ContentHandler#startDocument()
*/ */
public void startDocument() throws SAXException public void startDocument() throws SAXException {
{
m_needToCallStartDocument = true; m_needToCallStartDocument = true;
} }
public void startElement(String qName) throws SAXException {
public void startElement(String qName) throws SAXException
{
this.startElement(null, null, qName, null); this.startElement(null, null, qName, null);
} }
public void startElement(String namespaceURI, String localName, String qName) throws SAXException public void startElement(String namespaceURI, String localName,
{ String qName) throws SAXException {
this.startElement(namespaceURI, localName, qName, null); this.startElement(namespaceURI, localName, qName, null);
} }
public void startElement( public void startElement(String namespaceURI, String localName,
String namespaceURI, String elementName, Attributes atts)
String localName, throws SAXException
String elementName,
Attributes atts) throws SAXException
{ {
if (m_needToCallSetDocumentInfo) {
if (m_needToCallSetDocumentInfo){
super.setDocumentInfo(); super.setDocumentInfo();
m_needToCallSetDocumentInfo = false; m_needToCallSetDocumentInfo = false;
} }
/* we are notified of the start of an element */ /* we are notified of the start of an element */
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{
/* we have not yet sent the first element on its way */ /* we have not yet sent the first element on its way */
if (m_firstElementName != null) if (m_firstElementName != null) {
{
/* this is not the first element, but a later one. /* this is not the first element, but a later one.
* But we have the old element pending, so flush it out, * But we have the old element pending, so flush it out,
* then send this one on its way. * then send this one on its way.
@ -645,16 +570,14 @@ public final class ToUnknownStream extends SerializerBase
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see XSLOutputAttributes#getVersion() * @see XSLOutputAttributes#getVersion()
*/ */
public String getVersion() public String getVersion() {
{
return m_handler.getVersion(); return m_handler.getVersion();
} }
/** /**
* @see XSLOutputAttributes#setDoctype(String, String) * @see XSLOutputAttributes#setDoctype(String, String)
*/ */
public void setDoctype(String system, String pub) public void setDoctype(String system, String pub) {
{
m_handler.setDoctypePublic(pub); m_handler.setDoctypePublic(pub);
m_handler.setDoctypeSystem(system); m_handler.setDoctypeSystem(system);
} }
@ -665,10 +588,8 @@ public final class ToUnknownStream extends SerializerBase
* @param doctype the public doctype to set * @param doctype the public doctype to set
* @see XSLOutputAttributes#setDoctypePublic(String) * @see XSLOutputAttributes#setDoctypePublic(String)
*/ */
public void setDoctypePublic(String doctype) public void setDoctypePublic(String doctype) {
{
m_handler.setDoctypePublic(doctype); m_handler.setDoctypePublic(doctype);
m_setDoctypePublic_called = true;
} }
/** /**
@ -677,18 +598,15 @@ public final class ToUnknownStream extends SerializerBase
* @param doctype the system doctype to set * @param doctype the system doctype to set
* @see XSLOutputAttributes#setDoctypeSystem(String) * @see XSLOutputAttributes#setDoctypeSystem(String)
*/ */
public void setDoctypeSystem(String doctype) public void setDoctypeSystem(String doctype) {
{
m_handler.setDoctypeSystem(doctype); m_handler.setDoctypeSystem(doctype);
m_setDoctypeSystem_called = true;
} }
/** /**
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see XSLOutputAttributes#setEncoding(String) * @see XSLOutputAttributes#setEncoding(String)
*/ */
public void setEncoding(String encoding) public void setEncoding(String encoding) {
{
m_handler.setEncoding(encoding); m_handler.setEncoding(encoding);
} }
@ -696,34 +614,29 @@ public final class ToUnknownStream extends SerializerBase
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see XSLOutputAttributes#setIndent(boolean) * @see XSLOutputAttributes#setIndent(boolean)
*/ */
public void setIndent(boolean indent) public void setIndent(boolean indent) {
{
m_handler.setIndent(indent); m_handler.setIndent(indent);
} }
/** /**
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
*/ */
public void setIndentAmount(int value) public void setIndentAmount(int value) {
{
m_handler.setIndentAmount(value); m_handler.setIndentAmount(value);
} }
/** /**
* @see XSLOutputAttributes#setMediaType(String) * @see XSLOutputAttributes#setMediaType(String)
*/ */
public void setMediaType(String mediaType) public void setMediaType(String mediaType) {
{
m_handler.setMediaType(mediaType); m_handler.setMediaType(mediaType);
m_setMediaType_called = true;
} }
/** /**
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see XSLOutputAttributes#setOmitXMLDeclaration(boolean) * @see XSLOutputAttributes#setOmitXMLDeclaration(boolean)
*/ */
public void setOmitXMLDeclaration(boolean b) public void setOmitXMLDeclaration(boolean b) {
{
m_handler.setOmitXMLDeclaration(b); m_handler.setOmitXMLDeclaration(b);
} }
@ -731,27 +644,16 @@ public final class ToUnknownStream extends SerializerBase
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see XSLOutputAttributes#setStandalone(String) * @see XSLOutputAttributes#setStandalone(String)
*/ */
public void setStandalone(String standalone) public void setStandalone(String standalone) {
{
m_handler.setStandalone(standalone); m_handler.setStandalone(standalone);
} }
/**
* @see XSLOutputAttributes#setVersion(String)
*/
/** /**
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see org.xml.sax.ext.DeclHandler#attributeDecl(String, String, String, String, String) * @see org.xml.sax.ext.DeclHandler#attributeDecl(String, String, String, String, String)
*/ */
public void attributeDecl( public void attributeDecl(String arg0, String arg1, String arg2,
String arg0, String arg3, String arg4) throws SAXException {
String arg1,
String arg2,
String arg3,
String arg4)
throws SAXException
{
m_handler.attributeDecl(arg0, arg1, arg2, arg3, arg4); m_handler.attributeDecl(arg0, arg1, arg2, arg3, arg4);
} }
@ -761,8 +663,7 @@ public final class ToUnknownStream extends SerializerBase
*/ */
public void elementDecl(String arg0, String arg1) throws SAXException public void elementDecl(String arg0, String arg1) throws SAXException
{ {
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{
emitFirstTag(); emitFirstTag();
} }
m_handler.elementDecl(arg0, arg1); m_handler.elementDecl(arg0, arg1);
@ -778,8 +679,7 @@ public final class ToUnknownStream extends SerializerBase
String systemId) String systemId)
throws SAXException throws SAXException
{ {
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{
flush(); flush();
} }
m_handler.externalEntityDecl(name, publicId, systemId); m_handler.externalEntityDecl(name, publicId, systemId);
@ -792,8 +692,7 @@ public final class ToUnknownStream extends SerializerBase
public void internalEntityDecl(String arg0, String arg1) public void internalEntityDecl(String arg0, String arg1)
throws SAXException throws SAXException
{ {
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{
flush(); flush();
} }
m_handler.internalEntityDecl(arg0, arg1); m_handler.internalEntityDecl(arg0, arg1);
@ -806,29 +705,21 @@ public final class ToUnknownStream extends SerializerBase
public void characters(char[] characters, int offset, int length) public void characters(char[] characters, int offset, int length)
throws SAXException throws SAXException
{ {
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{
flush(); flush();
} }
m_handler.characters(characters, offset, length); m_handler.characters(characters, offset, length);
} }
/** /**
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see org.xml.sax.ContentHandler#endDocument() * @see org.xml.sax.ContentHandler#endDocument()
*/ */
public void endDocument() throws SAXException public void endDocument() throws SAXException {
{ if (m_firstTagNotEmitted) {
if (m_firstTagNotEmitted)
{
flush(); flush();
} }
m_handler.endDocument(); m_handler.endDocument();
} }
/** /**
@ -838,17 +729,14 @@ public final class ToUnknownStream extends SerializerBase
public void endElement(String namespaceURI, String localName, String qName) public void endElement(String namespaceURI, String localName, String qName)
throws SAXException throws SAXException
{ {
if (m_firstTagNotEmitted) if (m_firstTagNotEmitted) {
{
flush(); flush();
if (namespaceURI == null && m_firstElementURI != null) if (namespaceURI == null && m_firstElementURI != null)
namespaceURI = m_firstElementURI; namespaceURI = m_firstElementURI;
if (localName == null && m_firstElementLocalName != null) if (localName == null && m_firstElementLocalName != null)
localName = m_firstElementLocalName; localName = m_firstElementLocalName;
} }
m_handler.endElement(namespaceURI, localName, qName); m_handler.endElement(namespaceURI, localName, qName);
} }
@ -856,8 +744,7 @@ public final class ToUnknownStream extends SerializerBase
* Pass the call on to the underlying handler * Pass the call on to the underlying handler
* @see org.xml.sax.ContentHandler#endPrefixMapping(String) * @see org.xml.sax.ContentHandler#endPrefixMapping(String)
*/ */
public void endPrefixMapping(String prefix) throws SAXException public void endPrefixMapping(String prefix) throws SAXException {
{
m_handler.endPrefixMapping(prefix); m_handler.endPrefixMapping(prefix);
} }
@ -1071,12 +958,9 @@ public final class ToUnknownStream extends SerializerBase
m_wrapped_handler_not_initialized = false; m_wrapped_handler_not_initialized = false;
} }
private void emitFirstTag() throws SAXException private void emitFirstTag() throws SAXException {
{ if (m_firstElementName != null) {
if (m_firstElementName != null) if (m_wrapped_handler_not_initialized) {
{
if (m_wrapped_handler_not_initialized)
{
initStreamOutput(); initStreamOutput();
m_wrapped_handler_not_initialized = false; m_wrapped_handler_not_initialized = false;
} }
@ -1086,14 +970,11 @@ public final class ToUnknownStream extends SerializerBase
m_attributes = null; m_attributes = null;
// Output namespaces of first tag // Output namespaces of first tag
if (m_namespacePrefix != null) if (m_namespacePrefix != null) {
{
final int n = m_namespacePrefix.size(); final int n = m_namespacePrefix.size();
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++) {
{ final String prefix = m_namespacePrefix.get(i);
final String prefix = final String uri = m_namespaceURI.get(i);
(String) m_namespacePrefix.get(i);
final String uri = (String) m_namespaceURI.get(i);
m_handler.startPrefixMapping(prefix, uri, false); m_handler.startPrefixMapping(prefix, uri, false);
} }
m_namespacePrefix = null; m_namespacePrefix = null;
@ -1109,8 +990,7 @@ public final class ToUnknownStream extends SerializerBase
* Don't want to override static function on SerializerBase * Don't want to override static function on SerializerBase
* So added Unknown suffix to method name. * So added Unknown suffix to method name.
*/ */
private String getLocalNameUnknown(String value) private String getLocalNameUnknown(String value) {
{
int idx = value.lastIndexOf(':'); int idx = value.lastIndexOf(':');
if (idx >= 0) if (idx >= 0)
value = value.substring(idx + 1); value = value.substring(idx + 1);
@ -1121,13 +1001,12 @@ public final class ToUnknownStream extends SerializerBase
} }
/** /**
* Utility function to return prefix * Utility function to return prefix
* *
* Don't want to override static function on SerializerBase * Don't want to override static function on SerializerBase
* So added Unknown suffix to method name. * So added Unknown suffix to method name.
*/ */
private String getPrefixPartUnknown(String qname) private String getPrefixPartUnknown(String qname) {
{
final int index = qname.indexOf(':'); final int index = qname.indexOf(':');
return (index > 0) ? qname.substring(0, index) : EMPTYSTRING; return (index > 0) ? qname.substring(0, index) : EMPTYSTRING;
} }
@ -1139,8 +1018,7 @@ public final class ToUnknownStream extends SerializerBase
* *
* @return true if the first element is an opening <html> tag * @return true if the first element is an opening <html> tag
*/ */
private boolean isFirstElemHTML() private boolean isFirstElemHTML() {
{
boolean isHTML; boolean isHTML;
// is the first tag html, not considering the prefix ? // is the first tag html, not considering the prefix ?
@ -1148,29 +1026,27 @@ public final class ToUnknownStream extends SerializerBase
getLocalNameUnknown(m_firstElementName).equalsIgnoreCase("html"); getLocalNameUnknown(m_firstElementName).equalsIgnoreCase("html");
// Try to rule out if this is not to be an HTML document based on URI // Try to rule out if this is not to be an HTML document based on URI
if (isHTML if (isHTML &&
&& m_firstElementURI != null m_firstElementURI != null &&
&& !EMPTYSTRING.equals(m_firstElementURI)) !EMPTYSTRING.equals(m_firstElementURI))
{ {
// the <html> element has a non-trivial namespace // the <html> element has a non-trivial namespace
isHTML = false; isHTML = false;
} }
// Try to rule out if this is an not to be an HTML document based on prefix // Try to rule out if this is an not to be an HTML document based on prefix
if (isHTML && m_namespacePrefix != null) if (isHTML && m_namespacePrefix != null) {
{
/* the first element has a name of "html", but lets check the prefix. /* the first element has a name of "html", but lets check the prefix.
* If the prefix points to a namespace with a URL that is not "" * If the prefix points to a namespace with a URL that is not ""
* then the doecument doesn't start with an <html> tag, and isn't html * then the doecument doesn't start with an <html> tag, and isn't html
*/ */
final int max = m_namespacePrefix.size(); final int max = m_namespacePrefix.size();
for (int i = 0; i < max; i++) for (int i = 0; i < max; i++) {
{
final String prefix = m_namespacePrefix.get(i); final String prefix = m_namespacePrefix.get(i);
final String uri = m_namespaceURI.get(i); final String uri = m_namespaceURI.get(i);
if (m_firstElementPrefix != null if (m_firstElementPrefix != null &&
&& m_firstElementPrefix.equals(prefix) m_firstElementPrefix.equals(prefix) &&
&& !EMPTYSTRING.equals(uri)) !EMPTYSTRING.equals(uri))
{ {
// The first element has a prefix, so it can't be <html> // The first element has a prefix, so it can't be <html>
isHTML = false; isHTML = false;
@ -1181,11 +1057,11 @@ public final class ToUnknownStream extends SerializerBase
} }
return isHTML; return isHTML;
} }
/** /**
* @see Serializer#asDOMSerializer() * @see Serializer#asDOMSerializer()
*/ */
public DOMSerializer asDOMSerializer() throws IOException public DOMSerializer asDOMSerializer() throws IOException {
{
return m_handler.asDOMSerializer(); return m_handler.asDOMSerializer();
} }
@ -1194,15 +1070,14 @@ public final class ToUnknownStream extends SerializerBase
* specified in the cdata-section-elements attribute. * specified in the cdata-section-elements attribute.
* @see SerializationHandler#setCdataSectionElements(java.util.Vector) * @see SerializationHandler#setCdataSectionElements(java.util.Vector)
*/ */
public void setCdataSectionElements(ArrayList<String> URI_and_localNames) public void setCdataSectionElements(ArrayList<String> URI_and_localNames) {
{
m_handler.setCdataSectionElements(URI_and_localNames); m_handler.setCdataSectionElements(URI_and_localNames);
} }
/** /**
* @see ExtendedContentHandler#addAttributes(org.xml.sax.Attributes) * @see ExtendedContentHandler#addAttributes(org.xml.sax.Attributes)
*/ */
public void addAttributes(Attributes atts) throws SAXException public void addAttributes(Attributes atts) throws SAXException {
{
m_handler.addAttributes(atts); m_handler.addAttributes(atts);
} }
@ -1211,98 +1086,83 @@ public final class ToUnknownStream extends SerializerBase
* Simply returns the mappings of the wrapped handler. * Simply returns the mappings of the wrapped handler.
* @see ExtendedContentHandler#getNamespaceMappings() * @see ExtendedContentHandler#getNamespaceMappings()
*/ */
public NamespaceMappings getNamespaceMappings() public NamespaceMappings getNamespaceMappings() {
{
NamespaceMappings mappings = null; NamespaceMappings mappings = null;
if (m_handler != null) if (m_handler != null) {
{
mappings = m_handler.getNamespaceMappings(); mappings = m_handler.getNamespaceMappings();
} }
return mappings; return mappings;
} }
/** /**
* @see SerializationHandler#flushPending() * @see SerializationHandler#flushPending()
*/ */
public void flushPending() throws SAXException public void flushPending() throws SAXException {
{
flush(); flush();
m_handler.flushPending(); m_handler.flushPending();
} }
private void flush() private void flush() {
{ try {
try if (m_firstTagNotEmitted) {
{ emitFirstTag();
if (m_firstTagNotEmitted) }
{ if (m_needToCallStartDocument) {
emitFirstTag(); m_handler.startDocument();
} m_needToCallStartDocument = false;
if (m_needToCallStartDocument) }
{ } catch(SAXException e) {
m_handler.startDocument();
m_needToCallStartDocument = false;
}
}
catch(SAXException e)
{
throw new RuntimeException(e.toString()); throw new RuntimeException(e.toString());
} }
} }
/** /**
* @see ExtendedContentHandler#getPrefix * @see ExtendedContentHandler#getPrefix
*/ */
public String getPrefix(String namespaceURI) public String getPrefix(String namespaceURI) {
{
return m_handler.getPrefix(namespaceURI); return m_handler.getPrefix(namespaceURI);
} }
/** /**
* @see ExtendedContentHandler#entityReference(java.lang.String) * @see ExtendedContentHandler#entityReference(java.lang.String)
*/ */
public void entityReference(String entityName) throws SAXException public void entityReference(String entityName) throws SAXException {
{
m_handler.entityReference(entityName); m_handler.entityReference(entityName);
} }
/** /**
* @see ExtendedContentHandler#getNamespaceURI(java.lang.String, boolean) * @see ExtendedContentHandler#getNamespaceURI(java.lang.String, boolean)
*/ */
public String getNamespaceURI(String qname, boolean isElement) public String getNamespaceURI(String qname, boolean isElement) {
{
return m_handler.getNamespaceURI(qname, isElement); return m_handler.getNamespaceURI(qname, isElement);
} }
public String getNamespaceURIFromPrefix(String prefix) public String getNamespaceURIFromPrefix(String prefix) {
{
return m_handler.getNamespaceURIFromPrefix(prefix); return m_handler.getNamespaceURIFromPrefix(prefix);
} }
public void setTransformer(Transformer t) public void setTransformer(Transformer t) {
{
m_handler.setTransformer(t); m_handler.setTransformer(t);
if ((t instanceof SerializerTrace) && if ((t instanceof SerializerTrace) &&
(((SerializerTrace) t).hasTraceListeners())) { (((SerializerTrace) t).hasTraceListeners()))
m_tracer = (SerializerTrace) t; {
m_tracer = (SerializerTrace) t;
} else { } else {
m_tracer = null; m_tracer = null;
} }
} }
public Transformer getTransformer()
{ public Transformer getTransformer() {
return m_handler.getTransformer(); return m_handler.getTransformer();
} }
/** /**
* @see SerializationHandler#setContentHandler(org.xml.sax.ContentHandler) * @see SerializationHandler#setContentHandler(org.xml.sax.ContentHandler)
*/ */
public void setContentHandler(ContentHandler ch) public void setContentHandler(ContentHandler ch) {
{
m_handler.setContentHandler(ch); m_handler.setContentHandler(ch);
} }
/** /**
* This method is used to set the source locator, which might be used to * This method is used to set the source locator, which might be used to
* generated an error message. * generated an error message.
@ -1310,14 +1170,11 @@ public final class ToUnknownStream extends SerializerBase
* *
* @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator)
*/ */
public void setSourceLocator(SourceLocator locator) public void setSourceLocator(SourceLocator locator) {
{
m_handler.setSourceLocator(locator); m_handler.setSourceLocator(locator);
} }
protected void firePseudoElement(String elementName) protected void firePseudoElement(String elementName) {
{
if (m_tracer != null) { if (m_tracer != null) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();

View File

@ -3,13 +3,12 @@
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Licensed to the Apache Software Foundation (ASF) under one * Licensed to the Apache Software Foundation (ASF) under one or more
* or more contributor license agreements. See the NOTICE file * contributor license agreements. See the NOTICE file distributed with
* distributed with this work for additional information * this work for additional information regarding copyright ownership.
* regarding copyright ownership. The ASF licenses this file * The ASF licenses this file to You under the Apache License, Version 2.0
* to you under the Apache License, Version 2.0 (the "License"); * (the "License"); you may not use this file except in compliance with
* you may not use this file except in compliance with the License. * the License. You may obtain a copy of the License at
* 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
* *
@ -19,9 +18,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/*
* $Id: XSLOutputAttributes.java,v 1.2.4.1 2005/09/15 08:15:32 suresh_emailid Exp $
*/
package com.sun.org.apache.xml.internal.serializer; package com.sun.org.apache.xml.internal.serializer;
import java.util.ArrayList; import java.util.ArrayList;
@ -55,8 +52,7 @@ import java.util.ArrayList;
* *
* @xsl.usage internal * @xsl.usage internal
*/ */
interface XSLOutputAttributes interface XSLOutputAttributes {
{
/** /**
* Returns the previously set value of the value to be used as the public * Returns the previously set value of the value to be used as the public
* identifier in the document type declaration (DTD). * identifier in the document type declaration (DTD).
@ -65,6 +61,7 @@ interface XSLOutputAttributes
* output document. * output document.
*/ */
public String getDoctypePublic(); public String getDoctypePublic();
/** /**
* Returns the previously set value of the value to be used * Returns the previously set value of the value to be used
* as the system identifier in the document type declaration (DTD). * as the system identifier in the document type declaration (DTD).
@ -73,13 +70,15 @@ interface XSLOutputAttributes
* *
*/ */
public String getDoctypeSystem(); public String getDoctypeSystem();
/** /**
* @return the character encoding to be used in the output document. * @return the character encoding to be used in the output document.
*/ */
public String getEncoding(); public String getEncoding();
/** /**
* @return true if the output document should be indented to visually * @return true if the output document should be indented to visually
* indicate its structure. * indicate its structure.
*/ */
public boolean getIndent(); public boolean getIndent();
@ -87,21 +86,25 @@ interface XSLOutputAttributes
* @return the number of spaces to indent for each indentation level. * @return the number of spaces to indent for each indentation level.
*/ */
public int getIndentAmount(); public int getIndentAmount();
/** /**
* @return the mediatype the media-type or MIME type associated with the * @return the mediatype the media-type or MIME type associated with the
* output document. * output document.
*/ */
public String getMediaType(); public String getMediaType();
/** /**
* @return true if the XML declaration is to be omitted from the output * @return true if the XML declaration is to be omitted from the output
* document. * document.
*/ */
public boolean getOmitXMLDeclaration(); public boolean getOmitXMLDeclaration();
/** /**
* @return a value of "yes" if the <code>standalone</code> delaration is to * @return a value of "yes" if the <code>standalone</code> delaration is to
* be included in the output document. * be included in the output document.
*/ */
public String getStandalone(); public String getStandalone();
/** /**
* @return the version of the output format. * @return the version of the output format.
*/ */
@ -132,20 +135,23 @@ interface XSLOutputAttributes
public void setDoctype(String system, String pub); public void setDoctype(String system, String pub);
/** Set the value coming from the xsl:output doctype-public stylesheet attribute. /** Set the value coming from the xsl:output doctype-public stylesheet attribute.
* @param doctype the public identifier to be used in the DOCTYPE * @param doctype the public identifier to be used in the DOCTYPE
* declaration in the output document. * declaration in the output document.
*/ */
public void setDoctypePublic(String doctype); public void setDoctypePublic(String doctype);
/** Set the value coming from the xsl:output doctype-system stylesheet attribute. /** Set the value coming from the xsl:output doctype-system stylesheet attribute.
* @param doctype the system identifier to be used in the DOCTYPE * @param doctype the system identifier to be used in the DOCTYPE
* declaration in the output document. * declaration in the output document.
*/ */
public void setDoctypeSystem(String doctype); public void setDoctypeSystem(String doctype);
/** /**
* Sets the character encoding coming from the xsl:output encoding stylesheet attribute. * Sets the character encoding coming from the xsl:output encoding stylesheet attribute.
* @param encoding the character encoding * @param encoding the character encoding
*/ */
public void setEncoding(String encoding); public void setEncoding(String encoding);
/** /**
* Sets the value coming from the xsl:output indent stylesheet * Sets the value coming from the xsl:output indent stylesheet
* attribute. * attribute.
@ -153,18 +159,21 @@ interface XSLOutputAttributes
* indicate its structure. * indicate its structure.
*/ */
public void setIndent(boolean indent); public void setIndent(boolean indent);
/** /**
* Sets the value coming from the xsl:output media-type stylesheet attribute. * Sets the value coming from the xsl:output media-type stylesheet attribute.
* @param mediatype the media-type or MIME type associated with the output * @param mediatype the media-type or MIME type associated with the output
* document. * document.
*/ */
public void setMediaType(String mediatype); public void setMediaType(String mediatype);
/** /**
* Sets the value coming from the xsl:output omit-xml-declaration stylesheet attribute * Sets the value coming from the xsl:output omit-xml-declaration stylesheet attribute
* @param b true if the XML declaration is to be omitted from the output * @param b true if the XML declaration is to be omitted from the output
* document. * document.
*/ */
public void setOmitXMLDeclaration(boolean b); public void setOmitXMLDeclaration(boolean b);
/** /**
* Sets the value coming from the xsl:output standalone stylesheet attribute. * Sets the value coming from the xsl:output standalone stylesheet attribute.
* @param standalone a value of "yes" indicates that the * @param standalone a value of "yes" indicates that the
@ -172,6 +181,7 @@ interface XSLOutputAttributes
* document. * document.
*/ */
public void setStandalone(String standalone); public void setStandalone(String standalone);
/** /**
* Sets the value coming from the xsl:output version attribute. * Sets the value coming from the xsl:output version attribute.
* @param version the version of the output format. * @param version the version of the output format.
@ -194,6 +204,7 @@ interface XSLOutputAttributes
* @return The value of the parameter * @return The value of the parameter
*/ */
public String getOutputProperty(String name); public String getOutputProperty(String name);
/** /**
* Get the default value for a property that affects seraialization, * Get the default value for a property that affects seraialization,
* or null if there is none. It is possible that a non-default value * or null if there is none. It is possible that a non-default value
@ -203,6 +214,7 @@ interface XSLOutputAttributes
* @return The default value of the parameter, or null if there is no default value. * @return The default value of the parameter, or null if there is no default value.
*/ */
public String getOutputPropertyDefault(String name); public String getOutputPropertyDefault(String name);
/** /**
* Set the non-default value for a property that affects seraialization. * Set the non-default value for a property that affects seraialization.
* @param name The name of the property, which is just the local name * @param name The name of the property, which is just the local name
@ -216,7 +228,7 @@ interface XSLOutputAttributes
* </ul> * </ul>
* @val The non-default value of the parameter * @val The non-default value of the parameter
*/ */
public void setOutputProperty(String name, String val); public void setOutputProperty(String name, String val);
/** /**
* Set the default value for a property that affects seraialization. * Set the default value for a property that affects seraialization.
@ -231,5 +243,5 @@ interface XSLOutputAttributes
* </ul> * </ul>
* @val The default value of the parameter * @val The default value of the parameter
*/ */
public void setOutputPropertyDefault(String name, String val); public void setOutputPropertyDefault(String name, String val);
} }

View File

@ -81,6 +81,8 @@ public class XMLReaderManager {
private boolean _useCatalog; private boolean _useCatalog;
private CatalogFeatures _catalogFeatures; private CatalogFeatures _catalogFeatures;
private int _cdataChunkSize;
/** /**
* Hidden constructor * Hidden constructor
*/ */
@ -173,13 +175,12 @@ public class XMLReaderManager {
} }
} }
try { //reader is cached, but this property might have been reset
//reader is cached, but this property might have been reset JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
reader.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD); _accessExternalDTD, true);
} catch (SAXException se) {
XMLSecurityManager.printWarning(reader.getClass().getName(), JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE,
XMLConstants.ACCESS_EXTERNAL_DTD, se); _cdataChunkSize, false);
}
String lastProperty = ""; String lastProperty = "";
try { try {
@ -278,7 +279,8 @@ public class XMLReaderManager {
_xmlSecurityManager = (XMLSecurityManager)value; _xmlSecurityManager = (XMLSecurityManager)value;
} else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) {
_catalogFeatures = (CatalogFeatures)value; _catalogFeatures = (CatalogFeatures)value;
} else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) {
_cdataChunkSize = JdkXmlUtils.getValue(value, _cdataChunkSize);
} }
} }
} }

View File

@ -25,6 +25,7 @@
package jdk.xml.internal; package jdk.xml.internal;
import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings; import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings;
import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager; import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException; import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
@ -39,6 +40,7 @@ import org.xml.sax.XMLReader;
* Constants for use across JAXP processors. * Constants for use across JAXP processors.
*/ */
public class JdkXmlUtils { public class JdkXmlUtils {
/** /**
* Catalog features * Catalog features
*/ */
@ -58,11 +60,63 @@ public class JdkXmlUtils {
/** /**
* Default value of USE_CATALOG. This will read the System property * Default value of USE_CATALOG. This will read the System property
*/ */
public static final boolean USE_CATALOG_DEFAULT = public static final boolean USE_CATALOG_DEFAULT
SecuritySupport.getJAXPSystemProperty(SP_USE_CATALOG, true); = SecuritySupport.getJAXPSystemProperty(Boolean.class, SP_USE_CATALOG, "true");
/**
* JDK features (will be consolidated in the next major feature revamp
*/
public final static String CDATA_CHUNK_SIZE = "jdk.xml.cdataChunkSize";
public static final int CDATA_CHUNK_SIZE_DEFAULT
= SecuritySupport.getJAXPSystemProperty(Integer.class, CDATA_CHUNK_SIZE, "0");
/**
* Returns the value.
*
* @param value the specified value
* @param defValue the default value
* @return the value, or the default value if the value is null
*/
public static int getValue(Object value, int defValue) {
if (value == null) {
return defValue;
}
if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
return Integer.parseInt(String.valueOf(value));
} else {
throw new IllegalArgumentException("Unexpected class: "
+ value.getClass());
}
}
/**
* Sets the XMLReader instance with the specified property if the the
* property is supported, ignores error if not, issues a warning if so
* requested.
*
* @param reader an XMLReader instance
* @param property the name of the property
* @param value the value of the property
* @param warn a flag indicating whether a warning should be issued
*/
public static void setXMLReaderPropertyIfSupport(XMLReader reader, String property,
Object value, boolean warn) {
try {
reader.setProperty(property, value);
} catch (SAXNotRecognizedException | SAXNotSupportedException e) {
if (warn) {
XMLSecurityManager.printWarning(reader.getClass().getName(),
property, e);
}
}
}
/** /**
* Returns the value of a Catalog feature by the property name. * Returns the value of a Catalog feature by the property name.
*
* @param features a CatalogFeatures instance * @param features a CatalogFeatures instance
* @param name the name of a Catalog feature * @param name the name of a Catalog feature
* @return the value of a Catalog feature, null if the name does not match * @return the value of a Catalog feature, null if the name does not match
@ -106,10 +160,9 @@ public class JdkXmlUtils {
return builder.build(); return builder.build();
} }
/** /**
* Passing on the CatalogFeatures settings from one Xerces configuration object * Passing on the CatalogFeatures settings from one Xerces configuration
* to another. * object to another.
* *
* @param config1 a Xerces configuration object * @param config1 a Xerces configuration object
* @param config2 a Xerces configuration object * @param config2 a Xerces configuration object
@ -120,14 +173,13 @@ public class JdkXmlUtils {
boolean useCatalog = config1.getFeature(XMLConstants.USE_CATALOG); boolean useCatalog = config1.getFeature(XMLConstants.USE_CATALOG);
try { try {
config2.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog); config2.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog);
} } catch (XMLConfigurationException e) {
catch (XMLConfigurationException e) {
supportCatalog = false; supportCatalog = false;
} }
if (supportCatalog && useCatalog) { if (supportCatalog && useCatalog) {
try { try {
for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
config2.setProperty(f.getPropertyName(), config1.getProperty(f.getPropertyName())); config2.setProperty(f.getPropertyName(), config1.getProperty(f.getPropertyName()));
} }
} catch (XMLConfigurationException e) { } catch (XMLConfigurationException e) {
@ -137,8 +189,8 @@ public class JdkXmlUtils {
} }
/** /**
* Passing on the CatalogFeatures settings from a Xerces configuration object * Passing on the CatalogFeatures settings from a Xerces configuration
* to an XMLReader. * object to an XMLReader.
* *
* @param config a Xerces configuration object * @param config a Xerces configuration object
* @param reader an XMLReader * @param reader an XMLReader
@ -148,14 +200,13 @@ public class JdkXmlUtils {
boolean useCatalog = config.getFeature(XMLConstants.USE_CATALOG); boolean useCatalog = config.getFeature(XMLConstants.USE_CATALOG);
try { try {
reader.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog); reader.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog);
} } catch (SAXNotRecognizedException | SAXNotSupportedException e) {
catch (SAXNotRecognizedException | SAXNotSupportedException e) {
supportCatalog = false; supportCatalog = false;
} }
if (supportCatalog && useCatalog) { if (supportCatalog && useCatalog) {
try { try {
for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
reader.setProperty(f.getPropertyName(), config.getProperty(f.getPropertyName())); reader.setProperty(f.getPropertyName(), config.getProperty(f.getPropertyName()));
} }
} catch (SAXNotRecognizedException | SAXNotSupportedException e) { } catch (SAXNotRecognizedException | SAXNotSupportedException e) {

View File

@ -83,19 +83,26 @@ public class SecuritySupport {
} }
/** /**
* Reads boolean type system property. * Reads a system property.
* *
* @param <T> the type of the property value
* @param type the type of the property value
* @param propName the name of the property * @param propName the name of the property
* @param defValue the default value * @param defValue the default value
* @return the value of the property, or the default value of no system * @return the value of the property, or the default value of no system
* property is found * property is found
*/ */
public static boolean getJAXPSystemProperty(String propName, boolean defValue) { public static <T> T getJAXPSystemProperty(Class<T> type, String propName, String defValue) {
String value = getJAXPSystemProperty(propName); String value = getJAXPSystemProperty(propName);
if (value == null) { if (value == null) {
return defValue; value = defValue;
} }
return Boolean.parseBoolean(value); if (Integer.class.isAssignableFrom(type)) {
return type.cast(Integer.parseInt(value));
} else if (Boolean.class.isAssignableFrom(type)) {
return type.cast(Boolean.parseBoolean(value));
}
return type.cast(value);
} }
/** /**

View File

@ -55,7 +55,7 @@ TEE = tee
UNAME = uname UNAME = uname
UNIQ = uniq UNIQ = uniq
WC = wc WC = wc
ZIP = zip ZIPEXE = zip
# Get OS name from uname (Cygwin inexplicably adds _NT-5.1) # Get OS name from uname (Cygwin inexplicably adds _NT-5.1)
UNAME_S := $(shell $(UNAME) -s | $(CUT) -f1 -d_) UNAME_S := $(shell $(UNAME) -s | $(CUT) -f1 -d_)
@ -130,7 +130,7 @@ endif
ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \ ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \
&& $(CD) $(ABS_TEST_OUTPUT_DIR) \ && $(CD) $(ABS_TEST_OUTPUT_DIR) \
&& $(CHMOD) -R a+r . \ && $(CHMOD) -R a+r . \
&& $(ZIP) -q -r $(ARCHIVE_BUNDLE) . ) && $(ZIPEXE) -q -r $(ARCHIVE_BUNDLE) . )
# important results files # important results files
SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt") SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt")

View File

@ -23,4 +23,4 @@
# #
########################################################################### ###########################################################################
javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh 8147431 generic-all javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh 8169827 generic-all

File diff suppressed because one or more lines are too long

View File

@ -27,17 +27,20 @@ import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader; import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
@ -47,6 +50,7 @@ import org.testng.AssertJUnit;
import org.testng.annotations.Listeners; import org.testng.annotations.Listeners;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
@ -69,33 +73,10 @@ import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
* @run testng/othervm -DrunSecMngr=true transform.TransformerTest * @run testng/othervm -DrunSecMngr=true transform.TransformerTest
* @run testng/othervm transform.TransformerTest * @run testng/othervm transform.TransformerTest
* @summary Transformer Tests * @summary Transformer Tests
* @bug 6272879 6305029 6505031 8150704 8162598 * @bug 6272879 6305029 6505031 8150704 8162598 8169772
*/ */
@Listeners({jaxp.library.FilePolicy.class}) @Listeners({jaxp.library.FilePolicy.class})
public class TransformerTest { public class TransformerTest {
private Transformer createTransformer() throws TransformerException {
return TransformerFactory.newInstance().newTransformer();
}
private Transformer createTransformerFromInputstream(InputStream xslStream) throws TransformerException {
return TransformerFactory.newInstance().newTransformer(new StreamSource(xslStream));
}
private Transformer createTransformerFromResource(String xslResource) throws TransformerException {
return TransformerFactory.newInstance().newTransformer(new StreamSource(getClass().getResource(xslResource).toString()));
}
private Document transformInputStreamToDocument(Transformer transformer, InputStream sourceStream) throws TransformerException {
DOMResult response = new DOMResult();
transformer.transform(new StreamSource(sourceStream), response);
return (Document)response.getNode();
}
private StringWriter transformResourceToStringWriter(Transformer transformer, String xmlResource) throws TransformerException {
StringWriter sw = new StringWriter();
transformer.transform(new StreamSource(getClass().getResource(xmlResource).toString()), new StreamResult(sw));
return sw;
}
/** /**
* Reads the contents of the given file into a string. * Reads the contents of the given file into a string.
@ -302,10 +283,15 @@ public class TransformerTest {
System.out.println(sourceXml); System.out.println(sourceXml);
System.out.println(); System.out.println();
// transform to DOM result
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(new StreamSource(new ByteArrayInputStream(xsl.getBytes())));
DOMResult result = new DOMResult();
t.transform(new StreamSource(new ByteArrayInputStream(sourceXml.getBytes())), result);
Document document = (Document)result.getNode();
System.out.println("Result after transformation:"); System.out.println("Result after transformation:");
System.out.println("============================"); System.out.println("============================");
Document document = transformInputStreamToDocument(createTransformerFromInputstream(new ByteArrayInputStream(xsl.getBytes())),
new ByteArrayInputStream(sourceXml.getBytes()));
OutputFormat format = new OutputFormat(); OutputFormat format = new OutputFormat();
format.setIndenting(true); format.setIndenting(true);
new XMLSerializer(System.out, format).serialize(document); new XMLSerializer(System.out, format).serialize(document);
@ -335,13 +321,14 @@ public class TransformerTest {
// test SAXSource // test SAXSource
SAXSource saxSource = new SAXSource(new XMLReaderFor6305029(), new InputSource()); SAXSource saxSource = new SAXSource(new XMLReaderFor6305029(), new InputSource());
StringWriter resultWriter = new StringWriter(); StringWriter resultWriter = new StringWriter();
createTransformer().transform(saxSource, new StreamResult(resultWriter)); TransformerFactory tf = TransformerFactory.newInstance();
tf.newTransformer().transform(saxSource, new StreamResult(resultWriter));
AssertJUnit.assertEquals("Identity transform of SAXSource", XML_DOCUMENT, resultWriter.toString()); AssertJUnit.assertEquals("Identity transform of SAXSource", XML_DOCUMENT, resultWriter.toString());
// test StreamSource // test StreamSource
StreamSource streamSource = new StreamSource(new StringReader(XML_DOCUMENT)); StreamSource streamSource = new StreamSource(new StringReader(XML_DOCUMENT));
resultWriter = new StringWriter(); resultWriter = new StringWriter();
createTransformer().transform(streamSource, new StreamResult(resultWriter)); tf.newTransformer().transform(streamSource, new StreamResult(resultWriter));
AssertJUnit.assertEquals("Identity transform of StreamSource", XML_DOCUMENT, resultWriter.toString()); AssertJUnit.assertEquals("Identity transform of StreamSource", XML_DOCUMENT, resultWriter.toString());
} }
@ -351,10 +338,13 @@ public class TransformerTest {
*/ */
@Test @Test
public final void testBug6505031() throws TransformerException { public final void testBug6505031() throws TransformerException {
Transformer transformer = createTransformerFromResource("transform.xsl"); TransformerFactory tf = TransformerFactory.newInstance();
transformer.setParameter("config", getClass().getResource("config.xml").toString()); Transformer t = tf.newTransformer(new StreamSource(getClass().getResource("transform.xsl").toString()));
transformer.setParameter("mapsFile", getClass().getResource("maps.xml").toString()); t.setParameter("config", getClass().getResource("config.xml").toString());
String s = transformResourceToStringWriter(transformer, "template.xml").toString(); t.setParameter("mapsFile", getClass().getResource("maps.xml").toString());
StringWriter sw = new StringWriter();
t.transform(new StreamSource(getClass().getResource("template.xml").toString()), new StreamResult(sw));
String s = sw.toString();
Assert.assertTrue(s.contains("map1key1value") && s.contains("map2key1value")); Assert.assertTrue(s.contains("map1key1value") && s.contains("map2key1value"));
} }
@ -365,17 +355,20 @@ public class TransformerTest {
@Test @Test
public final void testBug8150704() throws TransformerException, IOException { public final void testBug8150704() throws TransformerException, IOException {
System.out.println("Testing transformation of Bug8150704-1.xml..."); System.out.println("Testing transformation of Bug8150704-1.xml...");
Transformer transformer = createTransformerFromResource("Bug8150704-1.xsl"); TransformerFactory tf = TransformerFactory.newInstance();
StringWriter result = transformResourceToStringWriter(transformer, "Bug8150704-1.xml"); Transformer t = tf.newTransformer(new StreamSource(getClass().getResource("Bug8150704-1.xsl").toString()));
String resultstring = result.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); StringWriter sw = new StringWriter();
t.transform(new StreamSource(getClass().getResource("Bug8150704-1.xml").toString()), new StreamResult(sw));
String resultstring = sw.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n");
String reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-1.ref").getPath())); String reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-1.ref").getPath()));
Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-1.xml does not match reference"); Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-1.xml does not match reference");
System.out.println("Passed."); System.out.println("Passed.");
System.out.println("Testing transformation of Bug8150704-2.xml..."); System.out.println("Testing transformation of Bug8150704-2.xml...");
transformer = createTransformerFromResource("Bug8150704-2.xsl"); t = tf.newTransformer(new StreamSource(getClass().getResource("Bug8150704-2.xsl").toString()));
result = transformResourceToStringWriter(transformer, "Bug8150704-2.xml"); sw = new StringWriter();
resultstring = result.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); t.transform(new StreamSource(getClass().getResource("Bug8150704-2.xml").toString()), new StreamResult(sw));
resultstring = sw.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n");
reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-2.ref").getPath())); reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-2.ref").getPath()));
Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-2.xml does not match reference"); Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-2.xml does not match reference");
System.out.println("Passed."); System.out.println("Passed.");
@ -422,11 +415,15 @@ public class TransformerTest {
System.out.println(sourceXml); System.out.println(sourceXml);
System.out.println(); System.out.println();
// transform to DOM result
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(new StreamSource(new ByteArrayInputStream(xsl.getBytes())));
DOMResult result = new DOMResult();
t.transform(new StreamSource(new ByteArrayInputStream(sourceXml.getBytes())), result);
Document document = (Document)result.getNode();
System.out.println("Result after transformation:"); System.out.println("Result after transformation:");
System.out.println("============================"); System.out.println("============================");
Document document = transformInputStreamToDocument(
createTransformerFromInputstream(new ByteArrayInputStream(xsl.getBytes())),
new ByteArrayInputStream(sourceXml.getBytes()));
OutputFormat format = new OutputFormat(); OutputFormat format = new OutputFormat();
format.setIndenting(true); format.setIndenting(true);
new XMLSerializer(System.out, format).serialize(document); new XMLSerializer(System.out, format).serialize(document);
@ -438,4 +435,38 @@ public class TransformerTest {
checkNodeNS8162598(document.getElementsByTagName("test5").item(0), "ns1", "ns1", null); checkNodeNS8162598(document.getElementsByTagName("test5").item(0), "ns1", "ns1", null);
Assert.assertNull(document.getElementsByTagName("test6").item(0).getNamespaceURI(), "unexpected namespace for test6"); Assert.assertNull(document.getElementsByTagName("test6").item(0).getNamespaceURI(), "unexpected namespace for test6");
} }
/**
* @bug 8169772
* @summary Test transformation of DOM with null valued text node
*
* This test would throw a NullPointerException during transform when the
* fix was not present.
*/
@Test
public final void testBug8169772() throws ParserConfigurationException,
SAXException, IOException, TransformerException
{
// create a small DOM
Document doc = DocumentBuilderFactory.newInstance().
newDocumentBuilder().parse(
new ByteArrayInputStream(
"<?xml version=\"1.0\"?><DOCROOT/>".getBytes()
)
);
// insert a bad element
Element e = doc.createElement("ERROR");
e.appendChild(doc.createTextNode(null));
doc.getDocumentElement().appendChild(e);
// transform
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(doc.getDocumentElement()), new StreamResult(bos)
);
System.out.println("Transformation result (DOM with null text node):");
System.out.println("================================================");
System.out.println(bos);
}
} }