Handle element node.

@param received
@param source
@param validationContext
16344
private void doElement(Node received, Node source,
            XmlMessageValidationContext validationContext, NamespaceContext namespaceContext, TestContext context) {

        doElementNameValidation(received, source);

        doElementNamespaceValidation(received, source);

        //check if element is ignored either by xpath or by ignore placeholder in source message
        if (XmlValidationUtils.isElementIgnored(source, received, validationContext.getIgnoreExpressions(), namespaceContext)) {
            return;
        }

        //work on attributes
        if (log.isDebugEnabled()) {
            log.debug("Validating attributes for element: " + received.getLocalName());
        }
        NamedNodeMap receivedAttr = received.getAttributes();
        NamedNodeMap sourceAttr = source.getAttributes();

        Assert.isTrue(countAttributes(receivedAttr) == countAttributes(sourceAttr),
                ValidationUtils.buildValueMismatchErrorMessage("Number of attributes not equal for element '"
                        + received.getLocalName() + "'", countAttributes(sourceAttr), countAttributes(receivedAttr)));

        for (int i = 0; i < receivedAttr.getLength(); i++) {
            doAttribute(received, receivedAttr.item(i), source, validationContext, namespaceContext, context);
        }

        //check if validation matcher on element is specified
        if (isValidationMatcherExpression(source)) {
            ValidationMatcherUtils.resolveValidationMatcher(source.getNodeName(),
                    received.getFirstChild().getNodeValue().trim(),
                    source.getFirstChild().getNodeValue().trim(),
                    context);
            return;
        }

        doText((Element) received, (Element) source);

        //work on child nodes
        List<Element> receivedChildElements = DomUtils.getChildElements((Element) received);
        List<Element> sourceChildElements = DomUtils.getChildElements((Element) source);

        Assert.isTrue(receivedChildElements.size() == sourceChildElements.size(),
                ValidationUtils.buildValueMismatchErrorMessage("Number of child elements not equal for element '"
                    + received.getLocalName() + "'", sourceChildElements.size(), receivedChildElements.size()));

        for (int i = 0; i < receivedChildElements.size(); i++) {
            this.validateXmlTree(receivedChildElements.get(i), sourceChildElements.get(i),
                    validationContext, namespaceContext, context);
        }

        if (log.isDebugEnabled()) {
            log.debug("Validation successful for element: " + received.getLocalName() +
                    " (" + received.getNamespaceURI() + ")");
        }
    }
255790
private void processSource(Context cx, String filename)
    {
        if (filename == null) {
            BufferedReader in = new BufferedReader
                (new InputStreamReader(System.in));
            String sourceName = "<stdin>";
            int lineno = 1;
            boolean hitEOF = false;
            do {
                int startline = lineno;
                System.err.print("js> ");
                System.err.flush();
                try {
                    String source = "";
                    // Collect lines of source to compile.
                    while(true) {
                        String newline;
                        newline = in.readLine();
                        if (newline == null) {
                            hitEOF = true;
                            break;
                        }
                        source = source + newline + "\n";
                        lineno++;
                        // Continue collecting as long as more lines
                        // are needed to complete the current
                        // statement.  stringIsCompilableUnit is also
                        // true if the source statement will result in
                        // any error other than one that might be
                        // resolved by appending more source.
                        if (cx.stringIsCompilableUnit(source))
                            break;
                    }
                    Object result = cx.evaluateString(this, source,
                                                      sourceName, startline,
                                                      null);
                    if (result != Context.getUndefinedValue()) {
                        System.err.println(Context.toString(result));
                    }
                }
                catch (WrappedException we) {
                    // Some form of exception was caught by JavaScript and
                    // propagated up.
                    System.err.println(we.getWrappedException().toString());
                    we.printStackTrace();
                }
                catch (EvaluatorException ee) {
                    // Some form of JavaScript error.
                    System.err.println("js: " + ee.getMessage());
                }
                catch (JavaScriptException jse) {
                    // Some form of JavaScript error.
                    System.err.println("js: " + jse.getMessage());
                }
                catch (IOException ioe) {
                    System.err.println(ioe.toString());
                }
                if (quitting) {
                    // The user executed the quit() function.
                    break;
                }
            } while (!hitEOF);
            System.err.println();
        } else {
            FileReader in = null;
            try {
                in = new FileReader(filename);
            }
            catch (FileNotFoundException ex) {
                Context.reportError("Couldn't open file \"" + filename + "\".");
                return;
            }

            try {
                // Here we evalute the entire contents of the file as
                // a script. Text is printed only if the print() function
                // is called.
                cx.evaluateReader(this, in, filename, 1, null);
            }
            catch (WrappedException we) {
                System.err.println(we.getWrappedException().toString());
                we.printStackTrace();
            }
            catch (EvaluatorException ee) {
                System.err.println("js: " + ee.getMessage());
            }
            catch (JavaScriptException jse) {
                System.err.println("js: " + jse.getMessage());
            }
            catch (IOException ioe) {
                System.err.println(ioe.toString());
            }
            finally {
                try {
                    in.close();
                }
                catch (IOException ioe) {
                    System.err.println(ioe.toString());
                }
            }
        }
    }
1331693
public void validate(JavaScriptObject newValues, final I_CmsJavaScriptObjectCallback onSuccess) {

        AsyncCallback<Map<String, String>> rpcCallback = new AsyncCallback<Map<String, String>>() {

            @SuppressWarnings("synthetic-access")
            public void onFailure(Throwable caught) {

                m_apiRoot.handleError(caught, null);
            }

            public void onSuccess(Map<String, String> result) {

                if (result == null) {
                    result = Maps.newHashMap();
                }
                onSuccess.call(CmsJsUtils.convertMapToJsObject(result));
            }
        };
        m_apiRoot.getRpcHelper().executeRpc(
            CmsXmlContentUgcApi.SERVICE.validateContent(
                m_content.getSessionId(),
                CmsJsUtils.convertJsObjectToMap(newValues),
                rpcCallback));

    }
724428
function processNode(node) {
            const entity = node.code.trim()
            if (!entity) {
                context.report({
                    node,
                    messageId: "missing",
                })
            }
        }
464574
private void passViolations(ConstraintValidatorContext context,
                                Set<ConstraintViolation<Object>> source) {
        for (final ConstraintViolation<Object> violation : source) {
            final Iterator<Node> nodeIter = violation.getPropertyPath()
                    .iterator();
            final ConstraintViolationBuilder builder = context
                    .buildConstraintViolationWithTemplate(violation
                            .getMessageTemplate());
            ConstraintValidatorContext nodeContext;

            if (nodeIter.hasNext()) {
                StringBuilder sb = new StringBuilder(nodeIter.next().getName());

                if (supportsConstraintComposition) {
                    while (nodeIter.hasNext()) {
                        sb.append('.').append(nodeIter.next());
                    }
                }

                builder.addNode(sb.toString()).addConstraintViolation();
            } else {
                builder.addConstraintViolation();
            }
        }
    }
1281466
public static boolean isElementIgnored(Node source, Node received, Set<String> ignoreExpressions, NamespaceContext namespaceContext) {
        if (isElementIgnored(received, ignoreExpressions, namespaceContext)) {
            if (log.isDebugEnabled()) {
                log.debug("Element: '" + received.getLocalName() + "' is on ignore list - skipped validation");
            }
            return true;
        } else if (source.getFirstChild() != null &&
                StringUtils.hasText(source.getFirstChild().getNodeValue()) &&
                source.getFirstChild().getNodeValue().trim().equals(Citrus.IGNORE_PLACEHOLDER)) {
            if (log.isDebugEnabled()) {
                log.debug("Element: '" + received.getLocalName() + "' is ignored by placeholder '" +
                        Citrus.IGNORE_PLACEHOLDER + "'");
            }
            return true;
        }
        return false;
    }
1182319
private void addSchemaInformationToValidationContext(Element messageElement, SchemaValidationContext context) {
        String schemaValidation = messageElement.getAttribute("schema-validation");
        if (StringUtils.hasText(schemaValidation)) {
            context.setSchemaValidation(Boolean.valueOf(schemaValidation));
        }

        String schema = messageElement.getAttribute("schema");
        if (StringUtils.hasText(schema)) {
            context.setSchema(schema);
        }

        String schemaRepository = messageElement.getAttribute("schema-repository");
        if (StringUtils.hasText(schemaRepository)) {
            context.setSchemaRepository(schemaRepository);
        }
    }
613932
public void process(ContentHandler handler) {
    try {
      if (logger.isInfoEnabled())
        logger.info("Processing input source with SAX content handler");

      XMLReader reader = makeReader(false);

      reader.setContentHandler(handler);

      reader.parse(content);
    } catch (SAXException e) {
      logger.error("Failed to process input source with SAX content handler",e);
      throw new MarkLogicInternalException(e);
    } catch (IOException e) {
      logger.error("Failed to process input source with SAX content handler",e);
      throw new MarkLogicInternalException(e);
    }
  }
746985
public void validate(StreamSource objectSource) throws ServerException {
        DOValidatorSchematronResult result = null;
        try {
            // Create a transformer that uses the validating stylesheet.
            // Run the Schematron validation of the Fedora object and
            // output results in DOM format.
            Transformer vtransformer =
                    validatingStyleSheet.newTransformer();
            DOMResult validationResult = new DOMResult();
            vtransformer.transform(objectSource, validationResult);
            result = new DOValidatorSchematronResult(validationResult);
        } catch (Exception e) {
        	Validation validation = new Validation("unknown");
        	String problem = "Schematron validation failed:".concat(e.getMessage());
        	validation.setObjectProblems(Collections.singletonList(problem));
            logger.error("Schematron validation failed", e);
            throw new ObjectValidityException(e.getMessage(), validation);
        }

        if (!result.isValid()) {
            String msg = null;
            try {
                msg = result.getXMLResult();
            } catch (Exception e) {
                logger.warn("Error getting XML result of schematron validation failure", e);
            }
        	Validation validation = new Validation("unknown");
        	if (msg == null) {
        		msg = "Unknown schematron error.  Error getting XML results of schematron validation";
        	}
        	validation.setObjectProblems(Collections.singletonList(msg));
            throw new ObjectValidityException(msg, validation);
        }
    }
1370342
protected void validateAttachmentContentData(String receivedContent, String controlContent, String controlContentId) {
        if (ignoreAllWhitespaces) {
            controlContent = StringUtils.trimAllWhitespace(controlContent);
            receivedContent = StringUtils.trimAllWhitespace(receivedContent);
        }

        Assert.isTrue(receivedContent.equals(controlContent),
                "Values not equal for attachment content '"
                        + controlContentId + "', expected '"
                        + controlContent.trim() + "' but was '"
                        + receivedContent.trim() + "'");
    }
470374
protected void validate( QueryContext context,
                             QueryCommand query,
                             Map<SelectorName, Table> usedSelectors ) {
        // // Resolve everything ...
        // Visitors.visitAll(query, new Validator(context, usedSelectors));
        // Resolve everything (except subqueries) ...
        Validator validator = new Validator(context, usedSelectors);
        query.accept(new WalkAllVisitor(validator) {
            @Override
            protected void enqueue( Visitable objectToBeVisited ) {
                if (objectToBeVisited instanceof Subquery) return;
                super.enqueue(objectToBeVisited);
            }
        });
    }
610257
private static void validateMessageText(String messageML) throws InvalidInputException {
    if (messageML == null) { throw new InvalidInputException("Message input is NULL"); }

    for (char ch : messageML.toCharArray()) {
      if (ch != '\n' && ch != '\r' && ch != '\t' && (ch < ' ')) {
        throw new InvalidInputException("Invalid control characters in message");
      }
    }
  }
1111479
protected void validateMessage(Message receivedMessage, TestContext context) throws IOException {
        // extract variables from received message content
        for (VariableExtractor variableExtractor : variableExtractors) {
            variableExtractor.extractVariables(receivedMessage, context);
        }

        if (validationCallback != null) {
            if (StringUtils.hasText(receivedMessage.getName())) {
                context.getMessageStore().storeMessage(receivedMessage.getName(), receivedMessage);
            } else {
                context.getMessageStore().storeMessage(context.getMessageStore().constructMessageName(this, getOrCreateEndpoint(context)), receivedMessage);
            }

            validationCallback.validate(receivedMessage, context);
        } else {
            Message controlMessage = createControlMessage(context, messageType);
            if (StringUtils.hasText(controlMessage.getName())) {
                context.getMessageStore().storeMessage(controlMessage.getName(), receivedMessage);
            } else {
                context.getMessageStore().storeMessage(context.getMessageStore().constructMessageName(this, getOrCreateEndpoint(context)), receivedMessage);
            }

            if (!CollectionUtils.isEmpty(validators)) {
                for (MessageValidator<? extends ValidationContext> messageValidator : validators) {
                    messageValidator.validateMessage(receivedMessage, controlMessage, context, validationContexts);
                }

                if (validators.parallelStream()
                                .map(Object::getClass)
                                .noneMatch(DefaultMessageHeaderValidator.class::isAssignableFrom)) {
                    MessageValidator defaultMessageHeaderValidator = context.getMessageValidatorRegistry().getDefaultMessageHeaderValidator();
                    if (defaultMessageHeaderValidator != null) {
                        defaultMessageHeaderValidator.validateMessage(receivedMessage, controlMessage, context, validationContexts);
                    }
                }
            } else {
                List<MessageValidator<? extends ValidationContext>> validators =
                        context.getMessageValidatorRegistry().findMessageValidators(messageType, receivedMessage);

                if (validators.isEmpty()) {
                    if (controlMessage.getPayload() instanceof String &&
                            StringUtils.hasText(controlMessage.getPayload(String.class))) {
                        throw new CitrusRuntimeException(String.format("Unable to find proper message validator for message type '%s' and validation contexts '%s'", messageType, validationContexts));
                    } else if (validationContexts.stream().anyMatch(item -> JsonPathMessageValidationContext.class.isAssignableFrom(item.getClass())
                            || XpathMessageValidationContext.class.isAssignableFrom(item.getClass())
                            || ScriptValidationContext.class.isAssignableFrom(item.getClass()))) {
                        throw new CitrusRuntimeException(String.format("Unable to find proper message validator for message type '%s' and validation contexts '%s'", messageType, validationContexts));
                    } else {
                        log.warn(String.format("Unable to find proper message validator for message type '%s' and validation contexts '%s'", messageType, validationContexts));
                    }
                }

                for (MessageValidator<? extends ValidationContext> messageValidator : validators) {
                    messageValidator.validateMessage(receivedMessage, controlMessage, context, validationContexts);
                }
            }
        }
    }
31855
private JsonPathMessageValidationContext getJsonPathMessageValidationContext(Element messageElement) {
        JsonPathMessageValidationContext context = new JsonPathMessageValidationContext();

        //check for validate elements, these elements can either have script, jsonPath or namespace validation information
        //for now we only handle jsonPath validation
        Map<String, Object> validateJsonPathExpressions = new HashMap<>();
        List<?> validateElements = DomUtils.getChildElementsByTagName(messageElement, "validate");
        if (validateElements.size() > 0) {
            for (Iterator<?> iter = validateElements.iterator(); iter.hasNext();) {
                Element validateElement = (Element) iter.next();
                extractJsonPathValidateExpressions(validateElement, validateJsonPathExpressions);
            }

            context.setJsonPathExpressions(validateJsonPathExpressions);
        }

        return context;
    }
725507
protected void validateXMLSchema(Message receivedMessage, XmlMessageValidationContext validationContext) {
        if (receivedMessage.getPayload() == null || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {
            return;
        }

        try {
            Document doc = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));

            if (!StringUtils.hasText(doc.getFirstChild().getNamespaceURI())) {
                return;
            }

            log.debug("Starting XML schema validation ...");

            XmlValidator validator = null;
            XsdSchemaRepository schemaRepository = null;
            if (validationContext.getSchema() != null) {
                validator = applicationContext.getBean(validationContext.getSchema(), XsdSchema.class).createValidator();
            } else if (validationContext.getSchemaRepository() != null) {
                schemaRepository = applicationContext.getBean(validationContext.getSchemaRepository(), XsdSchemaRepository.class);
            } else if (schemaRepositories.size() == 1) {
                schemaRepository = schemaRepositories.get(0);
            } else if (schemaRepositories.size() > 0) {
                for (XsdSchemaRepository repository : schemaRepositories) {
                    if (repository.canValidate(doc)) {
                        schemaRepository = repository;
                    }
                }
                
                if (schemaRepository == null) {
                    throw new CitrusRuntimeException(String.format("Failed to find proper schema repository in Spring bean context for validating element '%s(%s)'",
                            doc.getFirstChild().getLocalName(), doc.getFirstChild().getNamespaceURI()));
                }
            } else {
                log.warn("Neither schema instance nor schema repository defined - skipping XML schema validation");
                return;
            }
            
            if (schemaRepository != null) {
                if (!schemaRepository.canValidate(doc)) {
                    throw new CitrusRuntimeException(String.format("Unable to find proper XML schema definition for element '%s(%s)' in schema repository '%s'",
                            doc.getFirstChild().getLocalName(),
                            doc.getFirstChild().getNamespaceURI(),
                            schemaRepository.getName()));
                }

                List<Resource> schemas = new ArrayList<>();
                for (XsdSchema xsdSchema : schemaRepository.getSchemas()) {
                    if (xsdSchema instanceof XsdSchemaCollection) {
                        for (Resource resource : ((XsdSchemaCollection) xsdSchema).getSchemaResources()) {
                            schemas.add(resource);
                        }                            
                    } else if (xsdSchema instanceof WsdlXsdSchema) {
                        for (Resource resource : ((WsdlXsdSchema) xsdSchema).getSchemaResources()) {
                            schemas.add(resource);
                        }
                    } else {
                        synchronized (transformerFactory) {
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            try {
                                transformerFactory.newTransformer().transform(xsdSchema.getSource(), new StreamResult(bos));
                            } catch (TransformerException e) {
                                throw new CitrusRuntimeException("Failed to read schema " + xsdSchema.getTargetNamespace(), e);
                            }
                            schemas.add(new ByteArrayResource(bos.toByteArray()));
                        }
                    }
                }
                
                validator = XmlValidatorFactory.createValidator(schemas.toArray(new Resource[schemas.size()]), WsdlXsdSchema.W3C_XML_SCHEMA_NS_URI);
            }
            
            SAXParseException[] results = validator.validate(new DOMSource(doc));
            if (results.length == 0) {
                log.info("XML schema validation successful: All values OK");
            } else {
                log.error("XML schema validation failed for message:\n" +
                        XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));
                
                // Report all parsing errors
                log.debug("Found " + results.length + " schema validation errors");
                StringBuilder errors = new StringBuilder();
                for (SAXParseException e : results) {
                    errors.append(e.toString());
                    errors.append("\n");
                }
                log.debug(errors.toString());

                throw new ValidationException("XML schema validation failed:", results[0]);
            }
        } catch (IOException e) {
            throw new CitrusRuntimeException(e);
        }
    }
1205465
public static void validateMessage(String basePath, Document wsdl, SOAPMessage msg) throws XSDFormatException, XSDValidationException{
        LOG.debug("Validating message on WSDL");

        //get schema
        //Element schemaNode = (Element)wsdl.getElementsByTagNameNS(XMLConstants"http://www.w3.org/2001/XMLSchema","schema").item(0);
        NodeList schemaNodes = wsdl.getElementsByTagNameNS(
                XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");

        int nrSchemas = schemaNodes.getLength();

        Source[] schemas = new Source[nrSchemas];

        for (int i = 0; i < nrSchemas; i++) {
            schemas[i] = new DOMSource(schemaNodes.item(i));
        }

        //get body
        Element body = null;
        try {
            body = msg.getSOAPBody();
        } catch (SOAPException e) {
            throw S1SystemError.wrap(e);
        }

        if(msg.getAttachments().hasNext()){
            //copy
            body = (Element)body.cloneNode(true);
            //remove xop:Includes
            NodeList nl = body.getElementsByTagNameNS("http://www.w3.org/2004/08/xop/include","Include");
            for(int i=0;i<nl.getLength();i++){
                Node n = nl.item(i);
                n.getParentNode().removeChild(n);
            }
        }

        //validate Body children
        for(Element el:XMLFormat.getChildElementList(body,null,null)){
            XMLFormat.validate(basePath, schemas, el);
        }
    }
19572
private void validateText(String receivedMessagePayload, String controlMessagePayload) {
        if (!StringUtils.hasText(controlMessagePayload)) {
            log.debug("Skip message payload validation as no control message was defined");
            return;
        } else {
            Assert.isTrue(StringUtils.hasText(receivedMessagePayload), "Validation failed - " +
                    "expected message contents, but received empty message!");
        }

        if (!receivedMessagePayload.equals(controlMessagePayload)) {
            if (StringUtils.trimAllWhitespace(receivedMessagePayload).equals(StringUtils.trimAllWhitespace(controlMessagePayload))) {
                throw new ValidationException("Text values not equal (only whitespaces!), expected '" + controlMessagePayload + "' " +
                        "but was '" + receivedMessagePayload + "'");
            } else {
                throw new ValidationException("Text values not equal, expected '" + controlMessagePayload + "' " +
                        "but was '" + receivedMessagePayload + "'");
            }
        }
    }