Example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

List of usage examples for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

Introduction

In this page you can find the example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Prototype

String W3C_XML_SCHEMA_NS_URI

To view the source code for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Click Source Link

Document

W3C XML Schema Namespace URI.

Usage

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java

/**
 * Validates configuration XML against XML defined XSD schema.
 *
 * @param config//ww w. j  a v a 2 s. com
 *            {@link InputStream} to get configuration data from
 * @return map of found validation errors
 * @throws SAXException
 *             if there was an error parsing the configuration
 * @throws IOException
 *             if there is an error reading the configuration data
 */
public static Map<OpLevel, List<SAXParseException>> validate(InputStream config)
        throws SAXException, IOException {
    final Map<OpLevel, List<SAXParseException>> validationErrors = new HashMap<>();
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema();
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.WARNING, exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.ERROR, exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.FATAL, exception);
            }

            private void handleValidationError(OpLevel level, SAXParseException exception) {
                List<SAXParseException> lErrorsList = validationErrors.get(level);
                if (lErrorsList == null) {
                    lErrorsList = new ArrayList<>();
                    validationErrors.put(level, lErrorsList);
                }

                lErrorsList.add(exception);
            }
        });
        validator.validate(new StreamSource(config));
    } finally {
        if (config.markSupported()) {
            config.reset();
        }
    }

    return validationErrors;
}

From source file:io.inkstand.jcr.util.JCRContentLoaderTest.java

@Test(expected = InkstandRuntimeException.class)
@Ignore/*  w w w. java  2s. c o m*/
public void testLoadContent_validating_invalidResource() throws Exception {
    // prepare
    final URL resource = getClass().getResource("test01_inkstandJcrImport_v1-0_invalid.xml");
    final Session actSession = repository.login("admin", "admin");
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(getClass().getResource("inkstandJcrImport_v1-0.xsd"));
    // act
    subject.setSchema(schema);
    subject.loadContent(actSession, resource);
}

From source file:org.raml.parser.rule.SchemaRule.java

@Override
public List<ValidationResult> doValidateValue(ScalarNode node) {
    String value = node.getValue();
    List<ValidationResult> validationResults = super.doValidateValue(node);

    IncludeInfo globaSchemaIncludeInfo = null;
    ScalarNode schemaNode = getGlobalSchemaNode(value);
    if (schemaNode == null) {
        schemaNode = node;/*from w w w  .j  av  a 2  s .  c  o m*/
    } else {
        value = schemaNode.getValue();
        if (schemaNode.getTag().startsWith(INCLUDE_APPLIED_TAG)) {
            globaSchemaIncludeInfo = new IncludeInfo(schemaNode.getTag());
        }
    }
    if (value == null || isCustomTag(schemaNode.getTag())) {
        return validationResults;
    }

    String mimeType = ((ScalarNode) getParentTupleRule().getKey()).getValue();
    if (mimeType.contains("json")) {
        try {
            JsonNode jsonNode = JsonLoader.fromString(value);
            ProcessingReport report = VALIDATOR.validateSchema(jsonNode);
            if (!report.isSuccess()) {
                StringBuilder msg = new StringBuilder("invalid JSON schema");
                msg.append(getSourceErrorDetail(node));
                for (ProcessingMessage processingMessage : report) {
                    msg.append("\n").append(processingMessage.toString());
                }
                validationResults
                        .add(getErrorResult(msg.toString(), getLineOffset(schemaNode), globaSchemaIncludeInfo));
            }
        } catch (JsonParseException jpe) {
            String msg = "invalid JSON schema" + getSourceErrorDetail(node) + jpe.getOriginalMessage();
            JsonLocation loc = jpe.getLocation();
            validationResults.add(
                    getErrorResult(msg, getLineOffset(schemaNode) + loc.getLineNr(), globaSchemaIncludeInfo));
        } catch (IOException e) {
            String prefix = "invalid JSON schema" + getSourceErrorDetail(node);
            validationResults.add(getErrorResult(prefix + e.getMessage(), UNKNOWN, globaSchemaIncludeInfo));
        }
    } else if (mimeType.contains("xml")) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            factory.newSchema(new StreamSource(new StringReader(value)));
        } catch (SAXParseException e) {
            String msg = "invalid XML schema" + getSourceErrorDetail(node) + e.getMessage();
            validationResults.add(
                    getErrorResult(msg, getLineOffset(schemaNode) + e.getLineNumber(), globaSchemaIncludeInfo));
        } catch (SAXException e) {
            String msg = "invalid XML schema" + getSourceErrorDetail(node);
            validationResults.add(getErrorResult(msg, getLineOffset(schemaNode), globaSchemaIncludeInfo));
        }
    }
    return validationResults;
}

From source file:org.openwms.core.configuration.file.ApplicationPreferenceTest.java

/**
 * Just test to validate the given XML file against the schema declaration. If the XML file is not compliant with the schema, the test
 * will fail./*from   w  ww.  ja v  a  2s.  co m*/
 *
 * @throws Exception any error
 */
@Test
public void testReadPreferences() throws Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(ResourceUtils.getFile("classpath:preferences.xsd"));
    // Schema schema = schemaFactory.newSchema(new
    // URL("http://www.openwms.org/schema/preferences.xsd"));
    JAXBContext ctx = JAXBContext.newInstance("org.openwms.core.configuration.file");
    Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setSchema(schema);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override
        public boolean handleEvent(ValidationEvent event) {
            RuntimeException ex = new RuntimeException(event.getMessage(), event.getLinkedException());
            LOGGER.error(ex.getMessage());
            throw ex;
        }
    });

    Preferences prefs = Preferences.class.cast(unmarshaller
            .unmarshal(ResourceUtils.getFile("classpath:org/openwms/core/configuration/file/preferences.xml")));
    for (AbstractPreference pref : prefs.getApplications()) {
        LOGGER.info(pref.toString());
    }
    for (AbstractPreference pref : prefs.getModules()) {
        LOGGER.info(pref.toString());
    }
    for (AbstractPreference pref : prefs.getUsers()) {
        LOGGER.info(pref.toString());
    }
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }//from   w ww.ja  v  a  2s.c o  m
    validator.validate(new JAXBSource(context, document));
}

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

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {// ww w .  j  a  v  a 2  s .co m
        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:io.aino.agents.core.config.InputStreamConfigBuilder.java

/**
 * Validates the config file against XSD schema.
 *
 * @param stream InputStream to config file.
 *///from   w  w w .  j  ava 2 s  . c o m
private void validateSchema(InputStream stream) {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        InputStream xsdStream = this.getClass().getClassLoader().getResourceAsStream(LOGGER_SCHEMA);
        Schema schema = factory.newSchema(new StreamSource(xsdStream));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(stream));
    } catch (SAXException e) {
        throw new InvalidAgentConfigException("Failed to validate logger config.", e);
    } catch (IOException e) {
        throw new InvalidAgentConfigException("Failed to validate logger config.", e);
    }
}

From source file:mx.bigdata.sat.cfdi.CFDv3.java

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[] { new StreamSource(getClass().getResourceAsStream(XSD)),
            new StreamSource(getClass().getResourceAsStream(XSD_TFD)) };
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }// w  ww.ja  va 2 s.  com
    validator.validate(new JAXBSource(context, document));
}

From source file:org.mitre.stix.STIXSchema.java

/**
 * Private constructor to permit a single STIXSchema to exists.
 *//* w w w .  j a v  a 2s .  c o m*/
private STIXSchema() {

    this.version = ((Version) this.getClass().getPackage().getAnnotation(Version.class)).schema();

    ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(
            this.getClass().getClassLoader());
    Resource[] schemaResources;

    try {
        schemaResources = patternResolver.getResources("classpath:schemas/v" + version + "/**/*.xsd");

        prefixSchemaBindings = new HashMap<String, String>();

        String url, prefix, targetNamespace;
        Document schemaDocument;
        NamedNodeMap attributes;
        Node attribute;

        for (Resource resource : schemaResources) {

            url = resource.getURL().toString();

            schemaDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(resource.getInputStream());

            schemaDocument.getDocumentElement().normalize();

            attributes = schemaDocument.getDocumentElement().getAttributes();

            for (int i = 0; i < attributes.getLength(); i++) {

                attribute = attributes.item(i);

                targetNamespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace");

                if (attribute.getNodeName().startsWith("xmlns:")
                        && attribute.getNodeValue().equals(targetNamespace)) {

                    prefix = attributes.item(i).getNodeName().split(":")[1];

                    if ((prefixSchemaBindings.containsKey(prefix))
                            && (prefixSchemaBindings.get(prefix).split("schemas/v" + version + "/")[1]
                                    .startsWith("external"))) {

                        continue;

                    }

                    LOGGER.fine("     adding: " + prefix + " :: " + url);

                    prefixSchemaBindings.put(prefix, url);
                }
            }
        }

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

        Source[] schemas = new Source[prefixSchemaBindings.values().size()];

        int i = 0;
        for (String schemaLocation : prefixSchemaBindings.values()) {
            schemas[i++] = new StreamSource(schemaLocation);
        }

        schema = factory.newSchema(schemas);

        validator = schema.newValidator();
        validator.setErrorHandler(new ValidationErrorHandler());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(FileInputStream xmlPath, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;/*from w w  w  .j  a  v  a2  s  . c  om*/
    ValidationResult result;
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlPath);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}