You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@poi.apache.org by ki...@apache.org on 2020/08/28 20:49:50 UTC
svn commit: r1881284 [4/18] - in /xmlbeans/trunk/src:
main/java/org/apache/xmlbeans/ main/java/org/apache/xmlbeans/impl/common/
main/java/org/apache/xmlbeans/impl/schema/
main/java/org/apache/xmlbeans/impl/store/
main/java/org/apache/xmlbeans/impl/tool...
Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java
URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java?rev=1881284&r1=1881283&r2=1881284&view=diff
==============================================================================
--- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java (original)
+++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java Fri Aug 28 20:49:50 2020
@@ -15,21 +15,21 @@
package org.apache.xmlbeans.impl.common;
-import java.io.IOException;
-import java.io.StringReader;
-import java.lang.reflect.Method;
-import java.util.concurrent.TimeUnit;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
-
+import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlOptionsBean;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
+import javax.xml.XMLConstants;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParserFactory;
+import java.io.IOException;
+import java.io.StringReader;
+import java.lang.reflect.Method;
+import java.util.concurrent.TimeUnit;
+
/**
* Provides handy methods for working with SAX parsers and readers
*/
@@ -37,23 +37,24 @@ public final class SAXHelper {
private static final XBLogger logger = XBLogFactory.getLogger(SAXHelper.class);
private static long lastLog;
- private SAXHelper() {}
+ private SAXHelper() {
+ }
/**
* Creates a new SAX XMLReader, with sensible defaults
*/
- public static XMLReader newXMLReader(XmlOptionsBean options) throws SAXException, ParserConfigurationException {
+ public static XMLReader newXMLReader(XmlOptions options) throws SAXException, ParserConfigurationException {
XMLReader xmlReader = saxFactory(options).newSAXParser().getXMLReader();
xmlReader.setEntityResolver(IGNORING_ENTITY_RESOLVER);
trySetSAXFeature(xmlReader, XMLConstants.FEATURE_SECURE_PROCESSING);
trySetXercesSecurityManager(xmlReader, options);
return xmlReader;
}
-
+
public static final EntityResolver IGNORING_ENTITY_RESOLVER = new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId)
- throws SAXException, IOException {
+ throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
};
@@ -62,7 +63,7 @@ public final class SAXHelper {
return saxFactory(new XmlOptionsBean());
}
- static SAXParserFactory saxFactory(XmlOptionsBean options) {
+ static SAXParserFactory saxFactory(XmlOptions options) {
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
saxFactory.setValidating(false);
saxFactory.setNamespaceAware(true);
@@ -91,12 +92,12 @@ public final class SAXHelper {
logger.log(XBLogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame);
}
}
-
- private static void trySetXercesSecurityManager(XMLReader xmlReader, XmlOptionsBean options) {
+
+ private static void trySetXercesSecurityManager(XMLReader xmlReader, XmlOptions options) {
// Try built-in JVM one first, standalone if not
- for (String securityManagerClassName : new String[] {
- //"com.sun.org.apache.xerces.internal.util.SecurityManager",
- "org.apache.xerces.util.SecurityManager"
+ for (String securityManagerClassName : new String[]{
+ //"com.sun.org.apache.xerces.internal.util.SecurityManager",
+ "org.apache.xerces.util.SecurityManager"
}) {
try {
Object mgr = Class.forName(securityManagerClassName).newInstance();
@@ -107,7 +108,7 @@ public final class SAXHelper {
return;
} catch (Throwable e) { // NOSONAR - also catch things like NoClassDefError here
// throttle the log somewhat as it can spam the log otherwise
- if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
+ if (System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
logger.log(XBLogger.WARN, "SAX Security Manager could not be setup [log suppressed for 5 minutes]", e);
lastLog = System.currentTimeMillis();
}
@@ -119,7 +120,7 @@ public final class SAXHelper {
xmlReader.setProperty(XMLBeansConstants.ENTITY_EXPANSION_LIMIT, options.getEntityExpansionLimit());
} catch (SAXException e) { // NOSONAR - also catch things like NoClassDefError here
// throttle the log somewhat as it can spam the log otherwise
- if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
+ if (System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
logger.log(XBLogger.WARN, "SAX Security Manager could not be setup [log suppressed for 5 minutes]", e);
lastLog = System.currentTimeMillis();
}
Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java
URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java?rev=1881284&r1=1881283&r2=1881284&view=diff
==============================================================================
--- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java (original)
+++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java Fri Aug 28 20:49:50 2020
@@ -17,43 +17,37 @@ package org.apache.xmlbeans.impl.common;
import org.apache.xmlbeans.XmlError;
+import java.net.URI;
import java.util.AbstractCollection;
-import java.util.Iterator;
import java.util.Collections;
-import java.net.URI;
+import java.util.Iterator;
-public class XmlErrorPrinter extends AbstractCollection
-{
- private boolean _noisy;
- private URI _baseURI;
+public class XmlErrorPrinter extends AbstractCollection<XmlError> {
+ private final boolean _noisy;
+ private final URI _baseURI;
- public XmlErrorPrinter(boolean noisy, URI baseURI)
- {
+ public XmlErrorPrinter(boolean noisy, URI baseURI) {
_noisy = noisy;
_baseURI = baseURI;
}
- public boolean add(Object o)
- {
- if (o instanceof XmlError)
- {
- XmlError err = (XmlError)o;
+ public boolean add(XmlError err) {
+ if (err != null) {
if (err.getSeverity() == XmlError.SEVERITY_ERROR ||
- err.getSeverity() == XmlError.SEVERITY_WARNING)
+ err.getSeverity() == XmlError.SEVERITY_WARNING) {
System.err.println(err.toString(_baseURI));
- else if (_noisy)
+ } else if (_noisy) {
System.out.println(err.toString(_baseURI));
+ }
}
return false;
}
- public Iterator iterator()
- {
- return Collections.EMPTY_LIST.iterator();
+ public Iterator<XmlError> iterator() {
+ return Collections.emptyIterator();
}
- public int size()
- {
+ public int size() {
return 0;
}
}
Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java
URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java?rev=1881284&r1=1881283&r2=1881284&view=diff
==============================================================================
--- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java (original)
+++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java Fri Aug 28 20:49:50 2020
@@ -19,51 +19,48 @@ import org.apache.xmlbeans.XmlError;
import java.util.AbstractCollection;
import java.util.Collection;
-import java.util.Iterator;
import java.util.Collections;
+import java.util.Iterator;
-public class XmlErrorWatcher extends AbstractCollection
-{
- private Collection _underlying;
+public class XmlErrorWatcher extends AbstractCollection<XmlError> {
+ private final Collection<XmlError> _underlying;
private XmlError _firstError;
- public XmlErrorWatcher(Collection underlying)
- {
+ public XmlErrorWatcher(Collection<XmlError> underlying) {
_underlying = underlying;
}
- public boolean add(Object o)
- {
- if (_firstError == null && o instanceof XmlError && ((XmlError)o).getSeverity() == XmlError.SEVERITY_ERROR)
- _firstError = (XmlError)o;
- if (_underlying == null)
+ public boolean add(XmlError o) {
+ if (_firstError == null && o != null && o.getSeverity() == XmlError.SEVERITY_ERROR) {
+ _firstError = o;
+ }
+ if (_underlying == null) {
return false;
+ }
return _underlying.add(o);
}
- public Iterator iterator()
- {
- if (_underlying == null)
- return Collections.EMPTY_LIST.iterator();
+ public Iterator<XmlError> iterator() {
+ if (_underlying == null) {
+ return Collections.emptyIterator();
+ }
return _underlying.iterator();
}
- public int size()
- {
- if (_underlying == null)
+ public int size() {
+ if (_underlying == null) {
return 0;
+ }
return _underlying.size();
}
- public boolean hasError()
- {
+ public boolean hasError() {
return _firstError != null;
}
- public XmlError firstError()
- {
+ public XmlError firstError() {
return _firstError;
}
}
Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java
URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java?rev=1881284&r1=1881283&r2=1881284&view=diff
==============================================================================
--- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java (original)
+++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java Fri Aug 28 20:49:50 2020
@@ -15,51 +15,40 @@
package org.apache.xmlbeans.impl.schema;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
+import java.util.stream.Collectors;
-public class SchemaDependencies
-{
+public class SchemaDependencies {
// This class is NOT synchronized
- void registerDependency(String source, String target)
- {
- Set depSet = (Set) _dependencies.get(target);
- if (depSet == null)
- {
- depSet = new HashSet();
- _dependencies.put(target, depSet);
- }
- depSet.add(source);
- }
-
-
+ /**
+ * Records the list of files associated to each namespace.
+ * This is needed so that we can return a list of files that
+ * need to be compiled once we get a set of altered namespaces
+ */
+ private final Map<String, List<String>> _contributions = new HashMap<>();
/**
* Records anti-dependencies. Keys are namespaces and values are
* the lists of namespaces that depend on each key
*/
- private Map/*<String,Set<String>>*/ _dependencies;
+ private final Map<String, Set<String>> _dependencies = new HashMap<>();
+
+ void registerDependency(String source, String target) {
+ _dependencies.computeIfAbsent(target, k -> new HashSet<>()).add(source);
+ }
+
- Set computeTransitiveClosure(List modifiedNamespaces)
- {
- List nsList = new ArrayList(modifiedNamespaces);
- Set result = new HashSet(modifiedNamespaces);
- for (int i = 0; i < nsList.size(); i++)
- {
- Set deps = (Set) _dependencies.get(nsList.get(i));
- if (deps == null)
+ Set<String> computeTransitiveClosure(List<String> modifiedNamespaces) {
+ List<String> nsList = new ArrayList<>(modifiedNamespaces);
+ Set<String> result = new HashSet<>(modifiedNamespaces);
+ for (int i = 0; i < nsList.size(); i++) {
+ Set<String> deps = _dependencies.get(nsList.get(i));
+ if (deps == null) {
continue;
- for (Iterator it = deps.iterator(); it.hasNext(); )
- {
- String ns = (String) it.next();
- if (!result.contains(ns))
- {
+ }
+ for (String ns : deps) {
+ if (!result.contains(ns)) {
nsList.add(ns);
result.add(ns);
}
@@ -68,95 +57,52 @@ public class SchemaDependencies
return result;
}
- SchemaDependencies()
- {
- _dependencies = new HashMap();
- _contributions = new HashMap();
+ SchemaDependencies() {
}
- SchemaDependencies(SchemaDependencies base, Set updatedNs)
- {
- _dependencies = new HashMap();
- _contributions = new HashMap();
- for (Iterator it = base._dependencies.keySet().iterator(); it.hasNext(); )
- {
- String target = (String) it.next();
- if (updatedNs.contains(target))
+ SchemaDependencies(SchemaDependencies base, Set<String> updatedNs) {
+ for (String target : base._dependencies.keySet()) {
+ if (updatedNs.contains(target)) {
continue;
- Set depSet = new HashSet();
+ }
+ Set<String> depSet = new HashSet<>();
_dependencies.put(target, depSet);
- Set baseDepSet = (Set) base._dependencies.get(target);
- for (Iterator it2 = baseDepSet.iterator(); it2.hasNext(); )
- {
- String source = (String) it2.next();
- if (updatedNs.contains(source))
+ Set<String> baseDepSet = base._dependencies.get(target);
+ for (String source : baseDepSet) {
+ if (updatedNs.contains(source)) {
continue;
+ }
depSet.add(source);
}
}
- for (Iterator it = base._contributions.keySet().iterator(); it.hasNext(); )
- {
- String ns = (String) it.next();
- if (updatedNs.contains(ns))
+ for (String ns : base._contributions.keySet()) {
+ if (updatedNs.contains(ns)) {
continue;
- List fileList = new ArrayList();
+ }
+ List<String> fileList = new ArrayList<>();
_contributions.put(ns, fileList);
- List baseFileList = (List) base._contributions.get(ns);
- for (Iterator it2 = baseFileList.iterator(); it2.hasNext(); )
- fileList.add(it2.next());
+ fileList.addAll(base._contributions.get(ns));
}
}
- /**
- * Records the list of files associated to each namespace.
- * This is needed so that we can return a list of files that
- * need to be compiled once we get a set of altered namespaces
- */
- private Map/*<String,List<String>>*/ _contributions;
-
- void registerContribution(String ns, String fileURL)
- {
- List fileList = (List) _contributions.get(ns);
- if (fileList == null)
- {
- fileList = new ArrayList();
- _contributions.put(ns, fileList);
- }
- fileList.add(fileURL);
+ void registerContribution(String ns, String fileURL) {
+ _contributions.computeIfAbsent(ns, k -> new ArrayList<>()).add(fileURL);
}
- boolean isFileRepresented(String fileURL)
- {
- for (Iterator it = _contributions.values().iterator(); it.hasNext(); )
- {
- List fileList = (List) it.next();
- if (fileList.contains(fileURL))
- return true;
- }
- return false;
+ boolean isFileRepresented(String fileURL) {
+ return _contributions.values().stream().anyMatch(l -> l.contains(fileURL));
}
- List getFilesTouched(Set updatedNs)
- {
- List result = new ArrayList();
- for (Iterator it = updatedNs.iterator(); it.hasNext(); )
- {
- result.addAll((List) _contributions.get(it.next()));
- }
- return result;
+ List<String> getFilesTouched(Set<String> updatedNs) {
+ return updatedNs.stream().map(_contributions::get).
+ filter(Objects::nonNull).flatMap(List::stream).
+ collect(Collectors.toList());
}
- List getNamespacesTouched(Set modifiedFiles)
- {
- List result = new ArrayList();
- for (Iterator it = _contributions.keySet().iterator(); it.hasNext(); )
- {
- String ns = (String) it.next();
- List files = (List) _contributions.get(ns);
- for (int i = 0; i < files.size(); i++)
- if (modifiedFiles.contains(files.get(i)))
- result.add(ns);
- }
- return result;
+ List<String> getNamespacesTouched(Set<String> modifiedFiles) {
+ return _contributions.entrySet().stream().
+ filter(e -> e.getValue().stream().anyMatch(modifiedFiles::contains)).
+ map(Map.Entry::getKey).
+ collect(Collectors.toList());
}
}
Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java?rev=1881284&r1=1881283&r2=1881284&view=diff
==============================================================================
--- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java (original)
+++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java Fri Aug 28 20:49:50 2020
@@ -57,32 +57,15 @@ public final class SchemaTypeCodePrinter
getPrinter(opt).printType(writer, sType);
}
- /**
- * @deprecated
- */
- public static void printLoader(Writer writer, SchemaTypeSystem system,
- XmlOptions opt)
- throws IOException {
- getPrinter(opt).printLoader(writer, system);
- }
-
private static SchemaCodePrinter getPrinter(XmlOptions opt) {
- Object printer = XmlOptions.safeGet
- (opt, XmlOptions.SCHEMA_CODE_PRINTER);
- if (printer == null || !(printer instanceof SchemaCodePrinter)) {
- printer = new SchemaTypeCodePrinter(opt);
- }
- return (SchemaCodePrinter) printer;
+ SchemaCodePrinter printer = opt == null ? null : opt.getSchemaCodePrinter();
+ return printer == null ? new SchemaTypeCodePrinter(opt) : printer;
}
public SchemaTypeCodePrinter(XmlOptions opt) {
_indent = 0;
- String genversion = null;
-
- if (opt != null && XmlOptions.hasOption(opt, XmlOptions.GENERATE_JAVA_VERSION)) {
- genversion = (String) opt.get(XmlOptions.GENERATE_JAVA_VERSION);
- }
+ String genversion = (opt == null) ? null : opt.getGenerateJavaVersion();
if (genversion == null) {
genversion = XmlOptions.GENERATE_JAVA_14;
@@ -99,39 +82,6 @@ public final class SchemaTypeCodePrinter
_indent -= INDENT_INCREMENT;
}
- String encodeString(String s) {
- StringBuilder sb = new StringBuilder();
-
- sb.append('"');
-
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
-
- if (ch == '"') {
- sb.append('\\');
- sb.append('\"');
- } else if (ch == '\\') {
- sb.append('\\');
- sb.append('\\');
- } else if (ch == '\r') {
- sb.append('\\');
- sb.append('r');
- } else if (ch == '\n') {
- sb.append('\\');
- sb.append('n');
- } else if (ch == '\t') {
- sb.append('\\');
- sb.append('t');
- } else {
- sb.append(ch);
- }
- }
-
- sb.append('"');
-
- return sb.toString();
- }
-
void emit(String s) throws IOException {
int indent = _indent;
@@ -157,9 +107,6 @@ public final class SchemaTypeCodePrinter
private static String makeSafe(String s) {
Charset charset = Charset.forName(System.getProperty("file.encoding"));
- if (charset == null) {
- throw new IllegalStateException("Default character set is null!");
- }
CharsetEncoder cEncoder = charset.newEncoder();
StringBuilder result = new StringBuilder();
int i;
@@ -174,7 +121,7 @@ public final class SchemaTypeCodePrinter
if (cEncoder.canEncode(c)) {
result.append(c);
} else {
- String hexValue = Integer.toHexString((int) c);
+ String hexValue = Integer.toHexString(c);
switch (hexValue.length()) {
case 1:
result.append("\\u000").append(hexValue);
@@ -269,8 +216,8 @@ public final class SchemaTypeCodePrinter
case SchemaType.UNION:
emit(" * This is a union type. Instances are of one of the following types:");
SchemaType[] members = sType.getUnionConstituentTypes();
- for (int i = 0; i < members.length; i++) {
- emit(" * " + members[i].getFullJavaName());
+ for (SchemaType member : members) {
+ emit(" * " + member.getFullJavaName());
}
break;
}
@@ -310,26 +257,13 @@ public final class SchemaTypeCodePrinter
return name + "." + INDEX_CLASSNAME;
}
- static String shortIndexClassForSystem(SchemaTypeSystem system) {
- return INDEX_CLASSNAME;
- }
-
void printStaticTypeDeclaration(SchemaType sType, SchemaTypeSystem system) throws IOException {
- String interfaceShortName = sType.getShortJavaName();
emit("public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)");
indent();
emit("Factory.getTypeLoader().resolveHandle(\"" + ((SchemaTypeSystemImpl) system).handleForType(sType) + "\");");
outdent();
}
- /**
- * @deprecated
- */
- public void printLoader(Writer writer, SchemaTypeSystem system)
- throws IOException {
- // deprecated
- }
-
void printInnerType(SchemaType sType, SchemaTypeSystem system) throws IOException {
emit("");
@@ -350,9 +284,7 @@ public final class SchemaTypeCodePrinter
SchemaProperty[] props = getDerivedProperties(sType);
- for (int i = 0; i < props.length; i++) {
- SchemaProperty prop = props[i];
-
+ for (SchemaProperty prop : props) {
printPropertyGetters(
prop.getName(),
prop.isAttribute(),
@@ -549,11 +481,11 @@ public final class SchemaTypeCodePrinter
sType.getName().equals(sType.getBaseType().getName());
while (sType != null) {
SchemaType[] anonTypes = sType.getAnonymousTypes();
- for (int i = 0; i < anonTypes.length; i++) {
- if (anonTypes[i].isSkippedAnonymousType()) {
- printNestedInnerTypes(anonTypes[i], system);
+ for (SchemaType anonType : anonTypes) {
+ if (anonType.isSkippedAnonymousType()) {
+ printNestedInnerTypes(anonType, system);
} else {
- printInnerType(anonTypes[i], system);
+ printInnerType(anonType, system);
}
}
// For redefinition other than by extension for complex types, go ahead and print
@@ -658,8 +590,8 @@ public final class SchemaTypeCodePrinter
InterfaceExtension[] exts = sImpl.getInterfaceExtensions();
if (exts != null) {
- for (int i = 0; i < exts.length; i++) {
- sb.append(", " + exts[i].getInterface());
+ for (InterfaceExtension ext : exts) {
+ sb.append(", " + ext.getInterface());
}
}
@@ -808,10 +740,6 @@ public final class SchemaTypeCodePrinter
emit(" */");
}
- void printShortJavaDoc(String sentence) throws IOException {
- emit("/** " + sentence + " */");
- }
-
public static String javaStringEscape(String str) {
// forbidden: \n, \r, \", \\.
test:
@@ -864,17 +792,17 @@ public final class SchemaTypeCodePrinter
emit("");
SchemaStringEnumEntry[] entries = sType.getStringEnumEntries();
- HashSet seenValues = new HashSet();
- HashSet repeatValues = new HashSet();
- for (int i = 0; i < entries.length; i++) {
- String enumValue = entries[i].getString();
+ HashSet<String> seenValues = new HashSet<>();
+ HashSet<String> repeatValues = new HashSet<>();
+ for (SchemaStringEnumEntry entry : entries) {
+ String enumValue = entry.getString();
if (seenValues.contains(enumValue)) {
repeatValues.add(enumValue);
continue;
} else {
seenValues.add(enumValue);
}
- String constName = entries[i].getEnumName();
+ String constName = entry.getEnumName();
if (hasBase) {
emit("static final " + baseEnumClass + ".Enum " + constName + " = " + baseEnumClass + "." + constName + ";");
} else {
@@ -882,11 +810,11 @@ public final class SchemaTypeCodePrinter
}
}
emit("");
- for (int i = 0; i < entries.length; i++) {
- if (repeatValues.contains(entries[i].getString())) {
+ for (SchemaStringEnumEntry entry : entries) {
+ if (repeatValues.contains(entry.getString())) {
continue;
}
- String constName = "INT_" + entries[i].getEnumName();
+ String constName = "INT_" + entry.getEnumName();
if (hasBase) {
emit("static final int " + constName + " = " + baseEnumClass + "." + constName + ";");
} else {
@@ -929,9 +857,9 @@ public final class SchemaTypeCodePrinter
emit("private Enum(java.lang.String s, int i)");
emit(" { super(s, i); }");
emit("");
- for (int i = 0; i < entries.length; i++) {
- String constName = "INT_" + entries[i].getEnumName();
- int intValue = entries[i].getIntValue();
+ for (SchemaStringEnumEntry entry : entries) {
+ String constName = "INT_" + entry.getEnumName();
+ int intValue = entry.getIntValue();
emit("static final int " + constName + " = " + intValue + ";");
}
emit("");
@@ -942,9 +870,9 @@ public final class SchemaTypeCodePrinter
emit("new Enum[]");
emit("{");
indent();
- for (int i = 0; i < entries.length; i++) {
- String enumValue = entries[i].getString();
- String constName = "INT_" + entries[i].getEnumName();
+ for (SchemaStringEnumEntry entry : entries) {
+ String enumValue = entry.getString();
+ String constName = "INT_" + entry.getEnumName();
emit("new Enum(\"" + javaStringEscape(enumValue) + "\", " + constName + "),");
}
outdent();
@@ -984,8 +912,7 @@ public final class SchemaTypeCodePrinter
}
static boolean isJavaPrimitive(int javaType) {
- return (javaType < SchemaProperty.JAVA_FIRST_PRIMITIVE ? false :
- (javaType > SchemaProperty.JAVA_LAST_PRIMITIVE ? false : true));
+ return (javaType >= SchemaProperty.JAVA_FIRST_PRIMITIVE && (javaType <= SchemaProperty.JAVA_LAST_PRIMITIVE));
}
/**
@@ -1356,8 +1283,8 @@ public final class SchemaTypeCodePrinter
if (sType.getSimpleVariety() == SchemaType.UNION) {
SchemaType[] memberTypes = sType.getUnionMemberTypes();
- for (int i = 0; i < memberTypes.length; i++) {
- interfaces.append(", " + memberTypes[i].getFullJavaName().replace('$', '.'));
+ for (SchemaType memberType : memberTypes) {
+ interfaces.append(", " + memberType.getFullJavaName().replace('$', '.'));
}
}
@@ -1739,17 +1666,17 @@ public final class SchemaTypeCodePrinter
}
}
- String getIdentifier(Map qNameMap, QName qName) {
- return ((String[]) qNameMap.get(qName))[0];
+ String getIdentifier(Map<QName, String[]> qNameMap, QName qName) {
+ return qNameMap.get(qName)[0];
}
- String getSetIdentifier(Map qNameMap, QName qName) {
- String[] identifiers = (String[]) qNameMap.get(qName);
+ String getSetIdentifier(Map<QName, String[]> qNameMap, QName qName) {
+ String[] identifiers = qNameMap.get(qName);
return identifiers[1] == null ? identifiers[0] : identifiers[1];
}
- Map printStaticFields(SchemaProperty[] properties) throws IOException {
- final Map results = new HashMap();
+ Map<QName, String[]> printStaticFields(SchemaProperty[] properties) throws IOException {
+ final Map<QName, String[]> results = new HashMap<>();
emit("");
for (int i = 0; i < properties.length; i++) {
@@ -1777,9 +1704,9 @@ public final class SchemaTypeCodePrinter
emit("private static final org.apache.xmlbeans.QNameSet " + identifiers[1] +
" = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] { ");
indent();
- for (int j = 0; j < qnames.length; j++) {
- emit("new javax.xml.namespace.QName(\"" + qnames[j].getNamespaceURI() +
- "\", \"" + qnames[j].getLocalPart() + "\"),");
+ for (QName qname : qnames) {
+ emit("new javax.xml.namespace.QName(\"" + qname.getNamespaceURI() +
+ "\", \"" + qname.getLocalPart() + "\"),");
}
outdent();
@@ -2499,21 +2426,6 @@ public final class SchemaTypeCodePrinter
}
}
- static void getTypeName(Class c, StringBuffer sb) {
- int arrayCount = 0;
- while (c.isArray()) {
- c = c.getComponentType();
- arrayCount++;
- }
-
- sb.append(c.getName());
-
- for (int i = 0; i < arrayCount; i++) {
- sb.append("[]");
- }
-
- }
-
void printInnerTypeImpl(
SchemaType sType, SchemaTypeSystem system, boolean isInner) throws IOException {
String shortName = sType.getShortJavaImplName();
@@ -2538,16 +2450,16 @@ public final class SchemaTypeCodePrinter
// but we still need to implement them because this class is supposed to
// also implement all the interfaces
SchemaType baseType = sType.getBaseType();
- List extraProperties = null;
+ List<SchemaProperty> extraProperties = null;
while (!baseType.isSimpleType() && !baseType.isBuiltinType()) {
SchemaProperty[] baseProperties = baseType.getDerivedProperties();
- for (int i = 0; i < baseProperties.length; i++) {
- if (!(baseProperties[i].isAttribute() &&
- sType.getAttributeProperty(baseProperties[i].getName()) != null)) {
+ for (SchemaProperty baseProperty : baseProperties) {
+ if (!(baseProperty.isAttribute() &&
+ sType.getAttributeProperty(baseProperty.getName()) != null)) {
if (extraProperties == null) {
- extraProperties = new ArrayList();
+ extraProperties = new ArrayList<>();
}
- extraProperties.add(baseProperties[i]);
+ extraProperties.add(baseProperty);
}
}
baseType = baseType.getBaseType();
@@ -2555,11 +2467,8 @@ public final class SchemaTypeCodePrinter
properties = sType.getProperties();
if (extraProperties != null) {
- for (int i = 0; i < properties.length; i++) {
- extraProperties.add(properties[i]);
- }
- properties = (SchemaProperty[]) extraProperties.
- toArray(new SchemaProperty[extraProperties.size()]);
+ Collections.addAll(extraProperties, properties);
+ properties = extraProperties.toArray(new SchemaProperty[0]);
}
} else {
// complex content type implementations derive from base type impls
@@ -2568,11 +2477,9 @@ public final class SchemaTypeCodePrinter
properties = getDerivedProperties(sType);
}
- Map qNameMap = printStaticFields(properties);
-
- for (int i = 0; i < properties.length; i++) {
- SchemaProperty prop = properties[i];
+ Map<QName, String[]> qNameMap = printStaticFields(properties);
+ for (SchemaProperty prop : properties) {
QName name = prop.getName();
String xmlType = xmlTypeForProperty(prop);
@@ -2631,20 +2538,20 @@ public final class SchemaTypeCodePrinter
// not present in sType, because the redefined types do not
// have a generated class to represent them
SchemaProperty[] props = sType.getDerivedProperties();
- Map propsByName = new LinkedHashMap();
- for (int i = 0; i < props.length; i++) {
- propsByName.put(props[i].getName(), props[i]);
+ Map<QName, SchemaProperty> propsByName = new LinkedHashMap<>();
+ for (SchemaProperty prop : props) {
+ propsByName.put(prop.getName(), prop);
}
while (sType2 != null && name.equals(sType2.getName())) {
props = sType2.getDerivedProperties();
- for (int i = 0; i < props.length; i++) {
- if (!propsByName.containsKey(props[i].getName())) {
- propsByName.put(props[i].getName(), props[i]);
+ for (SchemaProperty prop : props) {
+ if (!propsByName.containsKey(prop.getName())) {
+ propsByName.put(prop.getName(), prop);
}
}
sType2 = sType2.getBaseType();
}
- return (SchemaProperty[]) propsByName.values().toArray(new SchemaProperty[0]);
+ return propsByName.values().toArray(new SchemaProperty[0]);
} else {
return sType.getDerivedProperties();
}
@@ -2658,14 +2565,14 @@ public final class SchemaTypeCodePrinter
InterfaceExtension[] exts = sImpl.getInterfaceExtensions();
if (exts != null) {
- for (int i = 0; i < exts.length; i++) {
- InterfaceExtension.MethodSignature[] methods = exts[i].getMethods();
+ for (InterfaceExtension ext : exts) {
+ InterfaceExtension.MethodSignature[] methods = ext.getMethods();
if (methods != null) {
- for (int j = 0; j < methods.length; j++) {
- printJavaDoc("Implementation method for interface " + exts[i].getStaticHandler());
- printInterfaceMethodDecl(methods[j]);
+ for (InterfaceExtension.MethodSignature method : methods) {
+ printJavaDoc("Implementation method for interface " + ext.getStaticHandler());
+ printInterfaceMethodDecl(method);
startBlock();
- printInterfaceMethodImpl(exts[i].getStaticHandler(), methods[j]);
+ printInterfaceMethodImpl(ext.getStaticHandler(), method);
endBlock();
}
}
@@ -2721,11 +2628,11 @@ public final class SchemaTypeCodePrinter
sType.getName().equals(sType.getBaseType().getName());
while (sType != null) {
SchemaType[] anonTypes = sType.getAnonymousTypes();
- for (int i = 0; i < anonTypes.length; i++) {
- if (anonTypes[i].isSkippedAnonymousType()) {
- printNestedTypeImpls(anonTypes[i], system);
+ for (SchemaType anonType : anonTypes) {
+ if (anonType.isSkippedAnonymousType()) {
+ printNestedTypeImpls(anonType, system);
} else {
- printInnerTypeImpl(anonTypes[i], system, true);
+ printInnerTypeImpl(anonType, system, true);
}
}
// For redefinition by extension, go ahead and print the anonymous
Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java?rev=1881284&r1=1881283&r2=1881284&view=diff
==============================================================================
--- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java (original)
+++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java Fri Aug 28 20:49:50 2020
@@ -15,172 +15,134 @@
package org.apache.xmlbeans.impl.schema;
+import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.common.QNameHelper;
-import org.apache.xmlbeans.impl.validator.ValidatingXMLInputStream;
-
import org.apache.xmlbeans.impl.store.Locale;
+import org.apache.xmlbeans.impl.validator.ValidatingXMLInputStream;
+import org.apache.xmlbeans.xml.stream.XMLInputStream;
+import org.apache.xmlbeans.xml.stream.XMLStreamException;
+import org.w3c.dom.DOMImplementation;
+import org.w3c.dom.Node;
-import org.apache.xmlbeans.SchemaAttributeGroup;
-import org.apache.xmlbeans.SchemaField;
-import org.apache.xmlbeans.SchemaGlobalAttribute;
-import org.apache.xmlbeans.SchemaGlobalElement;
-import org.apache.xmlbeans.SchemaModelGroup;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.SchemaTypeLoader;
-import org.apache.xmlbeans.XmlSaxHandler;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.XmlFactoryHook;
-import org.apache.xmlbeans.XmlBeans;
-
-import java.lang.reflect.Method;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamReader;
+import java.io.*;
import java.lang.reflect.InvocationTargetException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.File;
-import java.io.IOException;
-import java.io.FileInputStream;
-import java.util.List;
-import java.util.ArrayList;
+import java.lang.reflect.Method;
+import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
-import java.net.HttpURLConnection;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.List;
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLStreamReader;
-
-import org.w3c.dom.Node;
-import org.w3c.dom.DOMImplementation;
-
-import org.apache.xmlbeans.xml.stream.XMLInputStream;
-import org.apache.xmlbeans.xml.stream.XMLStreamException;
-
-public abstract class SchemaTypeLoaderBase implements SchemaTypeLoader
-{
+public abstract class SchemaTypeLoaderBase implements SchemaTypeLoader {
private static final String USER_AGENT = "XMLBeans/" + XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")";
- private static final Method _pathCompiler = getMethod( "org.apache.xmlbeans.impl.store.Path", "compilePath", new Class[] { String.class, XmlOptions.class } );
- private static final Method _queryCompiler = getMethod( "org.apache.xmlbeans.impl.store.Query", "compileQuery", new Class[] { String.class, XmlOptions.class } );
+ private static final Method _pathCompiler = getMethod("org.apache.xmlbeans.impl.store.Path", "compilePath", new Class[]{String.class, XmlOptions.class});
+ private static final Method _queryCompiler = getMethod("org.apache.xmlbeans.impl.store.Query", "compileQuery", new Class[]{String.class, XmlOptions.class});
- private static Method getMethod ( String className, String methodName, Class[] args )
- {
- try
- {
+ private static Method getMethod(String className, String methodName, Class[] args) {
+ try {
return
- Class.forName( className ).
- getDeclaredMethod( methodName, args );
- }
- catch (Exception e)
- {
+ Class.forName(className).
+ getDeclaredMethod(methodName, args);
+ } catch (Exception e) {
throw new IllegalStateException(
"Cannot find " + className + "." + methodName +
- ". verify that xmlstore " +
- "(from xbean.jar) is on classpath" );
+ ". verify that xmlstore " +
+ "(from xbean.jar) is on classpath");
}
}
- private static Object invokeMethod ( Method method, Object[] args )
- {
- try
- {
- return method.invoke( method, args );
- }
- catch ( InvocationTargetException e )
- {
+ private static Object invokeMethod(Method method, Object[] args) {
+ try {
+ return method.invoke(method, args);
+ } catch (InvocationTargetException e) {
Throwable t = e.getCause();
- IllegalStateException ise = new IllegalStateException( t.getMessage() );
- ise.initCause( t ); // need initCause() to support Java1.4
- throw ise;
- }
- catch ( Exception e )
- {
- IllegalStateException ise = new IllegalStateException( e.getMessage() );
- ise.initCause( e );
- throw ise;
+ throw new IllegalStateException(t.getMessage(), t);
+ } catch (Exception e) {
+ throw new IllegalStateException(e.getMessage(), e);
}
}
- private static String doCompilePath ( String pathExpr, XmlOptions options )
- {
- return (String) invokeMethod( _pathCompiler, new Object[] { pathExpr, options } );
+ private static String doCompilePath(String pathExpr, XmlOptions options) {
+ return (String) invokeMethod(_pathCompiler, new Object[]{pathExpr, options});
}
- private static String doCompileQuery ( String queryExpr, XmlOptions options )
- {
- return (String) invokeMethod( _queryCompiler, new Object[] { queryExpr, options } );
+ private static String doCompileQuery(String queryExpr, XmlOptions options) {
+ return (String) invokeMethod(_queryCompiler, new Object[]{queryExpr, options});
}
- public SchemaType findType(QName name)
- {
+ public SchemaType findType(QName name) {
SchemaType.Ref ref = findTypeRef(name);
- if (ref == null)
+ if (ref == null) {
return null;
+ }
SchemaType result = ref.get();
- assert(result != null);
+ assert (result != null);
return result;
}
- public SchemaType findDocumentType(QName name)
- {
+ public SchemaType findDocumentType(QName name) {
SchemaType.Ref ref = findDocumentTypeRef(name);
- if (ref == null)
+ if (ref == null) {
return null;
+ }
SchemaType result = ref.get();
- assert(result != null);
+ assert (result != null);
return result;
}
- public SchemaType findAttributeType(QName name)
- {
+ public SchemaType findAttributeType(QName name) {
SchemaType.Ref ref = findAttributeTypeRef(name);
- if (ref == null)
+ if (ref == null) {
return null;
+ }
SchemaType result = ref.get();
- assert(result != null);
+ assert (result != null);
return result;
}
- public SchemaModelGroup findModelGroup(QName name)
- {
+ public SchemaModelGroup findModelGroup(QName name) {
SchemaModelGroup.Ref ref = findModelGroupRef(name);
- if (ref == null)
+ if (ref == null) {
return null;
+ }
SchemaModelGroup result = ref.get();
- assert(result != null);
+ assert (result != null);
return result;
}
- public SchemaAttributeGroup findAttributeGroup(QName name)
- {
+ public SchemaAttributeGroup findAttributeGroup(QName name) {
SchemaAttributeGroup.Ref ref = findAttributeGroupRef(name);
- if (ref == null)
+ if (ref == null) {
return null;
+ }
SchemaAttributeGroup result = ref.get();
- assert(result != null);
+ assert (result != null);
return result;
}
- public SchemaGlobalElement findElement(QName name)
- {
+ public SchemaGlobalElement findElement(QName name) {
SchemaGlobalElement.Ref ref = findElementRef(name);
- if (ref == null)
+ if (ref == null) {
return null;
+ }
SchemaGlobalElement result = ref.get();
- assert(result != null);
+ assert (result != null);
return result;
}
- public SchemaGlobalAttribute findAttribute(QName name)
- {
+ public SchemaGlobalAttribute findAttribute(QName name) {
SchemaGlobalAttribute.Ref ref = findAttributeRef(name);
- if (ref == null)
+ if (ref == null) {
return null;
+ }
SchemaGlobalAttribute result = ref.get();
- assert(result != null);
+ assert (result != null);
return result;
}
@@ -188,264 +150,225 @@ public abstract class SchemaTypeLoaderBa
//
//
- public XmlObject newInstance ( SchemaType type, XmlOptions options )
- {
+ public XmlObject newInstance(SchemaType type, XmlOptions options) {
XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-
- if (hook != null)
- return hook.newInstance( this, type, options );
- return Locale.newInstance( this, type, options );
+ if (hook != null) {
+ return hook.newInstance(this, type, options);
+ }
+
+ return Locale.newInstance(this, type, options);
}
- public XmlObject parse ( String xmlText, SchemaType type, XmlOptions options ) throws XmlException
- {
+ public XmlObject parse(String xmlText, SchemaType type, XmlOptions options) throws XmlException {
XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-
- if (hook != null)
- return hook.parse( this, xmlText, type, options );
- return Locale.parseToXmlObject( this, xmlText, type, options );
+ if (hook != null) {
+ return hook.parse(this, xmlText, type, options);
+ }
+
+ return Locale.parseToXmlObject(this, xmlText, type, options);
}
/**
* @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API.
*/
- public XmlObject parse ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException
- {
+ public XmlObject parse(XMLInputStream xis, SchemaType type, XmlOptions options) throws XmlException, XMLStreamException {
XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-
- if (hook != null)
- return hook.parse( this, xis, type, options );
-
- return Locale.parseToXmlObject( this, xis, type, options );
+
+ if (hook != null) {
+ return hook.parse(this, xis, type, options);
+ }
+
+ return Locale.parseToXmlObject(this, xis, type, options);
}
- public XmlObject parse ( XMLStreamReader xsr, SchemaType type, XmlOptions options ) throws XmlException
- {
+ public XmlObject parse(XMLStreamReader xsr, SchemaType type, XmlOptions options) throws XmlException {
XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-
- if (hook != null)
- return hook.parse( this, xsr, type, options );
-
- return Locale.parseToXmlObject( this, xsr, type, options );
- }
-
- public XmlObject parse ( File file, SchemaType type, XmlOptions options ) throws XmlException, IOException
- {
- if (options == null)
- {
- options = new XmlOptions();
- options.put( XmlOptions.DOCUMENT_SOURCE_NAME, file.toURI().normalize().toString() );
- }
- else if (! options.hasOption(XmlOptions.DOCUMENT_SOURCE_NAME))
- {
- options = new XmlOptions( options );
- options.put( XmlOptions.DOCUMENT_SOURCE_NAME, file.toURI().normalize().toString() );
+ if (hook != null) {
+ return hook.parse(this, xsr, type, options);
}
- InputStream fis = new FileInputStream( file );
+ return Locale.parseToXmlObject(this, xsr, type, options);
+ }
- try
- {
- return parse( fis, type, options );
+ public XmlObject parse(File file, SchemaType type, XmlOptions options) throws XmlException, IOException {
+ String fileName = file.toURI().normalize().toString();
+ if (options == null) {
+ options = new XmlOptions();
+ options.setDocumentSourceName(fileName);
+ } else if (options.getDocumentSourceName() == null) {
+ options = new XmlOptions(options);
+ options.setDocumentSourceName(fileName);
}
- finally
- {
- fis.close();
+
+ try (InputStream fis = new FileInputStream(file)) {
+ return parse(fis, type, options);
}
}
- public XmlObject parse ( URL url, SchemaType type, XmlOptions options ) throws XmlException, IOException
- {
- if (options == null)
- {
+ public XmlObject parse(URL url, SchemaType type, XmlOptions options) throws XmlException, IOException {
+ if (options == null) {
options = new XmlOptions();
- options.put( XmlOptions.DOCUMENT_SOURCE_NAME, url.toString() );
+ options.setDocumentSourceName(url.toString());
+ } else if (options.getDocumentSourceName() == null) {
+ options = new XmlOptions(options);
+ options.setDocumentSourceName(url.toString());
}
- else if (! options.hasOption(XmlOptions.DOCUMENT_SOURCE_NAME))
- {
- options = new XmlOptions( options );
- options.put( XmlOptions.DOCUMENT_SOURCE_NAME, url.toString() );
- }
-
- URLConnection conn = null;
- InputStream stream = null;
- download: try
- {
-
- boolean redirected = false;
- int count = 0;
-
- do {
- conn = url.openConnection();
- conn.addRequestProperty("User-Agent", USER_AGENT);
- conn.addRequestProperty("Accept", "application/xml, text/xml, */*");
- if (conn instanceof HttpURLConnection)
- {
- HttpURLConnection httpcon = (HttpURLConnection)conn;
- int code = httpcon.getResponseCode();
- redirected = (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP);
- if (redirected && count > 5)
- redirected = false;
- if (redirected)
- {
- String newLocation = httpcon.getHeaderField("Location");
- if (newLocation == null)
- redirected = false;
- else
- {
- url = new URL(newLocation);
- count ++;
- }
+ boolean redirected = false;
+ int count = 0;
+ URLConnection conn;
+
+ do {
+ conn = url.openConnection();
+ conn.addRequestProperty("User-Agent", USER_AGENT);
+ conn.addRequestProperty("Accept", "application/xml, text/xml, */*");
+ if (conn instanceof HttpURLConnection) {
+ HttpURLConnection httpcon = (HttpURLConnection) conn;
+ int code = httpcon.getResponseCode();
+ redirected = (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP);
+ if (redirected && count > 5) {
+ redirected = false;
+ }
+
+ if (redirected) {
+ String newLocation = httpcon.getHeaderField("Location");
+ if (newLocation == null) {
+ redirected = false;
+ } else {
+ url = new URL(newLocation);
+ count++;
}
}
- } while (redirected);
+ }
+ } while (redirected);
- stream = conn.getInputStream();
- return parse( stream, type, options );
- }
- finally
- {
- if (stream != null)
- stream.close();
+ try (InputStream stream = conn.getInputStream()) {
+ return parse(stream, type, options);
}
}
- public XmlObject parse ( InputStream jiois, SchemaType type, XmlOptions options ) throws XmlException, IOException
- {
+ public XmlObject parse(InputStream jiois, SchemaType type, XmlOptions options) throws XmlException, IOException {
XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-
+
DigestInputStream digestStream = null;
-
+
setupDigest:
- if (options != null && options.hasOption( XmlOptions.LOAD_MESSAGE_DIGEST ))
- {
+ if (options != null && options.isLoadMessageDigest()) {
MessageDigest sha;
-
- try
- {
+
+ try {
sha = MessageDigest.getInstance("SHA");
- }
- catch (NoSuchAlgorithmException e)
- {
+ } catch (NoSuchAlgorithmException e) {
break setupDigest;
}
- digestStream = new DigestInputStream( jiois, sha );
+ digestStream = new DigestInputStream(jiois, sha);
jiois = digestStream;
}
- if (hook != null)
- return hook.parse( this, jiois, type, options );
+ if (hook != null) {
+ return hook.parse(this, jiois, type, options);
+ }
- XmlObject result = Locale.parseToXmlObject( this, jiois, type, options );
+ XmlObject result = Locale.parseToXmlObject(this, jiois, type, options);
- if (digestStream != null)
- result.documentProperties().setMessageDigest( digestStream.getMessageDigest().digest() );
+ if (digestStream != null) {
+ result.documentProperties().setMessageDigest(digestStream.getMessageDigest().digest());
+ }
return result;
}
- public XmlObject parse ( Reader jior, SchemaType type, XmlOptions options ) throws XmlException, IOException
- {
+ public XmlObject parse(Reader jior, SchemaType type, XmlOptions options) throws XmlException, IOException {
XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-
- if (hook != null)
- return hook.parse( this, jior, type, options );
- return Locale.parseToXmlObject( this, jior, type, options );
+ if (hook != null) {
+ return hook.parse(this, jior, type, options);
+ }
+
+ return Locale.parseToXmlObject(this, jior, type, options);
}
- public XmlObject parse ( Node node, SchemaType type, XmlOptions options ) throws XmlException
- {
+ public XmlObject parse(Node node, SchemaType type, XmlOptions options) throws XmlException {
XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-
- if (hook != null)
- return hook.parse( this, node, type, options );
- return Locale.parseToXmlObject( this, node, type, options );
+ if (hook != null) {
+ return hook.parse(this, node, type, options);
+ }
+
+ return Locale.parseToXmlObject(this, node, type, options);
}
- public XmlSaxHandler newXmlSaxHandler ( SchemaType type, XmlOptions options )
- {
+ public XmlSaxHandler newXmlSaxHandler(SchemaType type, XmlOptions options) {
XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-
- if (hook != null)
- return hook.newXmlSaxHandler( this, type, options );
- return Locale.newSaxHandler( this, type, options );
+ if (hook != null) {
+ return hook.newXmlSaxHandler(this, type, options);
+ }
+
+ return Locale.newSaxHandler(this, type, options);
}
- public DOMImplementation newDomImplementation ( XmlOptions options )
- {
- return Locale.newDomImplementation( this, options );
+ public DOMImplementation newDomImplementation(XmlOptions options) {
+ return Locale.newDomImplementation(this, options);
}
/**
* @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API.
*/
- public XMLInputStream newValidatingXMLInputStream ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException
- {
- return new ValidatingXMLInputStream( xis, this, type, options );
+ public XMLInputStream newValidatingXMLInputStream(XMLInputStream xis, SchemaType type, XmlOptions options) throws XmlException, XMLStreamException {
+ return new ValidatingXMLInputStream(xis, this, type, options);
}
//
//
//
- public String compilePath ( String pathExpr )
- {
- return compilePath( pathExpr, null );
+ public String compilePath(String pathExpr) {
+ return compilePath(pathExpr, null);
}
- public String compilePath ( String pathExpr, XmlOptions options )
- {
- return doCompilePath( pathExpr, options );
+ public String compilePath(String pathExpr, XmlOptions options) {
+ return doCompilePath(pathExpr, options);
}
- public String compileQuery ( String queryExpr )
- {
- return compileQuery( queryExpr, null );
+ public String compileQuery(String queryExpr) {
+ return compileQuery(queryExpr, null);
}
- public String compileQuery ( String queryExpr, XmlOptions options )
- {
- return doCompileQuery( queryExpr, options );
+ public String compileQuery(String queryExpr, XmlOptions options) {
+ return doCompileQuery(queryExpr, options);
}
/**
* Utility function to load a type from a signature.
- *
+ * <p>
* A signature is the string you get from type.toString().
*/
- public SchemaType typeForSignature(String signature)
- {
+ public SchemaType typeForSignature(String signature) {
int end = signature.indexOf('@');
String uri;
- if (end < 0)
- {
+ if (end < 0) {
uri = "";
end = signature.length();
- }
- else
- {
+ } else {
uri = signature.substring(end + 1);
}
- List parts = new ArrayList();
+ List<String> parts = new ArrayList<>();
- for (int index = 0; index < end; )
- {
+ for (int index = 0; index < end; ) {
int nextc = signature.indexOf(':', index);
int nextd = signature.indexOf('|', index);
- int next = (nextc < 0 ? nextd : nextd < 0 ? nextc : nextc < nextd ? nextc : nextd);
- if (next < 0 || next > end)
+ int next = (nextc < 0 ? nextd : nextd < 0 ? nextc : Math.min(nextc, nextd));
+ if (next < 0 || next > end) {
next = end;
+ }
String part = signature.substring(index, next);
parts.add(part);
index = next + 1;
@@ -453,149 +376,143 @@ public abstract class SchemaTypeLoaderBa
SchemaType curType = null;
- outer: for (int i = parts.size() - 1; i >= 0; i -= 1)
- {
- String part = (String)parts.get(i);
- if (part.length() < 1)
+ for (int i = parts.size() - 1; i >= 0; i -= 1) {
+ String part = parts.get(i);
+ if (part.length() < 1) {
throw new IllegalArgumentException();
+ }
int offset = (part.length() >= 2 && part.charAt(1) == '=') ? 2 : 1;
- cases: switch (part.charAt(0))
- {
+ cases:
+ switch (part.charAt(0)) {
case 'T':
- if (curType != null)
+ if (curType != null) {
throw new IllegalArgumentException();
+ }
curType = findType(QNameHelper.forLNS(part.substring(offset), uri));
- if (curType == null)
+ if (curType == null) {
return null;
+ }
break;
case 'D':
- if (curType != null)
+ if (curType != null) {
throw new IllegalArgumentException();
+ }
curType = findDocumentType(QNameHelper.forLNS(part.substring(offset), uri));
- if (curType == null)
+ if (curType == null) {
return null;
+ }
break;
case 'C': // deprecated
case 'R': // current
- if (curType != null)
+ if (curType != null) {
throw new IllegalArgumentException();
+ }
curType = findAttributeType(QNameHelper.forLNS(part.substring(offset), uri));
- if (curType == null)
+ if (curType == null) {
return null;
+ }
break;
case 'E':
case 'U': // distinguish qualified/unqualified TBD
- if (curType != null)
- {
- if (curType.getContentType() < SchemaType.ELEMENT_CONTENT)
+ if (curType != null) {
+ if (curType.getContentType() < SchemaType.ELEMENT_CONTENT) {
return null;
+ }
SchemaType[] subTypes = curType.getAnonymousTypes();
String localName = part.substring(offset);
- for (int j = 0; j < subTypes.length; j++)
- {
- SchemaField field = subTypes[j].getContainerField();
- if (field != null && !field.isAttribute() && field.getName().getLocalPart().equals(localName))
- {
- curType = subTypes[j];
+ for (SchemaType subType : subTypes) {
+ SchemaField field = subType.getContainerField();
+ if (field != null && !field.isAttribute() && field.getName().getLocalPart().equals(localName)) {
+ curType = subType;
break cases;
}
}
return null;
- }
- else
- {
+ } else {
SchemaGlobalElement elt = findElement(QNameHelper.forLNS(part.substring(offset), uri));
- if (elt == null)
+ if (elt == null) {
return null;
+ }
curType = elt.getType();
}
break;
case 'A':
case 'Q': // distinguish qualified/unqualified TBD
- if (curType != null)
- {
- if (curType.isSimpleType())
+ if (curType != null) {
+ if (curType.isSimpleType()) {
return null;
+ }
SchemaType[] subTypes = curType.getAnonymousTypes();
String localName = part.substring(offset);
- for (int j = 0; j < subTypes.length; j++)
- {
- SchemaField field = subTypes[j].getContainerField();
- if (field != null && field.isAttribute() && field.getName().getLocalPart().equals(localName))
- {
- curType = subTypes[j];
+ for (SchemaType subType : subTypes) {
+ SchemaField field = subType.getContainerField();
+ if (field != null && field.isAttribute() && field.getName().getLocalPart().equals(localName)) {
+ curType = subType;
break cases;
}
}
return null;
- }
- else
- {
+ } else {
SchemaGlobalAttribute attr = findAttribute(QNameHelper.forLNS(part.substring(offset), uri));
- if (attr == null)
+ if (attr == null) {
return null;
+ }
curType = attr.getType();
}
break;
case 'B':
- if (curType == null)
- {
+ if (curType == null) {
throw new IllegalArgumentException();
- }
- else
- {
- if (curType.getSimpleVariety() != SchemaType.ATOMIC)
+ } else {
+ if (curType.getSimpleVariety() != SchemaType.ATOMIC) {
return null;
+ }
SchemaType[] subTypes = curType.getAnonymousTypes();
- if (subTypes.length != 1)
+ if (subTypes.length != 1) {
return null;
+ }
curType = subTypes[0];
}
break;
case 'I':
- if (curType == null)
- {
+ if (curType == null) {
throw new IllegalArgumentException();
- }
- else
- {
- if (curType.getSimpleVariety() != SchemaType.LIST)
+ } else {
+ if (curType.getSimpleVariety() != SchemaType.LIST) {
return null;
+ }
SchemaType[] subTypes = curType.getAnonymousTypes();
- if (subTypes.length != 1)
+ if (subTypes.length != 1) {
return null;
+ }
curType = subTypes[0];
}
break;
case 'M':
- if (curType == null)
- {
+ if (curType == null) {
throw new IllegalArgumentException();
- }
- else
- {
+ } else {
int index;
- try
- {
+ try {
index = Integer.parseInt(part.substring(offset));
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
throw new IllegalArgumentException();
}
- if (curType.getSimpleVariety() != SchemaType.UNION)
+ if (curType.getSimpleVariety() != SchemaType.UNION) {
return null;
+ }
SchemaType[] subTypes = curType.getAnonymousTypes();
- if (subTypes.length <= index)
+ if (subTypes.length <= index) {
return null;
+ }
curType = subTypes[index];
}
break;
Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java?rev=1881284&r1=1881283&r2=1881284&view=diff
==============================================================================
--- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java (original)
+++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java Fri Aug 28 20:49:50 2020
@@ -34,10 +34,10 @@ public class SchemaTypeSystemCompiler {
private BindingConfig config;
private SchemaTypeLoader linkTo;
private XmlOptions options;
- private Collection errorListener;
+ private Collection<XmlError> errorListener;
private boolean javaize;
private URI baseURI;
- private Map sourcesToCopyMap;
+ private Map<String, String> sourcesToCopyMap;
private File schemasDir;
public SchemaTypeSystem getExistingTypeSystem() {
@@ -88,11 +88,11 @@ public class SchemaTypeSystemCompiler {
this.options = options;
}
- public Collection getErrorListener() {
+ public Collection<XmlError> getErrorListener() {
return errorListener;
}
- public void setErrorListener(Collection errorListener) {
+ public void setErrorListener(Collection<XmlError> errorListener) {
this.errorListener = errorListener;
}
@@ -112,11 +112,11 @@ public class SchemaTypeSystemCompiler {
this.baseURI = baseURI;
}
- public Map getSourcesToCopyMap() {
+ public Map<String, String> getSourcesToCopyMap() {
return sourcesToCopyMap;
}
- public void setSourcesToCopyMap(Map sourcesToCopyMap) {
+ public void setSourcesToCopyMap(Map<String, String> sourcesToCopyMap) {
this.sourcesToCopyMap = sourcesToCopyMap;
}
@@ -152,12 +152,12 @@ public class SchemaTypeSystemCompiler {
XmlObject[] input, BindingConfig config, SchemaTypeLoader linkTo, Filer filer, XmlOptions options)
throws XmlException {
options = XmlOptions.maskNull(options);
- ArrayList schemas = new ArrayList();
+ ArrayList<Schema> schemas = new ArrayList<>();
if (input != null) {
for (int i = 0; i < input.length; i++) {
if (input[i] instanceof Schema) {
- schemas.add(input[i]);
+ schemas.add((Schema) input[i]);
} else if (input[i] instanceof SchemaDocument && ((SchemaDocument) input[i]).getSchema() != null) {
schemas.add(((SchemaDocument) input[i]).getSchema());
} else {
@@ -166,12 +166,12 @@ public class SchemaTypeSystemCompiler {
}
}
- Collection userErrors = (Collection) options.get(XmlOptions.ERROR_LISTENER);
+ Collection<XmlError> userErrors = options.getErrorListener();
XmlErrorWatcher errorWatcher = new XmlErrorWatcher(userErrors);
SchemaTypeSystemImpl stsi = compileImpl(existingSTS, name,
- (Schema[]) schemas.toArray(new Schema[schemas.size()]),
- config, linkTo, options, errorWatcher, filer != null, (URI) options.get(XmlOptions.BASE_URI),
+ schemas.toArray(new Schema[0]),
+ config, linkTo, options, errorWatcher, filer != null, options.getBaseURI(),
null, null);
// if there is an error and compile didn't recover (stsi==null), throw exception
@@ -193,8 +193,8 @@ public class SchemaTypeSystemCompiler {
/* package */
static SchemaTypeSystemImpl compileImpl(SchemaTypeSystem system, String name,
Schema[] schemas, BindingConfig config, SchemaTypeLoader linkTo,
- XmlOptions options, Collection outsideErrors, boolean javaize,
- URI baseURI, Map sourcesToCopyMap, File schemasDir) {
+ XmlOptions options, Collection<XmlError> outsideErrors, boolean javaize,
+ URI baseURI, Map<String, String> sourcesToCopyMap, File schemasDir) {
if (linkTo == null) {
throw new IllegalArgumentException("Must supply linkTo");
}
@@ -204,7 +204,7 @@ public class SchemaTypeSystemCompiler {
// construct the state
StscState state = StscState.start();
- boolean validate = (options == null || !options.hasOption(XmlOptions.COMPILE_NO_VALIDATION));
+ boolean validate = (options == null || !options.isCompileNoValidation());
try {
state.setErrorListener(errorWatcher);
state.setBindingConfig(config);
@@ -219,27 +219,27 @@ public class SchemaTypeSystemCompiler {
linkTo = SchemaTypeLoaderImpl.build(new SchemaTypeLoader[]{BuiltinSchemaTypeSystem.get(), linkTo}, null, null);
state.setImportingTypeLoader(linkTo);
- List validSchemas = new ArrayList(schemas.length);
+ List<Schema> validSchemas = new ArrayList<>(schemas.length);
// load all the xsd files into it
if (validate) {
XmlOptions validateOptions = new XmlOptions().setErrorListener(errorWatcher);
- if (options.hasOption(XmlOptions.VALIDATE_TREAT_LAX_AS_SKIP)) {
+ if (options != null && options.isValidateTreatLaxAsSkip()) {
validateOptions.setValidateTreatLaxAsSkip();
}
- for (int i = 0; i < schemas.length; i++) {
- if (schemas[i].validate(validateOptions)) {
- validSchemas.add(schemas[i]);
+ for (Schema schema : schemas) {
+ if (schema.validate(validateOptions)) {
+ validSchemas.add(schema);
}
}
} else {
validSchemas.addAll(Arrays.asList(schemas));
}
- Schema[] startWith = (Schema[]) validSchemas.toArray(new Schema[validSchemas.size()]);
+ Schema[] startWith = validSchemas.toArray(new Schema[0]);
if (incremental) {
- Set namespaces = new HashSet();
+ Set<String> namespaces = new HashSet<>();
startWith = getSchemasToRecompile((SchemaTypeSystemImpl) system, startWith, namespaces);
state.initFromTypeSystem((SchemaTypeSystemImpl) system, namespaces);
} else {
@@ -262,7 +262,7 @@ public class SchemaTypeSystemCompiler {
StscJavaizer.javaizeAllTypes(javaize);
// construct the loader out of the state
- state.get().sts().loadFromStscState(state);
+ StscState.get().sts().loadFromStscState(state);
// fill in the source-copy map
if (sourcesToCopyMap != null) {
@@ -273,7 +273,7 @@ public class SchemaTypeSystemCompiler {
// EXPERIMENTAL: recovery from compilation errors and partial type system
if (state.allowPartial() && state.getRecovered() == errorWatcher.size()) {
// if partial type system allowed and all errors were recovered
- state.get().sts().setIncomplete(true);
+ StscState.get().sts().setIncomplete(true);
} else {
// if any non-recoverable errors, return null
return null;
@@ -284,7 +284,7 @@ public class SchemaTypeSystemCompiler {
((SchemaTypeSystemImpl) system).setIncomplete(true);
}
- return state.get().sts();
+ return StscState.get().sts();
} finally {
StscState.end();
}
@@ -297,29 +297,28 @@ public class SchemaTypeSystemCompiler {
* and of the entity resolvers that have been set up
*/
private static Schema[] getSchemasToRecompile(SchemaTypeSystemImpl system,
- Schema[] modified, Set namespaces) {
- Set modifiedFiles = new HashSet();
- Map haveFile = new HashMap();
- List result = new ArrayList();
- for (int i = 0; i < modified.length; i++) {
- String fileURL = modified[i].documentProperties().getSourceName();
+ Schema[] modified, Set<String> namespaces) {
+ Set<String> modifiedFiles = new HashSet<>();
+ Map<String, SchemaDocument.Schema> haveFile = new HashMap<>();
+ List<SchemaDocument.Schema> result = new ArrayList<>();
+ for (Schema schema : modified) {
+ String fileURL = schema.documentProperties().getSourceName();
if (fileURL == null) {
throw new IllegalArgumentException("One of the Schema files passed in" +
" doesn't have the source set, which prevents it to be incrementally" +
" compiled");
}
modifiedFiles.add(fileURL);
- haveFile.put(fileURL, modified[i]);
- result.add(modified[i]);
+ haveFile.put(fileURL, schema);
+ result.add(schema);
}
SchemaDependencies dep = system.getDependencies();
- List nss = dep.getNamespacesTouched(modifiedFiles);
+ List<String> nss = dep.getNamespacesTouched(modifiedFiles);
namespaces.addAll(dep.computeTransitiveClosure(nss));
- List needRecompilation = dep.getFilesTouched(namespaces);
+ List<String> needRecompilation = dep.getFilesTouched(namespaces);
StscState.get().setDependencies(new SchemaDependencies(dep, namespaces));
- for (int i = 0; i < needRecompilation.size(); i++) {
- String url = (String) needRecompilation.get(i);
- Schema have = (Schema) haveFile.get(url);
+ for (String url : needRecompilation) {
+ Schema have = haveFile.get(url);
if (have == null) {
// We have to load the file from the entity resolver
try {
@@ -337,17 +336,14 @@ public class SchemaTypeSystemCompiler {
result.add(sDoc.getSchema());
} catch (java.net.MalformedURLException mfe) {
StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"MalformedURLException", url, mfe.getMessage()}, null);
- continue;
- } catch (java.io.IOException ioe) {
+ } catch (IOException ioe) {
StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"IOException", url, ioe.getMessage()}, null);
- continue;
} catch (XmlException xmle) {
StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"XmlException", url, xmle.getMessage()}, null);
- continue;
}
}
}
- return (Schema[]) result.toArray(new Schema[result.size()]);
+ return result.toArray(new Schema[0]);
}
@@ -369,13 +365,12 @@ public class SchemaTypeSystemCompiler {
boolean success = true;
- List types = new ArrayList();
+ List<SchemaType> types = new ArrayList<>();
types.addAll(Arrays.asList(system.globalTypes()));
types.addAll(Arrays.asList(system.documentTypes()));
types.addAll(Arrays.asList(system.attributeTypes()));
- for (Iterator i = types.iterator(); i.hasNext(); ) {
- SchemaType type = (SchemaType) i.next();
+ for (SchemaType type : types) {
if (type.isBuiltinType()) {
continue;
}
@@ -385,40 +380,22 @@ public class SchemaTypeSystemCompiler {
String fjn = type.getFullJavaName();
- Writer writer = null;
-
- try {
+ try (Writer writer = filer.createSourceFile(fjn)) {
// Generate interface class
- writer = filer.createSourceFile(fjn);
SchemaTypeCodePrinter.printType(writer, type, options);
} catch (IOException e) {
System.err.println("IO Error " + e);
success = false;
- } finally {
- try {
- if (writer != null) {
- writer.close();
- }
- } catch (IOException e) {
- }
}
- try {
- // Generate Implementation class
- fjn = type.getFullJavaImplName();
- writer = filer.createSourceFile(fjn);
+ fjn = type.getFullJavaImplName();
+ try (Writer writer = filer.createSourceFile(fjn)) {
+ // Generate Implementation class
SchemaTypeCodePrinter.printTypeImpl(writer, type, options);
} catch (IOException e) {
System.err.println("IO Error " + e);
success = false;
- } finally {
- try {
- if (writer != null) {
- writer.close();
- }
- } catch (IOException e) {
- }
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@poi.apache.org
For additional commands, e-mail: commits-help@poi.apache.org