{@inheritDoc}
<p>
Text documents in MarkLogic cannot be cloned.
UnsupportedOperationException will be thrown if cloneNode is call on text
document. </>
<p>
DocumentType node will not be cloned as it is not part of the Expanded
Tree.</>
765979
public Node cloneNode(boolean deep) {
        try {
            if (isXMLDoc == UNKNOWN_TYPE) isXMLDoc = getDocumentType();
            if (isXMLDoc == NON_XML) {
                throw new UnsupportedOperationException(
                    "Text document cannot be cloned");
            }
            // initialize a new doc owner node
            initClonedOwnerDoc();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("Internal Error:" + e);
        }
        if (deep) {
            for (NodeImpl n = (NodeImpl) getFirstChild(); n != null; n = (NodeImpl) n
                .getNextSibling()) {
                ownerDocCloned.appendChild(n.cloneNode(ownerDocCloned, true));
            }
        }
        return ownerDocCloned;
    }
1182933
public Element cloneNode(final INestableNode parent) {
        final Element element = new Element(this.elementName);
        element.addAttributes(this.attributes);
        for (final INode child : getChildren()) {
            final INode clonedChild = child.cloneNode(element);
            element.addChild(clonedChild);
        }
        element.setLine(getLine());
        element.setCol(getCol());
        element.setParent(parent);
        return element;
    }
1205972
Document createDocument(NodeDataIndexing node) throws RepositoryException
   {
      Document aDoc = null;
      if (volatileIndex != null)
      {
         aDoc = volatileIndex.getAggregateIndexes(node.getIdentifier());
      }
      if (aDoc == null)
      {
         aDoc = handler.createDocument(node, nsMappings, version, true, volatileIndex);
      }
      return aDoc;
   }
966453
@Override
  public boolean visit(TypeDeclaration node) {
    TypeMirror serializableType = typeUtil.resolveJavaType("java.io.Serializable").asType();
    TypeMirror nodeType = node.getTypeElement().asType();
    boolean isSerializable = typeUtil.isAssignable(nodeType, serializableType);
    boolean stripReflection = !translationUtil.needsReflection(node.getTypeElement());
    return stripReflection && isSerializable;
  }
188287
private void deepCopy(Element origElement, Element copyElement) {
        List<Node> children = origElement.getChildElements();
        for(Node node : children) {
            try {
                if(node instanceof Content) {
                    Content content = (Content) ((Content) node).clone();
                    copyElement.addChildElement(content);
                } else {
                    Element element = (Element) ((Element) node).clone();
                    copyElement.addChildElement(element);
                    deepCopy((Element)node, element);
                }
            } catch (CloneNotSupportedException e) {
                throw new XmlModelException("Unable to clone object", e);
            }
        }
    }
1133873
public static void process(@NonNull Document textDocument, AnnotatableType... annotationTypes) {
      if (annotationTypes == null || annotationTypes.length == 0) {
         return;
      }

      for (AnnotatableType annotationType : annotationTypes) {
         if (annotationType == null) {
            continue;
         }

         if (textDocument.getAnnotationSet().isCompleted(annotationType)) {
            continue;
         }

         if (log.isLoggable(Level.FINEST)) {
            log.finest("Annotating for {0}", annotationType);
         }

         Annotator annotator = AnnotatorCache.getInstance().get(annotationType, textDocument.getLanguage());

         if (annotator == null) {
            throw new IllegalStateException("Could not get annotator for " + annotationType);
         }

         if (!annotator.satisfies().contains(annotationType)) {
            throw new IllegalStateException(annotator.getClass().getName() + " does not satisfy " + annotationType);
         }

         //Get the requirements out of the way
         for (AnnotatableType prereq : annotator.requires()) {
            process(textDocument, prereq);
         }

         annotator.annotate(textDocument);
         for (AnnotatableType type : annotator.satisfies()) {
            textDocument
               .getAnnotationSet()
               .setIsCompleted(type, true, annotator.getClass().getName() + "::" + annotator.getVersion());
         }

      }
   }
391676
private Content inheritThrowsDocumentation(Element holder,
            List<? extends TypeMirror> declaredExceptionTypes, Set<String> alreadyDocumented,
            TagletWriter writer) {
        Utils utils = writer.configuration().utils;
        Content result = writer.getOutputInstance();
        if (utils.isExecutableElement(holder)) {
            Map<List<? extends DocTree>, ExecutableElement> declaredExceptionTags = new LinkedHashMap<>();
            for (TypeMirror declaredExceptionType : declaredExceptionTypes) {
                Input input = new DocFinder.Input(utils, holder, this,
                        utils.getTypeName(declaredExceptionType, false));
                DocFinder.Output inheritedDoc = DocFinder.search(writer.configuration(), input);
                if (inheritedDoc.tagList.isEmpty()) {
                    String typeName = utils.getTypeName(declaredExceptionType, true);
                    input = new DocFinder.Input(utils, holder, this, typeName);
                    inheritedDoc = DocFinder.search(writer.configuration(), input);
                }
                if (!inheritedDoc.tagList.isEmpty()) {
                    if (inheritedDoc.holder == null) {
                        inheritedDoc.holder = holder;
                    }
                    declaredExceptionTags.put(inheritedDoc.tagList, (ExecutableElement)inheritedDoc.holder);
                }
            }
            result.addContent(throwsTagsOutput(declaredExceptionTags, writer, alreadyDocumented, false));
        }
        return result;
    }
876634
private function mapContentToNode($document, NodeInterface $node, $locale, $ignoreRequired)
    {
        $structure = $document->getStructure();
        $webspaceName = $this->inspector->getWebspace($document);
        $metadata = $this->inspector->getStructureMetadata($document);

        if (!$metadata) {
            throw new \RuntimeException(
                sprintf(
                    'Metadata for Structure Type "%s" was not found, does the file "%s.xml" exists?',
                    $document->getStructureType(),
                    $document->getStructureType()
                )
            );
        }

        foreach ($metadata->getProperties() as $propertyName => $structureProperty) {
            if (TitleSubscriber::PROPERTY_NAME === $propertyName) {
                continue;
            }

            $realProperty = $structure->getProperty($propertyName);
            $value = $realProperty->getValue();

            if (false === $ignoreRequired && $structureProperty->isRequired() && null === $value) {
                throw new MandatoryPropertyException(
                    sprintf(
                        'Property "%s" in structure "%s" is required but no value was given. Loaded from "%s"',
                        $propertyName,
                        $metadata->getName(),
                        $metadata->getResource()
                    )
                );
            }

            $contentTypeName = $structureProperty->getType();
            $contentType = $this->contentTypeManager->get($contentTypeName);

            // TODO: Only write if the property has been modified.

            $legacyProperty = $this->legacyPropertyFactory->createTranslatedProperty($structureProperty, $locale);
            $legacyProperty->setValue($value);

            $contentType->write(
                new SuluNode($node),
                $legacyProperty,
                null,
                $webspaceName,
                $locale,
                null
            );
        }
    }
204929
public Node cloneNode(Document doc, Node eold) {
    return doc.importNode(eold, true);
  }
1127545
@Override
  public XMLObject unmarshall(Element domElement) throws UnmarshallingException {

    Document newDocument = null;

    Node childNode = domElement.getFirstChild();
    while (childNode != null) {
      if (childNode.getNodeType() != Node.TEXT_NODE) {
        // We skip everything except for a text node.
        log.info("Ignoring node {} - it is not a text node", childNode.getNodeName());
      }
      else {
        newDocument = parseContents((Text) childNode, domElement);
        if (newDocument != null) {
          break;
        }
      }
      childNode = childNode.getNextSibling();
    }

    return super.unmarshall(newDocument != null ? newDocument.getDocumentElement() : domElement);
  }
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());
        }
    }
909699
public void validate(final Node document) throws SchemaValidationException
	{
		try
		{
			final Validator validator = schema.newValidator();

			validator.validate(new DOMSource(document));
		}
		catch (SAXException | IOException e)
		{
			throw new SchemaValidationException(e.getMessage(), e);
		}
	}
762716
@Override @DefinedBy(Api.COMPILER_TREE)
    public DCDocComment newDocCommentTree(List<? extends DocTree> fullBody, List<? extends DocTree> tags) {
        ListBuffer<DCTree> lb = new ListBuffer<>();
        lb.addAll(cast(fullBody));
        List<DCTree> fBody = lb.toList();

        // A dummy comment to keep the diagnostics logic happy.
        Comment c = new Comment() {
            @Override
            public String getText() {
                return null;
            }

            @Override
            public int getSourcePos(int index) {
                return Position.NOPOS;
            }

            @Override
            public CommentStyle getStyle() {
                return CommentStyle.JAVADOC;
            }

            @Override
            public boolean isDeprecated() {
                return false;
            }
        };
        Pair<List<DCTree>, List<DCTree>> pair = splitBody(fullBody);
        DCDocComment tree = new DCDocComment(c, fBody, pair.fst, pair.snd, cast(tags));
        return tree;
    }
562264
private void mergeExtensionsIntoDocument(Node target, Node extensions) throws Exception {
        final XPathFactory factory = XPathFactory.newInstance();
        final NodeList nodes = (NodeList) factory.newXPath().evaluate("//extensions", extensions, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            final Node extensionNode = nodes.item(i);
            String nameBasedXpath =  DomUtils.getNameBasedXPath(extensionNode, false);
            log.debug("Processing extension node: " + nameBasedXpath);

            final NodeList targetNodes = (NodeList) factory.newXPath().evaluate(nameBasedXpath, target, XPathConstants.NODESET);
            if (targetNodes.getLength() != 1) {
                throw new IllegalArgumentException("XPath "+nameBasedXpath+" not found in target");
            }
            Node targetNode = targetNodes.item(0);
            Node importedNode = targetNode.getOwnerDocument().importNode(extensionNode, true);
            targetNode.appendChild(importedNode);
        }
    }
784639
function markText(doc, from, to, options, type) {
    // Shared markers (across linked documents) are handled separately
    // (markTextShared will call out to this again, once per
    // document).
    if (options && options.shared) return markTextShared(doc, from, to, options, type);
    // Ensure we are in an operation.
    if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);

    var marker = new TextMarker(doc, type), diff = cmp(from, to);
    if (options) copyObj(options, marker, false);
    // Don't connect empty markers unless clearWhenEmpty is false
    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
      return marker;
    if (marker.replacedWith) {
      // Showing up as a widget implies collapsed (widget replaces text)
      marker.collapsed = true;
      marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
      if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
      if (options.insertLeft) marker.widgetNode.insertLeft = true;
    }
    if (marker.collapsed) {
      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
        throw new Error("Inserting collapsed marker partially overlapping an existing one");
      sawCollapsedSpans = true;
    }

    if (marker.addToHistory)
      addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);

    var curLine = from.line, cm = doc.cm, updateMaxLine;
    doc.iter(curLine, to.line + 1, function(line) {
      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
        updateMaxLine = true;
      if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
      addMarkedSpan(line, new MarkedSpan(marker,
                                         curLine == from.line ? from.ch : null,
                                         curLine == to.line ? to.ch : null));
      ++curLine;
    });
    // lineIsHidden depends on the presence of the spans, so needs a second pass
    if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
      if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
    });

    if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });

    if (marker.readOnly) {
      sawReadOnlySpans = true;
      if (doc.history.done.length || doc.history.undone.length)
        doc.clearHistory();
    }
    if (marker.collapsed) {
      marker.id = ++nextMarkerId;
      marker.atomic = true;
    }
    if (cm) {
      // Sync editor state
      if (updateMaxLine) cm.curOp.updateMaxLine = true;
      if (marker.collapsed)
        regChange(cm, from.line, to.line + 1);
      else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
        for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
      if (marker.atomic) reCheckSelection(cm.doc);
      signalLater(cm, "markerAdded", cm, marker);
    }
    return marker;
  }
1112354
@Override
    public String execute(EditXmlInputs inputs) throws Exception {
        Document doc = XmlUtils.createDocument(inputs.getXml(), inputs.getFilePath(), inputs.getParsingFeatures());
        NodeList nodeList = XmlUtils.readNode(doc, inputs.getXpath1(), XmlUtils.getNamespaceContext(inputs.getXml(), inputs.getFilePath()));
        Node childNode = null;
        Node node;

        if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) {
            childNode = XmlUtils.stringToNode(inputs.getValue(), doc.getXmlEncoding(), inputs.getParsingFeatures());
        }

        for (int i = 0; i < nodeList.getLength(); i++) {
            node = nodeList.item(i);

            if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) {
                childNode = doc.importNode(childNode, true);
                node.setTextContent(Constants.Inputs.EMPTY_STRING);
                node.appendChild(childNode);
            } else if (Constants.Inputs.TYPE_TEXT.equals(inputs.getType())) {
                node.setTextContent(inputs.getValue());
            } else if (Constants.Inputs.TYPE_ATTR.equals(inputs.getType())) {
                String attribute = ((Element) node).getAttribute(inputs.getName());
                if ((attribute != null) && (!StringUtils.isEmpty(attribute))) {
                    ((Element) node).setAttribute(inputs.getName(), inputs.getValue());
                }
            }
        }
        return DocumentUtils.documentToString(doc);
    }
173258
@SuppressWarnings("unchecked")
    public Object convertToEntity(Class entityType, String id, ObjectNode document) {
        try {
            if (ObjectNode.class.equals(entityType)) {
                return document;
            }

            Object defaultValue = InMemoryDocumentSessionOperations.getDefaultValue(entityType);
            Object entity = defaultValue;

            String documentType =_session.getConventions().getJavaClass(id, document);
            if (documentType != null) {
                Class type = Class.forName(documentType);
                if (entityType.isAssignableFrom(type)) {
                    entity = _session.getConventions().getEntityMapper().treeToValue(document, type);
                }
            }

            if (entity == defaultValue) {
                entity = _session.getConventions().getEntityMapper().treeToValue(document, entityType);
            }

            if (id != null) {
                _session.getGenerateEntityIdOnTheClient().trySetIdentity(entity, id);
            }

            return entity;
        } catch (Exception e) {
            throw new IllegalStateException("Could not convert document " + id + " to entity of type " + entityType.getName(), e);
        }
    }