luni, 15 iunie 2015

[OmniFaces utilities 2.1] Convenience method to return a node list matching given XPath expression


[OmniFaces utilities] The getNodeList() method return a node list matching given XPath expression.

Method:
Usage:

Before reading this post, please read about Xml#createDocument().

This example was practically "ripped up" from OmniFaces 2.1, WebXml class, which is used to parses the /WEB-INF/web.xml and all /META-INF/web-fragment files found in the classpath and offers methods to obtain information from them which is not available by the standard Servlet API.

import org.omnifaces.util.Xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
...
private static final String WEB_XML = "/WEB-INF/web.xml";

// the following elements will be resolved
private static final String XPATH_WELCOME_FILE = "welcome-file-list/welcome-file";
private static final String XPATH_EXCEPTION_TYPE = "error-page/exception-type";
private static final String XPATH_SECURITY_CONSTRAINT = "security-constraint";
...
ServletContext servletContext = (ServletContext) Faces.getExternalContext().getContext();
List<URL> urls = new ArrayList<>();
urls.add(servletContext.getResource(WEB_XML));
      
try {
    Document document = Xml.createDocument(urls);
   
    // DOM root available in memory
    Element root = document.getDocumentElement();
    // XPath
    XPath xpath = XPathFactory.newInstance().newXPath();
   
    // resolve XPATH_WELCOME_FILE
    NodeList welcomeFileList = getNodeList(root, xpath, XPATH_WELCOME_FILE);

    // resolve XPATH_EXCEPTION_TYPE
    NodeList exceptionTypes = getNodeList(root, xpath, XPATH_EXCEPTION_TYPE);
  
    // resolve XPATH_SECURITY_CONSTRAINT
    NodeList constraints = getNodeList(root, xpath, XPATH_SECURITY_CONSTRAINT);

} catch (...) {
    // ...
}

Niciun comentariu:

Trimiteți un comentariu