Best Citrus code snippet using com.consol.citrus.validation.xml.DomXmlMessageValidator.validateXmlHeaderFragment
Source:DomXmlMessageValidator.java
...88 Assert.isTrue(controlMessage.getHeaderData().size() <= receivedMessage.getHeaderData().size(),89 "Failed to validate header data XML fragments - found " +90 receivedMessage.getHeaderData().size() + " header fragments, expected " + controlMessage.getHeaderData().size());91 for (int i = 0; i < controlMessage.getHeaderData().size(); i++) {92 validateXmlHeaderFragment(receivedMessage.getHeaderData().get(i),93 controlMessage.getHeaderData().get(i), validationContext, context);94 }95 }96 log.info("XML message validation successful: All values OK");97 } catch (ClassCastException | DOMException | LSException e) {98 throw new CitrusRuntimeException(e);99 } catch (IllegalArgumentException e) {100 log.error("Failed to validate:\n" + XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));101 throw new ValidationException("Validation failed:", e);102 } catch (ValidationException ex) {103 log.error("Failed to validate:\n" + XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));104 throw ex;105 }106 }107 /**108 * Validate message with a DTD.109 *110 * @param dtdResource111 * @param receivedMessage112 */113 protected void validateDTD(Resource dtdResource, Message receivedMessage) {114 //TODO implement this115 }116 /**117 * Validate message with a XML schema.118 *119 * @param receivedMessage120 * @param validationContext121 */122 protected void validateXMLSchema(Message receivedMessage, XmlMessageValidationContext validationContext) {123 if (receivedMessage.getPayload() == null || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {124 return;125 }126 try {127 Document doc = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));128 if (!StringUtils.hasText(doc.getFirstChild().getNamespaceURI())) {129 return;130 }131 log.debug("Starting XML schema validation ...");132 XmlValidator validator = null;133 XsdSchemaRepository schemaRepository = null;134 if (validationContext.getSchema() != null) {135 validator = applicationContext.getBean(validationContext.getSchema(), XsdSchema.class).createValidator();136 } else if (validationContext.getSchemaRepository() != null) {137 schemaRepository = applicationContext.getBean(validationContext.getSchemaRepository(), XsdSchemaRepository.class);138 } else if (schemaRepositories.size() == 1) {139 schemaRepository = schemaRepositories.get(0);140 } else if (schemaRepositories.size() > 0) {141 for (XsdSchemaRepository repository : schemaRepositories) {142 if (repository.canValidate(doc)) {143 schemaRepository = repository;144 }145 }146 147 if (schemaRepository == null) {148 throw new CitrusRuntimeException(String.format("Failed to find proper schema repository in Spring bean context for validating element '%s(%s)'",149 doc.getFirstChild().getLocalName(), doc.getFirstChild().getNamespaceURI()));150 }151 } else {152 log.warn("Neither schema instance nor schema repository defined - skipping XML schema validation");153 return;154 }155 156 if (schemaRepository != null) {157 if (!schemaRepository.canValidate(doc)) {158 throw new CitrusRuntimeException(String.format("Unable to find proper XML schema definition for element '%s(%s)' in schema repository '%s'",159 doc.getFirstChild().getLocalName(),160 doc.getFirstChild().getNamespaceURI(),161 schemaRepository.getName()));162 }163 List<Resource> schemas = new ArrayList<>();164 for (XsdSchema xsdSchema : schemaRepository.getSchemas()) {165 if (xsdSchema instanceof XsdSchemaCollection) {166 for (Resource resource : ((XsdSchemaCollection) xsdSchema).getSchemaResources()) {167 schemas.add(resource);168 } 169 } else if (xsdSchema instanceof WsdlXsdSchema) {170 for (Resource resource : ((WsdlXsdSchema) xsdSchema).getSchemaResources()) {171 schemas.add(resource);172 }173 } else {174 synchronized (transformerFactory) {175 ByteArrayOutputStream bos = new ByteArrayOutputStream();176 try {177 transformerFactory.newTransformer().transform(xsdSchema.getSource(), new StreamResult(bos));178 } catch (TransformerException e) {179 throw new CitrusRuntimeException("Failed to read schema " + xsdSchema.getTargetNamespace(), e);180 }181 schemas.add(new ByteArrayResource(bos.toByteArray()));182 }183 }184 }185 186 validator = XmlValidatorFactory.createValidator(schemas.toArray(new Resource[schemas.size()]), WsdlXsdSchema.W3C_XML_SCHEMA_NS_URI);187 }188 189 SAXParseException[] results = validator.validate(new DOMSource(doc));190 if (results.length == 0) {191 log.info("XML schema validation successful: All values OK");192 } else {193 log.error("XML schema validation failed for message:\n" +194 XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));195 196 // Report all parsing errors197 log.debug("Found " + results.length + " schema validation errors");198 StringBuilder errors = new StringBuilder();199 for (SAXParseException e : results) {200 errors.append(e.toString());201 errors.append("\n");202 }203 log.debug(errors.toString());204 throw new ValidationException("XML schema validation failed:", results[0]);205 }206 } catch (IOException e) {207 throw new CitrusRuntimeException(e);208 }209 }210 /**211 * Validate namespaces in message. The method compares namespace declarations in the root212 * element of the received message to expected namespaces. Prefixes are important too, so213 * differing namespace prefixes will fail the validation.214 *215 * @param expectedNamespaces216 * @param receivedMessage217 */218 protected void validateNamespaces(Map<String, String> expectedNamespaces, Message receivedMessage) {219 if (CollectionUtils.isEmpty(expectedNamespaces)) { return; }220 if (receivedMessage.getPayload() == null || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {221 throw new ValidationException("Unable to validate message namespaces - receive message payload was empty");222 }223 log.debug("Start XML namespace validation");224 Document received = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));225 Map<String, String> foundNamespaces = XMLUtils.lookupNamespaces(receivedMessage.getPayload(String.class));226 if (foundNamespaces.size() != expectedNamespaces.size()) {227 throw new ValidationException("Number of namespace declarations not equal for node " +228 XMLUtils.getNodesPathName(received.getFirstChild()) + " found " +229 foundNamespaces.size() + " expected " + expectedNamespaces.size());230 }231 for (Entry<String, String> entry : expectedNamespaces.entrySet()) {232 String namespace = entry.getKey();233 String url = entry.getValue();234 if (foundNamespaces.containsKey(namespace)) {235 if (!foundNamespaces.get(namespace).equals(url)) {236 throw new ValidationException("Namespace '" + namespace +237 "' values not equal: found '" + foundNamespaces.get(namespace) +238 "' expected '" + url + "' in reference node " +239 XMLUtils.getNodesPathName(received.getFirstChild()));240 } else {241 if (log.isDebugEnabled()) {242 log.debug("Validating namespace " + namespace + " value as expected " + url + " - value OK");243 }244 }245 } else {246 throw new ValidationException("Missing namespace " + namespace + "(" + url + ") in node " +247 XMLUtils.getNodesPathName(received.getFirstChild()));248 }249 }250 log.info("XML namespace validation successful: All values OK");251 }252 private void doElementNameValidation(Node received, Node source) {253 //validate element name254 if (log.isDebugEnabled()) {255 log.debug("Validating element: " + received.getLocalName() + " (" + received.getNamespaceURI() + ")");256 }257 Assert.isTrue(received.getLocalName().equals(source.getLocalName()),258 ValidationUtils.buildValueMismatchErrorMessage("Element names not equal", source.getLocalName(), received.getLocalName()));259 }260 private void doElementNamespaceValidation(Node received, Node source) {261 //validate element namespace262 if (log.isDebugEnabled()) {263 log.debug("Validating namespace for element: " + received.getLocalName());264 }265 if (received.getNamespaceURI() != null) {266 Assert.isTrue(source.getNamespaceURI() != null,267 ValidationUtils.buildValueMismatchErrorMessage("Element namespace not equal for element '" +268 received.getLocalName() + "'", null, received.getNamespaceURI()));269 Assert.isTrue(received.getNamespaceURI().equals(source.getNamespaceURI()),270 ValidationUtils.buildValueMismatchErrorMessage("Element namespace not equal for element '" +271 received.getLocalName() + "'", source.getNamespaceURI(), received.getNamespaceURI()));272 } else {273 Assert.isTrue(source.getNamespaceURI() == null,274 ValidationUtils.buildValueMismatchErrorMessage("Element namespace not equal for element '" +275 received.getLocalName() + "'", source.getNamespaceURI(), null));276 }277 }278 /**279 * Validate message payloads by comparing to a control message.280 *281 * @param receivedMessage282 * @param validationContext283 * @param context284 */285 protected void validateMessageContent(Message receivedMessage, Message controlMessage, XmlMessageValidationContext validationContext,286 TestContext context) {287 if (controlMessage == null || controlMessage.getPayload() == null) {288 log.debug("Skip message payload validation as no control message was defined");289 return;290 }291 if (!(controlMessage.getPayload() instanceof String)) {292 throw new IllegalArgumentException(293 "DomXmlMessageValidator does only support message payload of type String, " +294 "but was " + controlMessage.getPayload().getClass());295 }296 String controlMessagePayload = controlMessage.getPayload(String.class);297 if (receivedMessage.getPayload() == null || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {298 Assert.isTrue(!StringUtils.hasText(controlMessagePayload),299 "Unable to validate message payload - received message payload was empty, control message payload is not");300 return;301 } else if (!StringUtils.hasText(controlMessagePayload)) {302 return;303 }304 log.debug("Start XML tree validation ...");305 Document received = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));306 Document source = XMLUtils.parseMessagePayload(controlMessagePayload);307 XMLUtils.stripWhitespaceNodes(received);308 XMLUtils.stripWhitespaceNodes(source);309 if (log.isDebugEnabled()) {310 log.debug("Received message:\n" + XMLUtils.serialize(received));311 log.debug("Control message:\n" + XMLUtils.serialize(source));312 }313 validateXmlTree(received, source, validationContext, namespaceContextBuilder.buildContext(314 receivedMessage, validationContext.getNamespaces()), context);315 }316 317 /**318 * Validates XML header fragment data.319 * @param receivedHeaderData320 * @param controlHeaderData321 * @param validationContext322 * @param context323 */324 private void validateXmlHeaderFragment(String receivedHeaderData, String controlHeaderData,325 XmlMessageValidationContext validationContext, TestContext context) {326 log.debug("Start XML header data validation ...");327 Document received = XMLUtils.parseMessagePayload(receivedHeaderData);328 Document source = XMLUtils.parseMessagePayload(controlHeaderData);329 XMLUtils.stripWhitespaceNodes(received);330 XMLUtils.stripWhitespaceNodes(source);331 if (log.isDebugEnabled()) {332 log.debug("Received header data:\n" + XMLUtils.serialize(received));333 log.debug("Control header data:\n" + XMLUtils.serialize(source));334 }335 validateXmlTree(received, source, validationContext, 336 namespaceContextBuilder.buildContext(new DefaultMessage(receivedHeaderData), validationContext.getNamespaces()),337 context);338 }...
validateXmlHeaderFragment
Using AI Code Generation
1public class ValidateXmlHeaderFragmentJavaIT extends TestNGCitrusTestRunner {2 @CitrusXmlTest(name = "ValidateXmlHeaderFragmentJavaIT")3 public void validateXmlHeaderFragmentJavaIT() {}4}5public void validateXmlHeaderFragmentJavaIT() {6 variable("xmlHeader", "${xmlUnit.xmlHeader}");7 variable("xmlHeaderFrag
validateXmlHeaderFragment
Using AI Code Generation
1[XmlMessageValidator]: # (validateXmlHeaderFragment="true")2[XmlMessageValidator]: # (validateXmlHeaderFragment="true")3[XmlMessageValidator]: # (validateXmlHeaderFragment="true")4[XmlMessageValidator]: # (validateXmlHeaderFragment="true")5[XmlMessageValidator]: # (validateXmlHeaderFragment="true")6[XmlMessageValidator]: # (validateXmlHeaderFragment="true")7[XmlMessageValidator]: # (validateXmlHeaderFragment="true")8[XmlMessageValidator]: # (validateXmlHeaderFragment="true")9[XmlMessageValidator]: # (validateXmlHeaderFragment="true")10[XmlMessageValidator]: # (validateXmlHeaderFragment="true")11[XmlMessageValidator]: # (validateXmlHeaderFragment="true")12[XmlMessageValidator]: # (validateXmlHeaderFragment="true")13[XmlMessageValidator]: # (validateXmlHeaderFragment="true")
validateXmlHeaderFragment
Using AI Code Generation
1validateXmlHeaderFragment("xmlHeaderFragment")2validateXmlHeaderFragment("xmlHeaderFragment")3validateXmlHeaderFragment("xmlHeaderFragment")4validateXmlHeaderFragment("xmlHeaderFragment")5validateXmlHeaderFragment("xmlHeaderFragment")6validateXmlHeaderFragment("xmlHeaderFragment")7validateXmlHeaderFragment("xmlHeaderFragment")8validateXmlHeaderFragment("xmlHeaderFragment")9validateXmlHeaderFragment("xmlHeaderFragment")10validateXmlHeaderFragment("xmlHeaderFragment")11validateXmlHeaderFragment("xmlHeaderFragment")12validateXmlHeaderFragment("xmlHeaderFragment")13validateXmlHeaderFragment("xmlHeaderFragment")
validateXmlHeaderFragment
Using AI Code Generation
1public void testValidateXmlHeaderFragment() {2 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";3 String xmlHeaderFragment = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";4 DomXmlMessageValidator validator = new DomXmlMessageValidator();5 validator.validateXmlHeaderFragment(xml, xmlHeaderFragment);6}7public void testValidateXmlHeaderFragment() {8 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";9 String xmlHeaderFragment = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";10 DomXmlMessageValidator validator = new DomXmlMessageValidator();11 validator.validateXmlHeaderFragment(xml, xmlHeaderFragment);12}13public void testValidateXmlHeaderFragment() {14 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";15 String xmlHeaderFragment = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";16 DomXmlMessageValidator validator = new DomXmlMessageValidator();17 validator.validateXmlHeaderFragment(xml, xmlHeaderFragment);18}19public void testValidateXmlHeaderFragment() {20 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";21 String xmlHeaderFragment = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";22 DomXmlMessageValidator validator = new DomXmlMessageValidator();23 validator.validateXmlHeaderFragment(xml,
validateXmlHeaderFragment
Using AI Code Generation
1public void test() {2 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";3 String validationErrorMessage = "Validation error: XML header fragment does not match expected result";4 validateXmlHeaderFragment(xml, validationErrorMessage);5}6public void validateXmlHeaderFragment(String xml, String validationErrorMessage) {7 DomXmlMessageValidator validator = new DomXmlMessageValidator();8 validator.validateXmlHeaderFragment(xml, validationErrorMessage);9}10at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateXmlHeaderFragment(DomXmlMessageValidator.java:95)11at com.consol.citrus.validation.xml.DomXmlMessageValidatorTest.validateXmlHeaderFragment(DomXmlMessageValidatorTest.java:18)12at com.consol.citrus.validation.xml.DomXmlMessageValidatorTest.test(DomXmlMessageValidatorTest.java:13)13at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)14at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)15at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)16at java.lang.reflect.Method.invoke(Method.java:498)17at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)18at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)19at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)20at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)21at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)22at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)23at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)24at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)25at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)26at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)27at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58
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!!