Creates a DOM Node from a TraX Source.

<p>If the source is a {@link DOMSource} its Node will be
returned, otherwise this delegates to {@link #toDocument}.</p>
961579
public static Node toNode(Source s,
                              DocumentBuilderFactory factory) {
        Node n = tryExtractNodeFromDOMSource(s);
        return n != null ? n : toDocument(s, factory);
    }
67897
public void transform(Source source, Result outputTarget)
          throws TransformerException
  {

    createResultContentHandler(outputTarget);
    
    /*
     * According to JAXP1.2, new SAXSource()/StreamSource()
     * should create an empty input tree, with a default root node. 
     * new DOMSource()creates an empty document using DocumentBuilder.
     * newDocument(); Use DocumentBuilder.newDocument() for all 3 situations,
     * since there is no clear spec. how to create an empty tree when
     * both SAXSource() and StreamSource() are used.
     */
    if ((source instanceof StreamSource && source.getSystemId()==null &&
       ((StreamSource)source).getInputStream()==null &&
       ((StreamSource)source).getReader()==null)||
       (source instanceof SAXSource &&
       ((SAXSource)source).getInputSource()==null &&
       ((SAXSource)source).getXMLReader()==null )||
       (source instanceof DOMSource && ((DOMSource)source).getNode()==null)){
      try {
        DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderF.newDocumentBuilder();
        String systemID = source.getSystemId();
        source = new DOMSource(builder.newDocument());

        // Copy system ID from original, empty Source to new Source
        if (systemID != null) {
          source.setSystemId(systemID);
        }
      } catch (ParserConfigurationException e){
        throw new TransformerException(e.getMessage());
      }           
    }
    
    try
    {
      if (source instanceof DOMSource)
      {
        DOMSource dsource = (DOMSource) source;
  
        m_systemID = dsource.getSystemId();
  
        Node dNode = dsource.getNode();
  
        if (null != dNode)
        {
          try
          {
            if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
              this.startDocument();
            try
            {
              if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
              {
                String data = dNode.getNodeValue();
                char[] chars = data.toCharArray();
                characters(chars, 0, chars.length);
              }
              else
              { 
                org.apache.xml.serializer.TreeWalker walker;
                walker = new org.apache.xml.serializer.TreeWalker(this, m_systemID);
                walker.traverse(dNode);
              }
            }
            finally
            {
              if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
                this.endDocument();
            }
          }
          catch (SAXException se)
          {
            throw new TransformerException(se);
          }
  
          return;
        }
        else
        {
          String messageStr = XSLMessages.createMessage(
            XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
  
          throw new IllegalArgumentException(messageStr);
        }
      }
  
      InputSource xmlSource = SAXSource.sourceToInputSource(source);
  
      if (null == xmlSource)
      {
        throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[]{source.getClass().getName()})); //"Can't transform a Source of type "
                                       //+ source.getClass().getName() + "!");
      }
  
      if (null != xmlSource.getSystemId())
        m_systemID = xmlSource.getSystemId();
  
      XMLReader reader = null;
      boolean managedReader = false;
  
      try
      {
        if (source instanceof SAXSource) {
          reader = ((SAXSource) source).getXMLReader();
        }
          
        if (null == reader) {
          try {
            reader = XMLReaderManager.getInstance().getXMLReader();
            managedReader = true;
          } catch (SAXException se) {
            throw new TransformerException(se);
          }
        } else {
          try {
            reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
                              true);
          } catch (org.xml.sax.SAXException se) {
            // We don't care.
          }
        }

        // Get the input content handler, which will handle the 
        // parse events and create the source tree. 
        ContentHandler inputHandler = this;
  
        reader.setContentHandler(inputHandler);
  
        if (inputHandler instanceof org.xml.sax.DTDHandler)
          reader.setDTDHandler((org.xml.sax.DTDHandler) inputHandler);
  
        try
        {
          if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
            reader.setProperty("http://xml.org/sax/properties/lexical-handler",
                               inputHandler);
  
          if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
            reader.setProperty(
              "http://xml.org/sax/properties/declaration-handler",
              inputHandler);
        }
        catch (org.xml.sax.SAXException se){}
  
        try
        {
          if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
            reader.setProperty("http://xml.org/sax/handlers/LexicalHandler",
                               inputHandler);
  
          if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
            reader.setProperty("http://xml.org/sax/handlers/DeclHandler",
                               inputHandler);
        }
        catch (org.xml.sax.SAXNotRecognizedException snre){}
  
        reader.parse(xmlSource);
      }
      catch (org.apache.xml.utils.WrappedRuntimeException wre)
      {
        Throwable throwable = wre.getException();
  
        while (throwable
               instanceof org.apache.xml.utils.WrappedRuntimeException)
        {
          throwable =
            ((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
        }
  
        throw new TransformerException(wre.getException());
      }
      catch (org.xml.sax.SAXException se)
      {
        throw new TransformerException(se);
      }
      catch (IOException ioe)
      {
        throw new TransformerException(ioe);
      } finally {
        if (managedReader) {
          XMLReaderManager.getInstance().releaseXMLReader(reader);
        }
      }
    }
    finally
    {
      if(null != m_outputStream)
      {
        try
        {
          m_outputStream.close();
        }
        catch(IOException ioe){}
        m_outputStream = null;
      }
    }
  }
29933
public CmsResource createXmlContent() throws CmsUgcException {

        checkNotFinished();
        checkEditResourceNotSet();

        CmsUgcSessionSecurityUtil.checkCreateContent(m_cms, m_configuration);
        try {
            I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(m_configuration.getResourceType());
            m_editResource = m_cms.createResource(getNewContentName(), type);
            return m_editResource;
        } catch (CmsException e) {
            LOG.error(e.getLocalizedMessage(), e);
            throw new CmsUgcException(e, CmsUgcConstants.ErrorCode.errMisc, e.getLocalizedMessage());
        }
    }
916334
public Object fromDomNode(Node domNode, boolean tryProviders) throws TranslationException {
        if (this instanceof XmlDocumentTranslator)
            return ((XmlDocumentTranslator)this).fromDomNode(domNode);
        else
            throw new UnsupportedOperationException("Translator: " + this.getClass().getName() + " does not implement" + XmlDocumentTranslator.class.getName());
    }
239481
public static Document toDocument(String xml) {
		try {

			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			documentBuilderFactory.setNamespaceAware(true);
			documentBuilderFactory.setIgnoringElementContentWhitespace(true);
			documentBuilderFactory.isIgnoringComments();
			documentBuilderFactory.setCoalescing(true);

			DocumentBuilder documentBuilder = documentBuilderFactory
					.newDocumentBuilder();

			InputSource inputSource = new InputSource();

			inputSource.setCharacterStream(new StringReader(xml));

			Document document = documentBuilder.parse(inputSource);

			removeUnusedNamespaces(document);

			return document;

		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		} catch (SAXException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
918091
protected void createDocument() throws ParserConfigurationException
    {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        DocumentType doctype = builder.getDOMImplementation().createDocumentType("html", "-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");
        doc = builder.getDOMImplementation().createDocument("http://www.w3.org/1999/xhtml", "html", doctype);
        
        head = doc.createElement("head");
        Element meta = doc.createElement("meta");
        meta.setAttribute("http-equiv", "content-type");
        meta.setAttribute("content", "text/html;charset=utf-8");
        head.appendChild(meta);
        title = doc.createElement("title");
        title.setTextContent("PDF Document");
        head.appendChild(title);
        globalStyle = doc.createElement("style");
        globalStyle.setAttribute("type", "text/css");
        //globalStyle.setTextContent(createGlobalStyle());
        head.appendChild(globalStyle);
        
        body = doc.createElement("body");
        
        Element root = doc.getDocumentElement();
        root.appendChild(head);
        root.appendChild(body);
    }
120522
public Document nodeToDom(org.w3c.dom.Node node) throws S2SException {
        try {
            javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance();
            javax.xml.transform.Transformer xf = tf.newTransformer();
            javax.xml.transform.dom.DOMResult dr = new javax.xml.transform.dom.DOMResult();
            xf.transform(new javax.xml.transform.dom.DOMSource(node), dr);
            return (Document) dr.getNode();

        }
        catch (javax.xml.transform.TransformerException ex) {
            throw new S2SException(ex.getMessage());
        }
    }
250308
public String docToString(Document node) throws S2SException {
        try {
            DOMSource domSource = new DOMSource(node);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            return writer.toString();
        }
        catch (Exception e) {
            throw new S2SException(e.getMessage(),e);
        }
    }
15995
public static Document buildControlDocument(String fromXML)
        throws SAXException, IOException {
        return buildDocument(newControlParser(), new StringReader(fromXML));
    }
891201
public Document stringToDom(String xmlSource) throws S2SException {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(new InputSource(new StringReader(xmlSource)));
        }
        catch (SAXException | IOException | ParserConfigurationException ex) {
            throw new S2SException(ex.getMessage(), ex);
        }
    }
477903
public static Element parse(InputSource source) throws IOException
   {
      try
      {
         Document doc;
         DocumentBuilder builder = getDocumentBuilder();
         synchronized (builder) //synchronize to prevent concurrent parsing on the same DocumentBuilder
         {
            doc = builder.parse(source);
         }
         return doc.getDocumentElement();
      }
      catch (SAXException se)
      {
         throw new IOException(se.toString());
      }
      finally
      {
         InputStream is = source.getByteStream();
         if (is != null)
         {
            is.close();
         }
         Reader r = source.getCharacterStream();
         if (r != null)
         {
            r.close();
         }
      }
   }
336290
public static String nodeToString(Node document) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        Source xmlSource = new DOMSource(document);
        Result outputTarget = new StreamResult(outputStream);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(xmlSource, outputTarget);

        return outputStream.toString();
    }
442423
@Nonnull
  public static ValidationSource createXMLSource (@Nonnull final IReadableResource aResource)
  {
    // Read on demand only
    return new ValidationSource (aResource.getPath (), () -> DOMReader.readXMLDOM (aResource), false)
    {
      @Override
      @Nonnull
      public Source getAsTransformSource ()
      {
        // Use resource as TransformSource to get error line and column
        return TransformSourceFactory.create (aResource);
      }
    };
  }
991156
function _mapDocumentToSource(source) {
        var node = exports.root;
        DOMHelpers.eachNode(source, function each(payload) {
            if (!node) {
                return true;
            }
            if (payload.closing) {
                var parent = node.findParentForNextNodeMatchingPayload(payload);
                if (!parent) {
                    return console.warn("Matching Parent not at " + payload.sourceOffset + " (" + payload.nodeName + ")");
                }
                parent.closeLocation = payload.sourceOffset;
                parent.closeLength = payload.sourceLength;
            } else {
                var next = node.findNextNodeMatchingPayload(payload);
                if (!next) {
                    return console.warn("Skipping Source Node at " + payload.sourceOffset);
                }
                node = next;
                node.location = payload.sourceOffset;
                node.length = payload.sourceLength;
                if (payload.closed) {
                    node.closed = payload.closed;
                }
            }
        });
    }
278708
public static InputStream documentToPrettyInputStream(Node document) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        Source xmlSource = new DOMSource(document);
        Result outputTarget = new StreamResult(outputStream);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.transform(xmlSource, outputTarget);

        InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
        return is;
    }
192191
public static org.w3c.dom.Element domElement(String xmlString) {
    org.w3c.dom.Element element = null;
    try {
      ByteArrayInputStream bais = new ByteArrayInputStream(
        xmlString.getBytes(Charset.forName("UTF-8")));
      element = getFactory().newDocumentBuilder().parse(bais)
        .getDocumentElement();
    } catch (SAXException e) {
      throw new MarkLogicIOException(
        "Could not make Element from xmlString" + xmlString, e);
    } catch (IOException e) {
      throw new MarkLogicIOException(
        "Could not make Element from xmlString" + xmlString, e);
    } catch (ParserConfigurationException e) {
      throw new MarkLogicIOException(
        "Could not make Element from xmlString" + xmlString, e);
    }
    return element;
  }
623639
@Override
    public PmdRuleSet create() {
        final SAXBuilder parser = new SAXBuilder();
        final Document dom;
        try {
            dom = parser.build(source);
        } catch (JDOMException | IOException e) {
            if (messages != null) {
                messages.addErrorText(INVALID_INPUT + " : " + e.getMessage());
            }
            LOG.error(INVALID_INPUT, e);
            return new PmdRuleSet();
        }

        final Element eltResultset = dom.getRootElement();
        final Namespace namespace = eltResultset.getNamespace();
        final PmdRuleSet result = new PmdRuleSet();

        final String name = eltResultset.getAttributeValue("name");
        final Element descriptionElement = getChild(eltResultset, namespace);

        result.setName(name);

        if (descriptionElement != null) {
            result.setDescription(descriptionElement.getValue());
        }

        for (Element eltRule : getChildren(eltResultset, "rule", namespace)) {
            PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue("ref"));
            pmdRule.setClazz(eltRule.getAttributeValue("class"));
            pmdRule.setName(eltRule.getAttributeValue("name"));
            pmdRule.setMessage(eltRule.getAttributeValue("message"));
            parsePmdPriority(eltRule, pmdRule, namespace);
            parsePmdProperties(eltRule, pmdRule, namespace);
            result.addRule(pmdRule);
        }
        return result;
    }