Best Cerberus-source code snippet using org.cerberus.util.XmlUtil
Source:XmlUnitService.java
...33import org.cerberus.service.xmlunit.InputTranslatorException;34import org.cerberus.service.xmlunit.InputTranslatorManager;35import org.cerberus.service.xmlunit.InputTranslatorUtil;36import org.cerberus.util.StringUtil;37import org.cerberus.util.XmlUtil;38import org.cerberus.util.XmlUtilException;39import org.custommonkey.xmlunit.DetailedDiff;40import org.custommonkey.xmlunit.Difference;41import org.custommonkey.xmlunit.XMLUnit;42import org.springframework.stereotype.Service;43import org.w3c.dom.Document;44import org.w3c.dom.Node;45import org.w3c.dom.NodeList;4647/**48 *49 * @author bcivel50 */51@Service52public class XmlUnitService implements IXmlUnitService {5354 /**55 * The associated {@link Logger} to this class56 */57 private static final Logger LOG = LogManager.getLogger(XmlUnitService.class);5859 /**60 * Difference value for null XPath61 */62 public static final String NULL_XPATH = "null";6364 /**65 * The default value for the getFromXML action66 */67 public static final String DEFAULT_GET_FROM_XML_VALUE = null;6869 /**70 * Prefixed input handling71 */72 private InputTranslatorManager<Document> inputTranslator;7374 @PostConstruct75 private void init() {76 initInputTranslator();77 initXMLUnitProperties();78 }7980 /**81 * Initializes {@link #inputTranslator} by two {@link InputTranslator}82 * <ul>83 * <li>One for handle the <code>url</code> prefix</li>84 * <li>One for handle without prefix</li>85 * </ul>86 */87 private void initInputTranslator() {88 inputTranslator = new InputTranslatorManager<Document>();89 // Add handling on the "url" prefix, to get URL input90 inputTranslator.addTranslator(new AInputTranslator<Document>("url") {91 @Override92 public Document translate(String input) throws InputTranslatorException {93 try {94 URL urlInput = new URL(InputTranslatorUtil.getValue(input));95 return XmlUtil.fromURL(urlInput);96 } catch (MalformedURLException e) {97 throw new InputTranslatorException(e);98 } catch (XmlUtilException e) {99 throw new InputTranslatorException(e);100 }101 }102 });103 // Add handling for raw XML input104 inputTranslator.addTranslator(new AInputTranslator<Document>(null) {105 @Override106 public Document translate(String input) throws InputTranslatorException {107 try {108 return XmlUtil.fromString(input);109 } catch (XmlUtilException e) {110 throw new InputTranslatorException(e);111 }112 }113 });114 }115116 /**117 * Initializes {@link XMLUnit} properties118 */119 private void initXMLUnitProperties() {120 XMLUnit.setIgnoreComments(true);121 XMLUnit.setIgnoreWhitespace(true);122 XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);123 XMLUnit.setCompareUnmatched(false);124 }125126 @Override127 public boolean isElementPresent(String lastSOAPResponse, String xpath) {128 if (xpath == null) {129 LOG.warn("Null argument");130 return false;131 }132133 try {134 return XmlUtil.evaluate(lastSOAPResponse, xpath).getLength() != 0;135 } catch (XmlUtilException e) {136 LOG.warn("Unable to check if element is present", e);137 }138139 return false;140 }141142 @Override143 public boolean isSimilarTree(String lastSOAPResponse, String xpath, String tree) {144 if (xpath == null || tree == null) {145 LOG.warn("Null argument");146 return false;147 }148149 try {150 NodeList candidates = XmlUtil.evaluate(lastSOAPResponse, xpath);151 for (Node candidate : new XmlUtil.IterableNodeList(candidates)) {152 boolean found = true;153 for (org.cerberus.service.xmlunit.Difference difference : Differences.fromString(getDifferencesFromXml(XmlUtil.toString(candidate), tree))) {154 if (!difference.getDiff().endsWith("/text()[1]")) {155 found = false;156 }157 }158159 if (found) {160 return true;161 }162 }163 } catch (XmlUtilException e) {164 LOG.warn("Unable to check similar tree", e);165 } catch (DifferencesException e) {166 LOG.warn("Unable to check similar tree", e);167 }168169 return false;170 }171172 @Override173 public String getFromXml(final String xmlToParse, final String xpath) {174 if (xpath == null) {175 LOG.warn("Null argument");176 return DEFAULT_GET_FROM_XML_VALUE;177 }178179 try {180 final Document document = StringUtil.isURL(xmlToParse) ? XmlUtil.fromURL(new URL(xmlToParse)) : XmlUtil.fromString(xmlToParse);181 final String result = XmlUtil.evaluateString(document, xpath);182 // Not that in case of multiple values then send the first one183 return result != null && result.length() > 0 ? result : DEFAULT_GET_FROM_XML_VALUE;184 } catch (XmlUtilException e) {185 LOG.warn("Unable to get from xml", e);186 } catch (MalformedURLException e) {187 LOG.warn("Unable to get from xml", e);188 }189190 return DEFAULT_GET_FROM_XML_VALUE;191 }192193 @Override194 public String getDifferencesFromXml(String left, String right) {195 try {196 // Gets the detailed diff between left and right argument197 Document leftDocument = inputTranslator.translate(left);198 Document rightDocument = inputTranslator.translate(right);199 DetailedDiff diffs = new DetailedDiff(XMLUnit.compareXML(leftDocument, rightDocument));200201 // Creates the result structure which will contain difference list202 Differences resultDiff = new Differences();203204 // Add each difference to our result structure205 for (Object diff : diffs.getAllDifferences()) {206 if (!(diff instanceof Difference)) {207 LOG.warn("Unable to handle no XMLUnit Difference " + diff);208 continue;209 }210 Difference wellTypedDiff = (Difference) diff;211 String xPathLocation = wellTypedDiff.getControlNodeDetail().getXpathLocation();212 // Null XPath location means additional data from the right213 // structure.214 // Then we retrieve XPath from the right structure.215 if (xPathLocation == null) {216 xPathLocation = wellTypedDiff.getTestNodeDetail().getXpathLocation();217 }218 // If location is still null, then both of left and right219 // differences have been marked as null220 // This case should never happen221 if (xPathLocation == null) {222 LOG.warn("Null left and right differences found");223 xPathLocation = NULL_XPATH;224 }225 resultDiff.addDifference(new org.cerberus.service.xmlunit.Difference(xPathLocation));226 }227228 // Finally returns the String representation of our result structure229 return resultDiff.mkString();230 } catch (InputTranslatorException e) {231 LOG.warn("Unable to get differences from XML", e);232 }233234 return null;235 }236237 @Override238 public String removeDifference(String pattern, String differences) {239 if (pattern == null || differences == null) {240 LOG.warn("Null argument");241 return null;242 }243244 try {245 // Gets the difference list from the differences246 Differences current = Differences.fromString(differences);247 Differences returned = new Differences();248249 // Compiles the given pattern250 Pattern compiledPattern = Pattern.compile(pattern);251 for (org.cerberus.service.xmlunit.Difference currentDiff : current.getDifferences()) {252 if (compiledPattern.matcher(currentDiff.getDiff()).matches()) {253 continue;254 }255 returned.addDifference(currentDiff);256 }257258 // Returns the empty String if there is no difference left, or the259 // String XML representation260 return returned.mkString();261 } catch (DifferencesException e) {262 LOG.warn("Unable to remove differences", e);263 }264265 return null;266 }267268 @Override269 public boolean isElementEquals(String lastSOAPResponse, String xpath, String expectedElement) {270 if (lastSOAPResponse == null || xpath == null || expectedElement == null) {271 LOG.warn("Null argument");272 return false;273 }274275 try {276 NodeList candidates = XmlUtil.evaluate(lastSOAPResponse, xpath);277 LOG.debug(candidates.toString());278 for (Document candidate : XmlUtil.fromNodeList(candidates)) {279 if (Differences.fromString(getDifferencesFromXml(XmlUtil.toString(candidate), expectedElement)).isEmpty()) {280 return true;281 }282 }283 } catch (XmlUtilException xue) {284 LOG.warn("Unable to check if element equality", xue);285 } catch (DifferencesException de) {286 LOG.warn("Unable to check if element equality", de);287 }288289 return false;290 }291292 @Override293 public Document getXmlDocument(String lastSOAPResponse) {294 Document document = null;295 try {296 document = XmlUtil.fromString(lastSOAPResponse);297 return document;298 } catch (XmlUtilException ex) {299 LOG.warn(ex);300 }301 return document;302 }303}
...
Source:XmlUtilTest.java
...41import org.w3c.dom.Document;42import org.w3c.dom.Element;43import org.xml.sax.SAXException;44/**45 * {@link XmlUtil} unit tests46 * 47 * @author abourdon48 */49@RunWith(MockitoJUnitRunner.class)50@PrepareForTest({ XmlUnitService.class })51@ContextConfiguration(locations = { "/applicationContextTest.xml" })52public class XmlUtilTest {53 @InjectMocks54 private XmlUnitService xmlUnitService;55 @BeforeClass56 public static void beforeClass() {57 XMLUnit.setIgnoreComments(true);58 XMLUnit.setIgnoreWhitespace(true);59 XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);60 XMLUnit.setCompareUnmatched(false);61 }62 public XmlUtilTest() {63 }64 @Before65 public void before() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {66 Method init = xmlUnitService.getClass().getDeclaredMethod("init");67 init.setAccessible(true);68 init.invoke(xmlUnitService);69 }70 @Test71 public void testNewDocument() throws XmlUtilException {72 Assert.assertTrue(XmlUtil.newDocument() instanceof Document);73 }74 @Test75 public void testToString() throws XmlUtilException, SAXException, IOException {76 Document doc = XmlUtil.newDocument();77 Element expected = doc.createElement("root");78 doc.appendChild(expected);79 Element child = doc.createElement("child");80 expected.appendChild(child);81 String actual = XmlUtil.toString(expected);82 DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML("<root><child/></root>", actual));83 Assert.assertTrue(diff.toString(), diff.similar());84 }85 @Test(expected = XmlUtilException.class)86 public void testToStringWithNullArguments() throws XmlUtilException {87 XmlUtil.toString(null);88 }89 @Test90 public void testFromString() throws XmlUtilException {91 Document expected = XmlUtil.newDocument();92 Element element = expected.createElement("root");93 expected.appendChild(element);94 Element child = expected.createElement("child");95 element.appendChild(child);96 Document actual = XmlUtil.fromString("<root><child/></root>");97 DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expected, actual));98 Assert.assertTrue(diff.toString(), diff.similar());99 }100 @Test(expected = XmlUtilException.class)101 public void testFromStringWithNullArguments() throws XmlUtilException {102 XmlUtil.fromString(null);103 }104 @Test105 public void testFromURL() throws XmlUtilException {106 Document expected = XmlUtil.newDocument();107 Element element = expected.createElement("root");108 expected.appendChild(element);109 Element child = expected.createElement("child");110 child.appendChild(expected.createTextNode("a"));111 element.appendChild(child);112 Document actual = XmlUtil.fromURL(getClass().getResource("input.xml"));113 DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expected, actual));114 Assert.assertTrue(diff.toString(), diff.similar());115 }116 @Test(expected = XmlUtilException.class)117 public void testFromURLWithNullArguments() throws XmlUtilException {118 XmlUtil.fromURL(null);119 }120 @Test121 public void testEvaluateDocument() throws XmlUtilException, DifferencesException {122 List<Document> expected = Arrays.asList(XmlUtil.fromString("<child><item1/></child>"), XmlUtil.fromString("<child><item2/></child>"));123 List<Document> actual = XmlUtil.fromNodeList(XmlUtil.evaluate(XmlUtil.fromString("<root><child><item1/></child><child><item2/></child></root>"), "/root/child"));124 Assert.assertEquals(expected.size(), actual.size());125 for (int i = 0; i < expected.size(); i++) {126 String differences = xmlUnitService.getDifferencesFromXml(XmlUtil.toString(expected.get(i)), XmlUtil.toString(actual.get(i)));127 Assert.assertTrue(Differences.fromString(differences).isEmpty());128 }129 }130 131 @Test132 public void testEvaluateDocumentWithNamespaces() throws XmlUtilException, DifferencesException {133 List<Document> expected = Arrays.asList(XmlUtil.fromURL(getClass().getResource("part.xml"), true));134 List<Document> actual = XmlUtil.fromNodeList(XmlUtil.evaluate(XmlUtil.fromURL(getClass().getResource("all.xml"), true), "//ns0:Response_1.0"));135 136 Assert.assertEquals(expected.size(), actual.size());137 for (int i = 0; i < expected.size(); i++) {138 String differences = xmlUnitService.getDifferencesFromXml(XmlUtil.toString(expected.get(i)), XmlUtil.toString(actual.get(i)));139 Assert.assertTrue(Differences.fromString(differences).isEmpty());140 }141 }142 @Test(expected = XmlUtilException.class)143 public void testEvaluateDocumentWithNullDocumentArgument() throws XmlUtilException {144 XmlUtil.evaluate((Document) null, "/foo");145 }146 @Test(expected = XmlUtilException.class)147 public void testEvaluateDocumentWithNullXPathArgument() throws XmlUtilException {148 XmlUtil.evaluate(XmlUtil.newDocument(), null);149 }150 @Test151 public void testEvaluateString() throws XmlUtilException, DifferencesException {152 List<String> expected = Arrays.asList("<child><item1/></child>", "<child><item2/></child>");153 List<String> actual = new ArrayList<String>();154 List<Document> actualDocuments = XmlUtil.fromNodeList(XmlUtil.evaluate("<root><child><item1/></child><child><item2/></child></root>", "/root/child"));155 for (Document actualDocument : actualDocuments) {156 actual.add(XmlUtil.toString(actualDocument));157 }158 Assert.assertEquals(expected.size(), actual.size());159 for (int i = 0; i < expected.size(); i++) {160 String differences = xmlUnitService.getDifferencesFromXml(expected.get(i), actual.get(i));161 Assert.assertTrue(Differences.fromString(differences).isEmpty());162 }163 }164 @Test(expected = XmlUtilException.class)165 public void testEvaluateStringWithNullDocumentArgument() throws XmlUtilException {166 XmlUtil.evaluate((String) null, "/foo");167 }168 @Test(expected = XmlUtilException.class)169 public void testEvaluateStringtWithNullXPathArgument() throws XmlUtilException {170 XmlUtil.evaluate("<foo/>", null);171 }172}...
XmlUtil
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2import java.io.*;3import java.util.*;4import org.w3c.dom.*;5import javax.xml.parsers.*;6import org.xml.sax.*;7import javax.xml.transform.*;8import javax.xml.transform.dom.*;9import javax.xml.transform.stream.*;10import org.xml.sax.helpers.*;11import org.xml.sax.helpers.DefaultHandler;12import org.xml.sax.SAXException;13import org.xml.sax.SAXParseException;14import org.xml.sax.Attributes;15import org.xml.sax.helpers.DefaultHandler;16import org.xml.sax.helpers.AttributesImpl;17import org.xml.sax.helpers.XMLReaderFactory;18import org.xml.sax.helpers.XMLFilterImpl;19import org.xml.sax.XMLReader;20import org.xml.sax.InputSource;21import org.xml.sax.ContentHandler;22import org.xml.sax.SAXException;23import org.xml.sax.SAXParseException;24import org.xml.sax.Attributes;25import org.xml.sax.helpers.DefaultHandler;26import org.xml.sax.helpers.AttributesImpl;27import org.xml.sax.helpers.XMLReaderFactory;28import org.xml.sax.helpers.XMLFilterImpl;29import org.xml.sax.XMLReader;30import org.xml.sax.InputSource;31import org.xml.sax.ContentHandler;32import org.xml.sax.SAXException;33import org.xml.sax.SAXParseException;34import org.xml.sax.Attributes;35import org.xml.sax.helpers.DefaultHandler;36import org.xml.sax.helpers.AttributesImpl;37import org.xml.sax.helpers.XMLReaderFactory;38import org.xml.sax.helpers.XMLFilterImpl;39import org.xml.sax.XMLReader;40import org.xml.sax.InputSource;41import org.xml.sax.ContentHandler;42import org.xml.sax.SAXException;43import org.xml.sax.SAXParseException;44import org.xml.sax.Attributes;45import org.xml.sax.helpers.DefaultHandler;46import org.xml.sax.helpers.AttributesImpl;47import org.xml.sax.helpers.XMLReaderFactory;48import org.xml.sax.helpers.XMLFilterImpl;49import org.xml.sax.XMLReader;50import org.xml.sax.InputSource;51import org.xml.sax.ContentHandler;52import org.xml.sax.SAXException;53import org.xml.sax.SAXParseException;54import org.xml.sax.Attributes;55import org.xml.sax.helpers.DefaultHandler;56import org.xml.sax.helpers.AttributesImpl;57import org.xml.sax.helpers.XMLReaderFactory;58import org.xml.sax.helpers.XMLFilterImpl;59import org.xml.sax.XMLReader;60import org.xml.sax.InputSource;61import org.xml.sax.ContentHandler;62import org.xml.sax.SAXException;63import org.xml.sax.SAXParseException;64import org.xml.sax.Attributes;65import org.xml.sax.helpers.DefaultHandler;66import org.xml.sax.helpers.AttributesImpl;67import org.xml.sax.helpers.XMLReaderFactory;
XmlUtil
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2import org.cerberus.util.XmlUtilException;3import org.cerberus.util.XmlValidator;4import org.cerberus.util.XmlValidatorException;5import org.cerberus.util.XmlValidatorFactory;6import org.w3c.dom.Document;7import org.w3c.dom.Node;8import org.w3c.dom.NodeList;9import java.io.File;10import java.io.IOException;11public class XmlUtilTest {12 public static void main(String[] args) {13 try {14 XmlValidator xmlValidator = XmlValidatorFactory.getXmlValidatorInstance();15 String xml = XmlUtil.getXmlString(new File("test.xml"));16 System.out.println(xml);17 Document document = XmlUtil.getXmlDocument(xml);18 System.out.println(document);19 System.out.println(nodeList);20 System.out.println(node);21 System.out.println(nodeContent);22 System.out.println(nodeContent2);23 System.out.println(nodeContent3);24 System.out.println(nodeContent4);25 System.out.println(nodeContent5);26 System.out.println(nodeContent6);27 System.out.println(nodeContent7);28 System.out.println(nodeContent8);29 System.out.println(nodeContent9);30 System.out.println(nodeContent10);31 System.out.println(nodeContent11);32 System.out.println(nodeContent12);
XmlUtil
Using AI Code Generation
1package org.cerberus.util;2import java.io.*;3import java.util.*;4import javax.xml.parsers.*;5import org.w3c.dom.*;6import org.xml.sax.*;7public class XmlUtil {8 public static String getValue(String tag, Element element) {9 NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();10 Node node = (Node) nodes.item(0);11 return node.getNodeValue();12 }13}14package org.cerberus.util;15import java.io.*;16import java.util.*;17import javax.xml.parsers.*;18import org.w3c.dom.*;19import org.xml.sax.*;20public class XmlUtil {21 public static String getValue(String tag, Element element) {22 NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();23 Node node = (Node) nodes.item(0);24 return node.getNodeValue();25 }26}27package org.cerberus.util;28import java.io.*;29import java.util.*;30import javax.xml.parsers.*;31import org.w3c.dom.*;32import org.xml.sax.*;33public class XmlUtil {34 public static String getValue(String tag, Element element) {35 NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();36 Node node = (Node) nodes.item(0);37 return node.getNodeValue();38 }39}
XmlUtil
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2import org.cerberus.util.XmlUtilException;3public class 3 {4 public static void main(String[] args) {5 try {6 XmlUtil xmlUtil = new XmlUtil();7 xmlUtil.parseXmlFile("C:\\Users\\user\\Desktop\\xml\\test.xml");8 String value = xmlUtil.getNodeValue("root/child1");9 System.out.println(value);10 } catch (XmlUtilException ex) {11 System.out.println(ex.getMessage());12 }13 }14}
XmlUtil
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2public class 3 {3 public static void main(String[] args) {4 String xml = "<root><node1>value1</node1><node2>value2</node2></root>";5 System.out.println(XmlUtil.getXmlValue(xml, xpath));6 }7}8import org.cerberus.util.XmlUtil;9public class 4 {10 public static void main(String[] args) {11 String xml = "<root><node1>value1</node1><node2>value2</node2></root>";12 System.out.println(XmlUtil.getXmlValue(xml, xpath));13 }14}15import org.cerberus.util.XmlUtil;16public class 5 {17 public static void main(String[] args) {18 String xml = "<root><node1>value1</node1><node2>value2</node2></root>";19 System.out.println(XmlUtil.getXmlValue(xml, xpath));20 }21}22import org.cerberus.util.XmlUtil;23public class 6 {24 public static void main(String[] args) {25 String xml = "<root><node1>value1</node1><node2>value2</node2></root>";26 System.out.println(XmlUtil.getXmlValue(xml, xpath));27 }28}29import org.cerberus.util.XmlUtil;30public class 7 {31 public static void main(String[] args) {32 String xml = "<root><node1>value1</node1><node2>value2</node2></root>";33 System.out.println(XmlUtil.getXmlValue(xml, xpath));34 }35}
XmlUtil
Using AI Code Generation
1import org.cerberus.util.XmlUtil;2import java.util.HashMap;3import java.util.Map;4public class 3 {5public static void main(String[] args) {6String xmlString = "<root><name>john</name><age>23</age></root>";7Map<String, String> map = new HashMap<String, String>();8map.put("name", "john");9map.put("age", "23");10System.out.println("XmlUtil.isEqualXml: " + XmlUtil.isEqualXml(xmlString, map));11}12}13XmlUtil.isEqualXml(String xmlString, Map<String, String> map)14import org.cerberus.util.XmlUtil;15import java.util.HashMap;16import java.util.Map;17import java.util.List;18import java.util.ArrayList;19public class 4 {20public static void main(String[] args) {21String xmlString = "<root><name>john</name><age>23</age></root>";22List<String> list = new ArrayList<String>();23list.add("john");24list.add("23");25System.out.println("XmlUtil.isEqualXml: " + XmlUtil.isEqualXml(xmlString, list));26}27}28XmlUtil.isEqualXml(String xmlString, List<String> list)29import org.cerberus.util.XmlUtil;30import java.util.HashMap;31import java.util.Map;32import java.util.List;33import java.util.ArrayList;34public class 5 {35public static void main(String[] args) {36String xmlString = "<root><name>john</name><age>23</age></root>";37System.out.println("XmlUtil.isEqualXml: " + XmlUtil.isEqualXml(xmlString, "john",
XmlUtil
Using AI Code Generation
1import org.cerberus.util.*;2import java.io.*;3{4public static void main(String args[])5{6String s1="C:/myjava/1.xml";7String s2="C:/myjava/2.xml";8String s3="C:/myjava/3.xml";9{10XmlUtil u=new XmlUtil();11u.createXml(s1);12u.createXml(s2);13u.createXml(s3);14}15catch(Exception e)16{17System.out.println(e);18}19}20}
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!!