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:edu.stanford.epad.common.util.EPADFileUtils.java

public static String validateXml(File f, String xsdSchema) throws Exception {
    try {//from   ww w .  j av  a 2 s.com
        FileInputStream xml = new FileInputStream(f);
        InputStream xsd = null;
        try {
            xsd = new FileInputStream(xsdSchema);
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new StreamSource(xsd));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(xml));
            return "";
        } catch (SAXException ex) {
            log.info("Error: validating template/annotation " + ex.getMessage());
            return ex.getMessage();
        } catch (IOException e) {
            log.info("Error: validating template/annotation " + e.getMessage());
            throw e;
        }
    } catch (IOException e) {
        log.info("Exception validating a file: " + f.getName());
        throw e;
    }
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.RulesMessageServiceBean.java

private Schema getSchemaForXsd(String xsdLocation) throws SAXException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL resource = getClass().getClassLoader().getResource(xsdLocation);
    return sf.newSchema(resource);
}

From source file:org.geowebcache.config.XMLConfiguration.java

static void validate(Node rootNode) throws SAXException, IOException {
    // Perform validation
    // TODO dont know why this one suddenly failed to look up, revert to
    // XMLConstants.W3C_XML_SCHEMA_NS_URI
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    InputStream is = XMLConfiguration.class.getResourceAsStream("geowebcache.xsd");

    Schema schema = factory.newSchema(new StreamSource(is));
    Validator validator = schema.newValidator();

    // debugPrint(rootNode);

    DOMSource domSrc = new DOMSource(rootNode);
    validator.validate(domSrc);//from  www.  ja v a  2  s  . c  o  m
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

public static boolean isValidXmlUsingClassPathSchema(File f, String xsdSchema) {
    try {//from  w  w w .  ja va2  s  . c o m
        log.debug("xml:" + f.getName() + " xsd:" + xsdSchema);
        FileInputStream xml = new FileInputStream(f);
        InputStream xsd = null;
        try {
            xsd = EPADFileUtils.class.getClassLoader().getResourceAsStream(xsdSchema);
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new StreamSource(xsd));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(xml));
            return true;
        } catch (SAXException ex) {
            log.info("Error: validating template/annotation " + ex.getMessage());
        } catch (IOException e) {
            log.info("Error: validating template/annotation " + e.getMessage());
        }
    } catch (IOException e) {
        log.info("Exception validating a file: " + f.getName());
    }
    return false;
}

From source file:integration.AbstractTest.java

/**
 * Parses the specified file and returns the document.
 * // w  ww  .  ja va2  s .c  om
 * @param file The file to parse.
 * @param schemaStreamArray The schema as array of stream sources used to validate the specified file.
 * @return
 * @throws Exception Thrown if an error occurred.
 */
protected Document parseFileWithStreamArray(File file, StreamSource[] schemaStreamArray) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("No file to parse.");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true); // This must be set to avoid error : cvc-elt.1: Cannot find the declaration of element 'OME'.
    SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SchemaResolver theTestClassResolver = new SchemaResolver();
    sFactory.setResourceResolver(theTestClassResolver);

    Schema theSchema = sFactory.newSchema(schemaStreamArray);

    /*
    // Version - one step parse and validate (print error to stdErr)
    dbf.setSchema(theSchema);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    */

    // Version - two step parse then validate (throws error as exception)
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    Validator validator = theSchema.newValidator();
    validator.validate(new DOMSource(theDoc));
    return theDoc;
}

From source file:com.maxl.java.aips2xml.Aips2Xml.java

static List<MedicalInformations.MedicalInformation> readAipsFile() {
    List<MedicalInformations.MedicalInformation> med_list = null;
    try {/*from  ww  w.  ja  va2s. c o  m*/
        JAXBContext context = JAXBContext.newInstance(MedicalInformations.class);

        // Validation
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(FILE_MEDICAL_INFOS_XSD));
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new MyErrorHandler());

        // Marshaller
        /*
        Marshaller ma = context.createMarshaller();
        ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        MedicalInformations medi_infos = new MedicalInformations();
        ma.marshal(medi_infos, System.out);
        */
        // Unmarshaller   
        long startTime = System.currentTimeMillis();
        if (SHOW_LOGS)
            System.out.print("- Unmarshalling Swissmedic xml ... ");

        FileInputStream fis = new FileInputStream(new File(FILE_MEDICAL_INFOS_XML));
        Unmarshaller um = context.createUnmarshaller();
        MedicalInformations med_infos = (MedicalInformations) um.unmarshal(fis);
        med_list = med_infos.getMedicalInformation();

        long stopTime = System.currentTimeMillis();
        if (SHOW_LOGS)
            System.out.println(med_list.size() + " medis in " + (stopTime - startTime) / 1000.0f + " sec");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return med_list;
}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

private static Schema getSchema() throws SAXException {

    final ResourceLoader resourceLoader = new ResourceLoader();
    final InputStream xadesXsd = resourceLoader.getResource(XAD_ESV141_XSD);
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    return factory.newSchema(new StreamSource(xadesXsd));
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * @throws IOException/*w ww .  j  a v  a2 s . c  om*/
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private static void initializeSchemas() throws IOException, SAXException, ParserConfigurationException {
    File[] schemaFiles = ResourceUtil.getFilenamesInDirectory("xsd/", TestBase.class.getClassLoader());
    schemas = new HashMap<String, Schema>();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (File file : schemaFiles) {
        try {
            Schema schema = sf.newSchema(file);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                private String nameSpace = null;
                private boolean found = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) {
                    if (!found) {
                        String tagName = null;
                        int ix = qName.indexOf(":");
                        if (ix >= 0) {
                            tagName = qName.substring(ix + 1);
                        } else {
                            tagName = qName;
                        }
                        if ("schema".equals(tagName)) {
                            nameSpace = attributes.getValue("targetNamespace");
                            found = true;
                        }
                    }
                }

                public String toString() {
                    return nameSpace;
                }
            };
            parser.parse(file, handler);
            if (handler.toString() != null) {
                schemas.put(handler.toString(), schema);
            } else {
                logger.warn("Error reading xml schema: " + file);
            }

        } catch (Exception e) {
            logger.warn("Invalid xml schema " + file);
            logger.debug("Stacktrace: ", e);
        }

    }
}

From source file:jeeves.utils.Xml.java

private static SchemaFactory factory() {
    return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Gets the <code>Schema</code> object for the provided <code>File</code>.
 * /*  w w w  . ja va  2  s  .  c o m*/
 * @param schemaStream The file containing the schema.
 * @return Returns the <code>Schema</code> object.
 * @throws Exception If anything fails.
 */
private static Schema getSchema(final String schemaFileName) throws Exception {
    if (schemaFileName == null) {
        throw new IllegalArgumentException(
                TestBase.class.getSimpleName() + ":getSchema:schemaFileName is null");
    }
    File schemaFile = new File(schemaFileName);

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema theSchema = sf.newSchema(schemaFile);
    return theSchema;
}