spotbugs fixes
git-svn-id: https://svn.apache.org/repos/asf/xmlbeans/trunk@1881992 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/main/java/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java
index facf329..75279b6 100644
--- a/src/main/java/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java
+++ b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java
@@ -15,48 +15,45 @@
package org.apache.xmlbeans.impl.inst2xsd;
import org.apache.xmlbeans.*;
-import org.apache.xmlbeans.impl.common.PrefixResolver;
import org.apache.xmlbeans.impl.common.ValidationContext;
import org.apache.xmlbeans.impl.common.XmlWhitespace;
import org.apache.xmlbeans.impl.inst2xsd.util.Attribute;
import org.apache.xmlbeans.impl.inst2xsd.util.Element;
-import org.apache.xmlbeans.impl.inst2xsd.util.TypeSystemHolder;
import org.apache.xmlbeans.impl.inst2xsd.util.Type;
+import org.apache.xmlbeans.impl.inst2xsd.util.TypeSystemHolder;
import org.apache.xmlbeans.impl.util.XsTypeConverter;
import org.apache.xmlbeans.impl.values.*;
import javax.xml.namespace.QName;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
/**
* @author Cezar Andrei ( cezar.andrei at bea.com )
* Date: Jul 26, 2004
*/
public class RussianDollStrategy
- implements XsdGenStrategy
-{
- static final String _xsi = "http://www.w3.org/2001/XMLSchema-instance";
+ implements XsdGenStrategy {
+ static final String _xsi = "http://www.w3.org/2001/XMLSchema-instance";
- static final QName _xsiNil = new QName( _xsi, "nil", "xsi" );
- static final QName _xsiType = new QName( _xsi, "type", "xsi" );
+ static final QName _xsiNil = new QName(_xsi, "nil", "xsi");
- public void processDoc(XmlObject[] instances, Inst2XsdOptions options, TypeSystemHolder typeSystemHolder)
- {
- for (int i = 0; i < instances.length; i++)
- {
- XmlObject instance = instances[i];
+ public void processDoc(XmlObject[] instances, Inst2XsdOptions options, TypeSystemHolder typeSystemHolder) {
+ for (XmlObject instance : instances) {
XmlCursor xc = instance.newCursor();
// xc on start doc
StringBuilder comment = new StringBuilder();
- while( !xc.isStart() )
- {
+ while (!xc.isStart()) {
xc.toNextToken();
- if( xc.isComment() )
+ if (xc.isComment()) {
comment.append(xc.getTextValue());
- else if (xc.isEnddoc())
+ } else if (xc.isEnddoc()) {
return;
+ }
}
// xc now on the root element
@@ -67,18 +64,14 @@
}
}
- protected Element addGlobalElement(Element withElem, TypeSystemHolder typeSystemHolder, Inst2XsdOptions options)
- {
+ protected Element addGlobalElement(Element withElem, TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) {
assert withElem.isGlobal();
Element intoElem = typeSystemHolder.getGlobalElement(withElem.getName());
- if (intoElem==null)
- {
+ if (intoElem == null) {
typeSystemHolder.addGlobalElement(withElem);
return withElem;
- }
- else
- {
+ } else {
combineTypes(intoElem.getType(), withElem.getType(), options);
combineElementComments(intoElem, withElem);
return intoElem;
@@ -86,8 +79,7 @@
}
protected Element processElement(XmlCursor xc, String comment,
- Inst2XsdOptions options, TypeSystemHolder typeSystemHolder)
- {
+ Inst2XsdOptions options, TypeSystemHolder typeSystemHolder) {
assert xc.isStart();
Element element = new Element();
element.setName(xc.getName());
@@ -98,22 +90,22 @@
StringBuilder textBuff = new StringBuilder();
StringBuilder commentBuff = new StringBuilder();
- List children = new ArrayList();
- List attributes = new ArrayList();
+ List<Element> children = new ArrayList<>();
+ List<Attribute> attributes = new ArrayList<>();
- loop: do
- {
+ loop:
+ do {
XmlCursor.TokenType tt = xc.toNextToken();
- switch (tt.intValue())
- {
+ switch (tt.intValue()) {
case XmlCursor.TokenType.INT_ATTR:
// todo check for xsi:type
// ignore xsi:... attributes other than xsi:nil
QName attName = xc.getName();
- if (!_xsiNil.getNamespaceURI().equals(attName.getNamespaceURI()))
+ if (!_xsiNil.getNamespaceURI().equals(attName.getNamespaceURI())) {
attributes.add(processAttribute(xc, options, element.getName().getNamespaceURI(), typeSystemHolder));
- else if (_xsiNil.equals(attName))
+ } else if (_xsiNil.equals(attName)) {
element.setNillable(true);
+ }
break;
@@ -155,38 +147,31 @@
throw new IllegalStateException("Unknown TokenType.");
}
}
- while( true );
+ while (true);
- String collapsedText = XmlWhitespace.collapse(textBuff.toString(), XmlWhitespace.WS_COLLAPSE);
+ String collapsedText = XmlWhitespace.collapse(textBuff.toString(), XmlWhitespace.WS_COLLAPSE);
String commnetStr = (comment == null ?
- ( commentBuff.length() == 0 ? null : commentBuff.toString() ) :
- ( commentBuff.length() == 0 ? comment : commentBuff.insert(0, comment).toString()) );
+ (commentBuff.length() == 0 ? null : commentBuff.toString()) :
+ (commentBuff.length() == 0 ? comment : commentBuff.insert(0, comment).toString()));
element.setComment(commnetStr);
- if (children.size()>0)
- {
+ if (children.size() > 0) {
// complex content
- if (collapsedText.length()>0)
- {
+ if (collapsedText.length() > 0) {
elemType.setContentType(Type.COMPLEX_TYPE_MIXED_CONTENT);
- }
- else
- {
+ } else {
elemType.setContentType(Type.COMPLEX_TYPE_COMPLEX_CONTENT);
}
processElementsInComplexType(elemType, children, element.getName().getNamespaceURI(), typeSystemHolder, options);
processAttributesInComplexType(elemType, attributes);
- }
- else
- {
+ } else {
// simple content
// hack workaround for being able to call xc.getNamespaceForPrefix()
XmlCursor xcForNamespaces = xc.newCursor();
xcForNamespaces.toParent();
- if (attributes.size()>0)
- {
+ if (attributes.size() > 0) {
elemType.setContentType(Type.COMPLEX_TYPE_SIMPLE_CONTENT);
Type extendedType = Type.createNamedType(
@@ -194,9 +179,7 @@
elemType.setExtensionType(extendedType);
processAttributesInComplexType(elemType, attributes);
- }
- else
- {
+ } else {
elemType.setContentType(Type.SIMPLE_TYPE_SIMPLE_CONTENT);
elemType.setName(processSimpleContentType(textBuff.toString(), options, xcForNamespaces));
@@ -208,23 +191,18 @@
xcForNamespaces.dispose(); // end hack
}
- checkIfReferenceToGlobalTypeIsNeeded( element, typeSystemHolder, options);
+ checkIfReferenceToGlobalTypeIsNeeded(element, typeSystemHolder, options);
return element;
}
- protected void processElementsInComplexType(Type elemType, List children, String parentNamespace,
- TypeSystemHolder typeSystemHolder, Inst2XsdOptions options)
- {
- Map elemNamesToElements = new HashMap();
+ protected void processElementsInComplexType(Type elemType, List<Element> children, String parentNamespace,
+ TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) {
+ Map<QName, Element> elemNamesToElements = new HashMap<>();
Element currentElem = null;
- for (Iterator iterator = children.iterator(); iterator.hasNext();)
- {
- Element child = (Element) iterator.next();
-
- if (currentElem==null)
- { // first element in this type
+ for (Element child : children) {
+ if (currentElem == null) { // first element in this type
checkIfElementReferenceIsNeeded(child, parentNamespace, typeSystemHolder, options);
elemType.addElement(child);
elemNamesToElements.put(child.getName(), child);
@@ -232,25 +210,19 @@
continue;
}
- if (currentElem.getName()==child.getName())
- { // same contiguos element
+ if (currentElem.getName() == child.getName()) { // same contiguos element
combineTypes(currentElem.getType(), child.getType(), options); // unify types
combineElementComments(currentElem, child);
// minOcc=0 maxOcc=unbounded
currentElem.setMinOccurs(0);
currentElem.setMaxOccurs(Element.UNBOUNDED);
- }
- else
- {
- Element sameElem = (Element)elemNamesToElements.get(child.getName());
- if (sameElem==null)
- { // new element name
+ } else {
+ Element sameElem = elemNamesToElements.get(child.getName());
+ if (sameElem == null) { // new element name
checkIfElementReferenceIsNeeded(child, parentNamespace, typeSystemHolder, options);
elemType.addElement(child);
elemNamesToElements.put(child.getName(), child);
- }
- else
- { //same non contiguos
+ } else { //same non contiguos
combineTypes(currentElem.getType(), child.getType(), options);
combineElementComments(currentElem, child);
elemType.setTopParticleForComplexOrMixedContent(Type.PARTICLE_CHOICE_UNBOUNDED);
@@ -261,17 +233,14 @@
}
protected void checkIfElementReferenceIsNeeded(Element child, String parentNamespace,
- TypeSystemHolder typeSystemHolder, Inst2XsdOptions options)
- {
- if (!child.getName().getNamespaceURI().equals(parentNamespace))
- {
+ TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) {
+ if (!child.getName().getNamespaceURI().equals(parentNamespace)) {
Element referencedElem = new Element();
referencedElem.setGlobal(true);
referencedElem.setName(child.getName());
referencedElem.setType(child.getType());
- if (child.isNillable())
- {
+ if (child.isNillable()) {
referencedElem.setNillable(true);
child.setNillable(false);
}
@@ -283,24 +252,19 @@
}
protected void checkIfReferenceToGlobalTypeIsNeeded(Element elem, TypeSystemHolder typeSystemHolder,
- Inst2XsdOptions options)
- {
+ Inst2XsdOptions options) {
// RussianDollDesign doesn't define global types
}
- protected void processAttributesInComplexType(Type elemType, List attributes)
- {
+ protected void processAttributesInComplexType(Type elemType, List<Attribute> attributes) {
assert elemType.isComplexType();
- for (Iterator iterator = attributes.iterator(); iterator.hasNext();)
- {
- Attribute att = (Attribute) iterator.next();
+ for (Attribute att : attributes) {
elemType.addAttribute(att);
}
}
protected Attribute processAttribute(XmlCursor xc, Inst2XsdOptions options, String parentNamespace,
- TypeSystemHolder typeSystemHolder)
- {
+ TypeSystemHolder typeSystemHolder) {
assert xc.isAttr() : "xc not on attribute";
Attribute attribute = new Attribute();
QName attName = xc.getName();
@@ -322,11 +286,9 @@
return attribute;
}
- protected void checkIfAttributeReferenceIsNeeded(Attribute attribute, String parentNamespace, TypeSystemHolder typeSystemHolder)
- {
+ protected void checkIfAttributeReferenceIsNeeded(Attribute attribute, String parentNamespace, TypeSystemHolder typeSystemHolder) {
if (!attribute.getName().getNamespaceURI().equals("") &&
- !attribute.getName().getNamespaceURI().equals(parentNamespace))
- {
+ !attribute.getName().getNamespaceURI().equals(parentNamespace)) {
// make attribute be a reference to a top level attribute in a different targetNamespace
Attribute referencedAtt = new Attribute();
referencedAtt.setGlobal(true);
@@ -339,33 +301,28 @@
}
}
- protected class SCTValidationContext
- implements ValidationContext
- {
+ protected static class SCTValidationContext
+ implements ValidationContext {
protected boolean valid = true;
- public boolean isValid()
- {
+ public boolean isValid() {
return valid;
}
- public void resetToValid()
- {
+ public void resetToValid() {
valid = true;
}
- public void invalid(String message)
- {
+ public void invalid(String message) {
valid = false;
}
- public void invalid(String code, Object[] args)
- {
+ public void invalid(String code, Object[] args) {
valid = false;
}
}
- private SCTValidationContext _validationContext = new SCTValidationContext();
+ private final SCTValidationContext _validationContext = new SCTValidationContext();
// List of precedence for smart simple primitive type determination
@@ -376,59 +333,54 @@
// anyUri ? - triggered only for http:// or www. constructs,
// list types ?
// string
- protected QName processSimpleContentType(String lexicalValue, Inst2XsdOptions options, final XmlCursor xc)
- {
+ protected QName processSimpleContentType(String lexicalValue, Inst2XsdOptions options, final XmlCursor xc) {
// check options and return xsd:string or if smart is enabled, look for a better type
- if (options.getSimpleContentTypes()==Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING)
+ if (options.getSimpleContentTypes() == Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING) {
return XmlString.type.getName();
+ }
- if (options.getSimpleContentTypes()!=Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART)
+ if (options.getSimpleContentTypes() != Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART) {
throw new IllegalArgumentException("Unknown value for Inst2XsdOptions.getSimpleContentTypes() :" + options.getSimpleContentTypes());
+ }
// Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART case
- try
- {
+ try {
XsTypeConverter.lexByte(lexicalValue);
return XmlByte.type.getName();
+ } catch (Exception ignored) {
}
- catch (Exception e) {}
- try
- {
+ try {
XsTypeConverter.lexShort(lexicalValue);
return XmlShort.type.getName();
+ } catch (Exception ignored) {
}
- catch (Exception e) {}
- try
- {
+ try {
XsTypeConverter.lexInt(lexicalValue);
return XmlInt.type.getName();
+ } catch (Exception ignored) {
}
- catch (Exception e) {}
- try
- {
+ try {
XsTypeConverter.lexLong(lexicalValue);
return XmlLong.type.getName();
+ } catch (Exception ignored) {
}
- catch (Exception e) {}
- try
- {
+ try {
XsTypeConverter.lexInteger(lexicalValue);
return XmlInteger.type.getName();
+ } catch (Exception ignored) {
}
- catch (Exception e) {}
- try
- {
+ try {
XsTypeConverter.lexFloat(lexicalValue);
return XmlFloat.type.getName();
+ } catch (Exception ignored) {
}
- catch (Exception e) {}
// // this not needed because it's lexical space is covered by float
// try
@@ -446,47 +398,45 @@
// catch (Exception e) {}
XmlDateImpl.validateLexical(lexicalValue, XmlDate.type, _validationContext);
- if (_validationContext.isValid())
+ if (_validationContext.isValid()) {
return XmlDate.type.getName();
+ }
_validationContext.resetToValid();
XmlDateTimeImpl.validateLexical(lexicalValue, XmlDateTime.type, _validationContext);
- if (_validationContext.isValid())
+ if (_validationContext.isValid()) {
return XmlDateTime.type.getName();
+ }
_validationContext.resetToValid();
XmlTimeImpl.validateLexical(lexicalValue, XmlTime.type, _validationContext);
- if (_validationContext.isValid())
+ if (_validationContext.isValid()) {
return XmlTime.type.getName();
+ }
_validationContext.resetToValid();
XmlDurationImpl.validateLexical(lexicalValue, XmlDuration.type, _validationContext);
- if (_validationContext.isValid())
+ if (_validationContext.isValid()) {
return XmlDuration.type.getName();
+ }
_validationContext.resetToValid();
// check for uri
- if (lexicalValue.startsWith("http://") || lexicalValue.startsWith("www."))
- {
+ if (lexicalValue.startsWith("http://") || lexicalValue.startsWith("www.")) {
XmlAnyUriImpl.validateLexical(lexicalValue, _validationContext);
- if (_validationContext.isValid())
+ if (_validationContext.isValid()) {
return XmlAnyURI.type.getName();
+ }
_validationContext.resetToValid();
}
// check for QName
int idx = lexicalValue.indexOf(':');
- if (idx>=0 && idx==lexicalValue.lastIndexOf(':') && idx+1<lexicalValue.length())
- {
- PrefixResolver prefixResolver = new PrefixResolver()
- {
- public String getNamespaceForPrefix(String prefix)
- { return xc.namespaceForPrefix(prefix); }
- };
-
- QName qname = XmlQNameImpl.validateLexical(lexicalValue, _validationContext, prefixResolver);
- if (_validationContext.isValid())
+ if (idx >= 0 && idx == lexicalValue.lastIndexOf(':') && idx + 1 < lexicalValue.length()) {
+ XmlQNameImpl.validateLexical(lexicalValue, _validationContext, xc::namespaceForPrefix);
+ if (_validationContext.isValid()) {
return XmlQName.type.getName();
+ }
_validationContext.resetToValid();
}
@@ -496,27 +446,26 @@
}
- protected void combineTypes(Type into, Type with, Inst2XsdOptions options)
- {
- if (into==with)
+ protected void combineTypes(Type into, Type with, Inst2XsdOptions options) {
+ if (into == with) {
return;
+ }
- if (into.isGlobal() && with.isGlobal() && into.getName().equals(with.getName()))
+ if (into.isGlobal() && with.isGlobal() && into.getName().equals(with.getName())) {
return;
+ }
- if (into.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT &&
- with.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT)
- {
+ if (into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT &&
+ with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT) {
combineSimpleTypes(into, with, options);
return;
}
- if ((into.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
- into.getContentType()==Type.COMPLEX_TYPE_SIMPLE_CONTENT) &&
- (with.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
- with.getContentType()==Type.COMPLEX_TYPE_SIMPLE_CONTENT) )
- {
+ if ((into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
+ into.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT) &&
+ (with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
+ with.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT)) {
// take the extension name if it's a complex type
QName intoTypeName = into.isComplexType() ? into.getExtensionType().getName() : into.getName();
QName withTypeName = with.isComplexType() ? with.getExtensionType().getName() : with.getName();
@@ -525,118 +474,121 @@
into.setContentType(Type.COMPLEX_TYPE_SIMPLE_CONTENT);
QName moreGeneralTypeName = combineToMoreGeneralSimpleType(intoTypeName, withTypeName);
- if (into.isComplexType())
- {
+ if (into.isComplexType()) {
Type extendedType = Type.createNamedType(moreGeneralTypeName, Type.SIMPLE_TYPE_SIMPLE_CONTENT);
into.setExtensionType(extendedType);
- }
- else
+ } else {
into.setName(moreGeneralTypeName);
+ }
combineAttributesOfTypes(into, with);
return;
}
- if (into.getContentType()==Type.COMPLEX_TYPE_COMPLEX_CONTENT &&
- with.getContentType()==Type.COMPLEX_TYPE_COMPLEX_CONTENT)
- {
+ if (into.getContentType() == Type.COMPLEX_TYPE_COMPLEX_CONTENT &&
+ with.getContentType() == Type.COMPLEX_TYPE_COMPLEX_CONTENT) {
combineAttributesOfTypes(into, with);
- combineElementsOfTypes(into, with, false, options);
+ combineElementsOfTypes(into, with, options);
return;
}
- if (into.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
- into.getContentType()==Type.COMPLEX_TYPE_SIMPLE_CONTENT ||
- with.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
- with.getContentType()==Type.COMPLEX_TYPE_SIMPLE_CONTENT)
- {
+ if (into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
+ into.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT ||
+ with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
+ with.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT) {
into.setContentType(Type.COMPLEX_TYPE_MIXED_CONTENT);
combineAttributesOfTypes(into, with);
- combineElementsOfTypes(into, with, true, options);
+ combineElementsOfTypes(into, with, options);
return;
}
- if ((into.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
- into.getContentType()==Type.COMPLEX_TYPE_SIMPLE_CONTENT ||
- into.getContentType()==Type.COMPLEX_TYPE_COMPLEX_CONTENT ||
- into.getContentType()==Type.COMPLEX_TYPE_MIXED_CONTENT) &&
- (with.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
- with.getContentType()==Type.COMPLEX_TYPE_SIMPLE_CONTENT ||
- with.getContentType()==Type.COMPLEX_TYPE_COMPLEX_CONTENT ||
- with.getContentType()==Type.COMPLEX_TYPE_MIXED_CONTENT) )
- {
+ if ((into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
+ into.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT ||
+ into.getContentType() == Type.COMPLEX_TYPE_COMPLEX_CONTENT ||
+ into.getContentType() == Type.COMPLEX_TYPE_MIXED_CONTENT) &&
+ (with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT ||
+ with.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT ||
+ with.getContentType() == Type.COMPLEX_TYPE_COMPLEX_CONTENT ||
+ with.getContentType() == Type.COMPLEX_TYPE_MIXED_CONTENT)) {
into.setContentType(Type.COMPLEX_TYPE_MIXED_CONTENT);
combineAttributesOfTypes(into, with);
- combineElementsOfTypes(into, with, false, options);
+ combineElementsOfTypes(into, with, options);
return;
}
throw new IllegalArgumentException("Unknown content type.");
}
- protected void combineSimpleTypes(Type into, Type with, Inst2XsdOptions options)
- {
- assert (into.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT &&
- with.getContentType()==Type.SIMPLE_TYPE_SIMPLE_CONTENT) : "Invalid arguments";
+ protected void combineSimpleTypes(Type into, Type with, Inst2XsdOptions options) {
+ assert (into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT &&
+ with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT) : "Invalid arguments";
//simple type simple content
into.setName(combineToMoreGeneralSimpleType(into.getName(), with.getName()));
// take care of enumeration values
- if (options.isUseEnumerations())
- {
+ if (options.isUseEnumerations()) {
into.addAllEnumerationsFrom(with);
- if (into.getEnumerationValues().size()>options.getUseEnumerations())
- {
+ if (into.getEnumerationValues().size() > options.getUseEnumerations()) {
into.closeEnumeration();
}
}
}
- protected QName combineToMoreGeneralSimpleType(QName t1, QName t2)
- {
- if (t1.equals(t2))
+ protected QName combineToMoreGeneralSimpleType(QName t1, QName t2) {
+ if (t1.equals(t2)) {
return t1;
+ }
- if (t2.equals(XmlShort.type.getName()) && t1.equals(XmlByte.type.getName()))
+ if (t2.equals(XmlShort.type.getName()) && t1.equals(XmlByte.type.getName())) {
return t2;
- if (t1.equals(XmlShort.type.getName()) && t2.equals(XmlByte.type.getName()))
+ }
+ if (t1.equals(XmlShort.type.getName()) && t2.equals(XmlByte.type.getName())) {
return t1;
+ }
if (t2.equals(XmlInt.type.getName()) &&
- (t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName())) )
+ (t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName()))) {
return t2;
+ }
if (t1.equals(XmlInt.type.getName()) &&
- (t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName())) )
+ (t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName()))) {
return t1;
+ }
if (t2.equals(XmlLong.type.getName()) &&
- (t1.equals(XmlInt.type.getName()) || t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName())) )
+ (t1.equals(XmlInt.type.getName()) || t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName()))) {
return t2;
+ }
if (t1.equals(XmlLong.type.getName()) &&
- (t2.equals(XmlInt.type.getName()) || t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName())) )
+ (t2.equals(XmlInt.type.getName()) || t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName()))) {
return t1;
+ }
if (t2.equals(XmlInteger.type.getName()) &&
(t1.equals(XmlLong.type.getName()) || t1.equals(XmlInt.type.getName()) ||
- t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName())) )
+ t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName()))) {
return t2;
+ }
if (t1.equals(XmlInteger.type.getName()) &&
(t2.equals(XmlLong.type.getName()) || t2.equals(XmlInt.type.getName()) ||
- t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName())) )
+ t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName()))) {
return t1;
+ }
if (t2.equals(XmlFloat.type.getName()) &&
(t1.equals(XmlInteger.type.getName()) ||
- t1.equals(XmlLong.type.getName()) || t1.equals(XmlInt.type.getName()) ||
- t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName())) )
+ t1.equals(XmlLong.type.getName()) || t1.equals(XmlInt.type.getName()) ||
+ t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName()))) {
return t2;
+ }
if (t1.equals(XmlFloat.type.getName()) &&
(t2.equals(XmlInteger.type.getName()) ||
- t2.equals(XmlLong.type.getName()) || t2.equals(XmlInt.type.getName()) ||
- t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName())) )
+ t2.equals(XmlLong.type.getName()) || t2.equals(XmlInt.type.getName()) ||
+ t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName()))) {
return t1;
+ }
//double, decimal will never get here since they don't get generated
@@ -644,18 +596,14 @@
return XmlString.type.getName();
}
- protected void combineAttributesOfTypes(Type into, Type from)
- {
+ protected void combineAttributesOfTypes(Type into, Type from) {
// loop through attributes: add fromAtt if they don't exist, combine them if they exist
outterLoop:
- for (int i = 0; i < from.getAttributes().size(); i++)
- {
- Attribute fromAtt = (Attribute)from.getAttributes().get(i);
- for (int j = 0; j < into.getAttributes().size(); j++)
- {
- Attribute intoAtt = (Attribute)into.getAttributes().get(j);
- if (intoAtt.getName().equals(fromAtt.getName()))
- {
+ for (int i = 0; i < from.getAttributes().size(); i++) {
+ Attribute fromAtt = from.getAttributes().get(i);
+ for (int j = 0; j < into.getAttributes().size(); j++) {
+ Attribute intoAtt = into.getAttributes().get(j);
+ if (intoAtt.getName().equals(fromAtt.getName())) {
intoAtt.getType().setName(
combineToMoreGeneralSimpleType(intoAtt.getType().getName(), fromAtt.getType().getName()));
continue outterLoop;
@@ -666,15 +614,11 @@
}
//optional attributes: if there are atts in into that are not in from, make them optional
- outterLoop:
- for (int i = 0; i < into.getAttributes().size(); i++)
- {
- Attribute intoAtt = (Attribute)into.getAttributes().get(i);
- for (int j = 0; j < from.getAttributes().size(); j++)
- {
- Attribute fromAtt = (Attribute)from.getAttributes().get(j);
- if (fromAtt.getName().equals(intoAtt.getName()))
- {
+ for (int i = 0; i < into.getAttributes().size(); i++) {
+ Attribute intoAtt = into.getAttributes().get(i);
+ for (int j = 0; j < from.getAttributes().size(); j++) {
+ Attribute fromAtt = from.getAttributes().get(j);
+ if (fromAtt.getName().equals(intoAtt.getName())) {
continue;
}
}
@@ -683,38 +627,34 @@
}
}
- protected void combineElementsOfTypes(Type into, Type from, boolean makeElementsOptional, Inst2XsdOptions options)
- {
+ protected void combineElementsOfTypes(Type into, Type from, Inst2XsdOptions options) {
boolean needsUnboundedChoice = false;
- if (into.getTopParticleForComplexOrMixedContent()!=Type.PARTICLE_SEQUENCE ||
- from.getTopParticleForComplexOrMixedContent()!=Type.PARTICLE_SEQUENCE)
+ if (into.getTopParticleForComplexOrMixedContent() != Type.PARTICLE_SEQUENCE ||
+ from.getTopParticleForComplexOrMixedContent() != Type.PARTICLE_SEQUENCE) {
needsUnboundedChoice = true;
+ }
- List res = new ArrayList();
+ List<Element> res = new ArrayList<>();
int fromStartingIndex = 0;
int fromMatchedIndex = -1;
int intoMatchedIndex = -1;
// for each element in into
- for (int i = 0; !needsUnboundedChoice && i < into.getElements().size(); i++)
- {
+ for (int i = 0; !needsUnboundedChoice && i < into.getElements().size(); i++) {
// try to find one with same name in from
- Element intoElement = (Element) into.getElements().get(i);
- for (int j = fromStartingIndex; j < from.getElements().size(); j++)
- {
- Element fromElement = (Element) from.getElements().get(j);
- if (intoElement.getName().equals(fromElement.getName()))
- {
+ Element intoElement = into.getElements().get(i);
+ for (int j = fromStartingIndex; j < from.getElements().size(); j++) {
+ Element fromElement = from.getElements().get(j);
+ if (intoElement.getName().equals(fromElement.getName())) {
fromMatchedIndex = j;
break;
}
}
// if not found, it's safe to add this one to result 'res' (as optional) and continue
- if ( fromMatchedIndex < fromStartingIndex )
- {
+ if (fromMatchedIndex < fromStartingIndex) {
res.add(intoElement);
intoElement.setMinOccurs(0);
continue;
@@ -723,79 +663,69 @@
// else try out all from elemens between fromStartingIndex to fromMatchedIndex
// to see if they match one of the into elements
intoMatchingLoop:
- for (int j2 = fromStartingIndex; j2 < fromMatchedIndex; j2++)
- {
- Element fromCandidate = (Element) from.getElements().get(j2);
+ for (int j2 = fromStartingIndex; j2 < fromMatchedIndex; j2++) {
+ Element fromCandidate = from.getElements().get(j2);
- for (int i2 = i+1; i2 < into.getElements().size(); i2++)
- {
- Element intoCandidate = (Element) into.getElements().get(i2);
- if (fromCandidate.getName().equals(intoCandidate.getName()))
- {
+ for (int i2 = i + 1; i2 < into.getElements().size(); i2++) {
+ Element intoCandidate = into.getElements().get(i2);
+ if (fromCandidate.getName().equals(intoCandidate.getName())) {
intoMatchedIndex = i2;
break intoMatchingLoop;
}
}
}
- if (intoMatchedIndex<i)
- {
+ if (intoMatchedIndex < i) {
// if none matched they are safe to be added to res as optional
- for (int j3 = fromStartingIndex; j3 < fromMatchedIndex; j3++)
- {
- Element fromCandidate = (Element) from.getElements().get(j3);
+ for (int j3 = fromStartingIndex; j3 < fromMatchedIndex; j3++) {
+ Element fromCandidate = from.getElements().get(j3);
res.add(fromCandidate);
fromCandidate.setMinOccurs(0);
}
// also since into[i] == from[fromMatchedIndex] add it only once
res.add(intoElement);
- Element fromMatchedElement = (Element)from.getElements().get(fromMatchedIndex);
+ Element fromMatchedElement = from.getElements().get(fromMatchedIndex);
- if (fromMatchedElement.getMinOccurs()<=0)
+ if (fromMatchedElement.getMinOccurs() <= 0) {
intoElement.setMinOccurs(0);
- if (fromMatchedElement.getMaxOccurs()==Element.UNBOUNDED)
+ }
+ if (fromMatchedElement.getMaxOccurs() == Element.UNBOUNDED) {
intoElement.setMaxOccurs(Element.UNBOUNDED);
+ }
combineTypes(intoElement.getType(), fromMatchedElement.getType(), options);
combineElementComments(intoElement, fromMatchedElement);
fromStartingIndex = fromMatchedIndex + 1;
- continue;
- }
- else
- {
+ } else {
// if matched it means into type will transform into a choice unbounded type
needsUnboundedChoice = true;
}
}
- for (int j = fromStartingIndex; j < from.getElements().size(); j++)
- {
- Element remainingFromElement = (Element) from.getElements().get(j);
+ for (int j = fromStartingIndex; j < from.getElements().size(); j++) {
+ Element remainingFromElement = from.getElements().get(j);
res.add(remainingFromElement);
remainingFromElement.setMinOccurs(0);
}
// if choice was detected
- if (needsUnboundedChoice)
- {
+ if (needsUnboundedChoice) {
into.setTopParticleForComplexOrMixedContent(Type.PARTICLE_CHOICE_UNBOUNDED);
outterLoop:
- for (int j = 0; j < from.getElements().size(); j++)
- {
- Element fromElem = (Element) from.getElements().get(j);
- for (int i = 0; i < into.getElements().size(); i++)
- {
- Element intoElem = (Element)into.getElements().get(i);
+ for (int j = 0; j < from.getElements().size(); j++) {
+ Element fromElem = from.getElements().get(j);
+ for (int i = 0; i < into.getElements().size(); i++) {
+ Element intoElem = into.getElements().get(i);
intoElem.setMinOccurs(1);
intoElem.setMaxOccurs(1);
- if (intoElem==fromElem)
+ if (intoElem == fromElem) {
continue outterLoop;
+ }
- if (intoElem.getName().equals(fromElem.getName()))
- {
+ if (intoElem.getName().equals(fromElem.getName())) {
combineTypes(intoElem.getType(), fromElem.getType(), options);
combineElementComments(intoElem, fromElem);
@@ -808,24 +738,19 @@
fromElem.setMinOccurs(1);
fromElem.setMaxOccurs(1);
}
- return;
- }
- else
- {
+ } else {
// into remains sequence but will contain the new list of elements res
into.setElements(res);
- return;
}
}
- protected void combineElementComments(Element into, Element with)
- {
- if (with.getComment()!=null && with.getComment().length()>0)
- {
- if (into.getComment()==null)
+ protected void combineElementComments(Element into, Element with) {
+ if (with.getComment() != null && with.getComment().length() > 0) {
+ if (into.getComment() == null) {
into.setComment(with.getComment());
- else
+ } else {
into.setComment(into.getComment() + with.getComment());
+ }
}
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Type.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Type.java
index b067624..e9d3a8e 100644
--- a/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Type.java
+++ b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Type.java
@@ -14,310 +14,261 @@
*/
package org.apache.xmlbeans.impl.inst2xsd.util;
-import org.apache.xmlbeans.XmlQName;
import org.apache.xmlbeans.XmlCursor;
-import org.apache.xmlbeans.impl.common.PrefixResolver;
+import org.apache.xmlbeans.XmlQName;
import org.apache.xmlbeans.impl.values.XmlQNameImpl;
import javax.xml.namespace.QName;
-import java.util.List;
import java.util.ArrayList;
+import java.util.List;
/**
* @author Cezar Andrei (cezar.andrei at bea.com) Date: Jul 16, 2004
*/
-public class Type
-{
+public class Type {
private QName _name;
private int _kind = SIMPLE_TYPE_SIMPLE_CONTENT;
// _kind value space
- public static final int SIMPLE_TYPE_SIMPLE_CONTENT = 1; // ie no atts, no elems, just text
- public static final int COMPLEX_TYPE_SIMPLE_CONTENT = 2; // ie atts*, no elems, text* - simple type extension
+ public static final int SIMPLE_TYPE_SIMPLE_CONTENT = 1; // ie no atts, no elems, just text
+ public static final int COMPLEX_TYPE_SIMPLE_CONTENT = 2; // ie atts*, no elems, text* - simple type extension
public static final int COMPLEX_TYPE_COMPLEX_CONTENT = 3; // ie atts*, elems, no text
- public static final int COMPLEX_TYPE_MIXED_CONTENT = 4; // ie atts*, elems, text
- public static final int COMPLEX_TYPE_EMPTY_CONTENT = 5; // no elems, no text, just atts
+ public static final int COMPLEX_TYPE_MIXED_CONTENT = 4; // ie atts*, elems, text
+ public static final int COMPLEX_TYPE_EMPTY_CONTENT = 5; // no elems, no text, just atts
private int _topParticleForComplexOrMixedContent = PARTICLE_SEQUENCE;
// _topParticleForComplexOrMixedContent
- public static final int PARTICLE_SEQUENCE = 1;
+ public static final int PARTICLE_SEQUENCE = 1;
public static final int PARTICLE_CHOICE_UNBOUNDED = 2;
- private List _elements; // size>0 COMPLEX
- private List _attributes; // size>0 COMPLEX
+ private List<Element> _elements; // size>0 COMPLEX
+ private List<Attribute> _attributes; // size>0 COMPLEX
private Type _extensionType;
private boolean _isGlobal = false;
- private List _enumerationValues;
+ private List<String> _enumerationValues;
private boolean _acceptsEnumerationValue = true;
- private List _enumerationQNames; // This is a special case where the lexical representation
- // is not enough for a value, the QNames need to be remembered
- // in case the _extensionType is QName
+ private List<QName> _enumerationQNames; // This is a special case where the lexical representation
+ // is not enough for a value, the QNames need to be remembered
+ // in case the _extensionType is QName
- protected Type()
- {}
+ protected Type() {
+ }
- public static Type createNamedType(QName name, int contentType)
- {
- assert name!=null;
+ public static Type createNamedType(QName name, int contentType) {
+ assert name != null;
Type type = new Type();
type.setName(name);
type.setContentType(contentType);
return type;
}
- public static Type createUnnamedType(int contentType)
- {
- assert contentType==SIMPLE_TYPE_SIMPLE_CONTENT ||
- contentType==COMPLEX_TYPE_SIMPLE_CONTENT ||
- contentType==COMPLEX_TYPE_COMPLEX_CONTENT ||
- contentType==COMPLEX_TYPE_MIXED_CONTENT ||
- contentType==COMPLEX_TYPE_EMPTY_CONTENT: "Unknown contentType: " + contentType;
+ public static Type createUnnamedType(int contentType) {
+ assert contentType == SIMPLE_TYPE_SIMPLE_CONTENT ||
+ contentType == COMPLEX_TYPE_SIMPLE_CONTENT ||
+ contentType == COMPLEX_TYPE_COMPLEX_CONTENT ||
+ contentType == COMPLEX_TYPE_MIXED_CONTENT ||
+ contentType == COMPLEX_TYPE_EMPTY_CONTENT : "Unknown contentType: " + contentType;
Type type = new Type();
type.setContentType(contentType);
return type;
}
- public QName getName()
- {
+ public QName getName() {
return _name;
}
- public void setName(QName name)
- {
+ public void setName(QName name) {
this._name = name;
}
/**
- * @return
- * SIMPLE_TYPE_SIMPLE_CONTENT // ie no atts, no elems, just text
- * COMPLEX_TYPE_SIMPLE_CONTENT // ie atts*, no elems, text* - simple type extension
- * COMPLEX_TYPE_COMPLEX_CONTENT // ie atts*, elems, no text
- * COMPLEX_TYPE_MIXED_CONTENT // ie atts*, elems, text
- * COMPLEX_TYPE_EMPTY_CONTENT // no elems, no text, just atts
+ * @return SIMPLE_TYPE_SIMPLE_CONTENT // ie no atts, no elems, just text
+ * COMPLEX_TYPE_SIMPLE_CONTENT // ie atts*, no elems, text* - simple type extension
+ * COMPLEX_TYPE_COMPLEX_CONTENT // ie atts*, elems, no text
+ * COMPLEX_TYPE_MIXED_CONTENT // ie atts*, elems, text
+ * COMPLEX_TYPE_EMPTY_CONTENT // no elems, no text, just atts
*/
- public int getContentType()
- {
+ public int getContentType() {
return _kind;
}
/**
* @param kind 4 kinds:
- * SIMPLE_TYPE_SIMPLE_CONTENT // ie no atts, no elems, just text
- * COMPLEX_TYPE_SIMPLE_CONTENT // ie atts*, no elems, text* - simple type extension
- * COMPLEX_TYPE_COMPLEX_CONTENT // ie atts*, elems, no text
- * COMPLEX_TYPE_MIXED_CONTENT // ie atts*, elems, text
- * COMPLEX_TYPE_EMPTY_CONTENT // no elems, no text, just atts
+ * SIMPLE_TYPE_SIMPLE_CONTENT // ie no atts, no elems, just text
+ * COMPLEX_TYPE_SIMPLE_CONTENT // ie atts*, no elems, text* - simple type extension
+ * COMPLEX_TYPE_COMPLEX_CONTENT // ie atts*, elems, no text
+ * COMPLEX_TYPE_MIXED_CONTENT // ie atts*, elems, text
+ * COMPLEX_TYPE_EMPTY_CONTENT // no elems, no text, just atts
*/
- public void setContentType(int kind)
- {
+ public void setContentType(int kind) {
this._kind = kind;
}
- public List getElements()
- {
+ public List<Element> getElements() {
ensureElements();
return _elements;
}
- public void addElement(Element element)
- {
+ public void addElement(Element element) {
ensureElements();
_elements.add(element);
}
- public void setElements(List elements)
- {
+ public void setElements(List<Element> elements) {
ensureElements();
_elements.clear();
_elements.addAll(elements);
}
- private void ensureElements()
- {
- if (_elements==null)
- _elements = new ArrayList();
+ private void ensureElements() {
+ if (_elements == null) {
+ _elements = new ArrayList<>();
+ }
}
- public List getAttributes()
- {
+ public List<Attribute> getAttributes() {
ensureAttributes();
return _attributes;
}
- public void addAttribute(Attribute attribute)
- {
+ public void addAttribute(Attribute attribute) {
ensureAttributes();
_attributes.add(attribute);
}
- public Attribute getAttribute(QName name)
- {
- for (int i = 0; i < _attributes.size(); i++)
- {
- Attribute attribute = (Attribute) _attributes.get(i);
- if (attribute.getName().equals(name))
- return attribute;
+ public Attribute getAttribute(QName name) {
+ for (Attribute value : _attributes) {
+ if (value.getName().equals(name)) {
+ return value;
+ }
}
return null;
}
- private void ensureAttributes()
- {
- if (_attributes==null)
- _attributes = new ArrayList();
+ private void ensureAttributes() {
+ if (_attributes == null) {
+ _attributes = new ArrayList<>();
+ }
}
- public boolean isComplexType()
- {
- return (_kind==COMPLEX_TYPE_COMPLEX_CONTENT ||
- _kind==COMPLEX_TYPE_MIXED_CONTENT||
- _kind==COMPLEX_TYPE_SIMPLE_CONTENT);
+ public boolean isComplexType() {
+ return (_kind == COMPLEX_TYPE_COMPLEX_CONTENT ||
+ _kind == COMPLEX_TYPE_MIXED_CONTENT ||
+ _kind == COMPLEX_TYPE_SIMPLE_CONTENT);
}
- public boolean hasSimpleContent()
- {
- return (_kind==SIMPLE_TYPE_SIMPLE_CONTENT ||
- _kind==COMPLEX_TYPE_SIMPLE_CONTENT);
+ public boolean hasSimpleContent() {
+ return (_kind == SIMPLE_TYPE_SIMPLE_CONTENT ||
+ _kind == COMPLEX_TYPE_SIMPLE_CONTENT);
}
/**
* @return PARTICLE_SEQUENCE or PARTICLE_CHOICE_UNBOUNDED
*/
- public int getTopParticleForComplexOrMixedContent()
- {
+ public int getTopParticleForComplexOrMixedContent() {
return _topParticleForComplexOrMixedContent;
}
/**
- * @param topParticleForComplexOrMixedContent PARTICLE_SEQUENCE or PARTICLE_CHOICE_UNBOUNDED
+ * @param topParticleForComplexOrMixedContent PARTICLE_SEQUENCE or PARTICLE_CHOICE_UNBOUNDED
*/
- public void setTopParticleForComplexOrMixedContent(int topParticleForComplexOrMixedContent)
- {
+ public void setTopParticleForComplexOrMixedContent(int topParticleForComplexOrMixedContent) {
this._topParticleForComplexOrMixedContent = topParticleForComplexOrMixedContent;
}
- public boolean isGlobal()
- {
+ public boolean isGlobal() {
return _isGlobal;
}
- public void setGlobal(boolean isGlobal)
- {
- assert isGlobal && getName()!=null;
+ public void setGlobal(boolean isGlobal) {
+ assert isGlobal && getName() != null;
_isGlobal = isGlobal;
}
- public Type getExtensionType()
- {
+ public Type getExtensionType() {
return _extensionType;
}
- public void setExtensionType(Type extendedType)
- {
+ public void setExtensionType(Type extendedType) {
assert _kind == COMPLEX_TYPE_SIMPLE_CONTENT : "Extension used only for type which are COMPLEX_TYPE_SIMPLE_CONTENT";
- assert extendedType!=null && extendedType.getName()!=null : "Extended type must be a named type.";
+ assert extendedType != null && extendedType.getName() != null : "Extended type must be a named type.";
_extensionType = extendedType;
}
- public List getEnumerationValues()
- {
+ public List<String> getEnumerationValues() {
ensureEnumerationValues();
return _enumerationValues;
}
- public List getEnumerationQNames()
- {
+ public List<QName> getEnumerationQNames() {
ensureEnumerationValues();
return _enumerationQNames;
}
- public void addEnumerationValue(String enumerationValue, final XmlCursor xc)
- {
- assert _kind==SIMPLE_TYPE_SIMPLE_CONTENT || _kind==COMPLEX_TYPE_SIMPLE_CONTENT : "Enumerations possible only on simple content";
+ public void addEnumerationValue(String enumerationValue, final XmlCursor xc) {
+ assert _kind == SIMPLE_TYPE_SIMPLE_CONTENT || _kind == COMPLEX_TYPE_SIMPLE_CONTENT : "Enumerations possible only on simple content";
ensureEnumerationValues();
- if (_acceptsEnumerationValue && !_enumerationValues.contains(enumerationValue))
- {
+ if (_acceptsEnumerationValue && !_enumerationValues.contains(enumerationValue)) {
_enumerationValues.add(enumerationValue);
- if (_name.equals(XmlQName.type.getName()))
- {
+ if (_name.equals(XmlQName.type.getName())) {
// check for QName
- PrefixResolver prefixResolver = new PrefixResolver()
- {
- public String getNamespaceForPrefix(String prefix)
- { return xc.namespaceForPrefix(prefix); }
- };
+ QName qname = XmlQNameImpl.validateLexical(enumerationValue, null, xc::namespaceForPrefix);
- QName qname = XmlQNameImpl.validateLexical(enumerationValue, null, prefixResolver);
-
- assert qname!=null : "The check for QName should allready have happened.";
+ assert qname != null : "The check for QName should allready have happened.";
_enumerationQNames.add(qname);
}
}
}
- private void ensureEnumerationValues()
- {
- if (_enumerationValues==null)
- {
- _enumerationValues = new ArrayList();
- _enumerationQNames = new ArrayList();
+ private void ensureEnumerationValues() {
+ if (_enumerationValues == null) {
+ _enumerationValues = new ArrayList<>();
+ _enumerationQNames = new ArrayList<>();
}
}
- public boolean isEnumeration()
- {
- return _acceptsEnumerationValue && _enumerationValues!=null && _enumerationValues.size()>1;
+ public boolean isEnumeration() {
+ return _acceptsEnumerationValue && _enumerationValues != null && _enumerationValues.size() > 1;
}
- public boolean isQNameEnumeration()
- {
- return isEnumeration() && _name.equals(XmlQName.type.getName()) && _enumerationQNames!=null && _enumerationQNames.size()>1;
+ public boolean isQNameEnumeration() {
+ return isEnumeration() && _name.equals(XmlQName.type.getName()) && _enumerationQNames != null && _enumerationQNames.size() > 1;
}
- public void closeEnumeration()
- {
- _acceptsEnumerationValue=false;
+ public void closeEnumeration() {
+ _acceptsEnumerationValue = false;
}
- public String toString()
- {
+ public String toString() {
return "Type{" +
- "_name = " + _name +
- ", _extensionType = " + _extensionType +
- ", _kind = " + _kind +
- ", _elements = " + _elements +
- ", _attributes = " + _attributes +
- "}";
+ "_name = " + _name +
+ ", _extensionType = " + _extensionType +
+ ", _kind = " + _kind +
+ ", _elements = " + _elements +
+ ", _attributes = " + _attributes +
+ "}";
}
- public void addAllEnumerationsFrom(Type from)
- {
- assert _kind==SIMPLE_TYPE_SIMPLE_CONTENT || _kind==COMPLEX_TYPE_SIMPLE_CONTENT : "Enumerations possible only on simple content";
+ public void addAllEnumerationsFrom(Type from) {
+ assert _kind == SIMPLE_TYPE_SIMPLE_CONTENT || _kind == COMPLEX_TYPE_SIMPLE_CONTENT : "Enumerations possible only on simple content";
ensureEnumerationValues();
- if (_name.equals(XmlQName.type.getName()) && from._name.equals(XmlQName.type.getName()))
- {
- for (int i = 0; i < from.getEnumerationValues().size(); i++)
- {
- String enumValue = (String) from.getEnumerationValues().get(i);
- QName enumQNameValue = (QName) from.getEnumerationQNames().get(i);
- if (_acceptsEnumerationValue && !_enumerationQNames.contains(enumQNameValue))
- {
- _enumerationValues.add(enumValue);
- _enumerationQNames.add(enumQNameValue);
+ if (_name.equals(XmlQName.type.getName()) && from._name.equals(XmlQName.type.getName())) {
+ for (int i = 0; i < from.getEnumerationValues().size(); i++) {
+ String enumValue = from.getEnumerationValues().get(i);
+ QName enumQNameValue = from.getEnumerationQNames().get(i);
+ if (_acceptsEnumerationValue && !_enumerationQNames.contains(enumQNameValue)) {
+ _enumerationValues.add(enumValue);
+ _enumerationQNames.add(enumQNameValue);
}
}
- }
- else
- {
- for (int i = 0; i < from.getEnumerationValues().size(); i++)
- {
- String enumValue = (String) from.getEnumerationValues().get(i);
- if (_acceptsEnumerationValue && !_enumerationValues.contains(enumValue))
- {
+ } else {
+ for (int i = 0; i < from.getEnumerationValues().size(); i++) {
+ String enumValue = from.getEnumerationValues().get(i);
+ if (_acceptsEnumerationValue && !_enumerationValues.contains(enumValue)) {
_enumerationValues.add(enumValue);
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java
index 70773c7..c427ddd 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java
@@ -16,60 +16,49 @@
package org.apache.xmlbeans.impl.schema;
import org.apache.xmlbeans.*;
-import org.apache.xmlbeans.impl.common.SystemCache;
import org.apache.xmlbeans.impl.common.QNameHelper;
+import org.apache.xmlbeans.impl.common.SystemCache;
import org.apache.xmlbeans.impl.common.XBeanDebug;
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
import javax.xml.namespace.QName;
-
import java.io.InputStream;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.Collections;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.IdentityHashMap;
-
import java.lang.ref.SoftReference;
+import java.util.*;
import static org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.METADATA_PACKAGE_GEN;
public class SchemaTypeLoaderImpl extends SchemaTypeLoaderBase {
- private ResourceLoader _resourceLoader;
- private ClassLoader _classLoader;
+ private final ResourceLoader _resourceLoader;
+ private final ClassLoader _classLoader;
private final SchemaTypeLoader[] _searchPath;
- private Map _classpathTypeSystems;
- private Map _classLoaderTypeSystems;
- private Map _elementCache;
- private Map _attributeCache;
- private Map _modelGroupCache;
- private Map _attributeGroupCache;
- private Map _idConstraintCache;
- private Map _typeCache;
- private Map _documentCache;
- private Map _attributeTypeCache;
- private Map _classnameCache;
+ private Map<String, SchemaTypeSystemImpl> _classpathTypeSystems;
+ private Map<String, SchemaTypeSystemImpl> _classLoaderTypeSystems;
+ private Map<QName, Object> _elementCache;
+ private Map<QName, Object> _attributeCache;
+ private Map<QName, Object> _modelGroupCache;
+ private Map<QName, Object> _attributeGroupCache;
+ private Map<QName, Object> _idConstraintCache;
+ private Map<QName, Object> _typeCache;
+ private Map<QName, Object> _documentCache;
+ private Map<QName, Object> _attributeTypeCache;
+ private Map<String, Object> _classnameCache;
private final String _metadataPath;
public static String METADATA_PACKAGE_LOAD = METADATA_PACKAGE_GEN;
private static final Object CACHED_NOT_FOUND = new Object();
- private static final String[] basePackage = { "org.apache.xmlbeans.metadata", "schemaorg_apache_xmlbeans" };
- private static final String[] baseSchemas = { "sXMLCONFIG", "sXMLLANG", "sXMLSCHEMA", "sXMLTOOLS" };
+ private static final String[] basePackage = {"org.apache.xmlbeans.metadata", "schemaorg_apache_xmlbeans"};
+ private static final String[] baseSchemas = {"sXMLCONFIG", "sXMLLANG", "sXMLSCHEMA", "sXMLTOOLS"};
-
-
- private static class SchemaTypeLoaderCache extends SystemCache
- {
+ private static class SchemaTypeLoaderCache extends SystemCache {
// The following maintains a cache of SchemaTypeLoaders per ClassLoader per Thread.
// I use soft references to allow the garbage collector to reclain the type loaders
// and/pr class loaders at will.
- private ThreadLocal _cachedTypeSystems =
- new ThreadLocal() { protected Object initialValue() { return new ArrayList(); } };
+ private final ThreadLocal<List<SoftReference<SchemaTypeLoaderImpl>>> _cachedTypeSystems = ThreadLocal.withInitial(ArrayList::new);
@Override
public void clearThreadLocals() {
@@ -78,38 +67,28 @@
super.clearThreadLocals();
}
- public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl)
- {
- ArrayList a = (ArrayList) _cachedTypeSystems.get();
+ public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl) {
+ List<SoftReference<SchemaTypeLoaderImpl>> a = _cachedTypeSystems.get();
int candidate = -1;
SchemaTypeLoaderImpl result = null;
- for ( int i = 0 ; i < a.size() ; i++ )
- {
- SchemaTypeLoaderImpl tl = (SchemaTypeLoaderImpl) ((SoftReference) a.get(i)).get();
+ for (int i = 0; i < a.size(); i++) {
+ SchemaTypeLoaderImpl tl = a.get(i).get();
- if (tl == null)
- {
- assert i > candidate;
+ if (tl == null) {
a.remove(i--);
- }
- else if (tl._classLoader == cl)
- {
- assert candidate == -1 && result == null;
-
+ } else if (tl._classLoader == cl) {
candidate = i;
result = tl;
-
break;
}
}
// Make sure the most recently accessed entry is at the beginning of the array
- if (candidate > 0)
- {
- Object t = a.get(0);
+ if (candidate > 0) {
+ SoftReference<SchemaTypeLoaderImpl> t = a.get(0);
a.set(0, a.get(candidate));
a.set(candidate, t);
}
@@ -117,32 +96,28 @@
return result;
}
- public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl)
- {
+ public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl) {
assert (stl instanceof SchemaTypeLoaderImpl) &&
((SchemaTypeLoaderImpl) stl)._classLoader == cl;
- ArrayList a = (ArrayList) _cachedTypeSystems.get();
+ List<SoftReference<SchemaTypeLoaderImpl>> a = _cachedTypeSystems.get();
// Make sure this entry is at the top of the stack
- if (a.size() > 0)
- {
- Object t = a.get(0);
- a.set(0, new SoftReference(stl));
+ if (a.size() > 0) {
+ SoftReference<SchemaTypeLoaderImpl> t = a.get(0);
+ a.set(0, new SoftReference<>((SchemaTypeLoaderImpl) stl));
a.add(t);
+ } else {
+ a.add(new SoftReference<>((SchemaTypeLoaderImpl) stl));
}
- else
- a.add(new SoftReference(stl));
}
}
- public static SchemaTypeLoaderImpl getContextTypeLoader ( )
- {
+ public static SchemaTypeLoaderImpl getContextTypeLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
SchemaTypeLoaderImpl result = (SchemaTypeLoaderImpl)
SystemCache.get().getFromTypeLoaderCache(cl);
- if (result == null)
- {
+ if (result == null) {
result =
new SchemaTypeLoaderImpl(
new SchemaTypeLoader[]{BuiltinSchemaTypeSystem.get()}, null, cl, null);
@@ -159,12 +134,11 @@
/**
* Initialize a SchemaTypeLoader via the given loaders and paths
*
- * @param searchPath the searchPath to use
+ * @param searchPath the searchPath to use
* @param resourceLoader the resourceLoader to use
- * @param classLoader the classLoader to use
- * @param metadataPath the custom metadata path
+ * @param classLoader the classLoader to use
+ * @param metadataPath the custom metadata path
* @return the schemaTypeLoader
- *
* @since XmlBeans 3.1.0
*/
public static SchemaTypeLoader build(final SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader, String metadataPath) {
@@ -173,18 +147,19 @@
list.add(searchPath);
- ClassLoader cl = (classLoader == null) ? SchemaDocument.class.getClassLoader() : classLoader;
+ ClassLoader cl = (classLoader == null) ? SchemaDocument.class.getClassLoader() : classLoader;
for (String prefix : basePackage) {
for (String holder : baseSchemas) {
String clName = prefix + ".system." + holder + ".TypeSystemHolder";
- if (cl.getResource(clName.replace(".","/")+".class") == null) {
+ if (cl.getResource(clName.replace(".", "/") + ".class") == null) {
// if the first class isn't found in the package, continue with the next package
break;
}
try {
- Class cls = Class.forName(clName, true, cl);
- list.add((SchemaTypeLoader)cls.getDeclaredField("typeSystem").get(null));
+ @SuppressWarnings("unchecked")
+ Class<? extends SchemaTypeLoader> cls = (Class<? extends SchemaTypeLoader>) Class.forName(clName, true, cl);
+ list.add((SchemaTypeLoader) cls.getDeclaredField("typeSystem").get(null));
} catch (Exception e) {
throw new XmlRuntimeException(e);
}
@@ -197,10 +172,9 @@
/**
* Just used to avoid duplicate path entries
*/
- private static class SubLoaderList
- {
- private final List<SchemaTypeLoader> theList = new ArrayList<SchemaTypeLoader>();
- private final Map<SchemaTypeLoader,Object> seen = new IdentityHashMap<SchemaTypeLoader,Object>();
+ private static class SubLoaderList {
+ private final List<SchemaTypeLoader> theList = new ArrayList<>();
+ private final Map<SchemaTypeLoader, Object> seen = new IdentityHashMap<>();
void add(SchemaTypeLoader[] searchPath) {
if (searchPath == null) {
@@ -208,7 +182,7 @@
}
for (SchemaTypeLoader stl : searchPath) {
if (stl instanceof SchemaTypeLoaderImpl) {
- SchemaTypeLoaderImpl sub = (SchemaTypeLoaderImpl)stl;
+ SchemaTypeLoaderImpl sub = (SchemaTypeLoaderImpl) stl;
if (sub._classLoader != null || sub._resourceLoader != null) {
add(sub);
} else {
@@ -235,19 +209,18 @@
/**
* Constructs a SchemaTypeLoaderImpl that searches for objects
* in the following order:
- *
+ * <p>
* (1) First on the searchPath of other SchemaTypeSystems supplied,
- * in order that they are listed.
+ * in order that they are listed.
* (2) Next on the classpath of .jar files or directories supplied,
- * in the order that they are listed. When types are returned in
- * this way, they are instantiated from a private typesystem.
- * In other words, if a type is loaded from another SchemaTypeLoaderImpl
- * that was initialized on the same file, the instance of the type will
- * be different.
+ * in the order that they are listed. When types are returned in
+ * this way, they are instantiated from a private typesystem.
+ * In other words, if a type is loaded from another SchemaTypeLoaderImpl
+ * that was initialized on the same file, the instance of the type will
+ * be different.
* (3) Finally on the classloader supplied.
*/
- private SchemaTypeLoaderImpl(SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader, String metadataPath)
- {
+ private SchemaTypeLoaderImpl(SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader, String metadataPath) {
_searchPath = (searchPath == null) ? EMPTY_SCHEMATYPELOADER_ARRAY : searchPath;
_resourceLoader = resourceLoader;
_classLoader = classLoader;
@@ -255,7 +228,7 @@
if (metadataPath != null) {
this._metadataPath = metadataPath;
} else {
- final String path26 = "schema" + METADATA_PACKAGE_LOAD.replace("/","_");
+ final String path26 = "schema" + METADATA_PACKAGE_LOAD.replace("/", "_");
this._metadataPath = (isPath30(_classLoader)) ? METADATA_PACKAGE_LOAD : path26;
}
@@ -271,94 +244,84 @@
/**
* Initializes the caches.
*/
- private final void initCaches()
- {
- _classpathTypeSystems = Collections.synchronizedMap(new HashMap());
- _classLoaderTypeSystems = Collections.synchronizedMap(new HashMap());
- _elementCache = Collections.synchronizedMap(new HashMap());
- _attributeCache = Collections.synchronizedMap(new HashMap());
- _modelGroupCache = Collections.synchronizedMap(new HashMap());
- _attributeGroupCache = Collections.synchronizedMap(new HashMap());
- _idConstraintCache = Collections.synchronizedMap(new HashMap());
- _typeCache = Collections.synchronizedMap(new HashMap());
- _documentCache = Collections.synchronizedMap(new HashMap());
- _attributeTypeCache = Collections.synchronizedMap(new HashMap());
- _classnameCache = Collections.synchronizedMap(new HashMap());
+ private void initCaches() {
+ _classpathTypeSystems = Collections.synchronizedMap(new HashMap<>());
+ _classLoaderTypeSystems = Collections.synchronizedMap(new HashMap<>());
+ _elementCache = Collections.synchronizedMap(new HashMap<>());
+ _attributeCache = Collections.synchronizedMap(new HashMap<>());
+ _modelGroupCache = Collections.synchronizedMap(new HashMap<>());
+ _attributeGroupCache = Collections.synchronizedMap(new HashMap<>());
+ _idConstraintCache = Collections.synchronizedMap(new HashMap<>());
+ _typeCache = Collections.synchronizedMap(new HashMap<>());
+ _documentCache = Collections.synchronizedMap(new HashMap<>());
+ _attributeTypeCache = Collections.synchronizedMap(new HashMap<>());
+ _classnameCache = Collections.synchronizedMap(new HashMap<>());
}
- SchemaTypeSystemImpl typeSystemForComponent(String searchdir, QName name)
- {
+ SchemaTypeSystemImpl typeSystemForComponent(String searchdir, QName name) {
String searchfor = searchdir + QNameHelper.hexsafedir(name) + ".xsb";
String tsname = null;
- if (_resourceLoader != null)
+ if (_resourceLoader != null) {
tsname = crackEntry(_resourceLoader, searchfor);
+ }
- if (_classLoader != null)
+ if (_classLoader != null) {
tsname = crackEntry(_classLoader, searchfor);
+ }
- if (tsname != null)
- return (SchemaTypeSystemImpl)typeSystemForName(tsname);
+ if (tsname != null) {
+ return (SchemaTypeSystemImpl) typeSystemForName(tsname);
+ }
return null;
}
- public SchemaTypeSystem typeSystemForName(String name)
- {
- if (_resourceLoader != null)
- {
+ public SchemaTypeSystem typeSystemForName(String name) {
+ if (_resourceLoader != null) {
SchemaTypeSystem result = getTypeSystemOnClasspath(name);
- if (result != null)
+ if (result != null) {
return result;
+ }
}
- if (_classLoader != null)
- {
+ if (_classLoader != null) {
SchemaTypeSystem result = getTypeSystemOnClassloader(name);
- if (result != null)
+ if (result != null) {
return result;
+ }
}
return null;
}
- SchemaTypeSystemImpl typeSystemForClassname(String searchdir, String name)
- {
+ SchemaTypeSystemImpl typeSystemForClassname(String searchdir, String name) {
String searchfor = searchdir + name.replace('.', '/') + ".xsb";
- if (_resourceLoader != null)
- {
+ if (_resourceLoader != null) {
String tsname = crackEntry(_resourceLoader, searchfor);
- if (tsname != null)
+ if (tsname != null) {
return getTypeSystemOnClasspath(tsname);
+ }
}
- if (_classLoader != null)
- {
+ if (_classLoader != null) {
String tsname = crackEntry(_classLoader, searchfor);
- if (tsname != null)
+ if (tsname != null) {
return getTypeSystemOnClassloader(tsname);
+ }
}
return null;
}
- SchemaTypeSystemImpl getTypeSystemOnClasspath(String name)
- {
- SchemaTypeSystemImpl result = (SchemaTypeSystemImpl)_classpathTypeSystems.get(name);
- if (result == null)
- {
- result = new SchemaTypeSystemImpl(_resourceLoader, name, this);
- _classpathTypeSystems.put(name, result);
- }
- return result;
+ SchemaTypeSystemImpl getTypeSystemOnClasspath(String name) {
+ return _classpathTypeSystems.computeIfAbsent(name, n -> new SchemaTypeSystemImpl(_resourceLoader, n, this));
}
- SchemaTypeSystemImpl getTypeSystemOnClassloader(String name)
- {
+ SchemaTypeSystemImpl getTypeSystemOnClassloader(String name) {
XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finding type system " + name + " on classloader", 0);
- SchemaTypeSystemImpl result = (SchemaTypeSystemImpl)_classLoaderTypeSystems.get(name);
- if (result == null)
- {
+ SchemaTypeSystemImpl result = _classLoaderTypeSystems.get(name);
+ if (result == null) {
XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Type system " + name + " not cached - consulting field", 0);
result = SchemaTypeSystemImpl.forName(name, _classLoader);
_classLoaderTypeSystems.put(name, result);
@@ -366,62 +329,51 @@
return result;
}
- static String crackEntry(ResourceLoader loader, String searchfor)
- {
+ static String crackEntry(ResourceLoader loader, String searchfor) {
InputStream is = loader.getResourceAsStream(searchfor);
- if (is == null)
- return null;
- return crackPointer(is);
+ return is == null ? null : crackPointer(is);
}
- static String crackEntry(ClassLoader loader, String searchfor)
- {
+ static String crackEntry(ClassLoader loader, String searchfor) {
InputStream stream = loader.getResourceAsStream(searchfor);
- if (stream == null)
- return null;
- return crackPointer(stream);
+ return stream == null ? null : crackPointer(stream);
}
- static String crackPointer(InputStream stream)
- {
+ static String crackPointer(InputStream stream) {
return SchemaTypeSystemImpl.crackPointer(stream);
}
- public boolean isNamespaceDefined(String namespace)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (_searchPath[i].isNamespaceDefined(namespace))
+ public boolean isNamespaceDefined(String namespace) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (schemaTypeLoader.isNamespaceDefined(namespace)) {
return true;
+ }
+ }
SchemaTypeSystem sts = typeSystemForComponent(_metadataPath + "/namespace/", new QName(namespace, "xmlns"));
return (sts != null);
}
- public SchemaType.Ref findTypeRef(QName name)
- {
- /**
- * The maps are synchronized, we use two accesses to the cache (one read
- * and one write), but the code inbetween is not synchronized. The
- * assumption is that the underlying datastructures (the search path and
- * the classloader) do not change, so two threads running the code in
- * parallel will come up with the same result.
- */
+ public SchemaType.Ref findTypeRef(QName name) {
+ // The maps are synchronized, we use two accesses to the cache (one read and one write), but the code in-between
+ // is not synchronized. The assumption is that the underlying datastructures (the search path and the classloader)
+ // do not change, so two threads running the code in parallel will come up with the same result.
Object cached = _typeCache.get(name);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaType.Ref result = (SchemaType.Ref) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].findTypeRef(name)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.findTypeRef(name))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/type/", name);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.findTypeRef(name);
- assert(result != null) : "Type system registered type " + QNameHelper.pretty(name) + " but does not return it";
+ assert (result != null) : "Type system registered type " + QNameHelper.pretty(name) + " but does not return it";
}
}
_typeCache.put(name, result == null ? CACHED_NOT_FOUND : result);
@@ -429,26 +381,25 @@
return result;
}
- public SchemaType typeForClassname(String classname)
- {
+ public SchemaType typeForClassname(String classname) {
classname = classname.replace('$', '.');
Object cached = _classnameCache.get(classname);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaType result = (SchemaType) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].typeForClassname(classname)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.typeForClassname(classname))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForClassname(_metadataPath + "/javaname/", classname);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.typeForClassname(classname);
- assert(result != null) : "Type system registered type " + classname + " but does not return it";
+ assert (result != null) : "Type system registered type " + classname + " but does not return it";
}
}
_classnameCache.put(classname, result == null ? CACHED_NOT_FOUND : result);
@@ -456,24 +407,23 @@
return result;
}
- public SchemaType.Ref findDocumentTypeRef(QName name)
- {
+ public SchemaType.Ref findDocumentTypeRef(QName name) {
Object cached = _documentCache.get(name);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaType.Ref result = (SchemaType.Ref) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].findDocumentTypeRef(name)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.findDocumentTypeRef(name))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/element/", name);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.findDocumentTypeRef(name);
- assert(result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not contain document type";
+ assert (result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not contain document type";
}
}
_documentCache.put(name, result == null ? CACHED_NOT_FOUND : result);
@@ -481,24 +431,23 @@
return result;
}
- public SchemaType.Ref findAttributeTypeRef(QName name)
- {
+ public SchemaType.Ref findAttributeTypeRef(QName name) {
Object cached = _attributeTypeCache.get(name);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaType.Ref result = (SchemaType.Ref) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].findAttributeTypeRef(name)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.findAttributeTypeRef(name))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attribute/", name);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.findAttributeTypeRef(name);
- assert(result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not contain attribute type";
+ assert (result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not contain attribute type";
}
}
_attributeTypeCache.put(name, result == null ? CACHED_NOT_FOUND : result);
@@ -506,24 +455,23 @@
return result;
}
- public SchemaGlobalElement.Ref findElementRef(QName name)
- {
+ public SchemaGlobalElement.Ref findElementRef(QName name) {
Object cached = _elementCache.get(name);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaGlobalElement.Ref result = (SchemaGlobalElement.Ref) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].findElementRef(name)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.findElementRef(name))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/element/", name);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.findElementRef(name);
- assert(result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not return it";
+ assert (result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not return it";
}
}
_elementCache.put(name, result == null ? CACHED_NOT_FOUND : result);
@@ -531,24 +479,23 @@
return result;
}
- public SchemaGlobalAttribute.Ref findAttributeRef(QName name)
- {
+ public SchemaGlobalAttribute.Ref findAttributeRef(QName name) {
Object cached = _attributeCache.get(name);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaGlobalAttribute.Ref result = (SchemaGlobalAttribute.Ref) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].findAttributeRef(name)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.findAttributeRef(name))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attribute/", name);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.findAttributeRef(name);
- assert(result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not return it";
+ assert (result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not return it";
}
}
_attributeCache.put(name, result == null ? CACHED_NOT_FOUND : result);
@@ -556,24 +503,23 @@
return result;
}
- public SchemaModelGroup.Ref findModelGroupRef(QName name)
- {
+ public SchemaModelGroup.Ref findModelGroupRef(QName name) {
Object cached = _modelGroupCache.get(name);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaModelGroup.Ref result = (SchemaModelGroup.Ref) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].findModelGroupRef(name)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.findModelGroupRef(name))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/modelgroup/", name);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.findModelGroupRef(name);
- assert(result != null) : "Type system registered model group " + QNameHelper.pretty(name) + " but does not return it";
+ assert (result != null) : "Type system registered model group " + QNameHelper.pretty(name) + " but does not return it";
}
}
_modelGroupCache.put(name, result == null ? CACHED_NOT_FOUND : result);
@@ -581,24 +527,23 @@
return result;
}
- public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name)
- {
+ public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) {
Object cached = _attributeGroupCache.get(name);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaAttributeGroup.Ref result = (SchemaAttributeGroup.Ref) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].findAttributeGroupRef(name)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.findAttributeGroupRef(name))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attributegroup/", name);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.findAttributeGroupRef(name);
- assert(result != null) : "Type system registered attribute group " + QNameHelper.pretty(name) + " but does not return it";
+ assert (result != null) : "Type system registered attribute group " + QNameHelper.pretty(name) + " but does not return it";
}
}
_attributeGroupCache.put(name, result == null ? CACHED_NOT_FOUND : result);
@@ -606,24 +551,23 @@
return result;
}
- public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name)
- {
+ public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) {
Object cached = _idConstraintCache.get(name);
- if (cached == CACHED_NOT_FOUND)
+ if (cached == CACHED_NOT_FOUND) {
return null;
+ }
SchemaIdentityConstraint.Ref result = (SchemaIdentityConstraint.Ref) cached;
- if (result == null)
- {
- for (int i = 0; i < _searchPath.length; i++)
- if (null != (result = _searchPath[i].findIdentityConstraintRef(name)))
+ if (result == null) {
+ for (SchemaTypeLoader schemaTypeLoader : _searchPath) {
+ if (null != (result = schemaTypeLoader.findIdentityConstraintRef(name))) {
break;
- if (result == null)
- {
+ }
+ }
+ if (result == null) {
SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/identityconstraint/", name);
- if (ts != null)
- {
+ if (ts != null) {
result = ts.findIdentityConstraintRef(name);
- assert(result != null) : "Type system registered identity constraint " + QNameHelper.pretty(name) + " but does not return it";
+ assert (result != null) : "Type system registered identity constraint " + QNameHelper.pretty(name) + " but does not return it";
}
}
_idConstraintCache.put(name, result == null ? CACHED_NOT_FOUND : result);
@@ -631,27 +575,29 @@
return result;
}
- public InputStream getSourceAsStream(String sourceName)
- {
+ public InputStream getSourceAsStream(String sourceName) {
InputStream result = null;
- if (!sourceName.startsWith("/"))
+ if (!sourceName.startsWith("/")) {
sourceName = "/" + sourceName;
+ }
- if (_resourceLoader != null)
+ if (_resourceLoader != null) {
result = _resourceLoader.getResourceAsStream(_metadataPath + "/src" + sourceName);
+ }
- if (result == null && _classLoader != null)
+ if (result == null && _classLoader != null) {
return _classLoader.getResourceAsStream(_metadataPath + "/src" + sourceName);
+ }
return result;
}
private static final SchemaTypeLoader[] EMPTY_SCHEMATYPELOADER_ARRAY = new SchemaTypeLoader[0];
- static
- {
- if (SystemCache.get() instanceof SystemCache)
+ static {
+ if (SystemCache.get() != null) {
SystemCache.set(new SchemaTypeLoaderCache());
+ }
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Cur.java b/src/main/java/org/apache/xmlbeans/impl/store/Cur.java
index bd1120a..dfadc7d 100755
--- a/src/main/java/org/apache/xmlbeans/impl/store/Cur.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Cur.java
@@ -28,6 +28,8 @@
import java.io.PrintStream;
import java.util.Map;
+import static org.apache.xmlbeans.impl.values.TypeStore.WS_PRESERVE;
+
// DOM Level 3
@@ -2303,7 +2305,7 @@
String getCharsAsString() {
assert isNormal() && _xobj != null;
- return getCharsAsString(Locale.WS_PRESERVE);
+ return getCharsAsString(WS_PRESERVE);
}
String getCharsAsString(int wsr) {
@@ -3190,8 +3192,8 @@
private final boolean _stripWhitespace;
private final boolean _stripComments;
private final boolean _stripProcinsts;
- private final Map<String,String> _substituteNamespaces;
- private final Map<String,String> _additionalNamespaces;
+ private final Map<String, String> _substituteNamespaces;
+ private final Map<String, String> _additionalNamespaces;
private String _doctypeName;
private String _doctypePublicId;
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java b/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java
index f81b744..d96663f 100755
--- a/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java
@@ -37,6 +37,8 @@
import java.util.Map;
import java.util.function.Supplier;
+import static org.apache.xmlbeans.impl.values.TypeStore.WS_PRESERVE;
+
public final class Cursor implements XmlCursor, ChangeListener {
static final int ROOT = Cur.ROOT;
static final int ELEM = Cur.ELEM;
@@ -1047,7 +1049,7 @@
// If there are no children (hopefully the common case), I can get the text faster.
if (_cur.hasChildren()) {
- return Locale.getTextValue(_cur, Locale.WS_PRESERVE, chars, offset, max);
+ return Locale.getTextValue(_cur, WS_PRESERVE, chars, offset, max);
}
// Fast way
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Locale.java b/src/main/java/org/apache/xmlbeans/impl/store/Locale.java
index 6649ac0..c6aa984 100755
--- a/src/main/java/org/apache/xmlbeans/impl/store/Locale.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Locale.java
@@ -21,8 +21,6 @@
import org.apache.xmlbeans.impl.store.Cur.Locations;
import org.apache.xmlbeans.impl.store.DomImpl.Dom;
import org.apache.xmlbeans.impl.store.Saaj.SaajCallback;
-import org.apache.xmlbeans.impl.values.TypeStore;
-import org.apache.xmlbeans.xml.stream.XMLEvent;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.xml.sax.ext.DeclHandler;
@@ -40,6 +38,9 @@
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
+
+import static org.apache.xmlbeans.impl.values.TypeStore.*;
public final class Locale
implements DOMImplementation, SaajCallback, XmlLocale {
@@ -52,11 +53,6 @@
static final int PROCINST = Cur.PROCINST;
static final int TEXT = Cur.TEXT;
- static final int WS_UNSPECIFIED = TypeStore.WS_UNSPECIFIED;
- static final int WS_PRESERVE = TypeStore.WS_PRESERVE;
- static final int WS_REPLACE = TypeStore.WS_REPLACE;
- static final int WS_COLLAPSE = TypeStore.WS_COLLAPSE;
-
static final String _xsi = "http://www.w3.org/2001/XMLSchema-instance";
static final String _schema = "http://www.w3.org/2001/XMLSchema";
static final String _openFragUri = "http://www.openuri.org/fragment";
@@ -286,15 +282,7 @@
return false;
}
- if (n1.getNamespaceURI() == n2.getNamespaceURI()) {
- return true;
- }
-
- if (n1.getNamespaceURI() == null || n2.getNamespaceURI() == null) {
- return false;
- }
-
- return n1.getNamespaceURI().equals(n2.getNamespaceURI());
+ return Objects.equals(n1.getNamespaceURI(), n2.getNamespaceURI());
}
private static void addNamespace(StringBuffer sb, QName name) {
@@ -341,12 +329,12 @@
sb.append(" got ");
addNamespace(sb, name);
} else if (namespacesSame(docElemName, name)) {
- sb.append(": document element local name mismatch ");
- sb.append("expected " + docElemName.getLocalPart());
- sb.append(" got " + name.getLocalPart());
+ sb.append(": document element local name mismatch expected ")
+ .append(docElemName.getLocalPart())
+ .append(" got ")
+ .append(name.getLocalPart());
} else {
- sb.append(": document element mismatch ");
- sb.append("got ");
+ sb.append(": document element mismatch got ");
sb.append(QNameHelper.pretty(name));
}
}
@@ -448,8 +436,6 @@
// Move to next token
- assert k != ATTR;
-
if (k != TEXT) {
start.toEnd();
}
@@ -521,7 +507,7 @@
public static DOMImplementation newDomImplementation(SchemaTypeLoader stl,
XmlOptions options) {
- return (DOMImplementation) getLocale(stl, options);
+ return getLocale(stl, options);
}
//
@@ -566,9 +552,8 @@
Cur parse(String s, SchemaType type, XmlOptions options)
throws XmlException {
- Reader r = new StringReader(s);
- try {
+ try (Reader r = new StringReader(s)) {
Cur c = getSaxLoader(options).load(this, new InputSource(r),
options);
@@ -579,11 +564,6 @@
assert false : "StringReader should not throw IOException";
throw new XmlException(e.getMessage(), e);
- } finally {
- try {
- r.close();
- } catch (IOException e) {
- }
}
}
@@ -640,14 +620,6 @@
return x;
}
- private static void lineNumber(XMLEvent xe, LoadContext context) {
- org.apache.xmlbeans.xml.stream.Location loc = xe.getLocation();
-
- if (loc != null) {
- context.lineNumber(loc.getLineNumber(), loc.getColumnNumber(), -1);
- }
- }
-
private static void lineNumber(XMLStreamReader xsr, LoadContext context) {
javax.xml.stream.Location loc = xsr.getLocation();
@@ -1037,7 +1009,7 @@
//
//
- private class XmlSaxHandlerImpl
+ private static class XmlSaxHandlerImpl
extends SaxHandler
implements XmlSaxHandler {
XmlSaxHandlerImpl(Locale l, SchemaType type, XmlOptions options) {
@@ -1096,8 +1068,8 @@
}
}
- private SchemaType _type;
- private XmlOptions _options;
+ private final SchemaType _type;
+ private final XmlOptions _options;
}
public static XmlSaxHandler newSaxHandler(SchemaTypeLoader stl,
@@ -1163,7 +1135,7 @@
static private class DocProps
extends XmlDocumentProperties {
- private HashMap _map = new HashMap();
+ private final HashMap<Object, Object> _map = new HashMap<>();
public Object put(Object key, Object value) {
return _map.put(key, value);
@@ -1182,7 +1154,6 @@
c.push();
while (c.toParent()) {
- ;
}
DocProps props = (DocProps) c.getBookmark(DocProps.class);
@@ -1305,7 +1276,7 @@
return processWhiteSpaceRule(s, wsr);
}
}
- } else if (wsr == Locale.WS_COLLAPSE) {
+ } else if (wsr == WS_COLLAPSE) {
if (CharUtil.isWhiteSpace(s.charAt(0)) ||
CharUtil.isWhiteSpace(s.charAt(l - 1))) {
return processWhiteSpaceRule(s, wsr);
@@ -1352,7 +1323,7 @@
return;
}
- if (_wsr == Locale.WS_PRESERVE) {
+ if (_wsr == WS_PRESERVE) {
CharUtil.getString(_sb, src, off, cch);
return;
}
@@ -1384,7 +1355,7 @@
start = i + 1;
- if (_wsr == Locale.WS_REPLACE) {
+ if (_wsr == WS_REPLACE) {
_sb.append(' ');
} else if (_state == NOSPACE_STATE) {
_state = SPACE_SEEN_STATE;
@@ -1414,26 +1385,22 @@
private int _wsr;
private char[] _srcBuf = new char[1024];
- private StringBuffer _sb;
+ private final StringBuffer _sb;
}
- private static ThreadLocal tl_scrubBuffer =
- new ThreadLocal() {
- protected Object initialValue() {
- return new SoftReference(new ScrubBuffer());
- }
- };
+ private static final ThreadLocal<SoftReference<ScrubBuffer>> tl_scrubBuffer =
+ ThreadLocal.withInitial(() -> new SoftReference<>(new ScrubBuffer()));
public static void clearThreadLocals() {
tl_scrubBuffer.remove();
}
static ScrubBuffer getScrubBuffer(int wsr) {
- SoftReference softRef = (SoftReference) tl_scrubBuffer.get();
- ScrubBuffer scrubBuffer = (ScrubBuffer) (softRef).get();
+ SoftReference<ScrubBuffer> softRef = tl_scrubBuffer.get();
+ ScrubBuffer scrubBuffer = softRef.get();
if (scrubBuffer == null) {
scrubBuffer = new ScrubBuffer();
- tl_scrubBuffer.set(new SoftReference(scrubBuffer));
+ tl_scrubBuffer.set(new SoftReference<>(scrubBuffer));
}
scrubBuffer.init(wsr);
@@ -1756,14 +1723,10 @@
return false;
}
- static void applyNamespaces(Cur c, Map namespaces) {
+ static void applyNamespaces(Cur c, Map<String, String> namespaces) {
assert c.isContainer();
- java.util.Iterator i = namespaces.keySet().iterator();
-
- while (i.hasNext()) {
- String prefix = (String) i.next();
-
+ for (String prefix : namespaces.keySet()) {
// Usually, this is the predefined xml namespace
if (!prefix.toLowerCase().startsWith("xml")) {
if (c.namespaceForPrefix(prefix, false) == null) {
@@ -1773,7 +1736,7 @@
c.createAttr(c._locale.createXmlns(prefix));
c.next();
- c.insertString((String) namespaces.get(prefix));
+ c.insertString(namespaces.get(prefix));
c.pop();
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java b/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java
index 7097dd2..ce42f7a 100644
--- a/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java
@@ -1114,7 +1114,7 @@
Object src = getChars(p, cch);
- if (wsr == Locale.WS_PRESERVE) {
+ if (wsr == WS_PRESERVE) {
return CharUtil.getString(src, _locale._offSrc, _locale._cchSrc);
}
@@ -1130,20 +1130,18 @@
if (offset == posMax()) {
offset = -1;
}
- return getCharsAsString(offset, cch,
- Locale.WS_PRESERVE);
+ return getCharsAsString(offset, cch, WS_PRESERVE);
}
String getCharsValueAsString(int off, int cch) {
- return getCharsAsString(off + 1, cch,
- Locale.WS_PRESERVE);
+ return getCharsAsString(off + 1, cch, WS_PRESERVE);
}
String getValueAsString(int wsr) {
if (!hasChildren()) {
Object src = getFirstChars();
- if (wsr == Locale.WS_PRESERVE) {
+ if (wsr == WS_PRESERVE) {
String s = CharUtil.getString(src, _locale._offSrc, _locale._cchSrc);
// Cache string to be able to use it later again
@@ -1200,7 +1198,7 @@
}
String getValueAsString() {
- return getValueAsString(Locale.WS_PRESERVE);
+ return getValueAsString(WS_PRESERVE);
}
// Returns just chars just after the begin tag ... does not get all the text if there are
@@ -1537,7 +1535,7 @@
// when I make the store capable of handling strong simple types this
// can be done ...
- String value = getValueAsString(Locale.WS_COLLAPSE);
+ String value = getValueAsString(WS_COLLAPSE);
String prefix, localname;
@@ -1930,7 +1928,7 @@
return false;
}
- String value = a.getValueAsString(Locale.WS_COLLAPSE);
+ String value = a.getValueAsString(WS_COLLAPSE);
return value.equals("true") || value.equals("1");
} finally {
@@ -1989,17 +1987,17 @@
public <T extends XmlObject> void find_all_element_users(QName name, List<T> fillMeUp) {
for (Xobj x = _firstChild; x != null; x = x._nextSibling) {
if (x.isElem() && x._name.equals(name)) {
- fillMeUp.add((T)x.getUser());
+ fillMeUp.add((T) x.getUser());
}
}
}
@SuppressWarnings("unchecked")
@Override
- public <T extends XmlObject> void find_all_element_users(QNameSet names, List<T> fillMeUp) {
+ public <T extends XmlObject> void find_all_element_users(QNameSet names, List<T> fillMeUp) {
for (Xobj x = _firstChild; x != null; x = x._nextSibling) {
if (x.isElem() && names.contains(x._name)) {
- fillMeUp.add((T)x.getUser());
+ fillMeUp.add((T) x.getUser());
}
}
}
@@ -2345,9 +2343,9 @@
find_all_element_users(elementName, elementsUser);
List<Xobj> elements = elementsUser.stream()
- .map(x -> (TypeStoreUser)x)
+ .map(x -> (TypeStoreUser) x)
.map(TypeStoreUser::get_store)
- .map(x -> (Xobj)x)
+ .map(x -> (Xobj) x)
.collect(Collectors.toList());
assert elements.size() == n;
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java b/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java
index d6ae6ff..4cdbcf1 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java
@@ -15,23 +15,20 @@
package org.apache.xmlbeans.impl.tool;
-import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument;
-import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemaEntry;
-import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument.DownloadedSchemas;
-import org.apache.xmlbeans.impl.util.HexBin;
-import org.apache.xmlbeans.impl.common.IOUtil;
-import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.XmlOptions;
+import org.apache.xmlbeans.impl.common.IOUtil;
+import org.apache.xmlbeans.impl.util.HexBin;
+import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemaEntry;
+import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument;
+import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument.DownloadedSchemas;
+import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
+import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.ByteArrayInputStream;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.HashMap;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
@@ -39,146 +36,121 @@
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
-import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
-import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
-
-public abstract class BaseSchemaResourceManager extends SchemaImportResolver
-{
+public abstract class BaseSchemaResourceManager extends SchemaImportResolver {
private static final String USER_AGENT = "XMLBeans/" + XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")";
private String _defaultCopyDirectory;
private DownloadedSchemasDocument _importsDoc;
- private Map _resourceForFilename = new HashMap();
- private Map _resourceForURL = new HashMap();
- private Map _resourceForNamespace = new HashMap();
- private Map _resourceForDigest = new HashMap();
- private Map _resourceForCacheEntry = new HashMap();
- private Set _redownloadSet = new HashSet();
+ private final Map<String, SchemaResource> _resourceForFilename = new HashMap<>();
+ private final Map<String, SchemaResource> _resourceForURL = new HashMap<>();
+ private final Map<String, SchemaResource> _resourceForNamespace = new HashMap<>();
+ private final Map<String, SchemaResource> _resourceForDigest = new HashMap<>();
+ private final Map<DownloadedSchemaEntry, SchemaResource> _resourceForCacheEntry = new HashMap<>();
+ private Set<SchemaResource> _redownloadSet = new HashSet<>();
- protected BaseSchemaResourceManager()
- {
+ protected BaseSchemaResourceManager() {
// concrete subclasses should call init in their constructors
}
- protected final void init()
- {
- if (fileExists(getIndexFilename()))
- {
- try
- {
- _importsDoc = DownloadedSchemasDocument.Factory.parse( inputStreamForFile( getIndexFilename() ) );
- }
- catch (IOException e)
- {
+ protected final void init() {
+ if (fileExists(getIndexFilename())) {
+ try {
+ _importsDoc = DownloadedSchemasDocument.Factory.parse(inputStreamForFile(getIndexFilename()));
+ } catch (IOException e) {
_importsDoc = null;
- }
- catch (Exception e)
- {
- throw (IllegalStateException)(new IllegalStateException("Problem reading xsdownload.xml: please fix or delete this file")).initCause(e);
+ } catch (Exception e) {
+ throw new IllegalStateException("Problem reading xsdownload.xml: please fix or delete this file", e);
}
}
- if (_importsDoc == null)
- {
- try
- {
+ if (_importsDoc == null) {
+ try {
_importsDoc = DownloadedSchemasDocument.Factory.parse(
"<dls:downloaded-schemas xmlns:dls='http://www.bea.com/2003/01/xmlbean/xsdownload' defaultDirectory='" + getDefaultSchemaDir() + "'/>"
);
- }
- catch (Exception e)
- {
- throw (IllegalStateException)(new IllegalStateException()).initCause(e);
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
}
}
String defaultDir = _importsDoc.getDownloadedSchemas().getDefaultDirectory();
- if (defaultDir == null)
- defaultDir = getDefaultSchemaDir();;
+ if (defaultDir == null) {
+ defaultDir = getDefaultSchemaDir();
+ }
_defaultCopyDirectory = defaultDir;
// now initialize data structures
DownloadedSchemaEntry[] entries = _importsDoc.getDownloadedSchemas().getEntryArray();
- for (int i = 0; i < entries.length; i++)
- {
- updateResource(entries[i]);
+ for (DownloadedSchemaEntry entry : entries) {
+ updateResource(entry);
}
}
- public final void writeCache() throws IOException
- {
+ public final void writeCache() throws IOException {
InputStream input = _importsDoc.newInputStream(new XmlOptions().setSavePrettyPrint());
writeInputStreamToFile(input, getIndexFilename());
}
- public final void processAll(boolean sync, boolean refresh, boolean imports)
- {
- if (refresh)
- {
- _redownloadSet = new HashSet();
- }
- else
- {
- _redownloadSet = null;
- }
+ public final void processAll(boolean sync, boolean refresh, boolean imports) {
+ _redownloadSet = refresh ? new HashSet<>() : null;
String[] allFilenames = getAllXSDFilenames();
- if (sync)
+ if (sync) {
syncCacheWithLocalXsdFiles(allFilenames, false);
+ }
- SchemaResource[] starters = (SchemaResource[])
- _resourceForFilename.values().toArray(new SchemaResource[0]);
+ SchemaResource[] starters = _resourceForFilename.values().toArray(new SchemaResource[0]);
- if (refresh)
+ if (refresh) {
redownloadEntries(starters);
+ }
- if (imports)
+ if (imports) {
resolveImports(starters);
+ }
_redownloadSet = null;
}
- public final void process(String[] uris, String[] filenames, boolean sync, boolean refresh, boolean imports)
- {
- if (refresh)
- {
- _redownloadSet = new HashSet();
- }
- else
- {
- _redownloadSet = null;
- }
+ public final void process(String[] uris, String[] filenames, boolean sync, boolean refresh, boolean imports) {
+ _redownloadSet = refresh ? new HashSet<>() : null;
- if (filenames.length > 0)
+ if (filenames.length > 0) {
syncCacheWithLocalXsdFiles(filenames, true);
- else if (sync)
+ } else if (sync) {
syncCacheWithLocalXsdFiles(getAllXSDFilenames(), false);
-
- Set starterset = new HashSet();
-
- for (int i = 0; i < uris.length; i++)
- {
- SchemaResource resource = (SchemaResource)lookupResource(null, uris[i]);
- if (resource != null)
- starterset.add(resource);
}
- for (int i = 0; i < filenames.length; i++)
- {
- SchemaResource resource = (SchemaResource)_resourceForFilename.get(filenames);
- if (resource != null)
+ Set<SchemaResource> starterset = new HashSet<>();
+
+ for (String s : uris) {
+ SchemaResource resource = (SchemaResource) lookupResource(null, s);
+ if (resource != null) {
starterset.add(resource);
+ }
}
- SchemaResource[] starters = (SchemaResource[])
- starterset.toArray(new SchemaResource[0]);
+ for (String filename : filenames) {
+ SchemaResource resource = _resourceForFilename.get(filename);
+ if (resource != null) {
+ starterset.add(resource);
+ }
+ }
- if (refresh)
+ SchemaResource[] starters = starterset.toArray(new SchemaResource[0]);
+
+ if (refresh) {
redownloadEntries(starters);
+ }
- if (imports)
+ if (imports) {
resolveImports(starters);
+ }
_redownloadSet = null;
}
@@ -186,56 +158,49 @@
/**
* Adds items to the cache that point to new files that aren't
* described in the cache, and optionally deletes old entries.
- *
+ * <p>
* If an old file is gone and a new file is
* found with exactly the same contents, the cache entry is moved
* to point to the new file.
*/
- public final void syncCacheWithLocalXsdFiles(String[] filenames, boolean deleteOnlyMentioned)
- {
- Set seenResources = new HashSet();
- Set vanishedResources = new HashSet();
+ public final void syncCacheWithLocalXsdFiles(String[] filenames, boolean deleteOnlyMentioned) {
+ Set<SchemaResource> seenResources = new HashSet<>();
+ Set<SchemaResource> vanishedResources = new HashSet<>();
- for (int i = 0; i < filenames.length; i++)
- {
- String filename = filenames[i];
-
+ for (String filename : filenames) {
// first, if the filename matches exactly, trust the filename
- SchemaResource resource = (SchemaResource)_resourceForFilename.get(filename);
- if (resource != null)
- {
- if (fileExists(filename))
+ SchemaResource resource = _resourceForFilename.get(filename);
+ if (resource != null) {
+ if (fileExists(filename)) {
seenResources.add(resource);
- else
+ } else {
vanishedResources.add(resource);
+ }
continue;
}
// new file that is not in the index?
// not if the digest is known to the index and the original file is gone - that's a rename!
String digest = null;
- try
- {
+ try {
digest = shaDigestForFile(filename);
- resource = (SchemaResource)_resourceForDigest.get(digest);
- if (resource != null)
- {
+ resource = _resourceForDigest.get(digest);
+ if (resource != null) {
String oldFilename = resource.getFilename();
- if (!fileExists(oldFilename))
- {
+ if (!fileExists(oldFilename)) {
warning("File " + filename + " is a rename of " + oldFilename);
resource.setFilename(filename);
seenResources.add(resource);
- if (_resourceForFilename.get(oldFilename) == resource)
+ if (_resourceForFilename.get(oldFilename) == resource) {
_resourceForFilename.remove(oldFilename);
- if (_resourceForFilename.containsKey(filename))
+ }
+ if (_resourceForFilename.containsKey(filename)) {
_resourceForFilename.put(filename, resource);
+ }
continue;
}
}
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
// unable to read digest... no problem, ignore then
}
@@ -243,68 +208,65 @@
DownloadedSchemaEntry newEntry = addNewEntry();
newEntry.setFilename(filename);
warning("Caching information on new local file " + filename);
- if (digest != null)
+ if (digest != null) {
newEntry.setSha1(digest);
+ }
seenResources.add(updateResource(newEntry));
}
- if (deleteOnlyMentioned)
+ if (deleteOnlyMentioned) {
deleteResourcesInSet(vanishedResources, true);
- else
+ } else {
deleteResourcesInSet(seenResources, false);
+ }
}
/**
* Iterates through every entry and refetches it from its primary URL,
* if known. Replaces the contents of the file if the data is different.
*/
- private void redownloadEntries(SchemaResource[] resources)
- {
- for (int i = 0; i < resources.length; i++)
- {
- redownloadResource(resources[i]);
+ private void redownloadEntries(SchemaResource[] resources) {
+ for (SchemaResource resource : resources) {
+ redownloadResource(resource);
}
}
- private void deleteResourcesInSet(Set seenResources, boolean setToDelete)
- {
- Set seenCacheEntries = new HashSet();
- for (Iterator i = seenResources.iterator(); i.hasNext(); )
- {
- SchemaResource resource = (SchemaResource)i.next();
+ private void deleteResourcesInSet(Set<SchemaResource> seenResources, boolean setToDelete) {
+ Set<DownloadedSchemaEntry> seenCacheEntries = new HashSet<>();
+ for (SchemaResource resource : seenResources) {
seenCacheEntries.add(resource._cacheEntry);
}
DownloadedSchemas downloadedSchemas = _importsDoc.getDownloadedSchemas();
- for (int i = 0; i < downloadedSchemas.sizeOfEntryArray(); i++)
- {
+ for (int i = 0; i < downloadedSchemas.sizeOfEntryArray(); i++) {
DownloadedSchemaEntry cacheEntry = downloadedSchemas.getEntryArray(i);
- if (seenCacheEntries.contains(cacheEntry) == setToDelete)
- {
- SchemaResource resource = (SchemaResource)_resourceForCacheEntry.get(cacheEntry);
- warning("Removing obsolete cache entry for " + resource.getFilename());
+ if (seenCacheEntries.contains(cacheEntry) == setToDelete) {
+ SchemaResource resource = _resourceForCacheEntry.get(cacheEntry);
- if (resource != null)
- {
+ if (resource != null) {
+ warning("Removing obsolete cache entry for " + resource.getFilename());
_resourceForCacheEntry.remove(cacheEntry);
- if (resource == _resourceForFilename.get(resource.getFilename()))
+ if (resource == _resourceForFilename.get(resource.getFilename())) {
_resourceForFilename.remove(resource.getFilename());
+ }
- if (resource == _resourceForDigest.get(resource.getSha1()))
+ if (resource == _resourceForDigest.get(resource.getSha1())) {
_resourceForDigest.remove(resource.getSha1());
+ }
- if (resource == _resourceForNamespace.get(resource.getNamespace()))
+ if (resource == _resourceForNamespace.get(resource.getNamespace())) {
_resourceForNamespace.remove(resource.getNamespace());
+ }
// Finally, any or all URIs
String[] urls = resource.getSchemaLocationArray();
- for (int j = 0; j < urls.length; j++)
- {
- if (resource == _resourceForURL.get(urls[j]))
- _resourceForURL.remove(urls[j]);
+ for (String url : urls) {
+ if (resource == _resourceForURL.get(url)) {
+ _resourceForURL.remove(url);
+ }
}
}
@@ -314,141 +276,130 @@
}
}
- private SchemaResource updateResource(DownloadedSchemaEntry entry)
- {
+ private SchemaResource updateResource(DownloadedSchemaEntry entry) {
// The file
String filename = entry.getFilename();
- if (filename == null)
+ if (filename == null) {
return null;
+ }
SchemaResource resource = new SchemaResource(entry);
_resourceForCacheEntry.put(entry, resource);
- if (!_resourceForFilename.containsKey(filename))
+ if (!_resourceForFilename.containsKey(filename)) {
_resourceForFilename.put(filename, resource);
+ }
// The digest
String digest = resource.getSha1();
- if (digest != null)
- {
- if (!_resourceForDigest.containsKey(digest))
+ if (digest != null) {
+ if (!_resourceForDigest.containsKey(digest)) {
_resourceForDigest.put(digest, resource);
+ }
}
// Next, the namespace
String namespace = resource.getNamespace();
- if (namespace != null)
- {
- if (!_resourceForNamespace.containsKey(namespace))
+ if (namespace != null) {
+ if (!_resourceForNamespace.containsKey(namespace)) {
_resourceForNamespace.put(namespace, resource);
+ }
}
// Finally, any or all URIs
String[] urls = resource.getSchemaLocationArray();
- for (int j = 0; j < urls.length; j++)
- {
- if (!_resourceForURL.containsKey(urls[j]))
- _resourceForURL.put(urls[j], resource);
+ for (String url : urls) {
+ if (!_resourceForURL.containsKey(url)) {
+ _resourceForURL.put(url, resource);
+ }
}
return resource;
}
- private static DigestInputStream digestInputStream(InputStream input)
- {
+ private static DigestInputStream digestInputStream(InputStream input) {
MessageDigest sha;
- try
- {
+ try {
sha = MessageDigest.getInstance("SHA");
- }
- catch (NoSuchAlgorithmException e)
- {
- throw (IllegalStateException)(new IllegalStateException().initCause(e));
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException(e);
}
- DigestInputStream str = new DigestInputStream(input, sha);
-
- return str;
+ return new DigestInputStream(input, sha);
}
- private DownloadedSchemaEntry addNewEntry()
- {
+ private DownloadedSchemaEntry addNewEntry() {
return _importsDoc.getDownloadedSchemas().addNewEntry();
}
- private class SchemaResource implements SchemaImportResolver.SchemaResource
- {
- SchemaResource(DownloadedSchemaEntry entry)
- {
+ private class SchemaResource implements SchemaImportResolver.SchemaResource {
+ SchemaResource(DownloadedSchemaEntry entry) {
_cacheEntry = entry;
}
DownloadedSchemaEntry _cacheEntry;
- public void setFilename(String filename)
- {
+ public void setFilename(String filename) {
_cacheEntry.setFilename(filename);
}
- public String getFilename()
- {
+ public String getFilename() {
return _cacheEntry.getFilename();
}
- public Schema getSchema()
- {
- if (!fileExists(getFilename()))
+ public Schema getSchema() {
+ if (!fileExists(getFilename())) {
redownloadResource(this);
-
- try
- {
- return SchemaDocument.Factory.parse(inputStreamForFile(getFilename())).getSchema();
}
- catch (Exception e)
- {
+
+ try {
+ return SchemaDocument.Factory.parse(inputStreamForFile(getFilename())).getSchema();
+ } catch (Exception e) {
return null; // return null if _any_ problems reading schema file
}
}
- public String getSha1()
- {
+ public String getSha1() {
return _cacheEntry.getSha1();
}
- public String getNamespace()
- {
+ public String getNamespace() {
return _cacheEntry.getNamespace();
}
- public void setNamespace(String namespace)
- {
+ public void setNamespace(String namespace) {
_cacheEntry.setNamespace(namespace);
}
- public String getSchemaLocation()
- {
- if (_cacheEntry.sizeOfSchemaLocationArray() > 0)
+ public String getSchemaLocation() {
+ if (_cacheEntry.sizeOfSchemaLocationArray() > 0) {
return _cacheEntry.getSchemaLocationArray(0);
+ }
return null;
}
- public String[] getSchemaLocationArray()
- {
+ public String[] getSchemaLocationArray() {
return _cacheEntry.getSchemaLocationArray();
}
- public int hashCode()
- {
+ public int hashCode() {
return getFilename().hashCode();
}
- public boolean equals(Object obj)
- {
- return this == obj || getFilename().equals(((SchemaResource)obj).getFilename());
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+
+ if (!(obj instanceof SchemaResource)) {
+ return false;
+ }
+
+ SchemaResource sr = (SchemaResource) obj;
+ return getFilename().equals(sr.getFilename());
}
- public void addSchemaLocation(String schemaLocation)
- {
+ public void addSchemaLocation(String schemaLocation) {
_cacheEntry.addSchemaLocation(schemaLocation);
}
}
@@ -458,74 +409,72 @@
* given import. Should return a SchemaResource whose
* "equals" relationship reveals when a SchemaResource is
* duplicated and shouldn't be examined again.
- *
+ * <p>
* Returns null if the resource reference should be ignored.
*/
- public SchemaImportResolver.SchemaResource lookupResource(String nsURI, String schemaLocation)
- {
+ public SchemaImportResolver.SchemaResource lookupResource(String nsURI, String schemaLocation) {
SchemaResource result = fetchFromCache(nsURI, schemaLocation);
- if (result != null)
- {
- if (_redownloadSet != null)
- {
+ if (result != null) {
+ if (_redownloadSet != null) {
redownloadResource(result);
}
return result;
}
- if (schemaLocation == null)
- {
+ if (schemaLocation == null) {
warning("No cached schema for namespace '" + nsURI + "', and no url specified");
return null;
}
result = copyOrIdentifyDuplicateURL(schemaLocation, nsURI);
- if (_redownloadSet != null)
+ if (_redownloadSet != null) {
_redownloadSet.add(result);
+ }
return result;
}
- private SchemaResource fetchFromCache(String nsURI, String schemaLocation)
- {
+ private SchemaResource fetchFromCache(String nsURI, String schemaLocation) {
SchemaResource result;
- if (schemaLocation != null)
- {
- result = (SchemaResource)_resourceForURL.get(schemaLocation);
- if (result != null)
+ if (schemaLocation != null) {
+ result = _resourceForURL.get(schemaLocation);
+ if (result != null) {
return result;
+ }
}
- if (nsURI != null)
- {
- result = (SchemaResource)_resourceForNamespace.get(nsURI);
- if (result != null)
+ if (nsURI != null) {
+ result = _resourceForNamespace.get(nsURI);
+ if (result != null) {
return result;
+ }
}
return null;
}
- private String uniqueFilenameForURI(String schemaLocation) throws IOException, URISyntaxException
- {
- String localFilename = new URI( schemaLocation ).getRawPath();
+ private String uniqueFilenameForURI(String schemaLocation) throws IOException, URISyntaxException {
+ String localFilename = new URI(schemaLocation).getRawPath();
int i = localFilename.lastIndexOf('/');
- if (i >= 0)
+ if (i >= 0) {
localFilename = localFilename.substring(i + 1);
- if (localFilename.endsWith(".xsd"))
+ }
+ if (localFilename.endsWith(".xsd")) {
localFilename = localFilename.substring(0, localFilename.length() - 4);
- if (localFilename.length() == 0)
+ }
+ if (localFilename.length() == 0) {
localFilename = "schema";
+ }
// TODO: remove other unsafe characters for filenames?
String candidateFilename = localFilename;
int suffix = 1;
- while (suffix < 1000)
- {
+ while (suffix < 1000) {
String candidate = _defaultCopyDirectory + "/" + candidateFilename + ".xsd";
- if (!fileExists(candidate))
+ if (!fileExists(candidate)) {
return candidate;
+ }
suffix += 1;
candidateFilename = localFilename + suffix;
}
@@ -533,54 +482,47 @@
throw new IOException("Problem with filename " + localFilename + ".xsd");
}
- private void redownloadResource(SchemaResource resource)
- {
- if (_redownloadSet != null)
- {
- if (_redownloadSet.contains(resource))
+ private void redownloadResource(SchemaResource resource) {
+ if (_redownloadSet != null) {
+ if (_redownloadSet.contains(resource)) {
return;
+ }
_redownloadSet.add(resource);
}
String filename = resource.getFilename();
String schemaLocation = resource.getSchemaLocation();
- String digest = null;
+ String digest;
// nothing to do?
- if (schemaLocation == null || filename == null)
+ if (schemaLocation == null || filename == null) {
return;
+ }
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
- try
- {
- URL url = new URL( schemaLocation );
+ try {
+ URL url = new URL(schemaLocation);
URLConnection conn = url.openConnection();
conn.addRequestProperty("User-Agent", USER_AGENT);
conn.addRequestProperty("Accept", "application/xml, text/xml, */*");
DigestInputStream input = digestInputStream(conn.getInputStream());
IOUtil.copyCompletely(input, buffer);
digest = HexBin.bytesToString(input.getMessageDigest().digest());
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage());
return;
}
- if (digest.equals(resource.getSha1()) && fileExists(filename))
- {
+ if (digest.equals(resource.getSha1()) && fileExists(filename)) {
warning("Resource " + filename + " is unchanged from " + schemaLocation + ".");
return;
}
- try
- {
+ try {
InputStream source = new ByteArrayInputStream(buffer.toByteArray());
writeInputStreamToFile(source, filename);
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
warning("Could not write to file " + filename + " for " + schemaLocation + ":" + e.getMessage());
return;
}
@@ -588,47 +530,38 @@
warning("Refreshed " + filename + " from " + schemaLocation);
}
- private SchemaResource copyOrIdentifyDuplicateURL(String schemaLocation, String namespace)
- {
+ private SchemaResource copyOrIdentifyDuplicateURL(String schemaLocation, String namespace) {
String targetFilename;
String digest;
SchemaResource result;
- try
- {
+ try {
targetFilename = uniqueFilenameForURI(schemaLocation);
- }
- catch (URISyntaxException e)
- {
+ } catch (URISyntaxException e) {
warning("Invalid URI '" + schemaLocation + "':" + e.getMessage());
return null;
- }
- catch (IOException e)
- {
+ } catch (IOException e) {
warning("Could not create local file for " + schemaLocation + ":" + e.getMessage());
return null;
}
- try
- {
- URL url = new URL( schemaLocation );
+ try {
+ URL url = new URL(schemaLocation);
DigestInputStream input = digestInputStream(url.openStream());
writeInputStreamToFile(input, targetFilename);
digest = HexBin.bytesToString(input.getMessageDigest().digest());
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage());
return null;
}
- result = (SchemaResource)_resourceForDigest.get(digest);
- if (result != null)
- {
+ result = _resourceForDigest.get(digest);
+ if (result != null) {
deleteFile(targetFilename);
result.addSchemaLocation(schemaLocation);
- if (!_resourceForURL.containsKey(schemaLocation))
+ if (!_resourceForURL.containsKey(schemaLocation)) {
_resourceForURL.put(schemaLocation, result);
+ }
return result;
}
@@ -637,8 +570,9 @@
DownloadedSchemaEntry newEntry = addNewEntry();
newEntry.setFilename(targetFilename);
newEntry.setSha1(digest);
- if (namespace != null)
+ if (namespace != null) {
newEntry.setNamespace(namespace);
+ }
newEntry.addSchemaLocation(schemaLocation);
return updateResource(newEntry);
}
@@ -646,23 +580,26 @@
/**
* Updates actual namespace in the table.
*/
- public void reportActualNamespace(SchemaImportResolver.SchemaResource rresource, String actualNamespace)
- {
- SchemaResource resource = (SchemaResource)rresource;
+ public void reportActualNamespace(SchemaImportResolver.SchemaResource rresource, String actualNamespace) {
+ SchemaResource resource = (SchemaResource) rresource;
String oldNamespace = resource.getNamespace();
- if (oldNamespace != null && _resourceForNamespace.get(oldNamespace) == resource)
+ if (oldNamespace != null && _resourceForNamespace.get(oldNamespace) == resource) {
_resourceForNamespace.remove(oldNamespace);
- if (!_resourceForNamespace.containsKey(actualNamespace))
+ }
+ if (!_resourceForNamespace.containsKey(actualNamespace)) {
_resourceForNamespace.put(actualNamespace, resource);
+ }
resource.setNamespace(actualNamespace);
}
- private String shaDigestForFile(String filename) throws IOException
- {
+ private String shaDigestForFile(String filename) throws IOException {
DigestInputStream str = digestInputStream(inputStreamForFile(filename));
byte[] dummy = new byte[4096];
- for (int i = 1; i > 0; i = str.read(dummy));
+ int i = 1;
+ while (i > 0) {
+ i = str.read(dummy);
+ }
str.close();
@@ -671,13 +608,11 @@
// SOME METHODS TO OVERRIDE ============================
- protected String getIndexFilename()
- {
+ protected String getIndexFilename() {
return "./xsdownload.xml";
}
- protected String getDefaultSchemaDir()
- {
+ protected String getDefaultSchemaDir() {
return "./schema";
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
index b3f59ef..8f254e1 100644
--- a/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
+++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
@@ -132,6 +132,6 @@
}
byte[] res = md5.digest(_value);
- return hashcode = res[0] << 24 + res[1] << 16 + res[2] << 8 + res[3];
+ return hashcode = (res[0] << 24) | (res[1] << 16) | (res[2] << 8) | res[3];
}
}
diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
index 112c03d..51e0fe0 100644
--- a/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
+++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
@@ -133,7 +133,7 @@
}
byte[] res = md5.digest(_value);
- return hashcode = res[0] << 24 + res[1] << 16 + res[2] << 8 + res[3];
+ return hashcode = (res[0] << 24) | (res[1] << 16) | (res[2] << 8) | res[3];
}
}