Best Karate code snippet using com.intuit.karate.XmlUtils.compile
Source:Script.java
...152 }153 public static final boolean isVariableAndSpaceAndPath(String text) {154 return text.matches("^" + VARIABLE_PATTERN_STRING + "\\s+.+");155 }156 private static final Pattern VAR_AND_PATH_PATTERN = Pattern.compile("\\w+");157 public static StringUtils.Pair parseVariableAndPath(String text) {158 Matcher matcher = VAR_AND_PATH_PATTERN.matcher(text);159 matcher.find();160 String name = text.substring(0, matcher.end());161 String path;162 if (matcher.end() == text.length()) {163 path = "";164 } else {165 path = text.substring(matcher.end());166 }167 if (isXmlPath(path) || isXmlPathFunction(path)) {168 // xml, don't prefix for json169 } else {170 path = "$" + path;171 }172 return StringUtils.pair(name, path);173 }174 public static ScriptValue evalKarateExpressionForMatch(String text, ScenarioContext context) {175 return evalKarateExpression(text, context);176 }177 private static ScriptValue result(ScriptValue called, CallResult result, boolean reuseParentConfig, ScenarioContext context) {178 if (reuseParentConfig) { // if shared scope179 context.configure(new Config(result.config)); // re-apply config from time of snapshot180 if (result.vars != null) {181 context.vars.clear();182 context.vars.putAll(result.vars.copy(false)); // clone for safety 183 }184 }185 return result.value.copy(false); // clone result for safety 186 }187 private static ScriptValue callWithCache(String callKey, ScriptValue called, String arg, ScenarioContext context, boolean reuseParentConfig) {188 // IMPORTANT: the call result is always shallow-cloned before returning189 // so that call result (if java Map) is not mutated by other scenarios190 final FeatureContext featureContext = context.featureContext;191 CallResult result = featureContext.callCache.get(callKey);192 if (result != null) {193 context.logger.trace("callonce cache hit for: {}", callKey);194 return result(called, result, reuseParentConfig, context);195 }196 long startTime = System.currentTimeMillis();197 context.logger.trace("callonce waiting for lock: {}", callKey);198 synchronized (featureContext) {199 result = featureContext.callCache.get(callKey); // retry200 if (result != null) {201 long endTime = System.currentTimeMillis() - startTime;202 context.logger.warn("this thread waited {} milliseconds for callonce lock: {}", endTime, callKey);203 return result(called, result, reuseParentConfig, context);204 }205 // this thread is the 'winner'206 context.logger.info(">> lock acquired, begin callonce: {}", callKey);207 ScriptValue resultValue = call(called, arg, context, reuseParentConfig);208 // we clone result (and config) here, to snapshot state at the point the callonce was invoked209 // this prevents the state from being clobbered by the subsequent steps of this210 // first scenario that is about to use the result211 ScriptValueMap clonedVars = called.isFeature() && reuseParentConfig ? context.vars.copy(false) : null;212 result = new CallResult(resultValue.copy(false), new Config(context.getConfig()), clonedVars);213 featureContext.callCache.put(callKey, result);214 context.logger.info("<< lock released, cached callonce: {}", callKey);215 return resultValue; // another routine will apply globally if needed216 }217 }218 public static ScriptValue getIfVariableReference(String text, ScenarioContext context) {219 if (isVariable(text)) {220 // don't re-evaluate if this is clearly a direct reference to a variable221 // this avoids un-necessary conversion of xml into a map in some cases 222 // e.g. 'Given request foo' - where foo is a ScriptValue of type XML223 ScriptValue value = context.vars.get(text);224 if (value != null) {225 return value;226 }227 }228 return null;229 }230 public static ScriptValue evalKarateExpression(String text, ScenarioContext context) {231 text = StringUtils.trimToNull(text);232 if (text == null) {233 return ScriptValue.NULL;234 }235 ScriptValue varValue = getIfVariableReference(text, context);236 if (varValue != null) {237 return varValue;238 }239 boolean callOnce = isCallOnceSyntax(text);240 if (callOnce || isCallSyntax(text)) { // special case in form "callBegin foo arg"241 if (callOnce) {242 text = text.substring(9);243 } else {244 text = text.substring(5);245 }246 StringUtils.Pair pair = parseCallArgs(text);247 ScriptValue called = evalKarateExpression(pair.left, context);248 if (callOnce) {249 return callWithCache(pair.left, called, pair.right, context, false);250 } else {251 return call(called, pair.right, context, false);252 }253 } else if (isDollarPrefixedJsonPath(text)) {254 return evalJsonPathOnVarByName(ScriptValueMap.VAR_RESPONSE, text, context);255 } else if (isGetSyntax(text) || isDollarPrefixed(text)) { // special case in form256 // get json[*].path257 // $json[*].path258 // get /xml/path259 // get xpath-function(expression)260 int index = -1;261 if (text.startsWith("$")) {262 text = text.substring(1);263 } else if (text.startsWith("get[")) {264 int pos = text.indexOf(']');265 index = Integer.valueOf(text.substring(4, pos));266 text = text.substring(pos + 2);267 } else {268 text = text.substring(4);269 }270 String left;271 String right;272 if (isDollarPrefixedJsonPath(text)) { // edge case get[0] $..foo273 left = ScriptValueMap.VAR_RESPONSE;274 right = text;275 } else if (isVariableAndSpaceAndPath(text)) {276 int pos = text.indexOf(' ');277 right = text.substring(pos + 1);278 left = text.substring(0, pos);279 } else {280 StringUtils.Pair pair = parseVariableAndPath(text);281 left = pair.left;282 right = pair.right;283 }284 ScriptValue sv;285 if (isXmlPath(right) || isXmlPathFunction(right)) {286 sv = evalXmlPathOnVarByName(left, right, context);287 } else {288 sv = evalJsonPathOnVarByName(left, right, context);289 }290 if (index != -1 && sv.isListLike()) {291 List list = sv.getAsList();292 if (!list.isEmpty()) {293 return new ScriptValue(list.get(index));294 }295 }296 return sv;297 } else if (isJson(text)) {298 DocumentContext doc = JsonUtils.toJsonDoc(text);299 evalJsonEmbeddedExpressions(doc, context);300 return new ScriptValue(doc);301 } else if (isXml(text)) {302 Document doc = XmlUtils.toXmlDoc(text);303 evalXmlEmbeddedExpressions(doc, context);304 return new ScriptValue(doc);305 } else if (isXmlPath(text)) {306 return evalXmlPathOnVarByName(ScriptValueMap.VAR_RESPONSE, text, context);307 } else {308 // js expressions e.g. foo, foo(bar), foo.bar, foo + bar, foo + '', 5, true309 // including function declarations e.g. function() { }310 return evalJsExpression(text, context);311 }312 }313 private static ScriptValue getValuebyName(String name, ScenarioContext context) {314 ScriptValue value = context.vars.get(name);315 if (value == null) {316 throw new RuntimeException("no variable found with name: " + name);317 }318 return value;319 }320 // this is called only from the routine that evaluates karate expressions321 public static ScriptValue evalXmlPathOnVarByName(String name, String path, ScenarioContext context) {322 ScriptValue value = getValuebyName(name, context);323 Node node;324 switch (value.getType()) {325 case XML:326 node = value.getValue(Node.class);327 break;328 default:329 node = XmlUtils.fromMap(value.getAsMap());330 }331 ScriptValue sv = evalXmlPathOnXmlNode(node, path);332 if (sv == null) {333 throw new KarateException("xpath does not exist: " + path + " on " + name);334 }335 if (path.startsWith("count")) { // special case336 sv = new ScriptValue(sv.getAsInt());337 }338 return sv;339 }340 // hack: if this returns null - it means the node does not exist341 // this is relevant for the match routine to process #present and #notpresent macros342 public static ScriptValue evalXmlPathOnXmlNode(Node doc, String path) {343 NodeList nodeList;344 try {345 nodeList = XmlUtils.getNodeListByPath(doc, path);346 } catch (Exception e) {347 // hack, this happens for xpath functions that don't return nodes (e.g. count)348 String strValue = XmlUtils.getTextValueByPath(doc, path);349 ScriptValue sv = new ScriptValue(strValue);350 if (path.startsWith("count")) { // special case351 return new ScriptValue(sv.getAsInt());352 } else {353 return sv;354 }355 }356 int count = nodeList.getLength();357 if (count == 0) { // xpath / node does not exist !358 return null;359 }360 if (count == 1) {361 return nodeToValue(nodeList.item(0));362 }363 List list = new ArrayList();364 for (int i = 0; i < count; i++) {365 ScriptValue sv = nodeToValue(nodeList.item(i));366 list.add(sv.getValue());367 }368 return new ScriptValue(list);369 }370 private static ScriptValue nodeToValue(Node node) {371 int childElementCount = XmlUtils.getChildElementCount(node);372 if (childElementCount == 0) {373 // hack assuming this is the most common "intent"374 return new ScriptValue(node.getTextContent());375 }376 if (node.getNodeType() == Node.DOCUMENT_NODE) {377 return new ScriptValue(node);378 } else { // make sure we create a fresh doc else future xpath would run against original root379 return new ScriptValue(XmlUtils.toNewDocument(node));380 }381 }382 public static ScriptValue evalJsonPathOnVarByName(String name, String exp, ScenarioContext context) {383 ScriptValue value = getValuebyName(name, context);384 if (value.isJsonLike()) {385 DocumentContext jsonDoc = value.getAsJsonDocument();386 return new ScriptValue(jsonDoc.read(exp));387 } else if (value.isXml()) {388 Document xml = value.getValue(Document.class);389 DocumentContext xmlDoc = XmlUtils.toJsonDoc(xml);390 return new ScriptValue(xmlDoc.read(exp));391 } else {392 String str = value.getAsString();393 DocumentContext strDoc = JsonPath.parse(str);394 return new ScriptValue(strDoc.read(exp));395 }396 }397 public static ScriptValue evalJsExpression(String exp, ScenarioContext context) {398 return ScriptBindings.evalInNashorn(exp, context, null);399 }400 public static ScriptValue evalJsExpression(String exp, ScenarioContext context, ScriptValue selfValue, Object root, Object parent) {401 return ScriptBindings.evalInNashorn(exp, context, new ScriptEvalContext(selfValue, root, parent));402 }403 private static final String VARIABLE_PATTERN_STRING = "[a-zA-Z][\\w]*";404 private static final Pattern VARIABLE_PATTERN = Pattern.compile(VARIABLE_PATTERN_STRING);405 public static boolean isValidVariableName(String name) {406 return VARIABLE_PATTERN.matcher(name).matches();407 }408 public static void evalJsonEmbeddedExpressions(DocumentContext doc, ScenarioContext context) {409 Object o = doc.read("$");410 evalJsonEmbeddedExpressions("$", o, context, doc);411 }412 private static void evalJsonEmbeddedExpressions(String path, Object o, ScenarioContext context, DocumentContext root) {413 if (o == null) {414 return;415 }416 if (o instanceof Map) {417 Map<String, Object> map = (Map<String, Object>) o;418 // collect keys first, since they could be removed by the 'remove if null' ##(macro)...
Source:ScriptBridge.java
...754 public Properties getProperties() {755 return System.getProperties();756 }757 public String extract(String text, String regex, int group) {758 Pattern pattern = Pattern.compile(regex);759 Matcher matcher = pattern.matcher(text);760 if (!matcher.find()) {761 context.logger.warn("failed to find pattern: {}", regex);762 return null;763 }764 return matcher.group(group);765 }766 public List<String> extractAll(String text, String regex, int group) {767 Pattern pattern = Pattern.compile(regex);768 Matcher matcher = pattern.matcher(text);769 List<String> list = new ArrayList();770 while (matcher.find()) {771 list.add(matcher.group(group));772 }773 return list;774 }775 public Http http(String url) {776 return Http.forUrl(context, url);777 }778 public void stop(int port) {779 Command.waitForSocket(port);780 }781 public void abort() {...
compile
Using AI Code Generation
1import com.intuit.karate.XmlUtils;2import org.w3c.dom.Document;3import org.w3c.dom.Element;4import org.w3c.dom.Node;5import org.w3c.dom.NodeList;6import javax.xml.xpath.XPathConstants;7import javax.xml.xpath.XPathExpressionException;8import javax.xml.xpath.XPathFactory;9import java.io.File;10import java.util.ArrayList;11import java.util.List;12import java.util.Map;13import java.util.HashMap;14import java.util.Arrays;15import java.util.Collections;16import java.util.Iterator;17import java.util.LinkedHashMap;18import java.util.Set;19import java.util.HashSet;20import java.util.stream.Collectors;21import java.util.stream.Stream;22import java.util.stream.IntStream;23import java.util.stream.StreamSupport;24public class 4 {25 public static void main(String[] args) throws Exception {26 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><child1>value1</child1><child2>value2</child2><child3>value3</child3><child4>value4</child4></root>";27 Document doc = XmlUtils.compile(xml);28 Element root = doc.getDocumentElement();29 NodeList children = root.getChildNodes();30 Map<String, String> map = new HashMap<>();31 for (int i = 0; i < children.getLength(); i++) {32 Node child = children.item(i);33 if (child.getNodeType() != Node.ELEMENT_NODE) {34 continue;35 }36 String name = child.getNodeName();37 String value = child.getTextContent();38 map.put(name, value);39 }40 System.out.println(map);41 }42}43import com.intuit.karate.XmlUtils;44import org.w3c.dom.Document;45import org.w3c.dom.Element;46import org.w3c.dom.Node;47import org.w3c.dom.NodeList;48import javax.xml.xpath.XPathConstants;49import javax.xml.xpath.XPathExpressionException;50import javax.xml.xpath.XPathFactory;51import java.io.File;52import java.util.ArrayList;53import java.util.List;54import java.util.Map;55import java.util.HashMap;56import java.util.Arrays;57import java.util.Collections;58import java.util.Iterator;59import java.util.LinkedHashMap;60import java.util
compile
Using AI Code Generation
1import com.intuit.karate.XmlUtils;2import javax.xml.transform.Source;3import javax.xml.transform.stream.StreamSource;4import javax.xml.validation.Schema;5import javax.xml.validation.SchemaFactory;6import javax.xml.validation.Validator;7public class XmlValidation {8 public static void main(String[] args) throws Exception {9 Source xmlFile = new StreamSource(new File("C:/Users/1234/Desktop/1.xml"));10 Source xsdFile = new StreamSource(new File("C:/Users/1234/Desktop/2.xsd"));11 Schema schema = schemaFactory.newSchema(xsdFile);12 Validator validator = schema.newValidator();13 validator.validate(xmlFile);14 System.out.println(xmlFile.getSystemId() + " is valid");15 }16}
compile
Using AI Code Generation
1XmlUtils.compile("4.xml","4.xsd");2XmlUtils.validate("5.xml","5.xsd");3XmlUtils.validate("6.xml","6.xsd");4XmlUtils.validate("7.xml","7.xsd");5XmlUtils.validate("8.xml","8.xsd");6XmlUtils.validate("9.xml","9.xsd");7XmlUtils.validate("10.xml","10.xsd");8XmlUtils.validate("11.xml","11.xsd");9XmlUtils.validate("12.xml","12.xsd");10XmlUtils.validate("13.xml","13.xsd");11XmlUtils.validate("14.xml","14.xsd");12XmlUtils.validate("15.xml","15.xsd");13XmlUtils.validate("16.xml","16.xsd");14XmlUtils.validate("17.xml","17.xsd");15XmlUtils.validate("18.xml","18
compile
Using AI Code Generation
1package demo;2import java.io.File;3import java.io.IOException;4import java.util.Map;5import com.intuit.karate.XmlUtils;6public class demo {7 public static void main(String[] args) throws IOException {8 File file = new File("C:\\Users\\user\\Desktop\\demo\\4.xml");9 Map<String, Object> map = XmlUtils.toXmlDoc(file);10 System.out.println(map);11 }12}13{root={child1=[{child2={child3={child4=[{child5={child6=[{child7={child8=[{child9={child10=[{child11={child12=[{child13={child14=[{child15={child16=[{child17={child18=[{child19={child20=[{child21={child22=[{child23={child24=[{child25={child26=[{child27={child28=[{child29={child30=[{child31={child32=[{child33={child34=[{child35={child36=[{child37={child38=[{child39={child40=[{child41={child42=[{child43={child44=[{child45={child46=[{child47={child48=[{child49={child50=[{child51={child52=[{child53={child54=[{child55={child56=[{child57={child58=[{child59={child60=[{child61={child62=[{child63={child64=[{child65={child66=[{child67={child68=[{child69={child70=[{child71={child72=[{child73={child74=[{child75={child76=[{child77={child78=[{child79={child80=[{child81={child82=[{child83={child84=[{child85={child86=[{child87={child88=[{child89={child90=[{child91={child92=[{child93={child94=[{child95={child96=[{child97={child98=[{child99={child100=[{child101={child102=[{child103={child104=[{child105={child106=[{child107={child108=[{child109={child110=[{child111={child112=[{child113={child114=[{child115={child116
compile
Using AI Code Generation
1package com.intuit.karate;2import java.io.File;3import java.io.IOException;4import java.util.Map;5import org.w3c.dom.Document;6public class XmlUtils {7 public static Document compile(String xmlString, Map<String, String> namespaces) throws IOException {8 File file = File.createTempFile("karate", ".xml");9 FileUtils.writeToFile(file, xmlString);10 return compile(file, namespaces);11 }12}13package com.intuit.karate;14import java.io.File;15import java.io.IOException;16import java.util.Map;17import org.w3c.dom.Document;18public class XmlUtils {19 public static Document compile(File file, Map<String, String> namespaces) throws IOException {20 Document doc = XmlUtils.toDocument(file);21 if (namespaces != null) {22 doc = XmlUtils.applyNamespaces(doc, namespaces);23 }24 return doc;25 }26}27package com.intuit.karate;28import java.io.File;29import java.io.IOException;30import java.util.Map;31import org.w3c.dom.Document;32public class XmlUtils {33 public static Document compile(File file, Map<String, String> namespaces) throws IOException {34 Document doc = XmlUtils.toDocument(file);35 if (namespaces != null) {36 doc = XmlUtils.applyNamespaces(doc, namespaces);37 }38 return doc;39 }40}41package com.intuit.karate;42import java.io.File;43import java.io.IOException;44import java.util.Map;45import org.w3c.dom.Document;46public class XmlUtils {47 public static Document compile(File file, Map<String, String> namespaces) throws IOException {48 Document doc = XmlUtils.toDocument(file);49 if (namespaces != null) {50 doc = XmlUtils.applyNamespaces(doc, namespaces);51 }52 return doc;53 }54}55package com.intuit.karate;56import java.io.File;57import java.io.IOException;58import java.util.Map;59import org.w3c.dom.Document;
compile
Using AI Code Generation
1import com.intuit.karate.XmlUtils;2import java.util.Map;3import java.io.File;4import java.io.StringWriter;5import java.io.PrintWriter;6import java.io.StringReader;7import org.apache.commons.io.FileUtils;8import org.apache.commons.io.IOUtils;9import org.w3c.dom.Document;10import org.xml.sax.InputSource;11public class 4 {12 public static void main(String[] args) throws Exception {13 File file = new File("C:/Users/lenovo/Desktop/4.xml");14 String xml = FileUtils.readFileToString(file, "UTF-8");15 Document doc = XmlUtils.compile(new InputSource(new StringReader(xml)));16 org.w3c.dom.Element root = doc.getDocumentElement();17 org.w3c.dom.Element child = (org.w3c.dom.Element) root.getElementsByTagName("child").item(0);18 String text = child.getTextContent();19 System.out.println(text);20 }21}22import com.intuit.karate.JsonUtils;23import java.util.Map;24import java.io.File;25import java.io.StringWriter;26import java.io.PrintWriter;27import java.io.StringReader;28import org.apache.commons.io.FileUtils;29import org.apache.commons.io.IOUtils;30import org.w3c.dom.Document;31import org.xml.sax.InputSource;32import org.json.JSONObject;33import org.json.XML;34public class 5 {35 public static void main(String[] args) throws Exception {36 File file = new File("C:/Users/lenovo/Desktop/5.xml");37 String xml = FileUtils.readFileToString(file, "UTF-8");38 JSONObject json = XML.toJSONObject(xml);39 String xml2 = XML.toString(json);40 System.out.println(xml2);41 }42}43import com.intuit.karate.Json
compile
Using AI Code Generation
1package com.intuit.karate;2import java.io.File;3public class XmlUtilsTest {4 public static void main(String[] args) throws Exception {5 XmlUtils.compile(new File("xmlfile.xml"), new File("xmlfile.class"));6 }7}8package com.intuit.karate;9import java.io.File;10import java.util.List;11import java.util.Map;12public class XmlUtilsTest {13 public static void main(String[] args) throws Exception {14 File file = new File("xmlfile.class");15 Map<String, Object> map = XmlUtils.toMap(file);16 System.out.println("map = " + map);17 List<Map<String, Object>> list = XmlUtils.toList(file);18 System.out.println("list = " + list);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!!