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:gov.nih.nci.ncicb.tcga.dcc.qclive.util.QCliveXMLSchemaValidator.java

protected Boolean validateSchema(final List<Source> schemaSourceList, final Document document,
        final File xmlFile, final QcContext context) throws SAXException, IOException {

    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // instantiate the schema
    Schema schema = factory.newSchema(schemaSourceList.toArray(new Source[] {}));
    // now validate the file against the schema
    // note: supposedly there is a way to just let the XML document figure
    // out its own schema based on what is referred to, but
    // I could not get that to work, which is why I am looking for the
    // schema in the attribute

    final DOMSource source = new DOMSource(document);
    final Validator validator = schema.newValidator();

    // wow this looks dumb, but isValid has to be final to be accessed from
    // within an inner class
    // and this was IDEA's solution to the problem: make it an array and set
    // the first element of the array
    final boolean[] isValid = new boolean[] { true };

    // add error handler that will add validation errors and warnings
    // directly to the QcContext object
    validator.setErrorHandler(new ErrorHandler() {
        public void warning(final SAXParseException exception) {
            context.addWarning(new StringBuilder().append(xmlFile.getName()).append(": ")
                    .append(exception.getMessage()).toString());
        }/* ww w  .  j a  v a2s . c  o m*/

        public void error(final SAXParseException exception) {
            context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR,
                    xmlFile.getName(), new StringBuilder().append(xmlFile.getName()).append(": ")
                            .append(exception.getMessage()).toString()));
            isValid[0] = false;
        }

        public void fatalError(final SAXParseException exception) throws SAXException {
            context.getArchive().setDeployStatus(Archive.STATUS_INVALID);
            throw exception;
        }
    });
    validator.validate(source);
    return isValid[0];
}

From source file:com.evolveum.midpoint.prism.xml.XsdTypeMapper.java

private static <T> Class<T> toJavaType(QName xsdType, boolean errorIfNoMapping) {
    Class<T> javaType = xsdToJavaTypeMap.get(xsdType);
    if (javaType == null) {
        if (errorIfNoMapping && xsdType.getNamespaceURI().equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
            throw new IllegalArgumentException("No type mapping for XSD type " + xsdType);
        } else {//w  w  w  .  j  a  va  2  s .  com
            return null;
        }
    }
    return javaType;
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Validates an xml object graph against its schema. Therefore it reads the
 * version from the root tag and tries to load the related xsd file from the
 * classpath./*w ww .  j  a v a2s . co m*/
 * 
 * @param xmlRootNode
 *            root xml node of the document to validate
 * @throws InvalidConfigurationException
 *             if the validation could not be performed or the xml graph is
 *             invalid against the schema
 */
private static void validateDocumentAgainstSchema(final Document xmlRootNode)
        throws InvalidConfigurationException {
    final Element rootElement = xmlRootNode.getDocumentElement();
    final String version = rootElement.getAttribute("version");
    String schemaFileName = "persistence_" + version.replace(".", "_") + ".xsd";

    try {
        final List validationErrors = new ArrayList();
        final String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
        final StreamSource streamSource = new StreamSource(getStreamFromClasspath(schemaFileName));
        final Schema schemaDefinition = SchemaFactory.newInstance(schemaLanguage).newSchema(streamSource);

        final Validator schemaValidator = schemaDefinition.newValidator();
        schemaValidator.setErrorHandler(new ErrorLogger("XML InputStream", validationErrors));
        schemaValidator.validate(new DOMSource(xmlRootNode));

        if (!validationErrors.isEmpty()) {
            final String exceptionText = "persistence.xml is not conform against the supported schema definitions.";
            throw new InvalidConfigurationException(exceptionText);
        }
    } catch (SAXException e) {
        final String exceptionText = "Error validating persistence.xml against schema defintion, caused by: ";
        throw new InvalidConfigurationException(exceptionText, e);
    } catch (IOException e) {
        final String exceptionText = "Error opening xsd schema file. The given persistence.xml descriptor version "
                + version + " might not be supported yet.";
        throw new InvalidConfigurationException(exceptionText, e);
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.grid.PSCStudyService.java

@Transactional(readOnly = false)
public edu.northwestern.bioinformatics.studycalendar.grid.Study createStudy(
        edu.northwestern.bioinformatics.studycalendar.grid.Study gridStudy)
        throws RemoteException, StudyCreationException {

    if (gridStudy == null) {
        String message = "method parameter  is null";
        logger.error(message);//from   ww w .j a v  a2  s .  c om
        StudyCreationException studyCreationException = new StudyCreationException();
        studyCreationException.setFaultString(message);
        studyCreationException.setFaultReason(message);
        throw studyCreationException;
    }
    StringWriter studyXml = new StringWriter();

    String studyDocumentXml = "";
    try {

        Utils.serializeObject(gridStudy,
                new javax.xml.namespace.QName("http://bioinformatics.northwestern.edu/ns/psc", "study",
                        XMLConstants.W3C_XML_SCHEMA_NS_URI),
                studyXml);

        logger.info("study xml:" + studyXml.toString());

        studyDocumentXml = studyXml.getBuffer().toString();

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(studyDocumentXml.getBytes());

        studyXMLReader.readAndSave(byteArrayInputStream);

    } catch (StudyCalendarValidationException exception) {
        String message = "error while importing the study:studyXml-" + studyDocumentXml + " exception message:"
                + exception.getMessage();
        logger.error(message);
        StudyCreationException studyCreationException = new StudyCreationException();
        studyCreationException.setFaultString(message);
        studyCreationException.setFaultReason(message);
        throw studyCreationException;

    } catch (Exception e) {
        String message = "error while importing the study:assigned_identifier="
                + gridStudy.getAssignedIdentifier() + " exception message:" + e.getMessage();
        logger.error(message);
        throw new RemoteException(message);

    }

    return null;
}

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

public static <T> ValidationResult validate(InputStream xmlStream, 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 o m
    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(xmlStream);
    } 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);

}

From source file:eu.delving.x3ml.X3MLEngine.java

private static SchemaFactory schemaFactory() {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {/*from  w  w w  .j  a v a  2s.  c  o  m*/
        //            schemaFactory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.CTA_FULL_XPATH_CHECKING_FEATURE, true);
        schemaFactory.setResourceResolver(new ResourceResolver());
    } catch (Exception e) {
        throw new RuntimeException("Configuring schema factory", e);
    }
    return schemaFactory;
}

From source file:com.rest4j.ApiFactory.java

/**
 * Create the API instance. The XML describing the API is read, preprocessed, analyzed for errors,
 * and the internal structures for Java object marshalling and unmarshalling are created, as
 * well as endpoint mappings.//from w  ww .  j  a va  2  s.c o m
 *
 * @return The API instance
 * @throws ConfigurationException When there is a problem with your XML description.
 */
public API createAPI() throws ConfigurationException {
    try {
        JAXBContext context;
        if (extObjectFactory == null)
            context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class);
        else
            context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class, extObjectFactory);
        Document xml = getDocument();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Source apiXsdSource = new StreamSource(getClass().getResourceAsStream("api.xsd"));
        List<Source> xsds = new ArrayList<Source>();
        xsds.add(apiXsdSource);
        Schema schema;
        if (!StringUtils.isEmpty(extSchema)) {
            xsds.add(new StreamSource(getClass().getClassLoader().getResourceAsStream(extSchema)));
        }
        xsds.add(new StreamSource(getClass().getResourceAsStream("html.xsd")));
        schema = schemaFactory.newSchema(xsds.toArray(new Source[xsds.size()]));

        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        JAXBElement<com.rest4j.impl.model.API> element = (JAXBElement<com.rest4j.impl.model.API>) unmarshaller
                .unmarshal(xml);
        com.rest4j.impl.model.API root = element.getValue();
        APIImpl api;
        api = new APIImpl(root, pathPrefix, serviceProvider,
                factories.toArray(new ObjectFactory[factories.size()]),
                fieldFilters.toArray(new FieldFilter[fieldFilters.size()]), permissionChecker);
        return api;
    } catch (javax.xml.bind.UnmarshalException e) {
        if (e.getLinkedException() instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e.getLinkedException();
            throw new ConfigurationException("Cannot parse " + apiDescriptionXml, spe);
        }
        throw new AssertionError(e);
    } catch (ConfigurationException e) {
        throw e;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:ar.com.tadp.xml.rinzo.core.resources.validation.XMLStringValidator.java

private Validator createValidator(StreamSource[] sources) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    sf.setFeature("http://apache.org/xml/features/xinclude", true);
    Schema schema = sf.newSchema(sources);
    return schema.newValidator();
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Validate the configuration against XML Schema.
 *
 * @throws ConfigException if not valid//from   w  w  w.j  av  a2  s  . c  o  m
 */
private void validateXMLConfiguration(InputStream xmlConfigurationStream) throws IOException, ConfigException {
    assert xmlConfigurationStream != null;
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        final Schema schema = sf
                .newSchema(MathMLCanonicalizer.class.getResource(Settings.getProperty("configSchema")));

        final Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlConfigurationStream));
    } catch (SAXException ex) {
        throw new ConfigException("configuration not valid\n" + ex.getMessage(), ex);
    }
}

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

@Override
public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[XSD.length];
    for (int i = 0; i < XSD.length; i++) {
        schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
    }//from   ww  w .j  a v  a  2s  .com
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(context, document));
}