Best Cerberus-source code snippet using org.cerberus.util.XmlUtil.UniversalNamespaceCache
Source:XmlUtil.java
...116 * @author abourdon117 * @see <a href="https://www.ibm.com/developerworks/library/x-nmspccontext/#N10158">...</a>118 */119 @SuppressWarnings("unchecked")120 public static final class UniversalNamespaceCache implements NamespaceContext {121 /**122 * The associated {@link Logger} to this class123 */124 private static final Logger LOG = LogManager.getLogger(UniversalNamespaceCache.class);125 public static final boolean DEFAULT_TOP_LEVEL_ONLY = false;126 /**127 * The associated maps between prefixes and URIs128 */129 private Map<String, String> prefix2Uri = new HashMap<>();130 private Map<String, String> uri2Prefix = new HashMap<>();131 public UniversalNamespaceCache(Document document) {132 this(document, DEFAULT_TOP_LEVEL_ONLY);133 }134 /**135 * This constructor parses the document and stores all namespaces it can136 * find. If toplevelOnly is <code>true</code>, only namespaces in the137 * root are used.138 *139 * @param document source document140 * @param toplevelOnly restriction of the search to enhance performance141 */142 public UniversalNamespaceCache(Document document, boolean toplevelOnly) {143 examineNode(document.getFirstChild(), toplevelOnly);144 if (LOG.isDebugEnabled()) {145 LOG.debug("Hereunder list of found namespaces (prefix, uri):");146 for (Map.Entry<String, String> items : prefix2Uri.entrySet()) {147 LOG.debug("{}, {}", items.getKey(), items.getValue());148 }149 }150 }151 /**152 * A single node is read, the namespace attributes are extracted and153 * stored.154 *155 * @param node to examine156 * @param attributesOnly if <code>true</code> no recursion happens157 */158 private void examineNode(Node node, boolean attributesOnly) {159 if (node == null) {160 LOG.warn("Unable to examine null node");161 return;162 }163 NamedNodeMap attributes = node.getAttributes();164 for (int i = 0; i < attributes.getLength(); i++) {165 Node attribute = attributes.item(i);166 storeAttribute((Attr) attribute);167 }168 if (!attributesOnly) {169 for (Node child : new IterableNodeList(node.getChildNodes())) {170 if (child.getNodeType() == Node.ELEMENT_NODE) {171 examineNode(child, false);172 }173 }174 }175 }176 /**177 * This method looks at an attribute and stores it, if it is a namespace178 * attribute.179 *180 * @param attribute to examine181 */182 private void storeAttribute(Attr attribute) {183 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI())) {184 putInCache(XMLConstants.XMLNS_ATTRIBUTE.equals(attribute.getNodeName()) ? XMLConstants.DEFAULT_NS_PREFIX : attribute.getLocalName(), attribute.getNodeValue());185 }186 }187 /**188 * Put the given prefix and URI in cache189 *190 * @param prefix to put in cache191 * @param uri to put in cache192 */193 private void putInCache(String prefix, String uri) {194 prefix2Uri.put(prefix, uri);195 uri2Prefix.put(uri, prefix);196 }197 /**198 * This method is called by XPath. It returns the namespace URI199 * associated to the given prefix.200 *201 * @param prefix to search for202 * @return uri203 */204 @Override205 public String getNamespaceURI(String prefix) {206 return prefix2Uri.get(prefix);207 }208 /**209 * This method is not needed in this context, but can be implemented in210 * a similar way.211 */212 @Override213 public String getPrefix(String namespaceURI) {214 return uri2Prefix.get(namespaceURI);215 }216 @Override217 @SuppressWarnings("rawtypes")218 public Iterator getPrefixes(String namespaceURI) {219 return null;220 }221 }222 /**223 * Returns a new {@link Document} instance from the default224 * {@link DocumentBuilder}225 *226 * @return a new {@link Document} instance from the default227 * {@link DocumentBuilder}228 * @throws XmlUtilException if an error occurred229 */230 public static Document newDocument() throws XmlUtilException {231 try {232 DocumentBuilderFactory resultDocFactory = DocumentBuilderFactory.newInstance();233 DocumentBuilder resultDocBuilder = resultDocFactory.newDocumentBuilder();234 return resultDocBuilder.newDocument();235 } catch (ParserConfigurationException e) {236 throw new XmlUtilException(e);237 }238 }239 /**240 * Returns a {@link String} representation of the {@link Node} given in241 * argument242 *243 * @param node the {@link Node} from which create the {@link String}244 * representation245 * @return the {@link String} representation of the {@link Node} given in246 * argument247 * @throws XmlUtilException if {@link Node} cannot be represented as a248 * {@link String}249 */250 public static String toString(Node node) throws XmlUtilException {251 if (node == null) {252 throw new XmlUtilException("Cannot parse a null node");253 }254 try {255 StreamResult xmlOutput = new StreamResult(new StringWriter());256 Transformer transformer = TransformerFactory.newInstance().newTransformer();257 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");258 transformer.transform(new DOMSource(node), xmlOutput);259 return xmlOutput.getWriter().toString();260 } catch (TransformerFactoryConfigurationError | TransformerException e) {261 throw new XmlUtilException(e);262 }263 }264 /**265 * Returns a {@link Document} representation of the {@link String} given in266 * argument267 *268 * @param xml the {@link String} from which create the {@link Document}269 * representation270 * @param namespaceAwareness if namespaces have to be taking into account271 * during parsing272 * @return the {@link Document} representation of the {@link String} given273 * in argument274 * @throws XmlUtilException if {@link String} cannot be represented as a275 * {@link Document}276 */277 public static Document fromString(String xml, boolean namespaceAwareness) throws XmlUtilException {278 if (xml == null) {279 throw new XmlUtilException("Cannot parse a null XML file");280 }281 try {282 return newDocumentBuilder(namespaceAwareness, true).parse(new InputSource(new StringReader(xml)));283 } catch (SAXException | IOException | ParserConfigurationException e) {284 throw new XmlUtilException(e);285 }286 }287 /**288 * The {@link #fromString(String, boolean)} version by using the289 * {@link #DEFAULT_NAMESPACE_AWARENESS} value290 */291 public static Document fromString(String xml) throws XmlUtilException {292 return fromString(xml, DEFAULT_NAMESPACE_AWARENESS);293 }294 /**295 * Returns a {@link Document} representation of the {@link URL} given in296 * argument297 *298 * @param url the {@link URL} from which create the {@link Document}299 * representation300 * @param namespaceAwareness if namespaces have to be taking into account301 * during parsing302 * @return the {@link Document} representation of the {@link URL} given in303 * argument304 * @throws XmlUtilException if {@link URL} cannot be represented as a305 * {@link Document}306 */307 public static Document fromURL(URL url, boolean namespaceAwareness) throws XmlUtilException {308 if (url == null) {309 throw new XmlUtilException("Cannot parse a null URL");310 }311 try {312 return newDocumentBuilder(namespaceAwareness, true).parse(new BufferedInputStream(url.openStream()));313 } catch (SAXException | IOException | ParserConfigurationException e) {314 throw new XmlUtilException(e);315 }316 }317 /**318 * The {@link #fromURL(URL, boolean)} version by using the319 * {@link #DEFAULT_NAMESPACE_AWARENESS} value320 *321 * @see #fromURL(URL, boolean)322 */323 public static Document fromURL(URL url) throws XmlUtilException {324 return fromURL(url, DEFAULT_NAMESPACE_AWARENESS);325 }326 /**327 * Evaluates the given xpath against the given document and produces new328 * document which satisfy the xpath expression.329 *330 * @param document the document to search against the given xpath331 * @param xpath the xpath expression332 * @return a list of new document which gather all results which satisfy the333 * xpath expression against the given document.334 * @throws XmlUtilException if an error occurred335 */336 public static NodeList evaluate(Document document, String xpath) throws XmlUtilException {337 if (document == null || xpath == null) {338 throw new XmlUtilException("Unable to evaluate null document or xpath");339 }340 XPathFactory xpathFactory = XPathFactory.newInstance();341 XPath xpathObject = xpathFactory.newXPath();342 xpathObject.setNamespaceContext(new UniversalNamespaceCache(document));343 NodeList nodeList = null;344 try {345 XPathExpression expr = xpathObject.compile(xpath);346 nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);347 } catch (XPathExpressionException xpee) {348 throw new XmlUtilException(xpee);349 }350 if (nodeList == null) {351 throw new XmlUtilException("Evaluation caused a null result");352 }353 return nodeList;354 }355 /**356 * Evaluates the given xpath against the given document and produces string357 * which satisfy the xpath expression.358 *359 * @param document the document to search against the given xpath360 * @param xpath the xpath expression361 * @return a string which satisfy the xpath expression against the given362 * document.363 * @throws XmlUtilException if an error occurred364 */365 public static String evaluateString(Document document, String xpath) throws XmlUtilException {366 if (document == null || xpath == null) {367 throw new XmlUtilException("Unable to evaluate null document or xpath");368 }369 XPathFactory xpathFactory = XPathFactory.newInstance();370 XPath xpathObject = xpathFactory.newXPath();371 xpathObject.setNamespaceContext(new UniversalNamespaceCache(document));372 String result = null;373 try {374 XPathExpression expr = xpathObject.compile(xpath);375 result = (String) expr.evaluate(document, XPathConstants.STRING);376 } catch (XPathExpressionException xpee) {377 throw new XmlUtilException(xpee);378 }379 if (result == null) {380 throw new XmlUtilException("Evaluation caused a null result");381 }382 return result;383 }384 public static Node evaluateNode(Document doc, String xpath) throws XmlUtilException {385 if (doc == null || xpath == null) {386 throw new XmlUtilException("Unable to evaluate null document or xpath");387 }388 XPathFactory xpathFactory = XPathFactory.newInstance();389 XPath xpathObject = xpathFactory.newXPath();390 xpathObject.setNamespaceContext(new UniversalNamespaceCache(doc));391 Node node = null;392 try {393 XPathExpression expr = xpathObject.compile(xpath);394 node = (Node) expr.evaluate(doc, XPathConstants.NODE);395 } catch (XPathExpressionException xpee) {396 throw new XmlUtilException(xpee);397 }398 if (node == null) {399 throw new XmlUtilException("Evaluation caused a null result");400 }401 return node;402 }403 /**404 * {@link String} version of the {@link #evaluate(Document, String)} method...
Source:XmlUtilUniversalNamespaceCacheTest.java
...19 */20package org.cerberus.util;21import javax.xml.XMLConstants;22import junit.framework.Assert;23import org.cerberus.util.XmlUtil.UniversalNamespaceCache;24import org.junit.Test;25/**26 * {@link UniversalNamespaceCache} test suite27 * 28 * @author abourdon29 */30public class XmlUtilUniversalNamespaceCacheTest {31 @Test32 public void testUniversalNamespaceCache() throws XmlUtilException {33 UniversalNamespaceCache cache = new UniversalNamespaceCache(XmlUtil.fromURL(getClass().getResource("namespaces.xml")));34 Assert.assertEquals("http://default", cache.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX));35 Assert.assertEquals("http://prefix", cache.getNamespaceURI("prefix"));36 Assert.assertEquals("http://other", cache.getNamespaceURI("other"));37 }38}...
UniversalNamespaceCache
Using AI Code Generation
1import java.io.File;2import java.io.FileInputStream;3import java.io.FileNotFoundException;4import java.io.IOException;5import java.util.HashMap;6import java.util.Iterator;7import java.util.Map;8import javax.xml.parsers.DocumentBuilder;9import javax.xml.parsers.DocumentBuilderFactory;10import javax.xml.parsers.ParserConfigurationException;11import org.w3c.dom.Document;12import org.w3c.dom.Element;13import org.w3c.dom.Node;14import org.w3c.dom.NodeList;15import org.xml.sax.SAXException;16public class XmlUtil {17 public static void main(String[] args) {18 File file = new File("C:\\Users\\sushil\\Desktop\\3.xml");19 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();20 documentBuilderFactory.setNamespaceAware(true);21 DocumentBuilder documentBuilder;22 Document document = null;23 try {24 documentBuilder = documentBuilderFactory.newDocumentBuilder();25 document = documentBuilder.parse(file);26 } catch (ParserConfigurationException | SAXException | IOException e) {27 e.printStackTrace();28 }29 Map<String, String> map = UniversalNamespaceCache(document, false);30 System.out.println(map);31 }32 public static Map UniversalNamespaceCache(Document doc, boolean inclusive) {33 Map<String, String> nsMap = new HashMap<String, String>();34 if (doc == null) {35 return nsMap;36 }37 Element root = doc.getDocumentElement();38 if (root == null) {39 return nsMap;40 }41 String rootPrefix = root.getPrefix();42 if (rootPrefix != null) {43 nsMap.put(rootPrefix, root.getNamespaceURI());44 }45 NodeList nl = doc.getElementsByTagName("*");46 for (int i = 0; i < nl.getLength(); i++) {47 Node n = nl.item(i);48 if (n.getNodeType() == Node.ELEMENT_NODE) {49 Element e = (Element) n;50 String prefix = e.getPrefix();51 String uri = e.getNamespaceURI();52 if (prefix != null && uri != null && !nsMap.containsKey(prefix)) {53 nsMap.put(prefix, uri);54 }55 }56 }57 if (inclusive) {58 Node parent = root.getParentNode();59 while (parent != null) {60 if (parent.getNodeType() == Node.ELEMENT_NODE) {61 Element e = (Element) parent;62 String prefix = e.getPrefix();63 String uri = e.getNamespaceURI();64 if (prefix != null
UniversalNamespaceCache
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2import org.w3c.dom.Document;3import javax.xml.parsers.DocumentBuilder;4import javax.xml.parsers.DocumentBuilderFactory;5import java.io.File;6public class XmlUtilTest {7 public static void main(String[] args) {8 try {9 File fXmlFile = new File("C:\\Users\\user\\Desktop\\xml\\test.xml");10 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();11 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();12 Document doc = dBuilder.parse(fXmlFile);13 XmlUtil xmlUtil = new XmlUtil();14 } catch (Exception e) {15 e.printStackTrace();16 }17 }18}19import org.cerberus.util.XmlUtil;20import org.w3c.dom.Document;21import javax.xml.parsers.DocumentBuilder;22import javax.xml.parsers.DocumentBuilderFactory;23import java.io.File;24public class XmlUtilTest {25 public static void main(String[] args) {26 try {27 File fXmlFile = new File("C:\\Users\\user\\Desktop\\xml\\test.xml");28 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();29 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();30 Document doc = dBuilder.parse(fXmlFile);31 XmlUtil xmlUtil = new XmlUtil();32 } catch (Exception e) {33 e.printStackTrace();34 }35 }36}37import org.cerberus.util.XmlUtil;38import org.w3c.dom.Document;39import javax.xml.parsers.DocumentBuilder;40import javax.xml.parsers.DocumentBuilderFactory;41import java.io.File;42public class XmlUtilTest {43 public static void main(String[] args) {44 try {45 File fXmlFile = new File("C:\\Users\\user\\Desktop\\xml\\test.xml");46 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();47 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();48 Document doc = dBuilder.parse(fXmlFile);
UniversalNamespaceCache
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2import org.w3c.dom.Document;3import org.w3c.dom.Element;4import org.w3c.dom.NodeList;5import org.xml.sax.SAXException;6import javax.xml.parsers.ParserConfigurationException;7import javax.xml.transform.TransformerException;8import java.io.File;9import java.io.IOException;10import java.util.HashMap;11import java.util.Map;12public class 3 {13 public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {14 File xmlFile = new File("C:\\Users\\user\\Desktop\\xml\\3.xml");15 Document document = XmlUtil.parseXMLFile(xmlFile);16 Element rootElement = document.getDocumentElement();17 Map<String, String> namespaceMap = new HashMap<String, String>();18 XmlUtil.addNamespaceToXMLDocument(document, namespaceMap);19 XmlUtil.saveXMLDocument(document, xmlFile);20 }21}
UniversalNamespaceCache
Using AI Code Generation
1import java.io.*;2import java.util.*;3import java.util.Iterator;4import javax.xml.parsers.DocumentBuilder;5import javax.xml.parsers.DocumentBuilderFactory;6import javax.xml.parsers.ParserConfigurationException;7import javax.xml.xpath.XPath;8import javax.xml.xpath.XPathConstants;9import javax.xml.xpath.XPathExpression;10import javax.xml.xpath.XPathExpressionException;11import javax.xml.xpath.XPathFactory;12import org.w3c.dom.Document;13import org.w3c.dom.Node;14import org.w3c.dom.NodeList;15import org.w3c.dom.NamedNodeMap;16import org.xml.sax.SAXException;17public class 3 {18 public static void main(String[] args) throws Exception {19 File xmlFile = new File("C:\\Users\\sunny\\Desktop\\test.xml");20 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();21 DocumentBuilder builder = factory.newDocumentBuilder();22 Document document = builder.parse(xmlFile);23 XPathFactory xpathFactory = XPathFactory.newInstance();24 XPath xpath = xpathFactory.newXPath();25 for(int i = 0; i < nodeList.getLength(); i++) {26 Node node = nodeList.item(i);27 System.out.println(node.getNodeName());28 }29 }30}31import java.io.*;32import java.util.*;33import java.util.Iterator;34import javax.xml.parsers.DocumentBuilder;35import javax.xml.parsers.DocumentBuilderFactory;36import javax.xml.parsers.ParserConfigurationException;37import javax.xml.xpath.XPath;38import javax.xml.xpath.XPathConstants;39import javax.xml.xpath.XPathExpression;40import javax.xml.xpath.XPathExpressionException;41import javax.xml.xpath.XPathFactory;42import org.w3c.dom.Document;43import org.w3c.dom.Node;44import
UniversalNamespaceCache
Using AI Code Generation
1package org.cerberus.util;2import java.io.File;3import java.io.IOException;4import java.util.HashMap;5import java.util.Map;6import javax.xml.parsers.ParserConfigurationException;7import org.w3c.dom.Document;8import org.xml.sax.SAXException;9public class XmlUtil {10 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {11 File xmlFile = new File("3.xml");12 Document doc = XmlUtil.parse(xmlFile);13 Map<String, String> namespaceMap = new HashMap<String, String>();14 String value = XmlUtil.getNodeValue(doc, "name", namespaceMap);15 System.out.println(value);16 }17}18package org.cerberus.util;19import java.io.File;20import java.io.IOException;21import java.util.HashMap;22import java.util.Map;23import javax.xml.parsers.ParserConfigurationException;24import org.w3c.dom.Document;25import org.xml.sax.SAXException;26public class XmlUtil {27 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {28 File xmlFile = new File("4.xml");29 Document doc = XmlUtil.parse(xmlFile);30 Map<String, String> namespaceMap = new HashMap<String, String>();
UniversalNamespaceCache
Using AI Code Generation
1import java.io.File;2import java.io.FileInputStream;3import java.io.FileNotFoundException;4import java.io.IOException;5import java.io.InputStream;6import java.util.Iterator;7import java.util.List;8import java.util.Map;9import java.util.Set;10import java.util.logging.Level;11import java.util.logging.Logger;12import javax.xml.XMLConstants;13import javax.xml.namespace.NamespaceContext;14import javax.xml.parsers.DocumentBuilder;15import javax.xml.parsers.DocumentBuilderFactory;16import javax.xml.parsers.ParserConfigurationException;17import org.cerberus.util.XmlUtil;18import org.w3c.dom.Document;19import org.xml.sax.SAXException;20public class 3 {21 public static void main(String[] args) {22 File fXmlFile = new File("C:\\Users\\user\\Documents\\NetBeansProjects\\3\\src\\3\\test.xml");23 String prefix = "ns2";24 String namespace = "";25 try {26 InputStream is = new FileInputStream(fXmlFile);27 namespace = XmlUtil.getNamespace(prefix, is);28 System.out.println(namespace);29 } catch (FileNotFoundException ex) {30 Logger.getLogger(3.class.getName()).log(Level.SEVERE, null, ex);31 }32 }33}34import java.io.File;35import java.io.FileInputStream;36import java.io.FileNotFoundException;37import java.io.IOException;38import java.io.InputStream;39import java.util.Iterator;40import java.util.List;41import java.util.Map;42import java.util.Set;43import java.util.logging.Level;44import java.util.logging.Logger;45import javax.xml.XMLConstants;46import javax.xml.namespace.NamespaceContext;47import javax.xml.parsers.DocumentBuilder;48import javax.xml.parsers.DocumentBuilderFactory;49import javax.xml.parsers.ParserConfigurationException;50import org.cerberus.util.XmlUtil;51import org.w3c.dom.Document;52import org.xml.sax.SAXException;53public class 4 {54 public static void main(String[] args) {55 File fXmlFile = new File("C:\\Users\\user\\Documents\\NetBeansProjects\\4\\src\\4\\test.xml");56 String prefix = "ns2";
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!