I have a response and need to validate its structure to be valid json or not => I searched out the following way and applied in Katalon
String jsonPass =
"""
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
}
}
}
"""
ResponseObject response = resp.getResponseBodyContent()
boolean successful = WS.validateJsonAgainstSchema(response,jsonPass)
But an error occurred that I cannot use validateJsonAgainstSchema
I imported the following but it didn't work => Could you tell me what should I do?
import com.kms.katalon.core.testobject.ResponseObject
import com.kms.katalon.core.webservice.verification.WSResponseManager
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
Related
I am trying to validate a json schema against the json input.
I am using
org.everit.json.schema-1.0.0.jar
My json input
{
"id": 200,
"name": "Green Learner",
"cost": 0
}
My JSON SCHEMA .
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Youtube Channel",
"description": "Youtube Channel for software development training",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the the channle",
"type": "string"
},
"cost": {
"type": "number",
"minimum": 100,
"maximum":10000
}
},
"required": ["id", "name", "cost"]
}
JAVA Code for validation.
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.everit.json.schema.Schema;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
*
* #author amitkumar
*/
public class JsonValidate {
public static void main(String[] args) throws FileNotFoundException {
File schemaFile = new File("schema.json");
JSONTokener schemaData = new JSONTokener(new FileInputStream(schemaFile));
JSONObject jsonSchema = new JSONObject(schemaData);
//json data
File jsonData = new File("product_invalid.json");
JSONTokener jsonDataFile = new JSONTokener(new FileInputStream(jsonData));
JSONObject jsonObject = new JSONObject(jsonDataFile);
Schema schemaValidator = SchemaLoader.load(jsonSchema);
schemaValidator.validate(jsonObject);
System.out.println(jsonObject.getInt("cost"));
}
}
When i run the code with org.everit.json.schema-1.0.0.jar, i get following error message .
Exception in thread "main"
org.everit.json.schema.ValidationException:v0.0 is not higher or equal
to 100
This is the warning message i get when i use
json-schema-validator-1.0.42.jar comes with com.networknt it clearly mention me object name which got error.
$.Cost: 0.0 is not higher or equal to 100
i want to do the same with org.everit.json.schema-1.0.0.jar, which object in my json input got the error .It does not show me the object name .
If the library does not support your requirement, you could log the missing information by yourself. Something like
try {
schemaValidator.validate(jsonObject);
} catch(ValidationException e) {
LOG.error("Validation error in Object: '{}'", yourObjectName, e)
}
By the way, there are more newer versions than 1.0.0 of org.everit.json.schema available: https://search.maven.org/artifact/org.everit.json/org.everit.json.schema
Edit add additional information:
The ValidationException has methods like getPointerToViolation() which might get you the information you need. See JavaDoc of the current version: https://erosb.github.io/everit-json-schema/javadoc/1.12.2/org/everit/json/schema/ValidationException.html#getPointerToViolation()
Be aware, that version 1.0.0 does not have this methods (JavaDoc of v1.0.0)!
I am getting a ClassCastException while trying to test Avro schema evolution with a simple Java program.
Avro version: 1.10.0
customer-v1.avsc
{
"type": "record",
"namespace": "com.practice.kafka",
"name": "Customer",
"doc": "Avro schema for Customer",
"fields": [
{"name": "first_name", "type": "string", "doc": "Customer first name"},
{"name": "last_name", "type": "string", "doc": "Customer last name"},
{"name": "automated_email", "type": "boolean", "default": true, "doc": "Receive marketing emails or not"}
]
}
customer-v2.avsc
{
"type": "record",
"namespace": "com.practice.kafka",
"name": "CustomerV2",
"doc": "Avro schema for Customer",
"fields": [
{"name": "first_name", "type": "string", "doc": "Customer first name"},
{"name": "last_name", "type": "string", "doc": "Customer last name"},
{"name": "phone_number", "type": ["null","boolean"], "default": null, "doc": "Optional phone number"},
{"name": "email", "type": "string", "default": "missing#example.com", "doc": "Optional email address"}
]
}
Program to serialize v1 and deserialize v2
package com.practice.kafka;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import java.io.File;
import java.io.IOException;
public class BackwardSchemaEvolutionSample {
public static void main(String[] args) {
// Step 1 - Create specific record
Customer customer = Customer.newBuilder().setFirstName("John").setLastName("Doe").setAutomatedEmail(false).build();
// Step 2 - Write specific record to a file
final DatumWriter<Customer> datumWriter = new SpecificDatumWriter<>();
try (DataFileWriter<Customer> dataFileWriter = new DataFileWriter<>(datumWriter)) {
dataFileWriter.create(customer.getSchema(), new File("customer-v1.avro"));
dataFileWriter.append(customer);
} catch (IOException e) {
e.printStackTrace();
}
// Step 3 - Read specific record from a file
final File file = new File("customer-v1.avro");
final DatumReader<CustomerV2> datumReader = new SpecificDatumReader<>();
CustomerV2 customerRecord;
try (DataFileReader<CustomerV2> dataFileReader = new DataFileReader<>(file, datumReader)) {
customerRecord = dataFileReader.next();
System.out.println(customerRecord.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Result
Exception in thread "main" java.lang.ClassCastException: class com.practice.kafka.Customer cannot be cast to class com.practice.kafka.CustomerV2 (com.practice.kafka.Customer and com.practice.kafka.CustomerV2 are in unnamed module of loader 'app')
at com.practice.kafka.SchemaEvolutionSample.main(SchemaEvolutionSample.java:34)
Can you please let me know how to fix this error?
You defined 2 data types Customer and Customer2 and you cannot have any casting since they are not in inherit relation.
So Java can't do casting and you are getting ClassCastException.
In your code only solution is to catch ClassCastException and in catch block convert Customer to Customer2.
I assume that you are emulating changes of your schema in Kafka environment.
In this scenario you will extend existing avro schema by adding new fields, or removing old fields.
As far as the name of class stays the same, avro schema changes will work.
using 4.3.1 of open api generator and trying to get the java code out of the json.
In the json file I have the following (changed for example):
"xComponents": {
"type": "array",
"title": "This is a title",
"items": {
"oneOf": [
{
"$ref": "xComponent.AAA.schema.json"
},
{
"$ref": "xComponent.BBB.schema.json"
},
{
"$ref": "xComponent.CCC.schema.json"
},
{
"$ref": "xComponent.DDD.schema.json"
}
],
"type": "object"
},
"minItems": 1
}
It generates this list wierd class name that cannot get build:
private List<**OneOfxComponentAAASchemaJsonxComponentBBBSchemaJsonxComponentCCCSchemaJsonxComponentDDDSchemaJson**> xComponents =
new ArrayList<**OneOfxComponentAAASchemaJsonxComponentBBBSchemaJsonxComponentCCCSchemaJsonxComponentDDDSchemaJson**>();
Whats the correct way to deal with oneOf? what im I doing wrong (either with the json file or with the open api generator)?
In my play framework application, I have registered APIs in route file as:
POST /api/rmt-create-request controllers.Api.CreateRMTRequestForm
On action of controller, I am using following code to access formData submitted with form submit as :
public Result CreateRMTRequestForm()
{
Map<String, String[]> params = request().body().asMultipartFormData().asFormUrlEncoded();
Its working fine as API when I submit the form with forntend application.
I am trying to create APIs documentation with swagger.ui in which within swagger.json file I have written following JSON data.
"paths": {"/api/rmt-create-request": {
"post": {
"tags": [
"RMT APIs"
],
"description" : "Return newly created request data",
"operationId": "create-new-rmt-request",
"consumes": ["application/x-www-form-urlencoded"],
"parameters": [
{
"name": "rootNodeName",
"in": "formData",
"description": "Root node class name for item",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/rmt-request-data"
}
}
}
},
"default": {
"$ref": "#/components/responses/default"
}
}
}
},
While inspecting RequestHeader data, its not showing content-Type property with value 'multipart/form-data' as well as formData are not attached, which makes controller to throw null exception.
Can anyone help whats missing in swagger.json file ?
You are mixing OpenAPI 2.0 and 3.0 syntax.
In OpenAPI 3.0, request body (including form data) is defined using the requestBody keyword instead of in: formData parameters.
Also, OAS3 does not use consumes. The media types consumed by the operation are specified inside the requestBody.
"paths": {
"/api/rmt-create-request": {
"post": {
"tags": [
"RMT APIs"
],
"description": "Return newly created request data",
"operationId": "create-new-rmt-request",
"requestBody": {
"content": {
"multipart/form-data": { // or "application/x-www-form-urlencoded" - depending on what you need
"schema": {
"type": "object",
"properties": {
"rootNodeName": {
"type": "string",
"description": "Root node class name for item"
}
}
}
}
}
}
}
}
}
More information: Describing Request Body
Hi I'm using the JSON Schema evaluator in version 2.2.6 to validate my server responses. These responses can contain single objects of type A, B or C, but also composite objects, e.g., D containing an array of A objects. To reuse the schema definitions of each object, I started to describe all entities in the same file as described here. Now my problem is, that I have to reference one of those single objects when validating the response.
Here is my (not) SWE.
JSON schema file:
{
"id":"#root",
"properties": {
"objecta": {
"type": "object",
"id":"#objecta",
"properties": {
"attribute1": {"type": "integer"},
"attribute2": {"type": "null"},
},
"required": ["attribute1", "attribute2"]
},
"objectb": {
"type": "object",
"id":"#objectb",
"properties": {
"attribute1": {"type": "integer"},
"attribute2": {
"type": "array",
"items": {
"$ref": "#/objecta"
}
}
}
},
"required": ["attribute1", "attribute2"]
},
}
}
Now I want to validate a server response containing object B. For this, I tried the following:
public class SchemeValidator {
public static void main(String[] args) {
String jsonData = pseudoCodeFileLoad("exampleresponse/objectb.txt");
final File jsonSchemaFile = new File("resources/jsonschemes/completescheme.json");
final URI uri = jsonSchemaFile.toURI();
ProcessingReport report = null;
try {
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
final JsonSchema schema = factory.getJsonSchema(uri.toString() + "#objectb");
JsonNode data = JsonLoader.fromString(jsonData);
report = schema.validate(data);
} catch (JsonParseException jpex) {
// ... handle parsing errors etc.
}
}
}
The problem is that the scheme is not loaded correctly. I either get no error (even for invalid responses) or I get fatal: illegalJsonRef as the scheme seems to be empty. How can I use the schema of object b in my Java code? Thank you!!
It looks like your $ref is incorrect. It needs to be a relative reference from the base of the JSON Schema file (see here).
So your JSON schema would become:
{
"id":"#root",
"properties": {
"objecta": {
"type": "object",
"id":"#objecta",
"properties": {
"attribute1": {"type": "integer"},
"attribute2": {"type": "null"},
},
"required": ["attribute1", "attribute2"]
},
"objectb": {
"type": "object",
"id":"#objectb",
"properties": {
"attribute1": {"type": "integer"},
"attribute2": {
"type": "array",
"items": {
"$ref": "#/properties/objecta"
}
}
}
},
"required": ["attribute1", "attribute2"]
},
}
}
I've added '/properties' to your $ref. It's operating like XPath to the definition of the object in the schema file.