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:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java

public Unmarshaller getUnmarshaller() {
    Unmarshaller u = unmarshaller.get();
    if (!isValidating() && u.getSchema() != null) {
        u.setSchema(null);//  w w  w .ja v a  2  s.  co  m
    } else if (isValidating() && u.getSchema() == null) {
        // Load and set schema to validate against
        Schema schema;
        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
            List<URI> schemas = getAdditionalSchemas();
            URL t2flowExtendedXSD = T2FlowParser.class.getResource(T2FLOW_EXTENDED_XSD);
            schemas.add(t2flowExtendedXSD.toURI());

            List<Source> schemaSources = new ArrayList<>();
            for (URI schemaUri : schemas)
                schemaSources.add(new StreamSource(schemaUri.toASCIIString()));
            Source[] sources = schemaSources.toArray(new Source[schemaSources.size()]);
            schema = schemaFactory.newSchema(sources);
        } catch (SAXException e) {
            throw new RuntimeException("Can't load schemas", e);
        } catch (URISyntaxException | NullPointerException e) {
            throw new RuntimeException("Can't find schemas", e);
        }
        u.setSchema(schema);
    }
    return u;
}

From source file:org.kite9.diagram.server.AbstractKite9Controller.java

protected void validateXML(String xml) throws SAXException, IOException {
    // validate the xml against the schema
    InputSource is = new InputSource(new StringReader(xml));

    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(Diagram.class.getResourceAsStream("/adl_1.0.xsd"));
    Schema schema = factory.newSchema(schemaFile);

    Validator validator = schema.newValidator();

    SAXSource source = new SAXSource(is);
    validator.validate(source);// w w w  .j  a v a 2  s .  c o m
}

From source file:eu.artist.postmigration.eubt.executiontrace.abstractor.SOAPTraceAbstractor.java

/**
 * Validates soap trace (i.e., list of soap responses) against schema and
 * stores the result//  w w w  .ja  v a 2  s  .  co m
 * 
 * @param soapResponseTrace trace that contains soap responses
 * @return map of soap responses and their respective validation result
 * @throws EUBTException in case the schema location could not be found
 */
private LinkedMap<SOAPResponse, String> validateSoapTrace(final SOAPTrace soapResponseTrace)
        throws EUBTException {
    final LinkedMap<SOAPResponse, String> validationResults = new LinkedMap<SOAPResponse, String>();

    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Validator validator;
    try {
        final Schema schema = schemaFactory.newSchema(new URL(schemaLocation));
        validator = schema.newValidator();
    } catch (SAXException | IOException e) {
        throw new EUBTException("Failed to create Schema from Schema location " + schemaLocation
                + ". Detailed Exception: " + e.getMessage());
    }
    // for each soap response
    for (final Response response : soapResponseTrace.getResponses()) {
        String validationResult = VALIDATION_INVALID;
        final SOAPResponse soapResponse = (SOAPResponse) response;
        final SOAPEnvelope soapEnvelope = (SOAPEnvelope) soapResponse.getData();
        final OMElement bodyContent = soapEnvelope.getBody().getFirstElement();

        // create some invalid content
        //         SOAP12Factory factory = new SOAP12Factory();
        //         OMElement invalidElement = factory.createOMElement(new QName("blah"));
        //         OMNamespace invalidNamespace = factory.createOMNamespace("http://notMyNamespace.com", "invNS");
        //         OMAttribute invalidAttribute = factory.createOMAttribute("someAttribute", invalidNamespace, "attributeValue");
        //         bodyContent.addChild(invalidElement);
        //         bodyContent.addAttribute(invalidAttribute);

        // validate soap body content -> will cause an exception if not valid
        try {
            validator.validate(bodyContent.getSAXSource(true));
            // validation succeeded
            validationResult = VALIDATION_VALID;
            Debug.debug(this, "Successfully validated SOAP body content " + bodyContent);
        } catch (final IOException e) {
            throw new EUBTException("Failed to validate SOAP body content " + bodyContent
                    + ". Detailed Exception: " + e.getMessage());
        } catch (final SAXException e) {
            // validation failed
            Debug.debug(this, "Failed to validate soap SOAP content " + bodyContent + ". Detailed Exception: "
                    + e.getMessage());
        }
        // finished validating, store result
        validationResults.put(soapResponse, validationResult);
        validator.reset();
    } // for each soap response

    return validationResults;
}

From source file:AndroidUninstallStock.java

public static DocumentBuilderFactory getXmlDocFactory() throws SAXException {
    DocumentBuilderFactory xmlfactory = DocumentBuilderFactory.newInstance();
    xmlfactory.setIgnoringComments(true);
    xmlfactory.setCoalescing(true);/*from   www  . j  a  va 2s . c  o m*/
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4867706
    xmlfactory.setIgnoringElementContentWhitespace(true);
    xmlfactory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(AndroidUninstallStock.class.getResource("AndroidListSoft.xsd")));
    xmlfactory.setValidating(false); // not DTD
    return xmlfactory;
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given document agains an XSD schema
 *
 * @param document/*  ww w . j  av  a  2s .  c om*/
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(Document document, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult sResult = new StreamResult();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    sResult.setOutputStream(bos);
    transformer.transform(domSource, sResult);
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(is);
    return errorHandler.getValidationErrors();
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public Schema trySchemaCache(Collection<String> schemaPaths, ErrorListener errorListener) throws Exception {
    String key = StringUtils.join(schemaPaths, ";");
    Schema schema = schemaCache.get(key);
    if (schema == null) {
        logger.info("Compiling and caching schema(s) \"" + key + "\" ...");
        try {/* www. ja  va 2s . com*/
            ArrayList<Source> schemaSources = new ArrayList<Source>();
            for (String path : schemaPaths) {
                File file = new File(path);
                if (!file.isFile()) {
                    throw new FileNotFoundException(
                            "XML Schema file \"" + file.getAbsolutePath() + "\" not found");
                }
                schemaSources.add(new StreamSource(file));
            }
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setErrorHandler(new ValidatorErrorHandler("Schema file(s)"));
            schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        } catch (Exception e) {
            logger.error("Error compiling schema(s) \"" + key + "\"", e);
            throw e;
        }
        if (!developmentMode) {
            schemaCache.put(key, schema);
        }
    }
    return schema;
}

From source file:no.met.jtimeseries.service.TimeSeriesService.java

private Schema getLocationForecastSchema() throws SAXException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL locationForecastSchemaUrl = getLocationForecastSchemaUrl();
    Schema schema = sf.newSchema(locationForecastSchemaUrl);
    return schema;

}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given XML file against an XSD schema
 *
 * @param file/*from  w  ww  .  j  av  a 2  s  .  c  om*/
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(File file, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(file);
    return errorHandler.getValidationErrors();
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.ELTSchemaGridWidget.java

private boolean validateXML(InputStream xml, InputStream xsd) {
    try {/* w w  w .j  av  a 2  s. c  o  m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();

        validator.validate(new StreamSource(xml));
        return true;
    } catch (SAXException | IOException ex) {
        //MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
        MessageBox dialog = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_ERROR | SWT.OK);
        dialog.setText(Messages.ERROR);
        dialog.setMessage(Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
        logger.error(Messages.IMPORT_XML_FORMAT_ERROR);
        return false;
    }
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Loads the schema for the {@link Entity} class.
 *
 * @param schemaFile the path to the schema file
 *
 * @return the loaded schema//from   ww  w.  ja va  2 s. com
 *
 * @throws SAXException if any error occurs during loading the schema
 */
private Schema loadSchema(String schemaFile) throws SAXException {

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    return schemaFactory.newSchema(getClass().getResource(schemaFile));
}