Skip to content

Instantly share code, notes, and snippets.

@abramsba
Created January 30, 2016 22:49
Show Gist options
  • Save abramsba/e118d9ba8dcb522d324d to your computer and use it in GitHub Desktop.
Save abramsba/e118d9ba8dcb522d324d to your computer and use it in GitHub Desktop.
ABAP Validator
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;00
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.*;
/**
* Created by abramsbn on 28-1-2016.
* This class only validates an input XML against an XSD.
*/
public class AbapXmlValidator{
public static void main(String [] args) throws FileNotFoundException {
if (args.length != 2) {
error_no_input();
return;
}
DocumentBuilder xml_builder;
Document xml_document;
InputStream xml_source = new FileInputStream(new File(args[1]));
InputStream xsd_stream = new FileInputStream(new File(args[0]));
SchemaFactory schema_builder = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schema_source = new StreamSource(xsd_stream);
Schema schema;
Validator schema_validator;
try {
xml_builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
catch(ParserConfigurationException parser_error) {
java_error(parser_error);
return;
}
try {
xml_document = xml_builder.parse(xml_source);
}
catch (SAXException e) {
error_no_xml(e);
return;
}
catch (IOException e) {
java_error(e);
return;
}
try {
schema = schema_builder.newSchema(schema_source);
} catch (SAXException e) {
error_xsd_invalid(e);
return;
}
schema_validator = schema.newValidator();
try {
schema_validator.validate(new DOMSource(xml_document));
} catch (SAXException e) {
error_xml_invalid(e);
return;
} catch (IOException e) {
java_error(e);
return;
}
}
private static void java_error(Exception e) {
System.out.println(e.getMessage());
}
private static void error_xml_invalid(Exception e) {
java_error(e);
}
private static void error_xsd_invalid(Exception e) {
java_error(e);
}
private static void error_no_xml(Exception e) {
java_error(e);
}
private static void error_no_input() {
help();
}
private static void help() {
System.out.println("Usage: java -jar spv.jar \"<path_to_xsd>\" \"<path_to_xml>\"");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment