Question

I know this question has been asked here before but none of them are asking exactly what I am looking for.

I want to know how we can validate a RESTful service response(application/xml) against an XSD schema file via the groovy script. Yes, I have the xsd file on my local disk but I can't seem to understand how to provide the response as input for it to validate?

I have created a sample but one crucial part is missing. Can anyone plz assist?

import com.eviware.soapui.support.XmlHolder
import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.*
// setup validator
Validator validator;
def url = 'C:\\Documents and Settings\\schema\\sclBase.xsd'
log.info url
URI uri = new URI(url);
InputStream inp = uri.toURL().openStream();
try
{
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource entitySs = new StreamSource(inp);
Schema schema = factory.newSchema(entitySs);
assert(schema != null);
validator = schema.newValidator();

def response = new XmlHolder( messageExchange.responseContentAsXml )
log.info response
validator.validate(new StreamSource(new StringReader(response)))
}
finally
{
inp.close();
inp = null;
}

The error I am getting here is "->Illegal character at opaque part at index 2: C:\Documents and Settings\schema\sclBase.xsd"

Was it helpful?

Solution

Assuming you have the REST response in a String called response

import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory

String response = messageExchange.responseContent

new File( 'C:\\Documents and Settings\\schema\\sclBase.xsd' ).withReader { xsd ->
  SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI )
               .newSchema( new StreamSource( xsd ) )
               .newValidator()
               .validate( new StreamSource( new StringReader( response ) ) )

}

Should do it. You were closing the input stream before reading from it afaict (but you don't say what error you were getting)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top