Returns the RDF annotations required for in line editing.<p>

@param document the parent XML document
@param contentLocale the content locale
@param elementPath the element xpath to get the RDF annotation for

@return the RDFA
486126
public static String getRdfaAttributes(I_CmsXmlDocument document, Locale contentLocale, String elementPath) {

        I_CmsXmlSchemaType schemaType = document.getContentDefinition().getSchemaType(elementPath);
        if (schemaType != null) {
            String path = "";
            if (elementPath.contains("/")) {
                path += "/" + removePathIndexes(elementPath.substring(0, elementPath.lastIndexOf("/")) + ":");
            }
            path += getTypeUri(schemaType.getContentDefinition()) + "/" + elementPath;
            return String.format(
                RDFA_ATTRIBUTES,
                CmsContentDefinition.uuidToEntityId(document.getFile().getStructureId(), contentLocale.toString()),
                path);
        } else {
            return "";
        }
    }
879044
protected Document getXPathResultAsDocument(String select,
                                                Document document)
        throws ConfigurationException, TransformerException, XpathException {
        DOMResult result = new DOMResult();
        performTransform(getCopyTransformation(select), document, result);
        return (Document) result.getNode();
    }
883127
public static String getZealotXmlNameSpace(String xmlPath) {
        Document doc;
        try {
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlPath);
            doc = new SAXReader().read(is);
        } catch (Exception expected) {
            // 由于只是判断该文件是否能被正确解析，并不进行正式的解析，所有这里就不抛出和记录异常了.
            log.warn("解析路径为:'" + xmlPath + "'的xml文件出错，请检查其正确性");
            return null;
        }

        // 获取XML文件的根节点，判断其根节点是否为'zealots'，如果是则获取其属性nameSpace的值.
        Node root = doc.getRootElement();
        if (root != null && ROOT_NAME.equals(root.getName())) {
            String nameSpace = getNodeText(root.selectSingleNode(ZealotConst.ATTR_NAMESPACE));
            if (StringHelper.isBlank(nameSpace)) {
                log.warn("zealot xml文件:'" + xmlPath + "'的根节点nameSpace命名空间属性为配置，请配置，否则将被忽略!");
                return null;
            }
            return nameSpace;
        }

        return null;
    }
874638
@Nullable
    public static String findContentText(final Node rootNode, final XPath xPath, final String expression) {
        final Node node = findNode(rootNode, xPath, expression);
        if (node == null) {
            return null;
        }
        return node.getTextContent();
    }
346710
@Override
    @Scope(DocScope.IO)
    public XPathEvaluator evalXPath(final String xpath) {
        return new DefaultXPathEvaluator(projector, new DocumentResolver() {
            @Override
            public Document resolve(final Class<?>... resourceAwareClasses) throws IOException {
                return IOHelper.getDocumentFromURL(projector.config().createDocumentBuilder(), url, requestProperties, resourceAwareClasses);
            }
        }, xpath);
    }
431964
@Override
    public void getXliffFromDocuments(String srcLanguage, String trgLanguage,
            Map<DocumentType, Set<String>> documentsMap,
            OutputStream outputXliff) throws ServiceException, IOException {

        if (srcLanguage == null || srcLanguage.isEmpty()) {
            throw new IllegalArgumentException("Non-empty srcLanguage must be specified.");
        }
        if (trgLanguage == null || trgLanguage.isEmpty()) {
            throw new IllegalArgumentException("Non-empty trgLanguage must be specified.");
        }

        StringBuilder urlBuf = new StringBuilder();
        urlBuf
            .append(escapePathSegment(account.getInstanceId()))
            .append("/v2/doc-xliff/")
            .append(srcLanguage)
            .append("/")
            .append(trgLanguage);

        if (documentsMap != null && !documentsMap.isEmpty()) {
            urlBuf.append("?");
            int count = documentsMap.size();
            for (Map.Entry<DocumentType, Set<String>> entry : documentsMap.entrySet()) {
                DocumentType type = entry.getKey();
                Set<String> documentIds = entry.getValue();
                urlBuf.append(type.toString().toLowerCase()).append("=");
                boolean first = true;
                for (String docId : documentIds) {
                    if (first) {
                        first = false;
                    } else {
                        urlBuf.append(",");
                    }
                    urlBuf.append(docId);
                }
                count--;
            }
            if (count != 0) {
                urlBuf.append("&");
            }
        }

        ApiResponse resp = null;
        try {
            resp = invokeApi("GET", urlBuf.toString(), null, null, false);
        } catch (Exception e) {
            String errMsg = "Error while processing API request GET " + urlBuf;
            throw new ServiceException(errMsg, e);
        }
        assert resp != null;

        if (resp.contentType == null || !resp.contentType.equalsIgnoreCase("application/xliff+xml")) {
            throw new ServiceException("Received HTTP status: " + resp.status
                    + " with non-XLIFF response (" + resp.contentType + ") from GET"
                    + " " + urlBuf.toString());
        }
        assert resp.body != null;
        outputXliff.write(resp.body);
    }
568426
@Nonnull
  public IMicroDocument getAsDocument (@Nonnull @Nonempty final String sFullContextPath)
  {
    final String sNamespaceURL = CXMLSitemap.XML_NAMESPACE_0_9;
    final IMicroDocument ret = new MicroDocument ();
    final IMicroElement eSitemapindex = ret.appendElement (sNamespaceURL, ELEMENT_SITEMAPINDEX);
    int nIndex = 0;
    for (final XMLSitemapURLSet aURLSet : m_aURLSets)
    {
      final IMicroElement eSitemap = eSitemapindex.appendElement (sNamespaceURL, ELEMENT_SITEMAP);

      // The location of the sub-sitemaps must be prefixed with the full server
      // and context path
      eSitemap.appendElement (sNamespaceURL, ELEMENT_LOC)
              .appendText (sFullContextPath + "/" + getSitemapFilename (nIndex));

      final LocalDateTime aLastModification = aURLSet.getLastModificationDateTime ();
      if (aLastModification != null)
      {
        eSitemap.appendElement (sNamespaceURL, ELEMENT_LASTMOD)
                .appendText (PDTWebDateHelper.getAsStringXSD (aLastModification));
      }
      ++nIndex;
    }
    return ret;
  }
365043
public static List<String> getAttachmentLocales(CmsObject cms, CmsResource content) {

        List<CmsResource> detailOnlyResources = CmsDetailOnlyContainerUtil.getDetailOnlyResources(cms, content);
        Set<String> validLocaleNames = Sets.newHashSet();
        List<String> result = Lists.newArrayList();
        for (Locale locale : OpenCms.getLocaleManager().getAvailableLocales()) {
            validLocaleNames.add(locale.toString());
        }
        validLocaleNames.add(CmsDetailOnlyContainerUtil.LOCALE_ALL);
        for (CmsResource resource : detailOnlyResources) {
            String parent = CmsResource.getParentFolder(resource.getRootPath());
            String parentName = CmsResource.getName(parent);
            parentName = CmsFileUtil.removeTrailingSeparator(parentName);
            if (validLocaleNames.contains(parentName)) {
                result.add(parentName);
            }
        }
        return result;

    }
18413
private String createStringValue(CmsObject cms, I_CmsXmlDocument document) {

        Element data = m_element.element(CmsXmlPage.NODE_CONTENT);
        if (data == null) {
            String content = m_element.getText();
            m_element.clearContent();
            int index = m_element.getParent().elements(m_element.getQName()).indexOf(m_element);
            m_element.addAttribute(CmsXmlPage.ATTRIBUTE_NAME, getName() + index);
            m_element.addElement(CmsXmlPage.NODE_LINKS);
            m_element.addElement(CmsXmlPage.NODE_CONTENT).addCDATA(content);
            data = m_element.element(CmsXmlPage.NODE_CONTENT);
        }
        Attribute enabled = m_element.attribute(CmsXmlPage.ATTRIBUTE_ENABLED);

        String content = "";
        if ((enabled == null) || Boolean.valueOf(enabled.getText()).booleanValue()) {

            content = data.getText();

            CmsLinkTable linkTable = getLinkTable();
            if (!linkTable.isEmpty()) {

                // link processing: replace macros with links
                CmsLinkProcessor linkProcessor = document.getLinkProcessor(cms, linkTable);
                try {
                    content = linkProcessor.processLinks(content);
                } catch (ParserException e) {
                    // should better not happen
                    LOG.error(Messages.get().getBundle().key(Messages.ERR_XMLCONTENT_LINK_PROCESS_FAILED_0), e);
                }
            }
        }
        return content;
    }
246173
protected I_CmsXmlContentValue getBookmark(String path, Locale locale) {

        return m_bookmarks.get(getBookmarkName(path, locale));
    }
19950
public static Document getDocument(String xmlPath) {
        try {
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlPath);
            return new SAXReader().read(is);
        } catch (Exception e) {
            throw new XmlParseException("读取或解析xml文件失败，xmlPath是:" + xmlPath, e);
        }
    }
1168977
private static org.w3c.dom.Document toDom(final Document doc) {
        try {
            val xmlOutputter = new XMLOutputter();
            val elemStrWriter = new StringWriter();
            xmlOutputter.output(doc, elemStrWriter);
            val xmlBytes = elemStrWriter.toString().getBytes(Charset.defaultCharset());
            val dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            dbf.setFeature("http://apache.org/xml/features/validation/schema/normalized-value", false);
            dbf.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
            dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
            dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

            return dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xmlBytes));
        } catch (final Exception e) {
            LOGGER.trace(e.getMessage(), e);
            return null;
        }
    }
135688
Document getResourceAsDoc(String resource) throws Exception {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream is = cl.getResourceAsStream(resource);
        if (is != null) {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            // Fortify Mod: prevent external entity injection
            dbf.setExpandEntityReferences(false);
            DocumentBuilder db = dbf.newDocumentBuilder();
            // Fortify Mod: prevent external entity injection 
            TransformerFactory tf = TransformerFactory.newInstance();
            tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            Transformer t = tf.newTransformer();
            //Transformer t = TransformerFactory.newInstance().newTransformer();
	       // End Fortify Mod
            Document doc = db.newDocument();
            t.transform(new StreamSource(is), new DOMResult(doc));
            // Fortify Mod: Close the InputStream and release its resources
            is.close();
            return doc;
        } else {
            return null;
        }
    }
435195
public Pathref getPathrefFromNoderef(
            String layoutOwnerUsername, String dlmNoderef, org.dom4j.Element layout) {

        Validate.notNull(layoutOwnerUsername, "Argument 'layoutOwnerUsername' cannot be null.");
        Validate.notNull(dlmNoderef, "Argument 'dlmNoderef' cannot be null.");

        if (log.isTraceEnabled()) {
            StringBuilder msg = new StringBuilder();
            msg.append("createPathref: [layoutOwnerUsername='")
                    .append(layoutOwnerUsername)
                    .append("', dlmNoderef='")
                    .append(dlmNoderef)
                    .append("']");
            log.trace(msg.toString());
        }

        Pathref rslt = null; // default;  signifies we can't match a node

        final Matcher dlmNodeMatcher = DLM_NODE_PATTERN.matcher(dlmNoderef);
        if (dlmNodeMatcher.matches()) {
            final int userId = Integer.valueOf(dlmNodeMatcher.group(1));
            final String nodeId = dlmNodeMatcher.group(2);

            final String userName = this.userIdentityStore.getPortalUserName(userId);
            final Tuple<String, DistributedUserLayout> userLayoutInfo =
                    getUserLayoutTuple(userName, userId);

            if (userLayoutInfo.second == null) {
                this.log.warn(
                        "no layout for fragment user '"
                                + userLayoutInfo.first
                                + "' Specified dlmNoderef "
                                + dlmNoderef
                                + " cannot be resolved.");
                return null;
            }

            final Document fragmentLayout = userLayoutInfo.second.getLayout();
            final Node targetElement =
                    this.xPathOperations.evaluate(
                            "//*[@ID = $nodeId]",
                            Collections.singletonMap("nodeId", nodeId),
                            fragmentLayout,
                            XPathConstants.NODE);

            // We can only proceed if there's a valid match in the document
            if (targetElement != null) {
                String xpath = this.xmlUtilities.getUniqueXPath(targetElement);
                // Pathref objects that refer to portlets are expected to include
                // the fname as the 3rd element; other pathref objects should leave
                // that element blank.
                String fname = null;
                Node fnameAttr = targetElement.getAttributes().getNamedItem("fname");
                if (fnameAttr != null) {
                    fname = fnameAttr.getTextContent();
                }

                rslt = new Pathref(userLayoutInfo.first, xpath, fname);
            }
        }

        final Matcher userNodeMatcher = USER_NODE_PATTERN.matcher(dlmNoderef);
        if (userNodeMatcher.find()) {
            // We need a pathref based on the new style of layout b/c on
            // import this users own layout will not be in the database
            // when the path is computed back to an Id...
            final String structId = userNodeMatcher.group(1);
            final org.dom4j.Node target = layout.selectSingleNode("//*[@ID = '" + structId + "']");
            if (target == null) {
                this.log.warn(
                        "no match found on layout for user '"
                                + layoutOwnerUsername
                                + "' for the specified dlmNoderef:  "
                                + dlmNoderef);
                return null;
            }

            String fname = null;
            if (target.getName().equals("channel")) {
                fname = target.valueOf("@fname");
            }

            rslt = new Pathref(layoutOwnerUsername, target.getUniquePath(), fname);
        }

        return rslt;
    }
552826
static final DocumentFragment createContent(Document doc, String text) {

        // [#150] Text might hold XML content, which can be leniently identified by the presence
        //        of either < or & characters (other entities, like >, ", ' are not stricly XML content)
        if (text != null && (text.contains("<") || text.contains("&"))) {
            DocumentBuilder builder = JOOX.builder();

            try {

                // [#128] Trimming will get rid of leading and trailing whitespace, which would
                // otherwise cause a HIERARCHY_REQUEST_ERR raised by the parser
                text = text.trim();

                // There is a processing instruction. We can safely assume
                // valid XML and parse it as such
                if (text.startsWith("<?xml")) {
                    Document parsed = builder.parse(new InputSource(new StringReader(text)));
                    DocumentFragment fragment = parsed.createDocumentFragment();
                    fragment.appendChild(parsed.getDocumentElement());

                    return (DocumentFragment) doc.importNode(fragment, true);
                }

                // Any XML document fragment. To be on the safe side, fragments
                // are wrapped in a dummy root node
                else {
                    String wrapped = "<dummy>" + text + "</dummy>";
                    Document parsed = builder.parse(new InputSource(new StringReader(wrapped)));
                    DocumentFragment fragment = parsed.createDocumentFragment();
                    NodeList children = parsed.getDocumentElement().getChildNodes();

                    // appendChild removes children also from NodeList!
                    while (children.getLength() > 0) {
                        fragment.appendChild(children.item(0));
                    }

                    return (DocumentFragment) doc.importNode(fragment, true);
                }
            }

            // This does not occur
            catch (IOException ignore) {}

            // The XML content is invalid
            catch (SAXException ignore) {}
        }

        // Plain text or invalid XML
        return null;
    }
205157
protected Locale getLocaleToUse(CmsObject cms, CmsXmlContent xmlContent) {

        Locale contextLocale = cms.getRequestContext().getLocale();
        if (xmlContent.hasLocale(contextLocale)) {
            return contextLocale;
        }
        Locale defaultLocale = CmsLocaleManager.getDefaultLocale();
        if (xmlContent.hasLocale(defaultLocale)) {
            return defaultLocale;
        }
        if (!xmlContent.getLocales().isEmpty()) {
            return xmlContent.getLocales().get(0);
        } else {
            return defaultLocale;
        }
    }
836681
protected String parseOptionalStringValue(final String path) {

        final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);
        if (value == null) {
            return null;
        } else {
            return value.getStringValue(null);
        }
    }