Search in sources :

Example 6 with XmlType

use of javax.xml.bind.annotation.XmlType 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)

Example 7 with XmlType

use of javax.xml.bind.annotation.XmlType in project cxf by apache.

the class WadlGenerator method getSchemaCollection.

private SchemaCollection getSchemaCollection(ResourceTypes resourceTypes, JAXBContext context) {
    if (context == null) {
        return null;
    }
    SchemaCollection xmlSchemaCollection = new SchemaCollection();
    Collection<DOMSource> schemas = new HashSet<>();
    List<String> targetNamespaces = new ArrayList<>();
    try {
        for (DOMResult r : JAXBUtils.generateJaxbSchemas(context, CastUtils.cast(Collections.emptyMap(), String.class, DOMResult.class))) {
            Document doc = (Document) r.getNode();
            ElementQNameResolver theResolver = createElementQNameResolver(context);
            String tns = doc.getDocumentElement().getAttribute("targetNamespace");
            String tnsPrefix = doc.getDocumentElement().lookupPrefix(tns);
            if (tnsPrefix == null) {
                String tnsDecl = doc.getDocumentElement().getAttribute("xmlns:tns");
                tnsPrefix = tnsDecl != null && tnsDecl.equals(tns) ? "tns:" : "";
            } else {
                tnsPrefix += ":";
            }
            if (supportJaxbXmlType) {
                for (Class<?> cls : resourceTypes.getAllTypes().keySet()) {
                    if (isXmlRoot(cls)) {
                        continue;
                    }
                    XmlType root = cls.getAnnotation(XmlType.class);
                    if (root != null) {
                        QName typeName = theResolver.resolve(cls, new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                        if (typeName != null && tns.equals(typeName.getNamespaceURI())) {
                            QName elementName = resourceTypes.getXmlNameMap().get(cls);
                            if (elementName == null) {
                                elementName = typeName;
                            }
                            Element newElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
                            newElement.setAttribute("name", elementName.getLocalPart());
                            newElement.setAttribute("type", tnsPrefix + typeName.getLocalPart());
                            if (Modifier.isAbstract(cls.getModifiers()) && resourceTypes.getSubstitutions().values().contains(cls)) {
                                newElement.setAttribute("abstract", "true");
                            }
                            doc.getDocumentElement().appendChild(newElement);
                        }
                    }
                }
                if (supportJaxbSubstitutions) {
                    for (Map.Entry<Class<?>, Class<?>> entry : resourceTypes.getSubstitutions().entrySet()) {
                        QName typeName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                        for (Element element : DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(), Constants.URI_2001_SCHEMA_XSD, "element")) {
                            if (element.getAttribute("name").equals(typeName.getLocalPart())) {
                                QName groupName = theResolver.resolve(entry.getValue(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                                if (groupName != null) {
                                    element.setAttribute("substitutionGroup", tnsPrefix + groupName.getLocalPart());
                                }
                            }
                        }
                    }
                }
            }
            if (supportCollections && !resourceTypes.getCollectionMap().isEmpty()) {
                for (Map.Entry<Class<?>, QName> entry : resourceTypes.getCollectionMap().entrySet()) {
                    QName colQName = entry.getValue();
                    if (colQName == null) {
                        colQName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                        if (colQName != null) {
                            colQName = new QName(colQName.getNamespaceURI(), colQName.getLocalPart() + "s", colQName.getPrefix());
                        }
                    }
                    if (colQName == null) {
                        continue;
                    }
                    if (tns.equals(colQName.getNamespaceURI())) {
                        QName typeName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                        if (typeName != null) {
                            Element newElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
                            newElement.setAttribute("name", colQName.getLocalPart());
                            Element ctElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:complexType");
                            newElement.appendChild(ctElement);
                            Element seqElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:sequence");
                            ctElement.appendChild(seqElement);
                            Element xsElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
                            seqElement.appendChild(xsElement);
                            xsElement.setAttribute("ref", tnsPrefix + typeName.getLocalPart());
                            xsElement.setAttribute("minOccurs", "0");
                            xsElement.setAttribute("maxOccurs", "unbounded");
                            doc.getDocumentElement().appendChild(newElement);
                        }
                    }
                }
            }
            DOMSource source = new DOMSource(doc, r.getSystemId());
            schemas.add(source);
            if (!StringUtils.isEmpty(tns)) {
                targetNamespaces.add(tns);
            }
        }
    } catch (IOException e) {
        LOG.fine("No schema can be generated");
        return null;
    }
    boolean hackAroundEmptyNamespaceIssue = false;
    for (DOMSource r : schemas) {
        hackAroundEmptyNamespaceIssue = addSchemaDocument(xmlSchemaCollection, targetNamespaces, (Document) r.getNode(), r.getSystemId(), hackAroundEmptyNamespaceIssue);
    }
    return xmlSchemaCollection;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMResult(javax.xml.transform.dom.DOMResult) QName(javax.xml.namespace.QName) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) Annotation(java.lang.annotation.Annotation) XmlType(javax.xml.bind.annotation.XmlType) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 8 with XmlType

use of javax.xml.bind.annotation.XmlType in project wso2-synapse by wso2.

the class JsonXMLRootProvider method getXmlElementDeclMethod.

/**
 * Determine <code>@XmlElementDecl</code>-annotated factory method to create {@link JAXBElement}
 * for an <code>@XmlType</code>-annotated type
 *
 * @param type
 * @return element
 */
protected Method getXmlElementDeclMethod(Class<?> type) {
    XmlType xmlType = type.getAnnotation(XmlType.class);
    if (xmlType == null) {
        return null;
    }
    Class<?> factoryClass = xmlType.factoryClass();
    if (factoryClass == XmlType.DEFAULT.class) {
        String defaultObjectFactoryName = type.getPackage().getName() + ".ObjectFactory";
        try {
            factoryClass = Thread.currentThread().getContextClassLoader().loadClass(defaultObjectFactoryName);
        } catch (Exception e) {
            factoryClass = type;
        }
    }
    if (factoryClass.getAnnotation(XmlRegistry.class) == null) {
        return null;
    }
    XmlSchema xmlSchema = type.getPackage().getAnnotation(XmlSchema.class);
    String namespaceURI = getNamespaceURI(xmlType, xmlSchema);
    for (Method method : factoryClass.getDeclaredMethods()) {
        XmlElementDecl xmlElementDecl = method.getAnnotation(XmlElementDecl.class);
        if (xmlElementDecl != null && namespaceURI.equals(getNamespaceURI(xmlElementDecl, xmlSchema))) {
            if (method.getReturnType() == JAXBElement.class) {
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 1 && parameterTypes[0] == type) {
                    return method;
                }
            }
        }
    }
    return null;
}
Also used : XmlSchema(javax.xml.bind.annotation.XmlSchema) XmlElementDecl(javax.xml.bind.annotation.XmlElementDecl) Method(java.lang.reflect.Method) XmlRegistry(javax.xml.bind.annotation.XmlRegistry) JAXBException(javax.xml.bind.JAXBException) XmlType(javax.xml.bind.annotation.XmlType)

Example 9 with XmlType

use of javax.xml.bind.annotation.XmlType in project groovity by disney.

the class MetaPropertyLookup method getOrderedGettableProperties.

public static final MetaProperty[] getOrderedGettableProperties(Object o) {
    final Class<?> c = o.getClass();
    MetaProperty[] properties = orderedPropertiesCache.get(c);
    if (properties == null) {
        MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(c);
        List<MetaProperty> mps = mc.getProperties();
        TreeMap<String, MetaProperty> sortedProps;
        String[] declaredOrder = null;
        ModelOrder order = c.getAnnotation(ModelOrder.class);
        if (order != null) {
            declaredOrder = order.value();
        } else {
            XmlType xmlType = c.getAnnotation(XmlType.class);
            if (xmlType != null) {
                declaredOrder = xmlType.propOrder();
            }
        }
        if (declaredOrder != null && declaredOrder.length > 0) {
            final String[] declared = declaredOrder;
            final int dl = declared.length;
            Comparator<String> comp = new Comparator<String>() {

                @Override
                public int compare(String o1, String o2) {
                    int p1 = dl;
                    int p2 = dl;
                    for (int i = 0; i < dl; i++) {
                        String d = declared[i];
                        if (o1.equals(d)) {
                            p1 = i;
                        }
                        if (o2.equals(d)) {
                            p2 = i;
                        }
                        if (p1 < dl && p2 < dl) {
                            break;
                        }
                    }
                    if (p1 == p2) {
                        return o1.compareTo(o2);
                    }
                    return p1 - p2;
                }
            };
            sortedProps = new TreeMap<>(comp);
        } else {
            sortedProps = new TreeMap<>();
        }
        List<String> skipProperties = new ArrayList<>();
        skipProperties.add("class");
        skipProperties.add("binding");
        if (Map.class.isAssignableFrom(c) || Collection.class.isAssignableFrom(c)) {
            skipProperties.add("empty");
            if (NavigableMap.class.isAssignableFrom(c)) {
                skipProperties.add("firstEntry");
                skipProperties.add("lastEntry");
            }
        }
        for (MetaProperty mp : mps) {
            if (!skipProperties.contains(mp.getName()) && !Closeable.class.isAssignableFrom(mp.getType())) {
                // now check for skip annotations
                if (mp instanceof MetaBeanProperty) {
                    MetaBeanProperty mbp = ((MetaBeanProperty) mp);
                    if (mbp.getField() != null) {
                        ModelSkip skipAnn = mbp.getField().field.getAnnotation(ModelSkip.class);
                        if (skipAnn != null) {
                            continue;
                        }
                        if (mbp.getField().isStatic()) {
                            continue;
                        }
                    }
                    MetaMethod getter = mbp.getGetter();
                    if (getter instanceof CachedMethod) {
                        CachedMethod cm = (CachedMethod) getter;
                        ModelSkip skipAnn = cm.getCachedMethod().getAnnotation(ModelSkip.class);
                        if (skipAnn != null) {
                            continue;
                        }
                        if (cm.isStatic()) {
                            continue;
                        }
                        if (!cm.getCachedMethod().getDeclaringClass().equals(c)) {
                            // we may have an overridden method here
                            try {
                                Method override = c.getDeclaredMethod(cm.getCachedMethod().getName(), cm.getCachedMethod().getParameterTypes());
                                if (override.getAnnotation(ModelSkip.class) != null) {
                                    continue;
                                }
                            } catch (NoSuchMethodException | SecurityException e) {
                            }
                        }
                    }
                    if (mbp.getGetter() == null && mbp.getField() == null) {
                        continue;
                    }
                }
                sortedProps.put(mp.getName(), mp);
            }
        }
        properties = sortedProps.values().toArray(new MetaProperty[0]);
        orderedPropertiesCache.putIfAbsent(c, properties);
    }
    return properties;
}
Also used : ArrayList(java.util.ArrayList) CachedMethod(org.codehaus.groovy.reflection.CachedMethod) Comparator(java.util.Comparator) MethodMetaProperty(org.codehaus.groovy.runtime.metaclass.MethodMetaProperty) MetaProperty(groovy.lang.MetaProperty) MetaMethod(groovy.lang.MetaMethod) MetaBeanProperty(groovy.lang.MetaBeanProperty) CachedMethod(org.codehaus.groovy.reflection.CachedMethod) MetaMethod(groovy.lang.MetaMethod) Method(java.lang.reflect.Method) ModelOrder(com.disney.groovity.model.ModelOrder) XmlType(javax.xml.bind.annotation.XmlType) ModelSkip(com.disney.groovity.model.ModelSkip) MetaClass(groovy.lang.MetaClass) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NavigableMap(java.util.NavigableMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 10 with XmlType

use of javax.xml.bind.annotation.XmlType in project herd by FINRAOS.

the class DefinitionGenerator method processDefinitionClass.

/**
 * Processes a model class which can be converted into a Swagger definition. A model class must be a JAXB XmlType. This method may be called recursively.
 *
 * @param clazz the class to process.
 *
 * @throws MojoExecutionException if the class isn't an XmlType.
 */
private void processDefinitionClass(Class<?> clazz) throws MojoExecutionException {
    log.debug("Processing model class \"" + clazz.getName() + "\"");
    XmlType xmlType = clazz.getAnnotation(XmlType.class);
    if (xmlType == null) {
        log.debug("Model class \"" + clazz.getName() + "\" is not an XmlType so it will be skipped.");
    } else {
        String name = xmlType.name();
        if (!swagger.getDefinitions().containsKey(name)) {
            ModelImpl model = new ModelImpl();
            if (exampleClassNames.contains(clazz.getSimpleName())) {
                // Only provide examples for root elements. If we do them for child elements, the JSON examples use the XML examples which is a problem.
                model.setExample(new ExampleXmlGenerator(log, clazz).getExampleXml());
            }
            swagger.addDefinition(name, model);
            model.name(name);
            if (xsdParser != null) {
                model.setDescription(xsdParser.getAnnotation(name));
            }
            for (Field field : clazz.getDeclaredFields()) {
                processField(field, model);
            }
        }
    }
}
Also used : Field(java.lang.reflect.Field) ModelImpl(io.swagger.models.ModelImpl) XmlType(javax.xml.bind.annotation.XmlType)

Aggregations

XmlType (javax.xml.bind.annotation.XmlType)30 XmlRootElement (javax.xml.bind.annotation.XmlRootElement)10 QName (javax.xml.namespace.QName)10 Method (java.lang.reflect.Method)8 XmlSchema (javax.xml.bind.annotation.XmlSchema)7 Field (java.lang.reflect.Field)6 ArrayList (java.util.ArrayList)5 XmlAccessType (javax.xml.bind.annotation.XmlAccessType)4 ParameterizedType (java.lang.reflect.ParameterizedType)3 Type (java.lang.reflect.Type)3 XmlAccessorOrder (javax.xml.bind.annotation.XmlAccessorOrder)3 XmlElement (javax.xml.bind.annotation.XmlElement)3 PrintWriter (java.io.PrintWriter)2 Annotation (java.lang.annotation.Annotation)2 GenericArrayType (java.lang.reflect.GenericArrayType)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 JAXBContext (javax.xml.bind.JAXBContext)2 JAXBElement (javax.xml.bind.JAXBElement)2 JAXBBeanInfo (org.apache.cxf.common.jaxb.JAXBBeanInfo)2