Search in sources :

Example 1 with SchemaInfo

use of org.apache.cxf.service.model.SchemaInfo in project cxf by apache.

the class AbstractDataBinding method addSchemaDocument.

public XmlSchema addSchemaDocument(ServiceInfo serviceInfo, SchemaCollection col, Document d, String systemId, Collection<String> ids) {
    /*
         * Sanity check. The document has to remotely resemble a schema.
         */
    if (!XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(d.getDocumentElement().getNamespaceURI())) {
        QName qn = DOMUtils.getElementQName(d.getDocumentElement());
        throw new RuntimeException("Invalid schema document passed to " + "AbstractDataBinding.addSchemaDocument, " + "not in W3C schema namespace: " + qn);
    }
    if (!"schema".equals(d.getDocumentElement().getLocalName())) {
        QName qn = DOMUtils.getElementQName(d.getDocumentElement());
        throw new RuntimeException("Invalid schema document passed to " + "AbstractDataBinding.addSchemaDocument, " + "document element isn't 'schema': " + qn);
    }
    String ns = d.getDocumentElement().getAttribute("targetNamespace");
    boolean copied = false;
    if (StringUtils.isEmpty(ns)) {
        if (DOMUtils.getFirstElement(d.getDocumentElement()) == null) {
            hackAroundEmptyNamespaceIssue = true;
            return null;
        }
        // create a copy of the dom so we
        // can modify it.
        d = copy(d);
        copied = true;
        ns = serviceInfo.getInterface().getName().getNamespaceURI();
        d.getDocumentElement().setAttribute("targetNamespace", ns);
    }
    SchemaInfo schemaInfo = serviceInfo.getSchema(ns);
    if (schemaInfo != null && (systemId == null && schemaInfo.getSystemId() == null || systemId != null && systemId.equalsIgnoreCase(schemaInfo.getSystemId()))) {
        return schemaInfo.getSchema();
    }
    if (hackAroundEmptyNamespaceIssue) {
        d = doEmptyNamespaceHack(d, copied);
    }
    Node n = d.getDocumentElement().getFirstChild();
    boolean patchRequired = false;
    while (n != null) {
        if (n instanceof Element) {
            Element e = (Element) n;
            if (e.getLocalName().equals("import")) {
                patchRequired = true;
                break;
            }
        }
        n = n.getNextSibling();
    }
    if (patchRequired) {
        if (!copied) {
            d = copy(d);
        }
        n = d.getDocumentElement().getFirstChild();
        while (n != null) {
            if (n instanceof Element) {
                Element e = (Element) n;
                if (e.getLocalName().equals("import")) {
                    e = (Element) n;
                    String loc = e.getAttribute("schemaLocation");
                    if (ids == null || ids.contains(loc)) {
                        e.removeAttribute("schemaLocation");
                    }
                    updateSchemaLocation(e);
                    if (StringUtils.isEmpty(e.getAttribute("namespace"))) {
                        e.setAttribute("namespace", serviceInfo.getInterface().getName().getNamespaceURI());
                    }
                }
            }
            n = n.getNextSibling();
        }
    }
    SchemaInfo schema = new SchemaInfo(ns);
    schema.setSystemId(systemId);
    XmlSchema xmlSchema;
    synchronized (d) {
        xmlSchema = col.read(d, systemId);
        schema.setSchema(xmlSchema);
        schema.setElement(d.getDocumentElement());
    }
    serviceInfo.addSchema(schema);
    return xmlSchema;
}
Also used : XmlSchema(org.apache.ws.commons.schema.XmlSchema) QName(javax.xml.namespace.QName) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Example 2 with SchemaInfo

use of org.apache.cxf.service.model.SchemaInfo in project cxf by apache.

the class Stax2ValidationUtils method getValidator.

/**
 * 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, EmbeddedSchema> 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().size() > 0) {
                    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());
            }
            W3CMultiSchemaFactory factory = new W3CMultiSchemaFactory();
            // I don't think that we need the baseURI.
            try {
                ret = factory.loadSchemas(null, sources);
                endpoint.put(KEY, ret);
            } catch (XMLStreamException ex) {
                LOG.log(Level.INFO, "Problem loading schemas. Falling back to slower method.", ret);
                endpoint.put(KEY, null);
            }
        }
        return ret;
    }
}
Also used : XmlSchemaExternal(org.apache.ws.commons.schema.XmlSchemaExternal) XMLStreamException(javax.xml.stream.XMLStreamException) XmlSchema(org.apache.ws.commons.schema.XmlSchema) TreeMap(java.util.TreeMap) XMLValidationSchema(org.codehaus.stax2.validation.XMLValidationSchema) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Example 3 with SchemaInfo

use of org.apache.cxf.service.model.SchemaInfo in project cxf by apache.

the class JAXBEncoderDecoder method marshallException.

public static void marshallException(Marshaller marshaller, Exception elValue, MessagePartInfo part, Object source) {
    XMLStreamWriter writer = getStreamWriter(source);
    QName qn = part.getElementQName();
    try {
        writer.writeStartElement("ns1", qn.getLocalPart(), qn.getNamespaceURI());
        Class<?> cls = part.getTypeClass();
        XmlAccessType accessType = Utils.getXmlAccessType(cls);
        String namespace = part.getElementQName().getNamespaceURI();
        String attNs = namespace;
        SchemaInfo sch = part.getMessageInfo().getOperation().getInterface().getService().getSchema(namespace);
        if (sch == null) {
            LOG.warning("Schema associated with " + namespace + " is null");
            namespace = null;
            attNs = null;
        } else {
            if (!sch.isElementFormQualified()) {
                namespace = null;
            }
            if (!sch.isAttributeFormQualified()) {
                attNs = null;
            }
        }
        List<Member> combinedMembers = new ArrayList<>();
        for (Field f : Utils.getFields(cls, accessType)) {
            XmlAttribute at = f.getAnnotation(XmlAttribute.class);
            if (at == null) {
                combinedMembers.add(f);
            } else {
                QName fname = new QName(attNs, StringUtils.isEmpty(at.name()) ? f.getName() : at.name());
                ReflectionUtil.setAccessible(f);
                Object o = Utils.getFieldValue(f, elValue);
                DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
                writeObject(marshaller, frag, newJAXBElement(fname, String.class, o));
                if (attNs != null) {
                    writer.writeAttribute(attNs, fname.getLocalPart(), DOMUtils.getAllContent(frag));
                } else {
                    writer.writeAttribute(fname.getLocalPart(), DOMUtils.getAllContent(frag));
                }
            }
        }
        for (Method m : Utils.getGetters(cls, accessType)) {
            if (!m.isAnnotationPresent(XmlAttribute.class)) {
                combinedMembers.add(m);
            } else {
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                XmlAttribute at = m.getAnnotation(XmlAttribute.class);
                QName mname = new QName(namespace, StringUtils.isEmpty(at.name()) ? name : at.name());
                DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
                Object o = Utils.getMethodValue(m, elValue);
                writeObject(marshaller, frag, newJAXBElement(mname, String.class, o));
                if (attNs != null) {
                    writer.writeAttribute(attNs, mname.getLocalPart(), DOMUtils.getAllContent(frag));
                } else {
                    writer.writeAttribute(mname.getLocalPart(), DOMUtils.getAllContent(frag));
                }
            }
        }
        XmlAccessorOrder xmlAccessorOrder = cls.getAnnotation(XmlAccessorOrder.class);
        if (xmlAccessorOrder != null && xmlAccessorOrder.value().equals(XmlAccessOrder.ALPHABETICAL)) {
            Collections.sort(combinedMembers, new Comparator<Member>() {

                public int compare(Member m1, Member m2) {
                    return m1.getName().compareTo(m2.getName());
                }
            });
        }
        for (Member member : combinedMembers) {
            if (member instanceof Field) {
                Field f = (Field) member;
                QName fname = new QName(namespace, f.getName());
                ReflectionUtil.setAccessible(f);
                if (JAXBSchemaInitializer.isArray(f.getGenericType())) {
                    writeArrayObject(marshaller, writer, fname, f.get(elValue));
                } else {
                    Object o = Utils.getFieldValue(f, elValue);
                    writeObject(marshaller, writer, newJAXBElement(fname, String.class, o));
                }
            } else {
                // it's a Method
                Method m = (Method) member;
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                QName mname = new QName(namespace, name);
                if (JAXBSchemaInitializer.isArray(m.getGenericReturnType())) {
                    writeArrayObject(marshaller, writer, mname, m.invoke(elValue));
                } else {
                    Object o = Utils.getMethodValue(m, elValue);
                    writeObject(marshaller, writer, newJAXBElement(mname, String.class, o));
                }
            }
        }
        writer.writeEndElement();
        writer.flush();
    } catch (Exception e) {
        throw new Fault(new Message("MARSHAL_ERROR", LOG, e.getMessage()), e);
    } finally {
        StaxUtils.close(writer);
    }
}
Also used : XmlAttribute(javax.xml.bind.annotation.XmlAttribute) XmlAccessorOrder(javax.xml.bind.annotation.XmlAccessorOrder) Message(org.apache.cxf.common.i18n.Message) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Fault(org.apache.cxf.interceptor.Fault) Method(java.lang.reflect.Method) XMLStreamException(javax.xml.stream.XMLStreamException) JAXBException(javax.xml.bind.JAXBException) PrivilegedActionException(java.security.PrivilegedActionException) Field(java.lang.reflect.Field) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) XmlAccessType(javax.xml.bind.annotation.XmlAccessType) Member(java.lang.reflect.Member) DocumentFragment(org.w3c.dom.DocumentFragment) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Example 4 with SchemaInfo

use of org.apache.cxf.service.model.SchemaInfo in project cxf by apache.

the class JAXBSchemaInitializer method createBridgeXsElement.

private void createBridgeXsElement(MessagePartInfo part, QName qn, QName typeName) {
    XmlSchemaElement el = null;
    SchemaInfo schemaInfo = serviceInfo.getSchema(qn.getNamespaceURI());
    if (schemaInfo != null) {
        el = schemaInfo.getElementByQName(qn);
        if (el == null) {
            createXsElement(schemaInfo.getSchema(), part, typeName, schemaInfo);
        } else if (!typeName.equals(el.getSchemaTypeName())) {
            throw new Fault(new Message("CANNOT_CREATE_ELEMENT", LOG, qn, typeName, el.getSchemaTypeName()));
        }
        return;
    }
    XmlSchema schema = schemas.newXmlSchemaInCollection(qn.getNamespaceURI());
    if (qualifiedSchemas) {
        schema.setElementFormDefault(XmlSchemaForm.QUALIFIED);
    }
    schemaInfo = new SchemaInfo(qn.getNamespaceURI(), qualifiedSchemas, false);
    schemaInfo.setSchema(schema);
    el = createXsElement(schema, part, typeName, schemaInfo);
    NamespaceMap nsMap = new NamespaceMap();
    nsMap.add(WSDLConstants.CONVENTIONAL_TNS_PREFIX, schema.getTargetNamespace());
    nsMap.add(WSDLConstants.NP_SCHEMA_XSD, WSDLConstants.NS_SCHEMA_XSD);
    schema.setNamespaceContext(nsMap);
    serviceInfo.addSchema(schemaInfo);
}
Also used : Message(org.apache.cxf.common.i18n.Message) XmlSchema(org.apache.ws.commons.schema.XmlSchema) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap) Fault(org.apache.cxf.interceptor.Fault) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Example 5 with SchemaInfo

use of org.apache.cxf.service.model.SchemaInfo in project cxf by apache.

the class JAXBSchemaInitializer method buildExceptionType.

private void buildExceptionType(MessagePartInfo part, Class<?> cls) {
    SchemaInfo schemaInfo = null;
    for (SchemaInfo s : serviceInfo.getSchemas()) {
        if (s.getNamespaceURI().equals(part.getElementQName().getNamespaceURI())) {
            schemaInfo = s;
            break;
        }
    }
    XmlAccessorOrder xmlAccessorOrder = cls.getAnnotation(XmlAccessorOrder.class);
    XmlType xmlTypeAnno = cls.getAnnotation(XmlType.class);
    String[] propertyOrder = null;
    boolean respectXmlTypeNS = false;
    XmlSchema faultBeanSchema = null;
    if (xmlTypeAnno != null && !StringUtils.isEmpty(xmlTypeAnno.namespace()) && !xmlTypeAnno.namespace().equals(part.getElementQName().getNamespaceURI())) {
        respectXmlTypeNS = true;
        NamespaceMap nsMap = new NamespaceMap();
        nsMap.add(WSDLConstants.CONVENTIONAL_TNS_PREFIX, xmlTypeAnno.namespace());
        nsMap.add(WSDLConstants.NP_SCHEMA_XSD, WSDLConstants.NS_SCHEMA_XSD);
        SchemaInfo faultBeanSchemaInfo = createSchemaIfNeeded(xmlTypeAnno.namespace(), nsMap);
        faultBeanSchema = faultBeanSchemaInfo.getSchema();
    }
    if (xmlTypeAnno != null && xmlTypeAnno.propOrder().length > 0) {
        propertyOrder = xmlTypeAnno.propOrder();
    // TODO: handle @XmlAccessOrder
    }
    XmlSchema schema = null;
    if (schemaInfo == null) {
        NamespaceMap nsMap = new NamespaceMap();
        nsMap.add(WSDLConstants.CONVENTIONAL_TNS_PREFIX, part.getElementQName().getNamespaceURI());
        nsMap.add(WSDLConstants.NP_SCHEMA_XSD, WSDLConstants.NS_SCHEMA_XSD);
        schemaInfo = createSchemaIfNeeded(part.getElementQName().getNamespaceURI(), nsMap);
    }
    schema = schemaInfo.getSchema();
    // Before updating everything, make sure we haven't added this
    // type yet.  Multiple methods that throw the same exception
    // types will cause duplicates.
    String faultTypeName = xmlTypeAnno != null && !StringUtils.isEmpty(xmlTypeAnno.name()) ? xmlTypeAnno.name() : part.getElementQName().getLocalPart();
    XmlSchemaType existingType = schema.getTypeByName(faultTypeName);
    if (existingType != null) {
        return;
    }
    XmlSchemaElement el = new XmlSchemaElement(schema, true);
    el.setName(part.getElementQName().getLocalPart());
    part.setXmlSchema(el);
    schemaInfo.setElement(null);
    if (respectXmlTypeNS) {
        // create complexType in the new created schema for xmlType
        schema = faultBeanSchema;
    }
    XmlSchemaComplexType ct = new XmlSchemaComplexType(schema, true);
    ct.setName(faultTypeName);
    el.setSchemaTypeName(ct.getQName());
    XmlSchemaSequence seq = new XmlSchemaSequence();
    ct.setParticle(seq);
    String namespace = part.getElementQName().getNamespaceURI();
    XmlAccessType accessType = Utils.getXmlAccessType(cls);
    // 
    for (Field f : Utils.getFields(cls, accessType)) {
        // map field
        Type type = Utils.getFieldType(f);
        // generic return type.
        if ((type == null) && (f.getGenericType() instanceof ParameterizedType)) {
            type = f.getGenericType();
        }
        if (generateGenericType(type)) {
            buildGenericElements(schema, seq, f);
        } else {
            JAXBBeanInfo beanInfo = getBeanInfo(type);
            if (beanInfo != null) {
                XmlElement xmlElementAnno = f.getAnnotation(XmlElement.class);
                addElement(schema, seq, beanInfo, new QName(namespace, f.getName()), isArray(type), xmlElementAnno);
            }
        }
    }
    for (Method m : Utils.getGetters(cls, accessType)) {
        // map method
        Type type = Utils.getMethodReturnType(m);
        // generic return type.
        if ((type == null) && (m.getGenericReturnType() instanceof ParameterizedType)) {
            type = m.getGenericReturnType();
        }
        if (generateGenericType(type)) {
            buildGenericElements(schema, seq, m, type);
        } else {
            JAXBBeanInfo beanInfo = getBeanInfo(type);
            if (beanInfo != null) {
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                XmlElement xmlElementAnno = m.getAnnotation(XmlElement.class);
                addElement(schema, seq, beanInfo, new QName(namespace, name), isArray(type), xmlElementAnno);
            }
        }
    }
    // Create element in xsd:sequence for Exception.class
    if (Exception.class.isAssignableFrom(cls)) {
        addExceptionMessage(cls, schema, seq);
    }
    if (propertyOrder != null) {
        if (propertyOrder.length == seq.getItems().size()) {
            sortItems(seq, propertyOrder);
        } else if (propertyOrder.length > 1 || (propertyOrder.length == 1 && !propertyOrder[0].isEmpty())) {
            LOG.log(Level.WARNING, "propOrder in @XmlType doesn't define all schema elements :" + Arrays.toString(propertyOrder));
        }
    }
    if (xmlAccessorOrder != null && xmlAccessorOrder.value().equals(XmlAccessOrder.ALPHABETICAL) && propertyOrder == null) {
        sort(seq);
    }
    schemas.addCrossImports();
    part.setProperty(JAXBDataBinding.class.getName() + ".CUSTOM_EXCEPTION", Boolean.TRUE);
}
Also used : XmlAccessorOrder(javax.xml.bind.annotation.XmlAccessorOrder) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) QName(javax.xml.namespace.QName) Method(java.lang.reflect.Method) XmlSchemaType(org.apache.ws.commons.schema.XmlSchemaType) XmlType(javax.xml.bind.annotation.XmlType) ParameterizedType(java.lang.reflect.ParameterizedType) XmlSchemaSequence(org.apache.ws.commons.schema.XmlSchemaSequence) Field(java.lang.reflect.Field) GenericArrayType(java.lang.reflect.GenericArrayType) XmlSchemaComplexType(org.apache.ws.commons.schema.XmlSchemaComplexType) XmlSchemaType(org.apache.ws.commons.schema.XmlSchemaType) XmlAccessType(javax.xml.bind.annotation.XmlAccessType) Type(java.lang.reflect.Type) XmlSchemaSimpleType(org.apache.ws.commons.schema.XmlSchemaSimpleType) XmlType(javax.xml.bind.annotation.XmlType) ParameterizedType(java.lang.reflect.ParameterizedType) XmlSchema(org.apache.ws.commons.schema.XmlSchema) NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap) JAXBBeanInfo(org.apache.cxf.common.jaxb.JAXBBeanInfo) XmlElement(javax.xml.bind.annotation.XmlElement) XmlSchemaComplexType(org.apache.ws.commons.schema.XmlSchemaComplexType) XmlAccessType(javax.xml.bind.annotation.XmlAccessType) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Aggregations

SchemaInfo (org.apache.cxf.service.model.SchemaInfo)42 XmlSchema (org.apache.ws.commons.schema.XmlSchema)17 QName (javax.xml.namespace.QName)11 ServiceInfo (org.apache.cxf.service.model.ServiceInfo)11 Element (org.w3c.dom.Element)10 XmlSchemaElement (org.apache.ws.commons.schema.XmlSchemaElement)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)7 XMLStreamException (javax.xml.stream.XMLStreamException)7 Message (org.apache.cxf.common.i18n.Message)6 FileNotFoundException (java.io.FileNotFoundException)5 URL (java.net.URL)5 MessagePartInfo (org.apache.cxf.service.model.MessagePartInfo)5 InputSource (org.xml.sax.InputSource)5 SAXException (org.xml.sax.SAXException)5 SAXParseException (org.xml.sax.SAXParseException)5 File (java.io.File)4 Method (java.lang.reflect.Method)4 HashSet (java.util.HashSet)4 SchemaCollection (org.apache.cxf.common.xmlschema.SchemaCollection)4