How to use constructErrorMessage method of com.consol.citrus.validation.json.JsonTextMessageValidator class

Best Citrus code snippet using com.consol.citrus.validation.json.JsonTextMessageValidator.constructErrorMessage

Source:JsonTextMessageValidator.java Github

copy

Full Screen

...130 validationContext,131 applicationContext);132 if (!report.isSuccess()) {133 log.error("Failed to validate Json schema for message:\n" + receivedMessage.getPayload(String.class));134 throw new ValidationException(constructErrorMessage(report));135 }136 log.info("Json schema validation successful: All values OK");137 }138 /**139 * Validates JSON text with comparison to expected control JSON object.140 * JSON entries can be ignored with ignore placeholder.141 * 142 * @param elementName the current element name that is under verification in this method143 * @param receivedJson the received JSON text object.144 * @param controlJson the expected control JSON text.145 * @param validationContext the JSON message validation context.146 * @param context the current test context.147 * @param readContext the JSONPath read context.148 */149 @SuppressWarnings("rawtypes")150 public void validateJson(String elementName, JSONObject receivedJson, JSONObject controlJson, JsonMessageValidationContext validationContext, TestContext context, ReadContext readContext) {151 if (strict) {152 Assert.isTrue(controlJson.size() == receivedJson.size(),153 ValidationUtils.buildValueMismatchErrorMessage("Number of JSON entries not equal for element: '" + elementName + "'", controlJson.size(), receivedJson.size()));154 }155 for (Map.Entry<String, Object> controlJsonEntry : controlJson.entrySet()) {156 String controlKey = controlJsonEntry.getKey();157 Assert.isTrue(receivedJson.containsKey(controlKey),158 "Missing JSON entry: + '" + controlKey + "'");159 Object controlValue = controlJsonEntry.getValue();160 Object receivedValue = receivedJson.get(controlKey);161 // check if entry is ignored by placeholder162 if (isIgnored(controlKey, controlValue, receivedValue, validationContext.getIgnoreExpressions(), readContext)) {163 continue;164 }165 if (controlValue == null) {166 Assert.isTrue(receivedValue == null,167 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + controlKey + "'",168 null, receivedValue));169 } else if (receivedValue != null) {170 if (ValidationMatcherUtils.isValidationMatcherExpression(controlValue.toString())) {171 ValidationMatcherUtils.resolveValidationMatcher(controlKey,172 receivedValue.toString(),173 controlValue.toString(), context);174 } else if (controlValue instanceof JSONObject) {175 Assert.isTrue(receivedValue instanceof JSONObject,176 ValidationUtils.buildValueMismatchErrorMessage("Type mismatch for JSON entry '" + controlKey + "'",177 JSONObject.class.getSimpleName(), receivedValue.getClass().getSimpleName()));178 validateJson(controlKey, (JSONObject) receivedValue,179 (JSONObject) controlValue, validationContext, context, readContext);180 } else if (controlValue instanceof JSONArray) {181 Assert.isTrue(receivedValue instanceof JSONArray,182 ValidationUtils.buildValueMismatchErrorMessage("Type mismatch for JSON entry '" + controlKey + "'",183 JSONArray.class.getSimpleName(), receivedValue.getClass().getSimpleName()));184 JSONArray jsonArrayControl = (JSONArray) controlValue;185 JSONArray jsonArrayReceived = (JSONArray) receivedValue;186 if (log.isDebugEnabled()) {187 log.debug("Validating JSONArray containing " + jsonArrayControl.size() + " entries");188 }189 if (strict) {190 Assert.isTrue(jsonArrayControl.size() == jsonArrayReceived.size(),191 ValidationUtils.buildValueMismatchErrorMessage("JSONArray size mismatch for JSON entry '" + controlKey + "'",192 jsonArrayControl.size(), jsonArrayReceived.size()));193 }194 for (int i = 0; i < jsonArrayControl.size(); i++) {195 if (jsonArrayControl.get(i).getClass().isAssignableFrom(JSONObject.class)) {196 Assert.isTrue(jsonArrayReceived.get(i).getClass().isAssignableFrom(JSONObject.class),197 ValidationUtils.buildValueMismatchErrorMessage("Value types not equal for entry: '" + jsonArrayControl.get(i) + "'",198 JSONObject.class.getName(), jsonArrayReceived.get(i).getClass().getName()));199 validateJson(controlKey, (JSONObject) jsonArrayReceived.get(i),200 (JSONObject) jsonArrayControl.get(i), validationContext, context, readContext);201 } else {202 Assert.isTrue(jsonArrayControl.get(i).equals(jsonArrayReceived.get(i)),203 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + jsonArrayControl.get(i) + "'",204 jsonArrayControl.get(i), jsonArrayReceived.get(i)));205 }206 }207 } else {208 Assert.isTrue(controlValue.equals(receivedValue),209 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + controlKey + "'",210 controlValue, receivedValue));211 }212 } else if (ValidationMatcherUtils.isValidationMatcherExpression(controlValue.toString())) {213 ValidationMatcherUtils.resolveValidationMatcher(controlKey,214 null,215 controlValue.toString(), context);216 } else {217 Assert.isTrue(!StringUtils.hasText(controlValue.toString()),218 ValidationUtils.buildValueMismatchErrorMessage(219 "Values not equal for entry '" + controlKey + "'", controlValue.toString(), null));220 }221 if (log.isDebugEnabled()) {222 log.debug("Validation successful for JSON entry '" + controlKey + "' (" + controlValue + ")");223 }224 }225 }226 /**227 * Checks if given element node is either on ignore list or228 * contains @ignore@ tag inside control message229 * @param controlKey230 * @param controlValue231 * @param receivedJson232 * @param ignoreExpressions233 * @param readContext234 * @return235 */236 public boolean isIgnored(String controlKey, Object controlValue, Object receivedJson, Set<String> ignoreExpressions, ReadContext readContext) {237 if (controlValue != null && controlValue.toString().trim().equals(Citrus.IGNORE_PLACEHOLDER)) {238 if (log.isDebugEnabled()) {239 log.debug("JSON entry: '" + controlKey + "' is ignored by placeholder '" +240 Citrus.IGNORE_PLACEHOLDER + "'");241 }242 return true;243 }244 for (String jsonPathExpression : ignoreExpressions) {245 Object foundEntry = readContext.read(jsonPathExpression);246 if (foundEntry instanceof JSONArray && ((JSONArray) foundEntry).contains(receivedJson)) {247 if (log.isDebugEnabled()) {248 log.debug("JSON entry: '" + controlKey + "' is ignored - skip value validation");249 }250 return true;251 }252 if (foundEntry != null && foundEntry.equals(receivedJson)) {253 if (log.isDebugEnabled()) {254 log.debug("JSON entry: '" + controlKey + "' is ignored - skip value validation");255 }256 return true;257 }258 }259 return false;260 }261 @Override262 protected Class<JsonMessageValidationContext> getRequiredValidationContextType() {263 return JsonMessageValidationContext.class;264 }265 @Override266 public boolean supportsMessageType(String messageType, Message message) {267 if (!messageType.equalsIgnoreCase(MessageType.JSON.name())) {268 return false;269 }270 if (!(message.getPayload() instanceof String)) {271 return false;272 }273 if (StringUtils.hasText(message.getPayload(String.class)) &&274 !message.getPayload(String.class).trim().startsWith("{") &&275 !message.getPayload(String.class).trim().startsWith("[")) {276 return false;277 }278 return true;279 }280 /**281 * Set the validator strict mode.282 * @param strict283 */284 public void setStrict(boolean strict) {285 this.strict = strict;286 }287 /**288 * Set the validator strict mode.289 * @param strict290 * @return this object for chaining291 */292 public JsonTextMessageValidator strict(boolean strict) {293 setStrict(strict);294 return this;295 }296 void setSchemaRepositories(List<JsonSchemaRepository> schemaRepositories) {297 this.schemaRepositories = schemaRepositories;298 }299 /**300 * Constructs the error message of a failed validation based on the processing report passed from301 * com.github.fge.jsonschema.core.report302 * @param report The report containing the error message303 * @return A string representation of all messages contained in the report304 */305 private String constructErrorMessage(ProcessingReport report) {306 StringBuilder stringBuilder = new StringBuilder();307 stringBuilder.append("Json validation failed: ");308 report.forEach(processingMessage -> stringBuilder.append(processingMessage.getMessage()));309 return stringBuilder.toString();310 }311 /**312 * {@inheritDoc}313 */314 @Override315 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {316 this.applicationContext = applicationContext;317 }318 void setJsonSchemaValidation(JsonSchemaValidation jsonSchemaValidation) {319 this.jsonSchemaValidation = jsonSchemaValidation;...

Full Screen

Full Screen

constructErrorMessage

Using AI Code Generation

copy

Full Screen

1JsonTextMessageValidator jsonTextMessageValidator = new JsonTextMessageValidator();2String jsonTextMessageValidatorErrorMessage = jsonTextMessageValidator.constructErrorMessage("jsonTextMessageValidatorErrorMessage", "jsonTextMessageValidatorControlMessage", "jsonTextMessageValidatorReceivedMessage", "jsonTextMessageValidatorValidationContext");3XmlTextMessageValidator xmlTextMessageValidator = new XmlTextMessageValidator();4String xmlTextMessageValidatorErrorMessage = xmlTextMessageValidator.constructErrorMessage("xmlTextMessageValidatorErrorMessage", "xmlTextMessageValidatorControlMessage", "xmlTextMessageValidatorReceivedMessage", "xmlTextMessageValidatorValidationContext");5GroovyScriptMessageValidator groovyScriptMessageValidator = new GroovyScriptMessageValidator();6String groovyScriptMessageValidatorErrorMessage = groovyScriptMessageValidator.constructErrorMessage("groovyScriptMessageValidatorErrorMessage", "groovyScriptMessageValidatorControlMessage", "groovyScriptMessageValidatorReceivedMessage", "groovyScriptMessageValidatorValidationContext");7JavaScriptMessageValidator javaScriptMessageValidator = new JavaScriptMessageValidator();8String javaScriptMessageValidatorErrorMessage = javaScriptMessageValidator.constructErrorMessage("javaScriptMessageValidatorErrorMessage", "javaScriptMessageValidatorControlMessage", "javaScriptMessageValidatorReceivedMessage", "javaScriptMessageValidatorValidationContext");9RubyScriptMessageValidator rubyScriptMessageValidator = new RubyScriptMessageValidator();10String rubyScriptMessageValidatorErrorMessage = rubyScriptMessageValidator.constructErrorMessage("rubyScriptMessageValidatorErrorMessage", "rubyScriptMessageValidatorControlMessage", "rubyScriptMessageValidatorReceivedMessage",

Full Screen

Full Screen

constructErrorMessage

Using AI Code Generation

copy

Full Screen

1com.consol.citrus.validation.json.JsonTextMessageValidator: {}2com.consol.citrus.validation.xml.XmlTextMessageValidator: {}3com.consol.citrus.validation.script.GroovyScriptMessageValidator: {}4com.consol.citrus.validation.script.ScriptMessageValidator: {}5com.consol.citrus.validation.json.JsonPathMessageValidator: {}6com.consol.citrus.validation.json.JsonSchemaMessageValidator: {}7com.consol.citrus.validation.text.PlainTextMessageValidator: {}8com.consol.citrus.validation.xml.XsdMessageValidator: {}9com.consol.citrus.validation.xml.XmlSchemaMessageValidator: {}10com.consol.citrus.validation.json.JsonMessageValidator: {}11com.consol.citrus.validation.xml.XmlMessageValidator: {}12com.consol.citrus.validation.script.ScriptValidationContext: {}13com.consol.citrus.validation.script.GroovyScriptValidationContext: {}14com.consol.citrus.validation.json.JsonPathValidationContext: {}

Full Screen

Full Screen

constructErrorMessage

Using AI Code Generation

copy

Full Screen

1[org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jsonTextMessageValidator' defined in class path resource [com/consol/citrus/config/spring/CitrusSpringContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: com.consol.citrus.validation.json.JsonTextMessageValidator.constructErrorMessage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;]2public class TestClass extends AbstractTestNGCitrusTest {3public void test() {4variable("json", "{'name':'John', 'age':30, 'car':null}");5http().client("httpClient")6.post("/post")7.payload("${json}");8}9}10public class TestClass extends AbstractTestNGCitrusTest {11public void test() {12variable("json", "{'name':'John', 'age':30, 'car':null}");13http().client("httpClient")14.post("/post")15.payload("${json}");16}17}

Full Screen

Full Screen

constructErrorMessage

Using AI Code Generation

copy

Full Screen

1String errorMessage = JsonTextMessageValidator.constructErrorMessage(jsonPath, jsonPathValue, expectedValue, message);2String errorMessage = XpathMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);3String errorMessage = XmlTextMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);4String errorMessage = XmlTextMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);5String errorMessage = XsdMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);6String errorMessage = XsdMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);7String errorMessage = GroovyScriptMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);8String errorMessage = GroovyScriptMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);9String errorMessage = GroovyScriptMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);10String errorMessage = GroovyScriptMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);11String errorMessage = GroovyScriptMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);12String errorMessage = GroovyScriptMessageValidator.constructErrorMessage(xpath, xpathValue, expectedValue, message);

Full Screen

Full Screen

constructErrorMessage

Using AI Code Generation

copy

Full Screen

1public class JsonTextMessageValidatorTest {2 public void testJsonTextMessageValidator() {3 String json = "{ \"name\": \"John Doe\", \"age\": 33, \"address\": { \"street\": \"Main Street\", \"city\": \"Anytown\", \"state\": \"CA\" } }";4 JsonTextMessageValidator validator = new JsonTextMessageValidator();5 validator.setValidationContext(new DefaultValidationContext());6 validator.setJsonPathExpressions(Collections.singletonMap("$..name", "John Doe"));7 validator.validateMessage(new DefaultMessage(json));8 }9}10The following code shows how to use the validateMessage() method of com.consol.citrus.validation.json.JsonTextMessageValidator class:11public void validateMessage(Message message) {12 try {13 if (message.getPayload() instanceof String) {14 validateJson((String) message.getPayload());15 } else {16 validateJson(message.getPayload(String.class));17 }18 } catch (IOException e) {19 throw new CitrusRuntimeException("Failed to parse JSON payload", e);20 }21}22The following code shows how to use the validateJson() method of com.consol.citrus.validation.json.JsonTextMessageValidator class:23private void validateJson(String json) throws IOException {24 JsonNode jsonNode = JsonUtils.readTree(json);25 JsonPathContext context = JsonPathContext.from(jsonNode);26 for (Map.Entry<String, String> jsonPathExpression : jsonPathExpressions.entrySet()) {27 if (jsonPathExpression.getValue() != null) {28 String value = context.read(jsonPathExpression.getKey());29 if (!value.equals(jsonPathExpression.getValue())) {30 throw new ValidationException(constructErrorMessage(json, jsonPathExpression.getKey(), jsonPathExpression.getValue(), value));31 }32 } else {33 if (!context.exists(jsonPathExpression.getKey())) {34 throw new ValidationException(constructErrorMessage(json, jsonPathExpression.getKey(), "exists", "not found"));35 }36 }

Full Screen

Full Screen

constructErrorMessage

Using AI Code Generation

copy

Full Screen

1public class MyTest extends TestNGCitrusSupport{2 public void myTest(){3 variable("jsonString", "{'firstName': 'John', 'lastName': 'Doe', 'age': 30}");4 json().validate("${jsonString}");5 }6}7public class MyTest extends TestNGCitrusSupport{8 public void myTest(){9 variable("xmlString", "<firstName>John</firstName><lastName>Doe</lastName><age>30</age>");10 xml().validate("${xmlString}");11 }12}13public class MyTest extends TestNGCitrusSupport{14 public void myTest(){15 variable("jsonString", "{'firstName': 'John', 'lastName': 'Doe', 'age': 30}");16 json().validate("${jsonString}");17 }18}19public class MyTest extends TestNGCitrusSupport{20 public void myTest(){21 variable("xmlString", "<firstName>John</firstName><lastName>Doe</lastName><age>30</age>");22 xml().validate("${xmlString}");23 }24}25public class MyTest extends TestNGCitrusSupport{26 public void myTest(){27 variable("jsonString", "{'firstName': 'John', 'lastName': 'Doe', 'age': 30}");28 json().validate("${jsonString}");29 }30}31public class MyTest extends TestNGCitrusSupport{32 public void myTest(){33 variable("xmlString", "<firstName>John</firstName><lastName>Doe</lastName><age>30</age>");34 xml().validate("${xmlString}");35 }36}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Citrus automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful