Example usage for javax.xml.validation SchemaFactory newSchema

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

Introduction

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

Prototype

public abstract Schema newSchema(Source[] schemas) throws SAXException;

Source Link

Document

Parses the specified source(s) as a schema and returns it as a schema.

Usage

From source file:Main.java

public static Schema getSchema(String schemaString) {
    Schema schema = null;//  w  ww. ja v a2 s  . c  o  m
    try {
        if (schemaString != null) {
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            StreamSource ss = new StreamSource();
            ss.setReader(new StringReader(schemaString));
            schema = sf.newSchema(ss);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to create schemma from string: " + schemaString, e);
    }
    return schema;
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.data.QueryResultContainer.java

/**
 * Validates input XML file using 'queryResult.xsd' schema.
 *
 * @param xml xml/* w  ww . jav  a  2  s  . com*/
 * @throws IOException if file is not valid
 */
public static void validateXML(String xml) throws IOException {
    String xsdName = "queryResult.xsd";
    URL resource = QueryResultContainer.class.getClass().getResource(xsdName);
    if (resource == null) {
        throw new IllegalStateException("Cannot locate resource " + xsdName + " on classpath");
    }

    URL xsdFile;
    try {
        xsdFile = resource.toURI().toURL();
    } catch (MalformedURLException | URISyntaxException e) {
        throw new IOException(e);
    }

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Schema schema = factory.newSchema(xsdFile);
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new StringReader(xml)));
    } catch (SAXException e) {
        throw new IOException(e);
    }
}

From source file:com.betfair.cougar.marshalling.impl.databinding.xml.XMLUtils.java

public static Schema getSchema(JAXBContext context) {
    Result result = new ResultImplementation();
    SchemaOutputResolver outputResolver = new SchemaOutputResolverImpl(result);
    File tempFile = null;/*from  www  . j  a  v  a2  s  .c o m*/
    try {
        context.generateSchema(outputResolver);
        String schemaFile = result.getSystemId();
        if (schemaFile != null) {
            tempFile = new File(URI.create(schemaFile));
            String content = FileUtils.readFileToString(tempFile);

            // JAXB nicely generates a schema with element refs, unfortunately it also adds the nillable attribute to the
            // referencing element, which is invalid, it has to go on the target. this string manipulation is to move the
            // nillable attribute to the correct place, preserving it's value.
            Map<String, Boolean> referenceElementsWithNillable = new HashMap<>();
            BufferedReader br = new BufferedReader(new StringReader(content));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("<xs:element") && line.contains(" ref=\"") && line.contains(" nillable=\"")) {
                    // we've got a reference element with nillable set
                    int refStartIndex = line.indexOf(" ref=\"") + 6;
                    int refEndIndex = line.indexOf("\"", refStartIndex);
                    int nillableStartIndex = line.indexOf(" nillable=\"") + 11;
                    int nillableEndIndex = line.indexOf("\"", nillableStartIndex);
                    String ref = line.substring(refStartIndex, refEndIndex);
                    if (ref.startsWith("tns:")) {
                        ref = ref.substring(4);
                    }
                    String nillable = line.substring(nillableStartIndex, nillableEndIndex);
                    referenceElementsWithNillable.put(ref, Boolean.valueOf(nillable));
                }
            }
            // if we got some hits, then we need to rewrite this schema
            if (!referenceElementsWithNillable.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                br = new BufferedReader(new StringReader(content));
                while ((line = br.readLine()) != null) {
                    // these we need to remove the nillable section from
                    if (line.contains("<xs:element") && line.contains(" ref=\"")
                            && line.contains(" nillable=\"")) {
                        int nillableStartIndex = line.indexOf(" nillable=\"");
                        int nillableEndIndex = line.indexOf("\"", nillableStartIndex + 11);
                        line = line.substring(0, nillableStartIndex) + line.substring(nillableEndIndex + 1);
                    } else if (line.contains("<xs:element name=\"")) {
                        for (String key : referenceElementsWithNillable.keySet()) {
                            // this we need to add the nillable back to
                            String elementTagWithName = "<xs:element name=\"" + key + "\"";
                            if (line.contains(elementTagWithName)) {
                                int endOfElementName = line.indexOf(elementTagWithName)
                                        + elementTagWithName.length();
                                line = line.substring(0, endOfElementName) + " nillable=\""
                                        + referenceElementsWithNillable.get(key) + "\""
                                        + line.substring(endOfElementName);
                                break;
                            }
                        }
                    }
                    sb.append(line).append("\n");
                }
                content = sb.toString();
            }

            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            return sf.newSchema(new StreamSource(new StringReader(content)));
        }
    } catch (IOException e) {
        throw new PanicInTheCougar(e);
    } catch (SAXException e) {
        throw new PanicInTheCougar(e);
    } finally {
        if (tempFile != null)
            tempFile.delete();
    }
    return null;
}

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

/**
 * Validate an XML document against the given schema.
 *
 * @param xmlFileLocationUri//from  www .j  a 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:com.agimatec.validation.jsr303.xml.ValidationParser.java

static Schema getSchema(String xsd) {
    ClassLoader loader = PrivilegedActions.getClassLoader(ValidationParser.class);
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = loader.getResource(xsd);
    try {//from  w ww.j a  v  a 2 s  .  c  o  m
        return sf.newSchema(schemaUrl);
    } catch (SAXException e) {
        log.warn("Unable to parse schema: " + xsd, e);
        return null;
    }
}

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 {//  w  w w  .ja v a  2 s. c o 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.mymita.vaadlets.JAXBUtils.java

private static final Vaadlets unmarshal(final Reader aReader, final Resource theSchemaResource) {
    try {//from  w  ww.j a  va2s  . c  o  m
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            unmarshaller.setSchema(schema);
        }
        return unmarshaller
                .unmarshal(XMLInputFactory.newInstance().createXMLStreamReader(aReader), Vaadlets.class)
                .getValue();
    } catch (final JAXBException | SAXException | XMLStreamException | FactoryConfigurationError
            | IOException e) {
        throw new RuntimeException("Can't unmarschal", e);
    }
}

From source file:de.fhg.iais.model.aip.util.XmlUtilsTest.java

private static Document parseAndValidate(String xml, URL xsd) {
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema;// ww w.ja va 2s .  c o  m
    try {
        schema = factory.newSchema(xsd);
    } catch (final SAXException e) {
        throw new DbcException(e);
    }

    //        final Document xmlDocument = XmlUtils.parse(xml);
    final Document xmlDocument = XmlProcessor.buildDocumentFrom(xml);
    final Validator validator = schema.newValidator();
    try {
        validator.validate(new JDOMSource(xmlDocument));
        return xmlDocument;
    } catch (final SAXException e) {
        throw new DbcException(e);
    } catch (final IOException e) {
        throw new DbcException(e);
    }
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {/*from   w  ww.j a  v a 2  s.  com*/
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Marshaller marshaller = jc.createMarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            marshaller.setSchema(schema);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                new com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper() {

                    @Override
                    public String getPreferredPrefix(final String namespaceUri, final String suggestion,
                            final boolean requirePrefix) {
                        final String subpackage = namespaceUri.replaceFirst("http://www.mymita.com/vaadlets/",
                                "");
                        if (subpackage.equals("1.0.0")) {
                            return "";
                        }
                        return Iterables.getFirst(newArrayList(Splitter.on("/").split(subpackage).iterator()),
                                "");
                    }
                });
        marshaller.marshal(
                new JAXBElement<Vaadlets>(new QName("http://www.mymita.com/vaadlets/1.0.0", "vaadlets", ""),
                        Vaadlets.class, vaadlets),
                aWriter);
    } catch (final JAXBException | SAXException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException("Can't marschal", e);
    }
}

From source file:com.threeglav.sh.bauk.main.StreamHorizonEngine.java

private static final BaukConfiguration findConfiguration() {
    LOG.info(// ww  w.  ja  v  a2  s.  com
            "Trying to find configuration file. First if specified as {} system property and then as {} in classpath",
            CONFIG_FILE_PROP_NAME, DEFAULT_CONFIG_FILE_NAME);
    final String configFile = System.getProperty(CONFIG_FILE_PROP_NAME);
    InputStream is = null;
    if (StringUtil.isEmpty(configFile)) {
        LOG.info(
                "Was not able to find system property {}. Trying to find default configuration {} in classpath",
                CONFIG_FILE_PROP_NAME, DEFAULT_CONFIG_FILE_NAME);
        is = StreamHorizonEngine.class.getClassLoader().getResourceAsStream(DEFAULT_CONFIG_FILE_NAME);
        if (is == null) {
            LOG.error("Was not able to find file {} in the classpath. Unable to start application",
                    DEFAULT_CONFIG_FILE_NAME);
            return null;
        }
        LOG.info("Found configuration file {} in classpath", DEFAULT_CONFIG_FILE_NAME);
    } else {
        LOG.info("Found system property {}={}. Will try to load it as configuration...", CONFIG_FILE_PROP_NAME,
                configFile);
        final File cFile = new File(configFile);
        try {
            if (cFile.exists() && cFile.isFile()) {
                LOG.debug("Loading config file [{}] from file system", configFile);
                is = new FileInputStream(configFile);
            } else {
                LOG.debug("Loading config file [{}] from classpath", configFile);
                is = StreamHorizonEngine.class.getClass().getResourceAsStream(configFile);
            }
            LOG.info("Successfully found configuration [{}] on file system", configFile);
        } catch (final FileNotFoundException fnfe) {
            LOG.error("Was not able to find file {}. Use full, absolute path.", configFile);
            return null;
        }
    }
    if (is == null) {
        return null;
    }
    try {
        LOG.debug("Trying to load configuration from xml file");
        final JAXBContext jaxbContext = JAXBContext.newInstance(BaukConfiguration.class);
        final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory
                .newSchema(StreamHorizonEngine.class.getResource("/bauk_config.xsd"));
        jaxbUnmarshaller.setSchema(schema);
        final BaukConfiguration config = (BaukConfiguration) jaxbUnmarshaller.unmarshal(is);
        LOG.info("Successfully loaded configuration");
        return config;
    } catch (final Exception exc) {
        LOG.error("Exception while loading configuration", exc);
        exc.printStackTrace();
        return null;
    } finally {
        IOUtils.closeQuietly(is);
    }
}