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:org.sonar.plugins.xml.checks.XmlSchemaCheck.java

/**
 * Create xsd schema for a list of schema's.
 *//*from  w w  w  .j av  a2 s.com*/
private static Schema createSchema(String[] schemaList) {

    final String cacheKey = StringUtils.join(schemaList, ",");
    // first try to load a cached schema.
    Schema schema = cachedSchemas.get(cacheKey);
    if (schema != null) {
        return schema;
    }

    List<Source> schemaSources = new ArrayList<Source>();

    // load each schema in a StreamSource.
    for (String schemaReference : schemaList) {
        InputStream input = SchemaResolver.getBuiltinSchema(schemaReference);
        if (input == null) {
            throw new SonarException("Could not load schema: " + schemaReference);
        }
        schemaSources.add(new StreamSource(input));
    }

    // create a schema for the list of StreamSources.
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new SchemaResolver());

        schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        cachedSchemas.put(cacheKey, schema);
        return schema;
    } catch (SAXException e) {
        throw new SonarException(e);
    }
}

From source file:org.talend.mdm.commmon.metadata.MetadataRepository.java

public void load(InputStream inputStream, ValidationHandler handler) {
    if (inputStream == null) {
        throw new IllegalArgumentException("Input stream can not be null.");
    }//from  www  .  j a v a  2  s  .com
    // Validates data model using shared studio / server classes
    // Load user defined data model now
    Map<String, Object> options = new HashMap<String, Object>();
    options.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
    XSDParser parse = new XSDParser(options);
    parse.parse(inputStream);
    XSDSchema schema = parse.getSchema();
    if (schema == null) {
        throw new IllegalStateException(
                "No schema parsed from input (make sure stream contains a data model).");
    }
    schema.validate();
    EList<XSDDiagnostic> diagnostics = schema.getDiagnostics();
    for (XSDDiagnostic diagnostic : diagnostics) {
        XSDDiagnosticSeverity severity = diagnostic.getSeverity();
        if (XSDDiagnosticSeverity.ERROR_LITERAL.equals(severity)) {
            handler.error((TypeMetadata) null, "XSD validation error: " + diagnostic.getMessage(), null, -1, -1,
                    ValidationError.XML_SCHEMA);
        } else if (XSDDiagnosticSeverity.WARNING_LITERAL.equals(severity)) {
            handler.error((TypeMetadata) null, "XSD validation warning: " + diagnostic.getMessage(), null, -1,
                    -1, ValidationError.XML_SCHEMA);
        }
    }
    XmlSchemaWalker.walk(schema, this);
    // TMDM-4876 Additional processing for entity inheritance
    resolveAdditionalSuperTypes(this);
    // "Freeze" all types (ensure all soft references now point to actual types in the repository).
    nonInstantiableTypes.put(getUserNamespace(), freezeTypes(nonInstantiableTypes.get(getUserNamespace())));
    // "Freeze" all reusable type usages in the data model.
    freezeUsages();
    entityTypes.put(getUserNamespace(), freezeTypes(entityTypes.get(getUserNamespace())));
    // Validate types
    for (TypeMetadata type : getUserComplexTypes()) {
        if (!XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(type.getNamespace())) {
            type.validate(handler);
        }
    }
    for (TypeMetadata type : getNonInstantiableTypes()) {
        if (!XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(type.getNamespace())) {
            type.validate(handler);
        }
    }
    ValidationFactory.getRule(this).perform(handler); // Perform data model-scoped validation (e.g. cycles).
    handler.end();
    if (handler.getErrorCount() != 0) {
        LOGGER.error("Could not parse data model (" + handler.getErrorCount() + " error(s) found).");
    }
}

From source file:org.talend.mdm.commmon.metadata.MetadataRepository.java

@Override
public void visitComplexType(XSDComplexTypeDefinition type) {
    String typeName = type.getName();
    boolean isNonInstantiableType = currentTypeStack.isEmpty();
    if (isNonInstantiableType) {
        if (nonInstantiableTypes.get(getUserNamespace()) != null) {
            if (nonInstantiableTypes.get(getUserNamespace()).containsKey(typeName)) {
                // Ignore another definition of type (already processed).
                return;
            }/*from   ww  w.j av  a2  s.  c om*/
        }
        // There's no current 'entity' type being parsed, this is a complex type not to be used for entity but
        // might be referenced by others entities (for fields, inheritance...).
        ComplexTypeMetadata nonInstantiableType = new ComplexTypeMetadataImpl(targetNamespace, typeName, false,
                type.isAbstract());
        // Keep line and column of definition
        nonInstantiableType.setData(XSD_LINE_NUMBER, XSDParser.getStartLine(type.getElement()));
        nonInstantiableType.setData(XSD_COLUMN_NUMBER, XSDParser.getStartColumn(type.getElement()));
        nonInstantiableType.setData(XSD_DOM_ELEMENT, type.getElement());
        addTypeMetadata(nonInstantiableType);
        currentTypeStack.push(nonInstantiableType);
        // If type is used, declare usage
        List<ComplexTypeMetadata> usages = entityTypeUsage.get(type);
        for (ComplexTypeMetadata usage : usages) {
            nonInstantiableType.declareUsage(usage);
        }
    } else {
        // Keep track of the complex type used for entity type (especially for inheritance).
        if (typeName != null) {
            currentTypeStack.peek().setData(MetadataRepository.COMPLEX_TYPE_NAME, typeName);
        }
    }
    XSDComplexTypeContent particle = type.getContent();
    if (particle instanceof XSDParticle) {
        XSDParticle currentParticle = (XSDParticle) particle;
        if (currentParticle.getTerm() instanceof XSDModelGroup) {
            XSDModelGroup group = (XSDModelGroup) currentParticle.getTerm();
            EList<XSDParticle> particles = group.getContents();
            for (XSDParticle p : particles) {
                XSDParticleContent particleContent = p.getContent();
                XmlSchemaWalker.walk(particleContent, this);
            }
        }
    } else if (particle != null) {
        throw new IllegalArgumentException(
                "Not supported XML Schema particle: " + particle.getClass().getName());
    }
    // Adds the type information about super types.
    XSDTypeDefinition contentModel = type.getBaseTypeDefinition();
    if (contentModel != null) {
        if (!XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(contentModel.getTargetNamespace())
                && !Types.ANY_TYPE.equals(contentModel.getName())) {
            SoftTypeRef superType = new SoftTypeRef(this, contentModel.getTargetNamespace(),
                    contentModel.getName(), false);
            if (currentTypeStack.peek() instanceof ContainedComplexTypeMetadata) {
                superType.declareUsage(currentTypeStack.peek());
            }
            currentTypeStack.peek().addSuperType(superType);
            particle = type.getContent();
            if (particle instanceof XSDParticle) {
                XSDParticle currentParticle = (XSDParticle) particle;
                if (currentParticle.getTerm() instanceof XSDModelGroup) {
                    XSDModelGroup group = (XSDModelGroup) currentParticle.getTerm();
                    EList<XSDParticle> particles = group.getContents();
                    for (XSDParticle p : particles) {
                        XSDParticleContent particleContent = p.getContent();
                        XmlSchemaWalker.walk(particleContent, this);
                    }
                }
            } else if (particle != null) {
                throw new IllegalArgumentException(
                        "Not supported XML Schema particle: " + particle.getClass().getName());
            }
        }
    }
    if (isNonInstantiableType) {
        currentTypeStack.pop();
    }
}

From source file:org.talend.mdm.commmon.metadata.MetadataRepository.java

@Override
public void visitElement(XSDElementDeclaration element) {
    if (currentTypeStack.isEmpty()) { // "top level" elements means new MDM entity type
        String typeName = element.getName();
        if (getComplexType(typeName) != null) { // Don't process twice type
            return;
        }//from   w  ww  .java2s  .  c  om
        // If entity's type is abstract
        boolean isAbstract = false;
        XSDTypeDefinition typeDefinition = element.getTypeDefinition();
        if (typeDefinition != null && typeDefinition instanceof XSDComplexTypeDefinition) {
            isAbstract = ((XSDComplexTypeDefinition) typeDefinition).isAbstract();
        }
        // Id fields
        Map<String, XSDXPathDefinition> idFields = new LinkedHashMap<String, XSDXPathDefinition>();
        EList<XSDIdentityConstraintDefinition> constraints = element.getIdentityConstraintDefinitions();
        for (XSDIdentityConstraintDefinition constraint : constraints) {
            EList<XSDXPathDefinition> fields = constraint.getFields();
            for (XSDXPathDefinition field : fields) {
                idFields.put(field.getValue(), field);
            }
        }
        XmlSchemaAnnotationProcessorState state;
        try {
            XSDAnnotation annotation = element.getAnnotation();
            state = new XmlSchemaAnnotationProcessorState();
            for (XmlSchemaAnnotationProcessor processor : XML_ANNOTATIONS_PROCESSORS) {
                processor.process(this, null, annotation, state);
            }
        } catch (Exception e) {
            throw new RuntimeException(
                    "Annotation processing exception while parsing info for type '" + typeName + "'.", e);
        }
        // If write is not allowed for everyone, at least add "administration".
        if (state.getAllowWrite().isEmpty()) {
            state.getAllowWrite().add(ICoreConstants.ADMIN_PERMISSION);
        }
        ComplexTypeMetadata type = new ComplexTypeMetadataImpl(targetNamespace, typeName, state.getAllowWrite(),
                state.getDenyCreate(), state.getHide(), state.getDenyPhysicalDelete(),
                state.getDenyLogicalDelete(), state.getSchematron(), state.getPrimaryKeyInfo(),
                state.getLookupFields(), true, isAbstract, state.getWorkflowAccessRights());
        // Register parsed localized labels
        Map<Locale, String> localeToLabel = state.getLocaleToLabel();
        for (Map.Entry<Locale, String> entry : localeToLabel.entrySet()) {
            type.registerName(entry.getKey(), entry.getValue());
        }
        // Register parsed localized descriptions
        Map<Locale, String> localeToDescription = state.getLocaleToDescription();
        for (Map.Entry<Locale, String> entry : localeToDescription.entrySet()) {
            type.registerDescription(entry.getKey(), entry.getValue());
        }
        // Keep line and column of definition
        type.setData(XSD_LINE_NUMBER, XSDParser.getStartLine(element.getElement()));
        type.setData(XSD_COLUMN_NUMBER, XSDParser.getStartColumn(element.getElement()));
        type.setData(XSD_DOM_ELEMENT, element.getElement());
        addTypeMetadata(type);
        // Keep usage information
        entityTypeUsage.get(element.getType()).add(type);
        // Walk the fields
        currentTypeStack.push(type);
        {
            XmlSchemaWalker.walk(element.getType(), this);
        }
        currentTypeStack.pop();
        // Super types
        XSDElementDeclaration substitutionGroup = element.getSubstitutionGroupAffiliation();
        if (substitutionGroup != null
                && !XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(substitutionGroup.getTargetNamespace())
                && !Types.ANY_TYPE.equals(substitutionGroup.getName())) {
            if (!substitutionGroup.getResolvedElementDeclaration().equals(element)) {
                SoftTypeRef superType = new SoftTypeRef(this, substitutionGroup.getTargetNamespace(),
                        substitutionGroup.getName(), true);
                type.addSuperType(superType);
            }
        }
        // Register keys (TMDM-4470).
        for (Map.Entry<String, XSDXPathDefinition> unresolvedId : idFields.entrySet()) {
            SoftIdFieldRef keyField = new SoftIdFieldRef(this, type.getName(), unresolvedId.getKey());
            // Keep line and column of definition
            keyField.setData(XSD_LINE_NUMBER, XSDParser.getStartLine(unresolvedId.getValue().getElement()));
            keyField.setData(XSD_COLUMN_NUMBER, XSDParser.getStartColumn(unresolvedId.getValue().getElement()));
            keyField.setData(XSD_DOM_ELEMENT, unresolvedId.getValue().getElement());
            type.registerKey(keyField);
        }
        // TMDM-6264: An entity type without any key info is a element maybe referenced by others, but never an
        // entity.
        if (type.getKeyFields().isEmpty() && type.getSuperTypes().isEmpty()) {
            Map<String, TypeMetadata> userEntityTypes = entityTypes.get(getUserNamespace());
            if (userEntityTypes != null) {
                userEntityTypes.remove(type.getName());
            }
        }
    } else { // Non "top level" elements means fields for the MDM entity type being parsed
        FieldMetadata fieldMetadata;
        int minOccurs = ((XSDParticle) element.getContainer()).getMinOccurs();
        int maxOccurs = ((XSDParticle) element.getContainer()).getMaxOccurs();
        if (element.isElementDeclarationReference() && currentTypeStack.peek().getName()
                .equals(element.getResolvedElementDeclaration().getName())) {
            return;
        }
        if (element.getResolvedElementDeclaration() != null
                && element.getResolvedElementDeclaration().getTargetNamespace() == null) {
            fieldMetadata = createFieldMetadata(element.getResolvedElementDeclaration(),
                    currentTypeStack.peek(), minOccurs, maxOccurs);
        } else {
            fieldMetadata = createFieldMetadata(element, currentTypeStack.peek(), minOccurs, maxOccurs);
        }
        currentTypeStack.peek().addField(fieldMetadata);
    }
}

From source file:org.talend.mdm.commmon.metadata.MetadataUtils.java

/**
 * Returns the top level type for <code>type</code> parameter: this method returns the type before <i>anyType</i>
 * in type hierarchy. This does not apply to types declared in {@link XMLConstants#W3C_XML_SCHEMA_NS_URI}.
 * <ul>//from  www  .  j  a  va  2s .com
 * <li>In an MDM entity B inherits from A, getSuperConcreteType(B) returns A.</li>
 * <li>If a simple type LimitedString extends xsd:string, getSuperConcreteType(LimitedString) returns xsd:string.</li>
 * <li>getSuperConcreteType(xsd:long) returns xsd:long (even if xsd:long extends xsd:decimal).</li>
 * <li>If the type does not have any super type, this method returns the <code>type</code> parameter.</li>
 * </ul>
 *
 * @param type A non null type that may have super types.
 * @return The higher type in inheritance tree before <i>anyType</i>.
 */
public static TypeMetadata getSuperConcreteType(TypeMetadata type) {
    if (type == null) {
        return null;
    }
    // Move up the inheritance tree to find the "most generic" type (used when simple types inherits from XSD types,
    // in this case, the XSD type is interesting, not the custom one).
    while (!XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(type.getNamespace()) && !type.getSuperTypes().isEmpty()) {
        type = type.getSuperTypes().iterator().next();
    }
    return type;
}

From source file:org.talend.mdm.commmon.metadata.MetadataUtils.java

/**
 * Checks whether provided <code>field</code> is using a primitive type (i.e. a XSD datatype) or not.
 * @param field A {@link org.talend.mdm.commmon.metadata.FieldMetadata field}.
 * @return <code>true</code> if field's type is a XSD datatype, <code>false</code> otherwise.
 *///from w w w .jav a2 s  . c o m
public static boolean isPrimitiveTypeField(FieldMetadata field) {
    TypeMetadata fieldType = getSuperConcreteType(field.getType());
    return XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(fieldType.getNamespace());
}

From source file:org.talend.mdm.commmon.metadata.UnresolvedFieldMetadata.java

@Override
public TypeMetadata getType() {
    return new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.ANY_TYPE);
}

From source file:org.tinygroup.jspengine.xmlparser.ParserUtils.java

private static Schema getSchema(String schemaPublicId) throws SAXException {

    Schema schema = schemaCache.get(schemaPublicId);
    if (schema == null) {
        synchronized (schemaCache) {
            schema = schemaCache.get(schemaPublicId);
            if (schema == null) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                schemaFactory.setResourceResolver(new MyLSResourceResolver());
                schemaFactory.setErrorHandler(new MyErrorHandler());
                schema = schemaFactory.newSchema(new StreamSource(
                        ParserUtils.class.getResourceAsStream(schemaResourcePrefix + schemaPublicId)));
                schemaCache.put(schemaPublicId, schema);
            }/*from   w ww . ja va 2s.  c o  m*/
        }
    }

    return schema;
}

From source file:org.tonguetied.datatransfer.exporting.ResourcesTemplateTest.java

@Override
public void runAssertions() throws Exception {
    final Collection<File> files = FileUtils.listFiles(getOutputDir().getAbsoluteFile(), getOutputExtensions(),
            false);//  w  ww .ja  va2 s . c  o m
    assertEquals(3, files.size());
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Validator validator;
    StreamSource source;
    Document document;
    for (File file : files) {
        validator = new Validator(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        //            StreamSource schemaSource = new StreamSource(new File("D:/work/TongueTied/Application/resources/templates/freemarker/export/resxSchema.xml"));
        //            validator.addSchemaSource(schemaSource);
        //            boolean test = validator.isSchemaValid();
        source = new StreamSource(file);
        document = builder.parse(file);
        //            boolean isValid = validator.isInstanceValid(source);
        //            if (!isValid)
        //                for (Object error : validator.getInstanceErrors(source))
        //                    logger.error(error);
        //            assertTrue(isValid);
        //                bais = new ByteArrayInputStream(bytes);
        //                validator = new Validator(xml);
        //                validator.useXMLSchema(true);
        //                validator.setJAXP12SchemaSource(new File("D:/work/TongueTied/Application/resources/templates/freemarker/export/resxSchema.xml"));
        //                assertTrue("resource xml is invalid", validator.isValid());
        //                actual = new Properties();
        //                actual.load(bais);
        if ("ResourceTemplateTest.en-US.resx".equals(file.getName())) {
            assertXpathExists("/root/data[@name=\"akeyword\"]", document);
            assertXpathEvaluatesTo("split line \\\ncontinue on second", "/root/data[@name=\"akeyword\"]/value",
                    document);
            assertXpathExists("/root/data[@name=\"anotherkeyword\"]", document);
            assertXpathEvaluatesTo("", "/root/data[@name=\"anotherkeyword\"]/value", document);
            assertXpathExists("/root/data[@name=\"KeywordThree\"]", document);
            assertXpathEvaluatesTo("", "/root/data[@name=\"KeywordThree\"]/value", document);
        } else if ("ResourceTemplateTest.en-CN.resx".equals(file.getName())) {
            assertXpathExists("/root/data[@name=\"akeyword\"]", document);
            assertXpathEvaluatesTo("translation 1_1", "/root/data[@name=\"akeyword\"]/value", document);
            assertXpathExists("/root/data[@name=\"anotherkeyword\"]", document);
            assertXpathEvaluatesTo("unix linebreak \\\nanother line",
                    "/root/data[@name=\"anotherkeyword\"]/value", document);
            assertXpathExists("/root/data[@name=\"KeywordThree\"]", document);
            assertXpathEvaluatesTo("blah blah", "/root/data[@name=\"KeywordThree\"]/value", document);
        } else if ("ResourceTemplateTest.zh-CHS.resx".equals(file.getName())) {
            assertXpathExists("/root/data[@name=\"anotherkeyword\"]", document);
            assertXpathEvaluatesTo("xml < ! & \" '>", "/root/data[@name=\"anotherkeyword\"]/value", document);
            assertXpathExists("/root/data[@name=\"KeywordThree\"]", document);
            assertXpathEvaluatesTo("translation 3_1", "/root/data[@name=\"KeywordThree\"]/value", document);
        } else {
            fail("Unexpected file: " + file.getPath());
        }
    }
}

From source file:org.tridas.io.formats.tridasjson.TridasJSONFile.java

public void validate() throws ImpossibleConversionException {
    Schema schema = null;/*from  w w w. j  a v a  2s.c o m*/

    // Validate output against schema first
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL file = IOUtils.getFileInJarURL("schemas/tridas.xsd");
    if (file == null) {
        log.error("Could not find schema file");
    } else {
        try {
            schema = factory.newSchema(file);
        } catch (SAXException e) {
            log.error("Error getting TRiDaS schema for validation, not using.", e);
            throw new ImpossibleConversionException(I18n.getText("fileio.errorGettingSchema"));
        }
    }

    swriter = new StringWriter();
    // Marshaller code goes here...
    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance("org.tridas.schema");
        Marshaller m = jc.createMarshaller();
        m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new TridasNamespacePrefixMapper());
        if (schema != null) {
            m.setSchema(schema);
        }
        m.marshal(getTridasContainer(), swriter);

    } catch (Exception e) {
        log.error("Jaxb error", e);

        String cause = e.getCause().getMessage();
        if (cause != null) {
            throw new ImpossibleConversionException(I18n.getText("fileio.jaxbError") + " " + cause);
        } else {
            throw new ImpossibleConversionException(I18n.getText("fileio.jaxbError"));
        }

    }

}