A generic reading API to read all supported versions of the BusinessCard
from a DOM node.

@param aNode
Pre-parsed XML node to read. May not be <code>null</code>.
@return <code>null</code> if parsing fails.
@since 0.7.2
962433
@Nullable
  public static PDBusinessCard parseBusinessCard (@Nonnull final Node aNode)
  {
    ValueEnforcer.notNull (aNode, "Node");

    {
      // Read version 1
      final PD1BusinessCardMarshaller aMarshaller1 = new PD1BusinessCardMarshaller ();
      aMarshaller1.readExceptionCallbacks ().removeAll ();
      final PD1BusinessCardType aBC1 = aMarshaller1.read (aNode);
      if (aBC1 != null)
        try
        {
          return PD1APIHelper.createBusinessCard (aBC1);
        }
        catch (final IllegalArgumentException ex)
        {
          // If the BC does not adhere to the XSD
          // Happens if e.g. name is null
          return null;
        }
    }

    {
      // Read as version 2
      final PD2BusinessCardMarshaller aMarshaller2 = new PD2BusinessCardMarshaller ();
      aMarshaller2.readExceptionCallbacks ().removeAll ();
      final PD2BusinessCardType aBC2 = aMarshaller2.read (aNode);
      if (aBC2 != null)
        try
        {
          return PD2APIHelper.createBusinessCard (aBC2);
        }
        catch (final IllegalArgumentException ex)
        {
          // If the BC does not adhere to the XSD
          // Happens if e.g. name is null
          return null;
        }
    }

    {
      // Read as version 3
      final PD3BusinessCardMarshaller aMarshaller3 = new PD3BusinessCardMarshaller ();
      aMarshaller3.readExceptionCallbacks ().removeAll ();
      final PD3BusinessCardType aBC3 = aMarshaller3.read (aNode);
      if (aBC3 != null)
        try
        {
          return PD3APIHelper.createBusinessCard (aBC3);
        }
        catch (final IllegalArgumentException ex)
        {
          // If the BC does not adhere to the XSD
          // Happens if e.g. name is null
          return null;
        }
    }

    // Unsupported version
    return null;
  }
1061855
public org.w3c.dom.Node readNode()
        throws IOException
    {
        int tag = read();

        switch (tag) {
            case 'N':
                return null;

            case 'S':
            case 's':
            case 'X':
            case 'x':
                _isLastChunk = tag == 'S' || tag == 'X';
                _chunkLength = (read() << 8) + read();

                throw error("Can't handle string in this context");

            default:
                throw expect("string", tag);
        }
    }
482931
public static String getFormatFromXmlReader(Reader xmlReader) {
        Map<String, String> attributes = getAttributesFromXmlReader(xmlReader);
        String baseDictUri = attributes.get(NAACCR_XML_ROOT_ATT_BASE_DICT);
        String recordType = attributes.get(NAACCR_XML_ROOT_ATT_REC_TYPE);
        if (baseDictUri != null && recordType != null) {
            String version = NaaccrXmlDictionaryUtils.extractVersionFromUri(baseDictUri);
            if (NaaccrFormat.isVersionSupported(version) && NaaccrFormat.isRecordTypeSupported(recordType))
                return NaaccrFormat.getInstance(version, recordType).toString();
        }

        return null;
    }
853297
public void jjtAddChild (final Node aNode, final int nIndex)
  {
    if (m_aChildren == null)
      m_aChildren = new CSSNode [nIndex + 1];
    else
      if (nIndex >= m_aChildren.length)
      {
        // Does not really occur here
        final CSSNode [] aTmpArray = new CSSNode [nIndex + 1];
        System.arraycopy (m_aChildren, 0, aTmpArray, 0, m_aChildren.length);
        m_aChildren = aTmpArray;
      }
    m_aChildren[nIndex] = (CSSNode) aNode;
  }
1095987
public int read_attribute_asynch(final DeviceProxy deviceProxy, final String[] attnames)
            throws DevFailed {
        checkIfTango(deviceProxy, "read_attributes_asynch");

        build_connection(deviceProxy);

        // Create the request object
        // ----------------------------------
        Request request;
        if (deviceProxy.device_5 != null) {
            request = deviceProxy.device_5._request("read_attributes_5");
            setRequestArgsForReadAttr(request, attnames, get_source(deviceProxy),
                    DevLockManager.getInstance().getClntIdent(), AttributeValueList_5Helper.type());
            request.exceptions().add(MultiDevFailedHelper.type());
        }
        else if (deviceProxy.device_4 != null) {
            request = deviceProxy.device_4._request("read_attributes_4");
            setRequestArgsForReadAttr(request, attnames, get_source(deviceProxy),
                    DevLockManager.getInstance().getClntIdent(), AttributeValueList_4Helper.type());
            request.exceptions().add(MultiDevFailedHelper.type());
        }
        else if (deviceProxy.device_3 != null) {
            request = deviceProxy.device_3._request("read_attributes_3");
            setRequestArgsForReadAttr(request, attnames, get_source(deviceProxy), null,
                AttributeValueList_3Helper.type());
        }
        else if (deviceProxy.device_2 != null) {
            request = deviceProxy.device_2._request("read_attributes_2");
            setRequestArgsForReadAttr(request, attnames, get_source(deviceProxy), null,
                AttributeValueListHelper.type());
        }
        else {
            request = deviceProxy.device._request("read_attributes");
            setRequestArgsForReadAttr(request, attnames, null, null,
                    AttributeValueListHelper.type());
        }

        // send it (defered or just one way)
        request.send_deferred();

        // store request reference to read reply later
        return ApiUtil.put_async_request(
                new AsyncCallObject(request, deviceProxy, ATT_R, attnames));
    }
564688
@Override
    public final String getElementText() throws XMLStreamException {
        XMLEvent event = this.previousEvent;
        if (event == null) {
            throw new XMLStreamException(
                    "Must be on START_ELEMENT to read next text, element was null");
        }
        if (!event.isStartElement()) {
            throw new XMLStreamException(
                    "Must be on START_ELEMENT to read next text", event.getLocation());
        }

        final StringBuilder text = new StringBuilder();
        while (!event.isEndDocument()) {
            switch (event.getEventType()) {
                case XMLStreamConstants.CHARACTERS:
                case XMLStreamConstants.SPACE:
                case XMLStreamConstants.CDATA:
                    {
                        final Characters characters = event.asCharacters();
                        text.append(characters.getData());
                        break;
                    }
                case XMLStreamConstants.ENTITY_REFERENCE:
                    {
                        final EntityReference entityReference = (EntityReference) event;
                        final EntityDeclaration declaration = entityReference.getDeclaration();
                        text.append(declaration.getReplacementText());
                        break;
                    }
                case XMLStreamConstants.COMMENT:
                case XMLStreamConstants.PROCESSING_INSTRUCTION:
                    {
                        // Ignore
                        break;
                    }
                default:
                    {
                        throw new XMLStreamException(
                                "Unexpected event type '"
                                        + XMLStreamConstantsUtils.getEventName(event.getEventType())
                                        + "' encountered. Found event: "
                                        + event,
                                event.getLocation());
                    }
            }

            event = this.nextEvent();
        }

        return text.toString();
    }
1327564
@Override
	protected void parse(Node node) {
		NamedNodeMap attributes = node.getAttributes();
		version = getValueRecursive(attributes.getNamedItem("version"));

		NodeList childNodes = node.getChildNodes();
		for (int i = 0; i < childNodes.getLength(); i++) {
			Node child = childNodes.item(i);
			String nodeName = child.getNodeName();
			if ("Title".equalsIgnoreCase(nodeName)) {
				title = getValueRecursive(child);
			} else if ("Abstract".equalsIgnoreCase(nodeName)) {
				abstractt = getValueRecursive(child);
			} else if ("TileMaps".equalsIgnoreCase(nodeName)) {
				addTileMaps(child);
			}
		}
		if (title == null) {
			throw new IllegalArgumentException("Cannot parse XML into a TileMapServiceInfo object.");
		}

		setParsed(true);
	}
1312625
static public String getRootNodeName(String xml)
    {
        String rootNodeName = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setExpandEntityReferences(false);
            DocumentBuilder dBuilder = dbf.newDocumentBuilder();
            InputSource inputSource = new InputSource(new StringReader(xml));
            Document doc = dBuilder.parse(inputSource);
            doc.getDocumentElement().normalize();
            rootNodeName = doc.getDocumentElement().getNodeName();
        } catch (SAXException e) {
            System.out.println("SAX exception: " + e);
        } catch (IOException e) {
            System.out.println("IO exception: " + e);
        } catch (ParserConfigurationException e) {
            System.out.println("ParserConfiguration exception: " + e);
        }
        return rootNodeName;
    }
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;
    }
369710
public static Node read(InputStream inputStream) throws XmlException
    {
        try
        {
            DocumentBuilderFactory documentBuilderFactory = 
                DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = 
                documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(inputStream);
            Node node = document.getDocumentElement();
            return node;
        } 
        catch (ParserConfigurationException canNotHappen)
        {
            // Can not happen with a default configuration
            throw new XmlException("Could not create parser", canNotHappen);
        } 
        catch (SAXException e)
        {
            throw new XmlException("XML parsing error", e);
        }
        catch (IOException e)
        {
            throw new XmlException("IO error while reading XML", e);
        }

    }
1290948
public <T> JSONAPIDocument<List<T>> readDocumentCollection(InputStream dataStream, Class<T> clazz) {
		try {
			resourceCache.init();

			JsonNode rootNode = objectMapper.readTree(dataStream);

			// Validate
			ValidationUtils.ensureNotError(objectMapper, rootNode);
			ValidationUtils.ensureValidResource(rootNode);

			JsonNode dataNode = rootNode.get(DATA);

			// Parse data node without handling relationships
			List<T> resourceList = new ArrayList<>();

			if (dataNode != null && dataNode.isArray()) {
				for (JsonNode element : dataNode) {
					T pojo = readObject(element, clazz, false);
					resourceList.add(pojo);
				}
			}

			// Parse all included resources
			resourceCache.cache(parseIncluded(rootNode));

			// Connect data node's relationships now that all resources have been parsed
			for (int i = 0; i < resourceList.size(); i++) {
				JsonNode source = dataNode != null && dataNode.isArray() ? dataNode.get(i) : null;
				T resourceObject = resourceList.get(i);
				if (source != null && resourceObject != null) {
					handleRelationships(source, resourceObject);
				}
			}

			JSONAPIDocument<List<T>> result = new JSONAPIDocument<>(resourceList, objectMapper);

			// Handle top-level meta
			if (rootNode.has(META)) {
				result.setMeta(mapMeta(rootNode.get(META)));
			}

			// Handle top-level links
			if (rootNode.has(LINKS)) {
				result.setLinks(new Links(mapLinks(rootNode.get(LINKS))));
			}

			return result;
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			resourceCache.clear();
		}
	}
1005898
@Nonnull
  public static ValidationSource create (@Nullable final String sSystemID, @Nonnull final Node aNode)
  {
    ValueEnforcer.notNull (aNode, "Node");
    // Use the owner Document as fixed node
    return new ValidationSource (sSystemID, XMLHelper.getOwnerDocument (aNode), false);
  }
861592
public String getNodeText(Object inNode)
  {
    String strValue = null;
    
    if (inNode instanceof Node)
    {
      Node theNode = (Node)inNode;
      // Check the type of the node

      String nodeName = theNode.getNodeName();
      if(nodeName == null)
        nodeName = "null";
      StringBuffer wholeString = new StringBuffer(nodeName);
      StringBuffer nodeDetailStr = null;

      NamedNodeMap nodeMap = theNode.getAttributes();
      if(nodeMap != null)
      {
        for(int i=0;i<nodeMap.getLength();i++)
        {
          Node attrNode = nodeMap.item(i);
          if(nodeDetailStr == null)
            nodeDetailStr = new StringBuffer("");
          nodeDetailStr.append(" ");
          nodeDetailStr.append(attrNode.getNodeName());
          nodeDetailStr.append(":");
          nodeDetailStr.append(attrNode.getNodeValue());
          if(i < nodeMap.getLength()-1)
            nodeDetailStr.append(", ");
        }
      }

      if(nodeDetailStr == null)
      {
        // Note this gets the text associated with the first child element only.
        Node firstChild = theNode.getFirstChild();
        if(firstChild != null)
        {
          String firstChildStr = firstChild.getNodeValue();
          if(firstChildStr != null)
            nodeDetailStr = new StringBuffer(firstChildStr);
        }
      }
      
      if(nodeDetailStr == null)
      {
        wholeString.append("(null)");
      }
      else
      {
        wholeString.append("(");
        wholeString.append(nodeDetailStr);
        wholeString.append(")");
      }
        strValue = wholeString.toString(); 
    }  // eof is inNode instanceof Node
    
    return strValue;
  }
1332015
public <T> JSONAPIDocument<T> readDocument(InputStream dataStream, Class<T> clazz) {
		try {
			resourceCache.init();

			JsonNode rootNode = objectMapper.readTree(dataStream);

			// Validate
			ValidationUtils.ensureNotError(objectMapper, rootNode);
			ValidationUtils.ensureValidResource(rootNode);

			JsonNode dataNode = rootNode.get(DATA);

			// Parse data node without handling relationships
			T resourceObject;
			boolean cached = false;
			if (dataNode != null && dataNode.isObject()) {
				String identifier = createIdentifier(dataNode);
				cached = identifier != null && resourceCache.contains(identifier);

				if (cached) {
					resourceObject = (T) resourceCache.get(identifier);
				} else {
					resourceObject = readObject(dataNode, clazz, false);
				}
			} else {
				resourceObject = null;
			}

			// Parse all included resources
			resourceCache.cache(parseIncluded(rootNode));

			// Connect data node's relationships now that all resources have been parsed
			if (resourceObject != null && !cached) {
				handleRelationships(dataNode, resourceObject);
			}

			JSONAPIDocument<T> result = new JSONAPIDocument<>(resourceObject, objectMapper);

			// Handle top-level meta
			if (rootNode.has(META)) {
				result.setMeta(mapMeta(rootNode.get(META)));
			}

			// Handle top-level links
			if (rootNode.has(LINKS)) {
				result.setLinks(new Links(mapLinks(rootNode.get(LINKS))));
			}

			return result;
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			resourceCache.clear();
		}
	}
621645
@Override
    public boolean parseManagementInterfaces(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> operationsList)
            throws XMLStreamException {

        requireNoAttributes(reader);
        boolean interfaceDefined = false;
        while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
            requireNamespace(reader, namespace);
            final Element element = Element.forName(reader.getLocalName());
            switch (element) {
                case NATIVE_INTERFACE: {
                    interfaceDefined = true;
                    parseManagementInterface(reader, address, false, operationsList);
                    break;
                }
                case HTTP_INTERFACE: {
                    interfaceDefined = true;
                    parseManagementInterface(reader, address, true, operationsList);
                    break;
                }
                default: {
                    throw unexpectedElement(reader);
                }
            }
        }

        if (!interfaceDefined) {
            throw missingOneOf(reader, EnumSet.of(Element.NATIVE_INTERFACE, Element.HTTP_INTERFACE));
        }

        return true;
    }
262487
public static String getElementTagName(final Node aNode) {

        if (aNode != null && aNode.getNodeType() == Node.ELEMENT_NODE) {

            final Element theElement = (Element) aNode;
            return theElement.getTagName();
        }

        // The Node was not an Element.
        return null;
    }
951629
public static Node toNode(Source s) {
        Node n = tryExtractNodeFromDOMSource(s);
        return n != null ? n 
            : toDocument(s, DocumentBuilderFactoryConfigurer.Default.configure(DocumentBuilderFactory.newInstance()));
    }