Java Code Examples for org.apache.ws.commons.schema.XmlSchema#getTargetNamespace()

The following examples show how to use org.apache.ws.commons.schema.XmlSchema#getTargetNamespace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WSDLSchemaManager.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void addXmlSchemaImport(XmlSchema rootSchema, XmlSchema schema, File file) {
    // Make sure we haven't already imported the schema.
    String importNamespace = schema.getTargetNamespace();
    boolean included = false;
    for (XmlSchemaExternal ext : rootSchema.getExternals()) {
        if (ext instanceof XmlSchemaImport) {
            XmlSchemaImport imp = (XmlSchemaImport)ext;
            if (imp.getNamespace().equals(importNamespace)) {
                included = true;
                break;
            }
        }
    }

    if (!included) {
        XmlSchemaImport importSchema = new XmlSchemaImport(rootSchema);
        if (!ignoreImports) {
            importSchema.setSchemaLocation(file.toURI().toString());
        }
        importSchema.setNamespace(schema.getTargetNamespace());
    }
    if (!importedSchemas.containsKey(file)) {
        importedSchemas.put(file, schema);
    }
}
 
Example 2
Source File: TypesUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Scope generateAnonymousScopedName(Scope scope, XmlSchema schema) {
    Scope scopedName = null;
    XmlSchemaType anonSchemaType = null;
    int id = 0;
    do {
        id++;
        StringBuilder name = new StringBuilder();
        name.append('_');
        name.append("Anon").append(Integer.toString(id));
        name.append('_');
        name.append(scope.tail());
        scopedName = new Scope(scope.getParent(), name.toString());
        QName scopedQName = new QName(schema.getTargetNamespace(), scopedName.toString());
        anonSchemaType = schema.getTypeByName(scopedQName);
    } while (anonSchemaType != null);

    return scopedName;
}
 
Example 3
Source File: WSDLToCorbaHelper.java    From cxf with Apache License 2.0 6 votes vote down vote up
public XmlSchemaType getSchemaType(QName name) throws Exception {
    XmlSchemaType type = null;
    for (XmlSchema xmlSchema : xmlSchemaList.getXmlSchemas()) {
        String nspace = name.getNamespaceURI();
        if (nspace == null) {
            nspace = xmlSchema.getTargetNamespace();
        }
        //QName tname = createQName(nspace, name.getLocalPart(), "xsd");
        QName tname = createQName(nspace, name.getLocalPart(), "");
        type = findSchemaType(tname);
        if (type != null) {
            break;
        }
    }
    return type;
}
 
Example 4
Source File: AbstractXmlSchemaExtractorTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
protected void validateTargetSchemas(XmlSchemaElement testElement) throws XmlSchemaSerializer.XmlSchemaSerializerException, IOException, SAXException {

        final String testNamespace = testElement.getQName().getNamespaceURI();
        final XmlSchema[] schemas = xmlSchemaExtractor.getTargetSchemas().getXmlSchemas();

        for (XmlSchema targetSchema : schemas) {
            final String targetNamespace = targetSchema.getTargetNamespace();
            // skip XSD and XML namespaces, which break in StaxUtils.toString below
            if (targetNamespace.equals(XMLConstants.XML_NS_URI) || targetNamespace.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
                continue;
            }
            final Document schemaDocument = targetSchema.getSchemaDocument();
            if (targetNamespace.isEmpty()) {
                // remove invalid xmlns:tns="" attribute or it breaks StaxUtils.toString below
                schemaDocument.getDocumentElement().removeAttribute("xmlns:tns");
            }
            final String schemaString = StaxUtils.toString(schemaDocument);

            // validate against schema XSD
            XmlSchemaTestHelper.validateSchema(schemaString);

            if (testNamespace.equals(targetNamespace)) {
                // must have element in test namespace
                assertThat(targetSchema.getElements()).isNotEmpty();
            }

            // all schemas must not be empty
            assertThat(targetSchema.getItems()).isNotEmpty();

            // check that all targetSchema types and elements are present in sourceSchema
            final List<Element> sourceNodes = sourceSchemaNodes.get(targetNamespace);
            if (sourceNodes == null) {
                if (!targetNamespace.equals(testElement.getQName().getNamespaceURI())) {
                    fail("Unexpected missing source schema " + targetNamespace);
                }
            } else {
                XmlSchemaTestHelper.checkSubsetSchema(schemaDocument, sourceNodes);
            }
        }
    }
 
Example 5
Source File: JAXBDataBinding.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void addedEnumClassToCollector(SchemaCollection schemaCollection,
                                       ClassNameAllocatorImpl allocator) {
    //for (Element schemaElement : schemaList.values()) {
    for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
        String targetNamespace = schema.getTargetNamespace();
        if (StringUtils.isEmpty(targetNamespace)) {
            continue;
        }
        String packageName = context.mapPackageName(targetNamespace);
        if (!addedToClassCollector(packageName)) {
            allocator.assignClassName(packageName, "*");
        }
    }
}
 
Example 6
Source File: XmlSchemaUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * By convention, an element that is named in its schema's TNS can have a 'name' but
 * no QName. This can get inconvenient for consumers who want to think about qualified names.
 * Unfortunately, XmlSchema elements, unlike types, don't store a reference to their containing
 * schema.
 * @param element
 * @param schema
 */
public static QName getElementQualifiedName(XmlSchemaElement element, XmlSchema schema) {
    if (element.getQName() != null) {
        return element.getQName();
    } else if (element.getName() != null) {
        return new QName(schema.getTargetNamespace(), element.getName());
    } else {
        return null;
    }
}
 
Example 7
Source File: SchemaCollection.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * This function is not part of the XmlSchema API. Who knows why?
 *
 * @param namespaceURI targetNamespace
 * @return schema, or null.
 */
public XmlSchema getSchemaByTargetNamespace(String namespaceURI) {
    for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
        if (namespaceURI != null && namespaceURI.equals(schema.getTargetNamespace())
            || namespaceURI == null && schema.getTargetNamespace() == null) {
            return schema;
        }
    }
    return null;
}
 
Example 8
Source File: Stax2ValidationUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void addSchema(Map<String, Source> sources, XmlSchema schema, Element element)
        throws XMLStreamException {
    String schemaSystemId = schema.getSourceURI();
    if (null == schemaSystemId) {
        schemaSystemId = schema.getTargetNamespace();
    }
    sources.put(schema.getTargetNamespace(), new DOMSource(element, schemaSystemId));
}
 
Example 9
Source File: BindingHelper.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private String getSpecificationString(XmlSchemaExtractor schemaExtractor) throws ParserException {
    try {
        // copy source elements and types to target schema
        schemaExtractor.copyObjects();
        final SchemaCollection targetSchemas = schemaExtractor.getTargetSchemas();

        // serialize schemas as AtlasMap schemaset
        // schemaset is described at https://docs.atlasmap.io/#importing-xml-files-into-atlasmap
        final Document schemaSet = this.documentBuilder.parse(new InputSource(new StringReader(SCHEMA_SET_XML)));
        final Node additionalSchemas = schemaSet.getElementsByTagName("d:AdditionalSchemas").item(0);

        // insert schemas into schemaset
        final XmlSchema[] xmlSchemas = targetSchemas.getXmlSchemaCollection().getXmlSchemas();
        for (XmlSchema schema : xmlSchemas) {
            final String targetNamespace = schema.getTargetNamespace();

            // no need to add XSD and XML schema
            if (!targetNamespace.equals(XMLConstants.XML_NS_URI) &&
                !targetNamespace.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {

                // get the schema DOM document
                final Document schemaDocument = schema.getSchemaDocument();
                // remove targetnamespace declaration for no namespace schema
                if (targetNamespace.isEmpty()) {
                    // remove invalid xmlns:tns="" attribute or it breaks StaxUtils.toString below
                    schemaDocument.getDocumentElement().removeAttribute("xmlns:tns");
                }

                // import the schema into schemaset
                final Node documentElement = schemaSet.importNode(schemaDocument.getDocumentElement(), true);

                if (targetNamespace.equals(soapVersion.getNamespace())) {
                    // add soap envelope under schemaset as first child
                    schemaSet.getDocumentElement().insertBefore(documentElement, additionalSchemas);
                } else {
                    // add the schema under 'AdditionalSchemas'
                    additionalSchemas.appendChild(documentElement);
                }
            }
        }

        // write schemaset as string
        return StaxUtils.toString(schemaSet);

    } catch (XmlSchemaSerializer.XmlSchemaSerializerException | ParserException | SAXException | IOException e) {
        throw new ParserException(String.format("Error parsing %s for operation %s: %s",
            bindingMessageInfo.getMessageInfo().getType(),
            bindingMessageInfo.getBindingOperation().getOperationInfo().getName(),
            e.getMessage())
            , e);
    }
}
 
Example 10
Source File: ScopedNameVisitor.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static boolean findSchemaTypeInGlobalScope(Scope scope,
                                                   Definition defn,
                                                   XmlSchema currentSchema,
                                                   AST node,
                                                   WSDLASTVisitor wsdlVisitor,
                                                   VisitorTypeHolder holder) {
    XmlSchemaCollection schemas = wsdlVisitor.getSchemas();
    TypeMappingType typeMap = wsdlVisitor.getTypeMap();
    ModuleToNSMapper mapper = wsdlVisitor.getModuleToNSMapper();
    WSDLSchemaManager manager = wsdlVisitor.getManager();

    Scope scopedName = new Scope(scope, node);
    String name = node.toString();
    if (isFullyScopedName(node)) {
        scopedName = getFullyScopedName(new Scope(), node);
        name = scopedName.toString();
    }
    boolean result = findNonSchemaType(name, wsdlVisitor, holder);
    if (!result) {
        XmlSchema xmlSchema = currentSchema;
        QName qname = null;
        String tns = mapper.map(scopedName.getParent());
        if (tns != null) {
            xmlSchema = manager.getXmlSchema(tns);
            if (xmlSchema != null) {
                qname = new QName(xmlSchema.getTargetNamespace(), scopedName.tail());
            }
        } else {
            qname = new QName(xmlSchema.getTargetNamespace(), name);
        }
        XmlSchemaType stype = null;
        if (qname != null) {
            // Exceptions are treated as a special case as above
            if (exceptionMode) {
                qname = new QName(xmlSchema.getTargetNamespace(), qname.getLocalPart() + "Type");
            }
            stype = xmlSchema.getTypeByName(qname);
            if (stype == null) {
                stype = schemas.getTypeByQName(qname);
            }
        }
        if (stype != null) {
            result = true;
            if (holder != null) {
                holder.setSchemaType(stype);
                holder.setCorbaType(getCorbaSchemaType(xmlSchema, typeMap, stype, scopedName));
                //add a xmlschema import
                if (!currentSchema.getTargetNamespace().equals(xmlSchema.getTargetNamespace())) {
                    String importFile = wsdlVisitor.getOutputDir()
                        + System.getProperty("file.separator")
                        + scopedName.getParent().toString("_");
                    manager.addXmlSchemaImport(currentSchema, xmlSchema, importFile);
                }
            }
        }
    }
    return result;
}
 
Example 11
Source File: ScopedNameVisitor.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static boolean findScopeSchemaType(Scope scopedName, XmlSchema schemaRef,
                                       WSDLASTVisitor wsdlVisitor,
                                       VisitorTypeHolder holder) {

    XmlSchemaCollection schemas = wsdlVisitor.getSchemas();
    TypeMappingType typeMap = wsdlVisitor.getTypeMap();
    ModuleToNSMapper mapper = wsdlVisitor.getModuleToNSMapper();
    WSDLSchemaManager manager = wsdlVisitor.getManager();

    boolean result = findNonSchemaType(scopedName.toString(), wsdlVisitor, holder);
    if (!result) {
        QName qname = null;
        XmlSchema xmlSchema = schemaRef;
        String tns = wsdlVisitor.getModuleToNSMapper().map(scopedName.getParent());
        if (tns != null) {
            xmlSchema = wsdlVisitor.getManager().getXmlSchema(tns);
        }
        XmlSchemaType stype = null;
        if (xmlSchema != null) {
            // Exceptions are treated as a special case as for the
            // doc/literal style
            // in the schema we will have an element and a complextype
            // so the name
            // and the typename will be different.

            String scopedNameString = null;
            if (mapper.isDefaultMapping()) {
                scopedNameString = scopedName.toString();
            } else {
                scopedNameString = scopedName.tail();
            }

            if (exceptionMode) {
                qname = new QName(xmlSchema.getTargetNamespace(), scopedNameString + "Type");
            } else {
                qname = new QName(xmlSchema.getTargetNamespace(), scopedNameString);
            }

            stype = xmlSchema.getTypeByName(qname);
            if (stype == null) {
                stype = schemas.getTypeByQName(qname);
            }
        }
        if (stype != null) {
            result = true;
        }
        if (result && holder != null) {
            holder.setSchemaType(stype);
            holder.setCorbaType(getCorbaSchemaType(xmlSchema, typeMap, stype, scopedName));
            // add a xmlschema import
            if (!schemaRef.getTargetNamespace().equals(xmlSchema.getTargetNamespace())) {
                String importFile = wsdlVisitor.getOutputDir() + System.getProperty("file.separator")
                                    + scopedName.getParent().toString("_");
                manager.addXmlSchemaImport(schemaRef, xmlSchema, importFile);
            }
        }
    }
    return result;
}
 
Example 12
Source File: XercesSchemaValidationUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
void tryToParseSchemas(XmlSchemaCollection collection, DOMErrorHandler handler)
    throws Exception {

    final List<DOMLSInput> inputs = new ArrayList<>();
    final Map<String, LSInput> resolverMap = new HashMap<>();

    for (XmlSchema schema : collection.getXmlSchemas()) {
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
            continue;
        }
        Document document = new XmlSchemaSerializer().serializeSchema(schema, false)[0];
        DOMLSInput input = new DOMLSInput(document, schema.getTargetNamespace());
        resolverMap.put(schema.getTargetNamespace(), input);
        inputs.add(input);
    }

    try {

        Object schemaLoader = findMethod(impl, "createXSLoader").invoke(impl, new Object[1]);
        DOMConfiguration config = (DOMConfiguration)findMethod(schemaLoader, "getConfig").invoke(schemaLoader);

        config.setParameter("validate", Boolean.TRUE);
        config.setParameter("error-handler", handler);
        config.setParameter("resource-resolver", new LSResourceResolver() {
            public LSInput resolveResource(String type, String namespaceURI, String publicId,
                                           String systemId, String baseURI) {
                return resolverMap.get(namespaceURI);
            }
        });


        Method m = findMethod(schemaLoader, "loadInputList");
        String name = m.getParameterTypes()[0].getName() + "Impl";
        name = name.replace("xs.LS", "impl.xs.util.LS");
        Class<?> c = Class.forName(name);
        Object inputList = c.getConstructor(LSInput[].class, Integer.TYPE)
            .newInstance(inputs.toArray(new LSInput[0]), inputs.size());
        m.invoke(schemaLoader, inputList);
    } catch (InvocationTargetException e) {
        throw (Exception)e.getTargetException();
    }
}
 
Example 13
Source File: Stax2ValidationUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Create woodstox validator for a schema set.
 *
 * @throws XMLStreamException
 */
private XMLValidationSchema getValidator(Endpoint endpoint, ServiceInfo serviceInfo)
        throws XMLStreamException {
    synchronized (endpoint) {
        XMLValidationSchema ret = (XMLValidationSchema) endpoint.get(KEY);
        if (ret == null) {
            if (endpoint.containsKey(KEY)) {
                return null;
            }
            Map<String, Source> sources = new TreeMap<>();

            for (SchemaInfo schemaInfo : serviceInfo.getSchemas()) {
                XmlSchema sch = schemaInfo.getSchema();
                String uri = sch.getTargetNamespace();
                if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri)) {
                    continue;
                }

                if (sch.getTargetNamespace() == null && !sch.getExternals().isEmpty()) {
                    for (XmlSchemaExternal xmlSchemaExternal : sch.getExternals()) {
                        addSchema(sources, xmlSchemaExternal.getSchema(),
                                getElement(xmlSchemaExternal.getSchema().getSourceURI()));
                    }
                    continue;
                } else if (sch.getTargetNamespace() == null) {
                    throw new IllegalStateException("An Schema without imports must have a targetNamespace");
                }

                addSchema(sources, sch, schemaInfo.getElement());
            }

            try {
                // I don't think that we need the baseURI.
                Method method = multiSchemaFactory.getMethod("createSchema", String.class, Map.class);
                ret = (XMLValidationSchema) method.invoke(multiSchemaFactory.newInstance(), null, sources);
                endpoint.put(KEY, ret);
            } catch (Throwable t) {
                LOG.log(Level.INFO, "Problem loading schemas. Falling back to slower method.", ret);
                endpoint.put(KEY, null);
            }
        }
        return ret;
    }
}
 
Example 14
Source File: ImportRepairTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void tryToParseSchemas() throws Exception {
    // Get DOM Implementation using DOM Registry
    final List<DOMLSInput> inputs = new ArrayList<>();
    final Map<String, LSInput> resolverMap = new HashMap<>();

    for (XmlSchema schema : collection.getXmlSchemas()) {
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
            continue;
        }
        Document document = new XmlSchemaSerializer().serializeSchema(schema, false)[0];
        DOMLSInput input = new DOMLSInput(document, schema.getTargetNamespace());
        dumpSchema(document);
        resolverMap.put(schema.getTargetNamespace(), input);
        inputs.add(input);
    }

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XS-Loader");


    try {
        Object schemaLoader = findMethod(impl, "createXSLoader").invoke(impl, new Object[1]);
        DOMConfiguration config = (DOMConfiguration)findMethod(schemaLoader, "getConfig").invoke(schemaLoader);

        config.setParameter("validate", Boolean.TRUE);
        try {
            //bug in the JDK doesn't set this, but accesses it
            config.setParameter("http://www.oracle.com/xml/jaxp/properties/xmlSecurityPropertyManager",
                                Class.forName("com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager")
                                    .newInstance());

            config.setParameter("http://apache.org/xml/properties/security-manager",
                                Class.forName("com.sun.org.apache.xerces.internal.utils.XMLSecurityManager")
                                    .newInstance());
        } catch (Throwable t) {
            //ignore
        }
        config.setParameter("error-handler", new DOMErrorHandler() {

            public boolean handleError(DOMError error) {
                LOG.info("Schema parsing error: " + error.getMessage()
                         + " " + error.getType()
                         + " " + error.getLocation().getUri()
                         + " " + error.getLocation().getLineNumber()
                         + ":" + error.getLocation().getColumnNumber());
                throw new DOMErrorException(error);
            }
        });
        config.setParameter("resource-resolver", new LSResourceResolver() {

            public LSInput resolveResource(String type, String namespaceURI, String publicId,
                                           String systemId, String baseURI) {
                return resolverMap.get(namespaceURI);
            }
        });

        Method m = findMethod(schemaLoader, "loadInputList");
        String name = m.getParameterTypes()[0].getName() + "Impl";
        name = name.replace("xs.LS", "impl.xs.util.LS");
        Class<?> c = Class.forName(name);
        Object inputList = c.getConstructor(LSInput[].class, Integer.TYPE)
        .newInstance(inputs.toArray(new LSInput[0]), inputs.size());

        findMethod(schemaLoader, "loadInputList").invoke(schemaLoader, inputList);
    } catch (InvocationTargetException ite) {
        throw (Exception)ite.getTargetException();
    }
}