Example usage for javax.xml.validation SchemaFactory newInstance

List of usage examples for javax.xml.validation SchemaFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newInstance.

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

From source file:Main.java

/**
 * This method validate XML by XML File and XSD File.
 *
 * @param xml input XML File/* w ww. j  a v  a 2 s .co  m*/
 * @param xsd input XSD File
 *
 * @return true or false, valid or not
 */
public static boolean validateXMLByXSD(File xml, File xsd) {
    try {
        SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(xsd).newValidator()
                .validate(new StreamSource(xml));
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.vincibean.salestaxes.jaxb.JaxbFactory.java

/**
 * Factory method, creates a {@link Marshaller} from the context given in the constructor; moreover, ensure that
 * the marshalled XML data is formatted with linefeeds and indentation.  
 * @return an {@link Optional} object which may or may not contain a {@link Marshaller}
 *///from  www. j  a  v a2 s.  co m
public static Optional<Marshaller> createMarshaller(final Class<?> context) {
    try {
        Marshaller marshaller = JAXBContext.newInstance(context).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new ClassPathResource("receipt/Poiuyt.xsd").getFile()));
        marshaller.setEventHandler(new FoobarValidationEventHandler());
        return Optional.fromNullable(marshaller);
    } catch (JAXBException | SAXException | IOException e) {
        logger.warn("Exception on jaxb factory creation: ", e);
        return Optional.absent();
    }
}

From source file:Main.java

public static Schema getSchema(URL schemaURL) {
    Schema schema = null;// w  ww.ja v a 2s .c  o m
    try {
        if (schemaURL != null) {
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schema = sf.newSchema(schemaURL);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to create shcemma from URL " + schemaURL, e);
    }
    return schema;
}

From source file:com.aol.advertising.qiao.util.XmlConfigUtil.java

/**
 * Validate an XML document against the given schema.
 *
 * @param xmlFileLocationUri/*from   w w  w  . ja  v  a  2s . c  o  m*/
 *            Location URI of the document to be validated.
 * @param schemaLocationUri
 *            Location URI of the XML schema in W3C XML Schema Language.
 * @return true if valid, false otherwise.
 */
public static boolean validateXml(String xmlFileLocationUri, String schemaLocationUri) {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    InputStream is = null;
    try {
        Schema schema = factory.newSchema(CommonUtils.uriToURL(schemaLocationUri));
        Validator validator = schema.newValidator();
        URL url = CommonUtils.uriToURL(xmlFileLocationUri);
        is = url.openStream();
        Source source = new StreamSource(is);

        validator.validate(source);
        logger.info(">> successfully validated configuration file: " + xmlFileLocationUri);

        return true;
    } catch (SAXParseException e) {
        logger.error(e.getMessage() + " (line:" + e.getLineNumber() + ", col:" + e.getColumnNumber() + ")");

    } catch (Exception e) {
        if (e instanceof SAXParseException) {
            SAXParseException e2 = (SAXParseException) e;
            logger.error(e2.getMessage() + "at line:" + e2.getLineNumber() + ", col:" + e2.getColumnNumber());
        } else {
            logger.error(e.getMessage());
        }
    } finally {
        IOUtils.closeQuietly(is);
    }

    return false;
}

From source file:gov.nih.nci.cabig.caaers.utils.XmlValidator.java

public static boolean validateAgainstSchema(String xmlContent, String xsdUrl, StringBuffer validationResult) {
    boolean validXml = false;
    try {//from  ww w  . ja  va2  s. co  m
        // parse an XML document into a DOM tree
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(false);
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
        Document document = parser.parse(new InputSource(new StringReader(xmlContent)));

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // load a WXS schema, represented by a Schema instance
        Source schemaFile = new StreamSource(getResources(xsdUrl)[0].getFile());

        Schema schema = schemaFactory.newSchema(schemaFile);
        // create a Validator instance, which can be used to validate an instance document
        Validator validator = schema.newValidator();
        // validate the DOM tree
        validator.validate(new DOMSource(document));
        validXml = true;
    } catch (FileNotFoundException ex) {
        throw new CaaersSystemException("File Not found Exception", ex);
    } catch (IOException ioe) {
        validationResult.append(ioe.getMessage());
        logger.error(ioe.getMessage());
    } catch (SAXParseException spe) {
        validationResult.append("Line : " + spe.getLineNumber() + " - " + spe.getMessage());
        logger.error("Line : " + spe.getLineNumber() + " - " + spe.getMessage());
    } catch (SAXException e) {
        validationResult.append(e.toString());
        logger.error(e.toString());
    } catch (ParserConfigurationException pce) {
        validationResult.append(pce.getMessage());
    }
    return validXml;
}

From source file:com.spoledge.util.xml.XMLValidator.java

public XMLValidator(File schema) throws SAXException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    init(sf.newSchema(schema));//from  w  w  w.j  a v a2s . c  o  m
}

From source file:hadoopInstaller.io.XMLDocumentReader.java

public static Document parse(FileObject xmlDocument, FileObject xsdDocument)
        throws InstallerConfigurationParseError {

    try {/*  w  w  w .  j a  v a2 s  .co m*/
        // Validate against XML Schema
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(xsdDocument.getContent().getInputStream()));
        dbf.setValidating(false);
        dbf.setSchema(schema);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ParseErrorHandler());
        return db.parse(xmlDocument.getContent().getInputStream());
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new InstallerConfigurationParseError(e, "XMLDocumentReader.ParseError", xmlDocument.getName()); //$NON-NLS-1$
    }
}

From source file:io.konik.utils.InvoiceLoaderUtils.java

public static Validator getSchemaValidator() throws SAXException {
    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    URL schemaInvoice = notNull(InvoiceLoaderUtils.class.getResource(ZF_1_SCHEMA_XSD));
    Schema invoiceSchema = sf.newSchema(schemaInvoice);
    return invoiceSchema.newValidator();
}

From source file:com.ebay.jetstream.event.processor.esper.raw.EsperTestConfigurationValidator.java

public boolean validate(String instance, String schema) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {/*from w w  w .  j  ava  2s. co  m*/
        warnings = 0;
        errors = 0;
        fatalErrors = 0;
        try {
            //Set the validation feature
            factory.setFeature("http://xml.org/sax/features/validation", true);

            //Set the schema validation feature
            factory.setFeature("http://apache.org/xml/features/validation/schema", true);

            //Set schema full grammar checking
            factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

            // If there is an external schema set it
            if (schema != null) {
                SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                Schema s = sf.newSchema(new StreamSource(schema));
                factory.setSchema(s);
            }
            DocumentBuilder parser = factory.newDocumentBuilder();
            parser.setErrorHandler(this);
            // Parse and validate
            parser.parse(instance);
            // Return true if we made it this far with no errors
            return ((errors == 0) && (fatalErrors == 0));
        } catch (SAXException e) {
            log.error("Could not activate validation features - " + e.getMessage());
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return false;
}

From source file:com.aionemu.gameserver.dataholders.ReloadableData.java

protected Schema getSchema(String xml_schema) {
    Schema schema = null;/*from w  w  w  .  j a  v  a2s  . c  o  m*/
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        schema = sf.newSchema(new File(xml_schema));
    } catch (SAXException saxe) {
        throw new Error("Error while getting schema", saxe);
    }
    return schema;
}