Get an exception reporting an unexpected end tag for an XML element.
@param reader the stream reader
@return the exception
186575
public static XMLStreamException unexpectedEndElement(final XMLExtendedStreamReader reader) {
        return ControllerLogger.ROOT_LOGGER.unexpectedEndElement(reader.getName(), reader.getLocation());
    }
657913
public void parseXml(Reader reader) throws IOException, XmlPullParserException {
    this.xmlPullParser.setInput(reader);
    Xml.parseElement(this.xmlPullParser, this, this.defaultNamespaceDictionary, null);
  }
239623
private Exception handleXmlStreamException(XMLStreamException e) throws Exception {
        if (e.getNestedException() instanceof IOException) {
            return new IOException(e);
        }
        return e;
    }
1010232
@Override
  public MtasTokenCollection createTokenCollection(Reader reader)
      throws MtasParserException, MtasConfigException {
    Boolean hasRoot = rootTag == null ? true : false;
    Boolean parsingContent = contentTag == null ? true : false;
    String textContent = null;
    Integer unknownAncestors = 0;
    Integer lastOffset = 0;

    AtomicInteger position = new AtomicInteger(0);
    Map<String, Set<Integer>> idPositions = new HashMap<>();
    Map<String, Integer[]> idOffsets = new HashMap<>();

    Map<String, Map<Integer, Set<String>>> updateList = createUpdateList();
    Map<String, List<MtasParserObject>> currentList = createCurrentList();
    Map<String, Map<String, String>> variables = createVariables();

    tokenCollection = new MtasTokenCollection();
    MtasTokenIdFactory mtasTokenIdFactory = new MtasTokenIdFactory();
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {      
      XMLStreamReader streamReader = factory.createXMLStreamReader(reader);
      QName qname;
      try {
        int event = streamReader.getEventType();
        MtasParserType<?> currentType;
        MtasParserType<?> tmpCurrentType;
        MtasParserType<?> tmpVariableType;
        MtasParserObject currentObject = null;
        MtasParserObject variableObject = null;
        while (true) {
          switch (event) {
          case XMLStreamConstants.START_DOCUMENT:
            log.debug("start of document");
            String encodingScheme = streamReader.getCharacterEncodingScheme();
            if (encodingScheme == null) {
              //ignore for now
              log.info("No encodingScheme found, assume utf-8");
              //throw new MtasParserException("No encodingScheme found");              
            } else if (!encodingScheme.equalsIgnoreCase("utf-8")) {
              throw new MtasParserException(
                  "XML not UTF-8 encoded but '" + encodingScheme + "'");
            }
            break;
          case XMLStreamConstants.END_DOCUMENT:
            log.debug("end of document");
            break;
          case XMLStreamConstants.SPACE:
            // set offset (end of start-element)
            lastOffset = streamReader.getLocation().getCharacterOffset();
            break;
          case XMLStreamConstants.START_ELEMENT:
            // get data
            qname = streamReader.getName();
            // check for rootTag
            if (!hasRoot) {
              if (qname.equals(getQName(rootTag))) {
                hasRoot = true;
              } else {
                throw new MtasParserException("No " + rootTag);
              }
              // parse content
            } else {
              if ((tmpVariableType = variableTypes.get(qname)) != null) {
                variableObject = new MtasParserObject(tmpVariableType);
                collectAttributes(variableObject, streamReader);
                computeVariablesFromObject(variableObject, currentList,
                    variables);
              }
              if (parsingContent) {
                // check for relation : not within word, not within
                // groupAnnotation
                if ((currentList.get(MAPPING_TYPE_WORD).isEmpty())
                    && (currentList.get(MAPPING_TYPE_GROUP_ANNOTATION)
                        .isEmpty())
                    && (tmpCurrentType = relationTypes.get(qname)) != null) {
                  currentObject = new MtasParserObject(tmpCurrentType);
                  collectAttributes(currentObject, streamReader);
                  currentObject.setUnknownAncestorNumber(unknownAncestors);
                  currentObject.setRealOffsetStart(lastOffset);
                  if (!prevalidateObject(currentObject, currentList)) {
                    unknownAncestors++;
                  } else {
                    currentType = tmpCurrentType;
                    currentList.get(MAPPING_TYPE_RELATION).add(currentObject);
                    unknownAncestors = 0;
                  }
                  // check for relation annotation: not within word, but within
                  // relation
                } else if ((currentList.get(MAPPING_TYPE_WORD).isEmpty())
                    && (!currentList.get(MAPPING_TYPE_RELATION).isEmpty())
                    && (tmpCurrentType = relationAnnotationTypes
                        .get(qname)) != null) {
                  currentObject = new MtasParserObject(tmpCurrentType);
                  collectAttributes(currentObject, streamReader);
                  currentObject.setUnknownAncestorNumber(unknownAncestors);
                  currentObject.setRealOffsetStart(lastOffset);
                  if (!prevalidateObject(currentObject, currentList)) {
                    unknownAncestors++;
                  } else {
                    currentType = tmpCurrentType;
                    currentList.get(MAPPING_TYPE_RELATION_ANNOTATION)
                        .add(currentObject);
                    unknownAncestors = 0;
                  }
                  // check for group: not within word, not within relation, not
                  // within groupAnnotation
                } else if ((currentList.get(MAPPING_TYPE_WORD).isEmpty())
                    && (currentList.get(MAPPING_TYPE_RELATION).isEmpty())
                    && (currentList.get(MAPPING_TYPE_GROUP_ANNOTATION)
                        .isEmpty())
                    && (tmpCurrentType = groupTypes.get(qname)) != null) {
                  currentObject = new MtasParserObject(tmpCurrentType);
                  collectAttributes(currentObject, streamReader);
                  currentObject.setUnknownAncestorNumber(unknownAncestors);
                  currentObject.setRealOffsetStart(lastOffset);
                  if (!prevalidateObject(currentObject, currentList)) {
                    unknownAncestors++;
                  } else {
                    currentType = tmpCurrentType;
                    currentList.get(MAPPING_TYPE_GROUP).add(currentObject);
                    unknownAncestors = 0;
                  }
                  // check for group annotation: not within word, not within
                  // relation, but within group
                } else if ((currentList.get(MAPPING_TYPE_WORD).isEmpty())
                    && (currentList.get(MAPPING_TYPE_RELATION).isEmpty())
                    && (!currentList.get(MAPPING_TYPE_GROUP).isEmpty())
                    && (tmpCurrentType = groupAnnotationTypes
                        .get(qname)) != null) {
                  currentObject = new MtasParserObject(tmpCurrentType);
                  collectAttributes(currentObject, streamReader);
                  currentObject.setUnknownAncestorNumber(unknownAncestors);
                  currentObject.setRealOffsetStart(lastOffset);
                  if (!prevalidateObject(currentObject, currentList)) {
                    unknownAncestors++;
                  } else {
                    currentType = tmpCurrentType;
                    currentList.get(MAPPING_TYPE_GROUP_ANNOTATION)
                        .add(currentObject);
                    unknownAncestors = 0;
                  }
                  // check for word: not within relation, not within
                  // groupAnnotation, not within word, not within wordAnnotation
                } else if ((currentList.get(MAPPING_TYPE_RELATION).isEmpty())
                    && (currentList.get(MAPPING_TYPE_GROUP_ANNOTATION)
                        .isEmpty())
                    && (currentList.get(MAPPING_TYPE_WORD).isEmpty())
                    && (currentList.get(MAPPING_TYPE_WORD_ANNOTATION).isEmpty())
                    && (tmpCurrentType = wordTypes.get(qname)) != null) {
                  currentObject = new MtasParserObject(tmpCurrentType);
                  collectAttributes(currentObject, streamReader);
                  currentObject.setUnknownAncestorNumber(unknownAncestors);
                  currentObject.setOffsetStart(lastOffset);
                  currentObject.setRealOffsetStart(lastOffset);
                  if (!prevalidateObject(currentObject, currentList)) {
                    unknownAncestors++;
                  } else {
                    currentType = tmpCurrentType;
                    currentObject.addPosition(position.getAndIncrement());
                    currentList.get(MAPPING_TYPE_WORD).add(currentObject);
                    unknownAncestors = 0;
                  }
                  // check for word annotation: not within relation, not within
                  // groupAnnotation, but within word
                } else if ((currentList.get(MAPPING_TYPE_RELATION).isEmpty())
                    && (currentList.get(MAPPING_TYPE_GROUP_ANNOTATION)
                        .isEmpty())
                    && (!currentList.get(MAPPING_TYPE_WORD).isEmpty())
                    && (tmpCurrentType = wordAnnotationTypes
                        .get(qname)) != null) {
                  currentObject = new MtasParserObject(tmpCurrentType);
                  collectAttributes(currentObject, streamReader);
                  currentObject.addPositions(currentList.get(MAPPING_TYPE_WORD)
                      .get((currentList.get(MAPPING_TYPE_WORD).size() - 1))
                      .getPositions());
                  currentObject.setUnknownAncestorNumber(unknownAncestors);
                  currentObject.setRealOffsetStart(lastOffset);
                  if (!prevalidateObject(currentObject, currentList)) {
                    unknownAncestors++;
                  } else {
                    currentType = tmpCurrentType;
                    currentList.get(MAPPING_TYPE_WORD_ANNOTATION)
                        .add(currentObject);
                    unknownAncestors = 0;
                  }
                  // check for references: within relation
                } else if (!currentList.get(MAPPING_TYPE_RELATION).isEmpty()
                    && (tmpCurrentType = refTypes.get(qname)) != null) {
                  currentObject = new MtasParserObject(tmpCurrentType);
                  collectAttributes(currentObject, streamReader);
                  currentObject.setUnknownAncestorNumber(unknownAncestors);
                  currentObject.setRealOffsetStart(lastOffset);
                  if (!prevalidateObject(currentObject, currentList)) {
                    unknownAncestors++;
                  } else {
                    currentType = tmpCurrentType;
                    currentList.get(MAPPING_TYPE_REF).add(currentObject);
                    unknownAncestors = 0;
                    // add reference to ancestor relations
                    for (MtasParserObject currentRelation : currentList
                        .get(MAPPING_TYPE_RELATION)) {
                      currentRelation.addRefId(currentObject
                          .getAttribute(currentType.getRefAttributeName()));
                      // register mapping for relation (for recursive relations)
                      SortedSet<String> keyMapList;
                      if (currentRelation.getId() != null) {
                        if (relationKeyMap
                            .containsKey(currentRelation.getId())) {
                          keyMapList = relationKeyMap
                              .get(currentRelation.getId());
                        } else {
                          keyMapList = new TreeSet<>();
                          relationKeyMap.put(currentRelation.getId(),
                              keyMapList);
                        }
                        keyMapList.add(currentObject
                            .getAttribute(currentType.getRefAttributeName()));
                      }
                    }
                  }
                } else {
                  unknownAncestors++;
                }
                // check for start content
              } else if (qname.equals(getQName(contentTag))) {
                parsingContent = true;
                // unexpected
              } else if (!allowNonContent) {
                throw new MtasParserException(
                    "Unexpected " + qname.getLocalPart() + " in document");
              }
            }
            // set offset (end of start-element)
            lastOffset = streamReader.getLocation().getCharacterOffset();
            break;
          case XMLStreamConstants.END_ELEMENT:
            // set offset (end of end-element)
            lastOffset = streamReader.getLocation().getCharacterOffset();
            // get data
            qname = streamReader.getName();
            // parse content
            if (parsingContent) {
              if (unknownAncestors > 0) {
                unknownAncestors--;
                // check for reference: because otherwise currentList should
                // contain no references
              } else if (!currentList.get(MAPPING_TYPE_REF).isEmpty()) {
                if ((currentType = refTypes.get(qname)) != null) {
                  currentObject = currentList.get(MAPPING_TYPE_REF)
                      .remove(currentList.get(MAPPING_TYPE_REF).size() - 1);
                  assert currentObject.getType()
                      .equals(currentType) : "object expected to be "
                          + currentObject.getType().getName() + ", not "
                          + currentType.getName();
                  assert unknownAncestors == 0 : "error in administration "
                      + currentObject.getType().getName();
                  // ignore text and realOffset: not relevant
                  idPositions.put(currentObject.getId(),
                      currentObject.getPositions());
                  idOffsets.put(currentObject.getId(),
                      currentObject.getOffset());
                  currentObject.updateMappings(idPositions, idOffsets);
                  unknownAncestors = currentObject.getUnknownAncestorNumber();
                  computeMappingsFromObject(mtasTokenIdFactory, currentObject,
                      currentList, updateList);
                } else {
                  // this shouldn't happen
                }
                // check for wordAnnotation: because otherwise currentList
                // should contain no wordAnnotations
              } else if (!currentList.get(MAPPING_TYPE_WORD_ANNOTATION)
                  .isEmpty()) {
                if ((currentType = wordAnnotationTypes.get(qname)) != null) {
                  currentObject = currentList.get(MAPPING_TYPE_WORD_ANNOTATION)
                      .remove(
                          currentList.get(MAPPING_TYPE_WORD_ANNOTATION).size()
                              - 1);
                  assert currentObject.getType()
                      .equals(currentType) : "object expected to be "
                          + currentObject.getType().getName() + ", not "
                          + currentType.getName();
                  assert unknownAncestors == 0 : "error in administration "
                      + currentObject.getType().getName();
                  currentObject.setRealOffsetEnd(lastOffset);
                  idPositions.put(currentObject.getId(),
                      currentObject.getPositions());
                  idOffsets.put(currentObject.getId(),
                      currentObject.getOffset());
                  // offset always null, so update later with word (should be
                  // possible)
                  if ((currentObject.getId() != null)
                      && (!currentList.get(MAPPING_TYPE_WORD).isEmpty())) {
                    currentList.get(MAPPING_TYPE_WORD)
                        .get((currentList.get(MAPPING_TYPE_WORD).size() - 1))
                        .addUpdateableIdWithOffset(currentObject.getId());
                  }
                  currentObject.updateMappings(idPositions, idOffsets);
                  unknownAncestors = currentObject.getUnknownAncestorNumber();
                  computeMappingsFromObject(mtasTokenIdFactory, currentObject,
                      currentList, updateList);
                } else {
                  // this shouldn't happen
                }
                // check for word: because otherwise currentList should contain
                // no words
              } else if (!currentList.get(MAPPING_TYPE_WORD).isEmpty()) {
                if ((currentType = wordTypes.get(qname)) != null) {
                  currentObject = currentList.get(MAPPING_TYPE_WORD)
                      .remove(currentList.get(MAPPING_TYPE_WORD).size() - 1);
                  assert currentObject.getType()
                      .equals(currentType) : "object expected to be "
                          + currentObject.getType().getName() + ", not "
                          + currentType.getName();
                  assert unknownAncestors == 0 : "error in administration "
                      + currentObject.getType().getName();
                  currentObject.setOffsetEnd(lastOffset);
                  currentObject.setRealOffsetEnd(lastOffset);
                  // update ancestor groups with position and offset
                  for (MtasParserObject currentGroup : currentList
                      .get(MAPPING_TYPE_GROUP)) {
                    currentGroup.addPositions(currentObject.getPositions());
                    currentGroup.addOffsetStart(currentObject.getOffsetStart());
                    currentGroup.addOffsetEnd(currentObject.getOffsetEnd());
                  }
                  idPositions.put(currentObject.getId(),
                      currentObject.getPositions());
                  idOffsets.put(currentObject.getId(),
                      currentObject.getOffset());
                  currentObject.updateMappings(idPositions, idOffsets);
                  unknownAncestors = currentObject.getUnknownAncestorNumber();
                  computeMappingsFromObject(mtasTokenIdFactory, currentObject,
                      currentList, updateList);
                } else {
                  // this shouldn't happen
                }
                // check for group annotation: because otherwise currentList
                // should contain no groupAnnotations
              } else if (!currentList.get(MAPPING_TYPE_GROUP_ANNOTATION)
                  .isEmpty()) {
                if ((currentType = groupAnnotationTypes.get(qname)) != null) {
                  currentObject = currentList.get(MAPPING_TYPE_GROUP_ANNOTATION)
                      .remove(
                          currentList.get(MAPPING_TYPE_GROUP_ANNOTATION).size()
                              - 1);
                  assert currentObject.getType()
                      .equals(currentType) : "object expected to be "
                          + currentObject.getType().getName() + ", not "
                          + currentType.getName();
                  assert unknownAncestors == 0 : "error in administration "
                      + currentObject.getType().getName();
                  currentObject.setRealOffsetEnd(lastOffset);
                  idPositions.put(currentObject.getId(),
                      currentObject.getPositions());
                  idOffsets.put(currentObject.getId(),
                      currentObject.getOffset());
                  currentObject.updateMappings(idPositions, idOffsets);
                  unknownAncestors = currentObject.getUnknownAncestorNumber();
                  computeMappingsFromObject(mtasTokenIdFactory, currentObject,
                      currentList, updateList);
                } else {
                  // this shouldn't happen
                }
                // check for relation annotation
              } else if (!currentList.get(MAPPING_TYPE_RELATION_ANNOTATION)
                  .isEmpty()) {
                if ((currentType = relationAnnotationTypes
                    .get(qname)) != null) {
                  currentObject = currentList
                      .get(MAPPING_TYPE_RELATION_ANNOTATION).remove(currentList
                          .get(MAPPING_TYPE_RELATION_ANNOTATION).size() - 1);
                  assert currentObject.getType()
                      .equals(currentType) : "object expected to be "
                          + currentObject.getType().getName() + ", not "
                          + currentType.getName();
                  assert unknownAncestors == 0 : "error in administration "
                      + currentObject.getType().getName();
                  currentObject.setRealOffsetEnd(lastOffset);
                  idPositions.put(currentObject.getId(),
                      currentObject.getPositions());
                  idOffsets.put(currentObject.getId(),
                      currentObject.getOffset());
                  currentObject.updateMappings(idPositions, idOffsets);
                  unknownAncestors = currentObject.getUnknownAncestorNumber();
                  computeMappingsFromObject(mtasTokenIdFactory, currentObject,
                      currentList, updateList);
                } else {
                  // this shouldn't happen
                }
                // check for relation
              } else if (!currentList.get(MAPPING_TYPE_RELATION).isEmpty()) {
                if ((currentType = relationTypes.get(qname)) != null) {
                  currentObject = currentList.get(MAPPING_TYPE_RELATION).remove(
                      currentList.get(MAPPING_TYPE_RELATION).size() - 1);
                  assert currentObject.getType()
                      .equals(currentType) : "object expected to be "
                          + currentObject.getType().getName() + ", not "
                          + currentType.getName();
                  assert unknownAncestors == 0 : "error in administration "
                      + currentObject.getType().getName();
                  // ignore text: should not occur
                  currentObject.setRealOffsetEnd(lastOffset);
                  idPositions.put(currentObject.getId(),
                      currentObject.getPositions());
                  idOffsets.put(currentObject.getId(),
                      currentObject.getOffset());
                  currentObject.updateMappings(idPositions, idOffsets);
                  unknownAncestors = currentObject.getUnknownAncestorNumber();
                  computeMappingsFromObject(mtasTokenIdFactory, currentObject,
                      currentList, updateList);
                } else {
                  // this shouldn't happen
                }
                // check for group
              } else if (!currentList.get(MAPPING_TYPE_GROUP).isEmpty()) {
                if ((currentType = groupTypes.get(qname)) != null) {
                  currentObject = currentList.get(MAPPING_TYPE_GROUP)
                      .remove(currentList.get(MAPPING_TYPE_GROUP).size() - 1);
                  assert currentObject.getType()
                      .equals(currentType) : "object expected to be "
                          + currentObject.getType().getName() + ", not "
                          + currentType.getName();
                  assert unknownAncestors == 0 : "error in administration "
                      + currentObject.getType().getName();
                  // ignore text: should not occur
                  currentObject.setRealOffsetEnd(lastOffset);
                  idPositions.put(currentObject.getId(),
                      currentObject.getPositions());
                  idOffsets.put(currentObject.getId(),
                      currentObject.getOffset());
                  currentObject.updateMappings(idPositions, idOffsets);
                  unknownAncestors = currentObject.getUnknownAncestorNumber();
                  computeMappingsFromObject(mtasTokenIdFactory, currentObject,
                      currentList, updateList);
                } else {
                  unknownAncestors--;
                }
              } else if (qname.equals(getQName("text"))) {
                parsingContent = false;
                assert unknownAncestors == 0 : "error in administration unknownAncestors";
                assert currentList.get(MAPPING_TYPE_REF)
                    .isEmpty() : "error in administration references";
                assert currentList.get(MAPPING_TYPE_GROUP)
                    .isEmpty() : "error in administration groups";
                assert currentList.get(MAPPING_TYPE_GROUP_ANNOTATION)
                    .isEmpty() : "error in administration groupAnnotations";
                assert currentList.get(MAPPING_TYPE_WORD)
                    .isEmpty() : "error in administration words";
                assert currentList.get(MAPPING_TYPE_WORD_ANNOTATION)
                    .isEmpty() : "error in administration wordAnnotations";
                assert currentList.get(MAPPING_TYPE_RELATION)
                    .isEmpty() : "error in administration relations";
                assert currentList.get(MAPPING_TYPE_RELATION_ANNOTATION)
                    .isEmpty() : "error in administration relationAnnotations";
              }
            }
            // forget text
            textContent = null;
            break;
          case XMLStreamConstants.CHARACTERS:
            // set offset (end of start-element)
            lastOffset = streamReader.getLocation().getCharacterOffset();
            // check for text
            if (streamReader.hasText()) {
              textContent = streamReader.getText();
            }
            if (currentObject != null && unknownAncestors.equals(0)) {
              currentObject.addText(textContent);
            }
            break;
          default:
            break;
          }
          if (!streamReader.hasNext()) {
            break;
          }
          event = streamReader.next();
        }
      } finally {
        streamReader.close();
      }
      // final checks
      assert unknownAncestors == 0 : "error in administration unknownAncestors";
      assert hasRoot : "no " + rootTag;
    } catch (XMLStreamException e) {
      log.debug(e);      
      throw new MtasParserException("No valid XML: " + e.getMessage());
    }

    // update tokens with variable
    for (Entry<Integer, Set<String>> updateItem : updateList
        .get(UPDATE_TYPE_VARIABLE).entrySet()) {
      MtasToken token = tokenCollection.get(updateItem.getKey());
      String encodedPrefix = token.getPrefix();
      String encodedPostfix = token.getPostfix();
      token.setValue(decodeAndUpdateWithVariables(encodedPrefix, encodedPostfix,
          variables));
    }
    // update tokens with offset
    for (Entry<Integer, Set<String>> updateItem : updateList
        .get(UPDATE_TYPE_OFFSET).entrySet()) {
      Set<String> refIdList = new HashSet<>();
      for (String refId : updateItem.getValue()) {
        if (idPositions.containsKey(refId)) {
          refIdList.add(refId);
        }
        if (relationKeyMap.containsKey(refId)) {
          refIdList.addAll(recursiveCollect(refId, relationKeyMap, 10));
        }
      }
      for (String refId : refIdList) {
        Integer[] refOffset = idOffsets.get(refId);
        Integer tokenId = updateItem.getKey();
        if (tokenId != null && refOffset != null) {
          MtasToken token = tokenCollection.get(tokenId);
          token.addOffset(refOffset[0], refOffset[1]);
        }
      }
    }
    // update tokens with position
    for (Entry<Integer, Set<String>> updateItem : updateList
        .get(UPDATE_TYPE_POSITION).entrySet()) {
      HashSet<String> refIdList = new HashSet<>();
      for (String refId : updateItem.getValue()) {
        if (idPositions.containsKey(refId)) {
          refIdList.add(refId);
        }
        if (relationKeyMap.containsKey(refId)) {
          refIdList.addAll(recursiveCollect(refId, relationKeyMap, 10));
        }
      }
      for (String refId : refIdList) {
        Set<Integer> refPositions = idPositions.get(refId);
        Integer tokenId = updateItem.getKey();
        if (tokenId != null && refPositions != null) {
          MtasToken token = tokenCollection.get(tokenId);
          token.addPositions(refPositions);
        }
      }
    }
    // final check
    tokenCollection.check(autorepair, makeunique);
    return tokenCollection;
  }
1035208
@Override
    public void endElement( String uri, String localName, String qName )
        throws SAXException
    {
        flushCharacters();
        if ( stack.isEmpty() )
        {
            throw new IllegalStateException( "Stack must not be empty when closing the element " + qName
                + " around line " + locator.getLineNumber() + " and column " + locator.getColumnNumber() );
        }
        IndentCheckSaxHandler.ElementEntry startEntry = stack.pop();
        int indentDiff = lastIndent.size - startEntry.expectedIndent.size;
        int expectedIndent = startEntry.expectedIndent.size;
        if ( lastIndent.lineNumber != startEntry.foundIndent.lineNumber && indentDiff != 0 )
        {
            /*
             * diff should be zero unless we are on the same line as start element
             */
            int opValue = expectedIndent - lastIndent.size;
            String op = opValue > 0 ? "Insert" : "Delete";
            String units = opValue == 1 ? "space" : "spaces";
            String message = op + " " + Math.abs( opValue ) + " " + units + ". Expected " + expectedIndent + " found "
                + lastIndent.size + " spaces before end element </" + qName + ">";
            XmlFormatViolation violation =
                new XmlFormatViolation( file, locator.getLineNumber(), locator.getColumnNumber(), message );
            violationHandler.handle( violation );
        }
    }
910459
protected Driver parseDriver(XMLStreamReader reader) throws XMLStreamException, ParserException,
      ValidateException
   {
      String driverClass = null;
      String dataSourceClass = null;
      String xaDataSourceClass = null;

      //attributes reading

      String name = null;
      Integer majorVersion = null;
      Integer minorVersion = null;
      String module = null;

      Map<String, String> expressions = new HashMap<String, String>();
      
      for (int i = 0; i < reader.getAttributeCount(); i++)
      {
         switch (reader.getAttributeLocalName(i))
         {
            case XML.ATTRIBUTE_NAME : {
               name = attributeAsString(reader, XML.ATTRIBUTE_NAME, expressions);
               break;
            }
            case XML.ATTRIBUTE_MAJOR_VERSION : {
               majorVersion = attributeAsInt(reader, XML.ATTRIBUTE_MAJOR_VERSION, expressions);
               break;
            }
            case XML.ATTRIBUTE_MINOR_VERSION : {
               minorVersion = attributeAsInt(reader, XML.ATTRIBUTE_MINOR_VERSION, expressions);
               break;
            }
            case XML.ATTRIBUTE_MODULE : {
               module = attributeAsString(reader, XML.ATTRIBUTE_MODULE, expressions);
               break;
            }
            default :
               break;
         }
      }

      //elements reading
      while (reader.hasNext())
      {
         switch (reader.nextTag())
         {
            case END_ELEMENT : {
               if (XML.ELEMENT_DRIVER.equals(reader.getLocalName()))
               {
                  return new DriverImpl(name, majorVersion, minorVersion, module,
                                        driverClass, dataSourceClass, xaDataSourceClass,
                          !expressions.isEmpty() ? expressions : null);
               }
               else
               {
                  switch (reader.getLocalName())
                  {
                     case XML.ELEMENT_DATASOURCE_CLASS :
                     case XML.ELEMENT_XA_DATASOURCE_CLASS :
                     case XML.ELEMENT_DRIVER_CLASS :
                        break;
                     default :
                        throw new ParserException(bundle.unexpectedEndTag(reader.getLocalName()));
                  }
               }
               break;
            }
            case START_ELEMENT : {
               switch (reader.getLocalName())
               {
                  case XML.ELEMENT_DATASOURCE_CLASS : {
                     dataSourceClass = elementAsString(reader, XML.ELEMENT_DATASOURCE_CLASS, expressions);
                     break;
                  }
                  case XML.ELEMENT_XA_DATASOURCE_CLASS : {
                     xaDataSourceClass = elementAsString(reader, XML.ELEMENT_XA_DATASOURCE_CLASS, expressions);
                     break;
                  }
                  case XML.ELEMENT_DRIVER_CLASS : {
                     driverClass = elementAsString(reader, XML.ELEMENT_DRIVER_CLASS, expressions);
                     break;
                  }
                  default :
                     throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
               }
               break;
            }
         }
      }
      throw new ParserException(bundle.unexpectedEndOfDocument());
   }
392614
public static String readerAsString(Reader reader) {
    StringBuilder buffer = new StringBuilder();
    char[] chars = new char[16 * 1024];
    int numCharsRead;
    try {
      while ((numCharsRead = reader.read(chars, 0, chars.length)) != -1) {
        buffer.append(chars, 0, numCharsRead);
      }
      return buffer.toString();
    } catch (IOException e) {
      throw LOG.unableToReadFromReader(e);
    }
    finally {
      closeSilently(reader);
    }
  }
549825
public static XMLStreamException unexpectedElement(final XMLExtendedStreamReader reader, Set<String> possible) {
        final XMLStreamException ex = ControllerLogger.ROOT_LOGGER.unexpectedElement(reader.getName(), asStringList(possible), reader.getLocation());

        return new XMLStreamValidationException(ex.getMessage(),
                                                ValidationError.from(ex, ErrorType.UNEXPECTED_ELEMENT)
                                                        .element(reader.getName())
                                                        .alternatives(possible),
                                                ex);
    }
1183916
public synchronized XMLReader getXMLReader() throws SAXException {
        XMLReader reader;
        boolean readerInUse;

        if (m_readers == null) {
            // When the m_readers.get() method is called for the first time
            // on a thread, a new XMLReader will automatically be created.
            m_readers = new ThreadLocal();
        }

        if (m_inUse == null) {
            m_inUse = new Hashtable();
        }

        // If the cached reader for this thread is in use, construct a new
        // one; otherwise, return the cached reader.
        reader = (XMLReader) m_readers.get();
        boolean threadHasReader = (reader != null);
        if (!threadHasReader || m_inUse.get(reader) == Boolean.TRUE) {
            try {
                try {
                    // According to JAXP 1.2 specification, if a SAXSource
                    // is created using a SAX InputSource the Transformer or
                    // TransformerFactory creates a reader via the
                    // XMLReaderFactory if setXMLReader is not used
                    reader = XMLReaderFactory.createXMLReader();
                } catch (Exception e) {
                   try {
                        // If unable to create an instance, let's try to use
                        // the XMLReader from JAXP
                        if (m_parserFactory == null) {
                            m_parserFactory = SAXParserFactory.newInstance();
                            m_parserFactory.setNamespaceAware(true);
                        }

                        reader = m_parserFactory.newSAXParser().getXMLReader();
                   } catch (ParserConfigurationException pce) {
                       throw pce;   // pass along pce
                   }
                }
                try {
                    reader.setFeature(NAMESPACES_FEATURE, true);
                    reader.setFeature(NAMESPACE_PREFIXES_FEATURE, false);
                } catch (SAXException se) {
                    // Try to carry on if we've got a parser that
                    // doesn't know about namespace prefixes.
                }
            } catch (ParserConfigurationException ex) {
                throw new SAXException(ex);
            } catch (FactoryConfigurationError ex1) {
                throw new SAXException(ex1.toString());
            } catch (NoSuchMethodError ex2) {
            } catch (AbstractMethodError ame) {
            }

            // Cache the XMLReader if this is the first time we've created
            // a reader for this thread.
            if (!threadHasReader) {
                m_readers.set(reader);
                m_inUse.put(reader, Boolean.TRUE);
            }
        } else {
            m_inUse.put(reader, Boolean.TRUE);
        }

        return reader;
    }
291269
protected Validation parseValidation(XMLStreamReader reader) throws XMLStreamException, 
      ParserException, 
      ValidateException
   {
      Boolean validateOnMatch = Defaults.VALIDATE_ON_MATCH;
      Boolean useFastFail = Defaults.USE_FAST_FAIL;
      Boolean backgroundValidation = Defaults.BACKGROUND_VALIDATION;
      Long backgroundValidationMillis = null;

      Map<String, String> expressions = new HashMap<String, String>();

      while (reader.hasNext())
      {
         switch (reader.nextTag())
         {
            case END_ELEMENT : {
               switch (reader.getLocalName())
               {
                  case CommonXML.ELEMENT_VALIDATION :
                     return new ValidationImpl(validateOnMatch, backgroundValidation, backgroundValidationMillis,
                        useFastFail,
                             !expressions.isEmpty() ? expressions : null);
                  case CommonXML.ELEMENT_VALIDATE_ON_MATCH :
                  case CommonXML.ELEMENT_BACKGROUND_VALIDATION_MILLIS :
                  case CommonXML.ELEMENT_BACKGROUND_VALIDATION :
                  case CommonXML.ELEMENT_USE_FAST_FAIL :
                     break;
                  default :
                     throw new ParserException(bundle.unexpectedEndTag(reader.getLocalName()));
               }
            }
            case START_ELEMENT : {
               switch (reader.getLocalName())
               {
                  case CommonXML.ELEMENT_VALIDATE_ON_MATCH : {
                     validateOnMatch = elementAsBoolean(reader, CommonXML.ELEMENT_VALIDATE_ON_MATCH, expressions);
                     break;
                  }
                  case CommonXML.ELEMENT_BACKGROUND_VALIDATION_MILLIS : {
                     backgroundValidationMillis = elementAsLong(reader, CommonXML.ELEMENT_BACKGROUND_VALIDATION_MILLIS,
                                                                expressions);
                     break;
                  }
                  case CommonXML.ELEMENT_BACKGROUND_VALIDATION : {
                     backgroundValidation = elementAsBoolean(reader, CommonXML.ELEMENT_BACKGROUND_VALIDATION,
                                                             expressions);
                     break;
                  }
                  case CommonXML.ELEMENT_USE_FAST_FAIL : {
                     useFastFail = elementAsBoolean(reader, CommonXML.ELEMENT_USE_FAST_FAIL, expressions);
                     break;
                  }
                  default :
                     throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
               }
               break;
            }
         }
      }
      throw new ParserException(bundle.unexpectedEndOfDocument());
   }
689646
public static XMLStreamException missingRequiredElement(final XMLExtendedStreamReader reader, final Set<?> required) {
        final StringBuilder b = new StringBuilder();
        Iterator<?> iterator = required.iterator();
        while (iterator.hasNext()) {
            final Object o = iterator.next();
            b.append(o.toString());
            if (iterator.hasNext()) {
                b.append(", ");
            }
        }
        final XMLStreamException ex = ControllerLogger.ROOT_LOGGER.missingRequiredElements(b, reader.getLocation());

        Set<String> set = new HashSet<>();
        for (Object o : required) {
            String toString = o.toString();
            set.add(toString);
        }
        return new XMLStreamValidationException(ex.getMessage(),
                                                ValidationError.from(ex, ErrorType.REQUIRED_ELEMENTS_MISSING)
                                                        .element(reader.getName())
                                                        .alternatives(set),
                                                ex);
    }
432898
public static Tag exception(@Nullable Throwable exception) {
        if (exception == null) {
            return EXCEPTION_NONE;
        }
        String simpleName = exception.getClass().getSimpleName();
        return Tag.of("exception", simpleName.isEmpty() ? exception.getClass().getName() : simpleName);
    }
874901
public XmlWrapperParser createParser(Reader reader) {	    
        try {
			return new XmlWrapperParser(this, reader, getSupportedFormat());
		} catch (Exception e) {
			e.printStackTrace();
			throw new KriptonRuntimeException(e);
		}
	}
72436
protected Long elementAsLong(XMLStreamReader reader, String key, Map<String, String> expressions)
      throws XMLStreamException, ParserException
   {
      Long longValue = null;
      String elementtext = rawElementText(reader);

      if (key != null && expressions != null && elementtext != null && elementtext.indexOf("${") != -1)
         expressions.put(key, elementtext);
      
      try
      {
         longValue = Long.valueOf(getSubstitutionValue(elementtext));
      }
      catch (NumberFormatException nfe)
      {
         throw new ParserException(bundle.notValidNumber(elementtext, reader.getLocalName()));
      }

      return longValue;
   }
551056
public static Document parse(JsonReader reader) throws IOException, NotImplemented {
        reader.beginArray();
        int nodeType = reader.nextInt();


        CoreDocumentImpl doc = new DocumentImpl();

        if (nodeType == Node.ELEMENT_NODE) {
            addInitialElement(reader, doc);
        } else if (nodeType == Node.DOCUMENT_NODE) {
            addInitialDocNode(doc, reader);
        } else {
            throw new IllegalStateException("Don't know how to handle root node with type " + nodeType);
        }
        reader.endArray();
        return doc;
    }
107619
public static XMLStreamException createXMLStreamException(
            final String message,
            final XMLStreamReader reader,
            final Throwable cause) {
        final XMLStreamException exception = new XMLStreamException(message, reader.getLocation(), null);
        exception.initCause(cause);
        return exception;
    }
547931
public static void closeQuietly(final XMLStreamReader reader) {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (final Throwable t) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Ignoring exception that occurred when closing XMLStreamReader", t);
            }
        }
    }