Search in sources :

Example 11 with XmlType

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

the class RestControllerProcessor method processRestMethodParameter.

/**
 * Process a REST method parameter.
 *
 * @param parameterSource the parameter source information.
 * @param operation the Swagger operation.
 * @param methodParamDescriptions the method parameter Javadoc descriptions.
 *
 * @throws MojoExecutionException if any problems were encountered.
 */
private void processRestMethodParameter(ParameterSource<JavaClassSource> parameterSource, Operation operation, Map<String, String> methodParamDescriptions) throws MojoExecutionException {
    log.debug("Processing parameter \"" + parameterSource.getName() + "\".");
    try {
        AnnotationSource<JavaClassSource> requestParamAnnotationSource = parameterSource.getAnnotation(RequestParam.class);
        AnnotationSource<JavaClassSource> requestBodyAnnotationSource = parameterSource.getAnnotation(RequestBody.class);
        AnnotationSource<JavaClassSource> pathVariableAnnotationSource = parameterSource.getAnnotation(PathVariable.class);
        if (requestParamAnnotationSource != null) {
            log.debug("Parameter \"" + parameterSource.getName() + "\" is a RequestParam.");
            QueryParameter queryParameter = new QueryParameter();
            queryParameter.name(requestParamAnnotationSource.getStringValue("value").trim());
            queryParameter.setRequired(BooleanUtils.toBoolean(requestParamAnnotationSource.getStringValue("required")));
            setParameterType(parameterSource, queryParameter);
            operation.parameter(queryParameter);
            setParamDescription(parameterSource, methodParamDescriptions, queryParameter);
        } else if (requestBodyAnnotationSource != null) {
            log.debug("Parameter \"" + parameterSource.getName() + "\" is a RequestBody.");
            // Add the class name to the list of classes which we will create an example for.
            exampleClassNames.add(parameterSource.getType().getSimpleName());
            BodyParameter bodyParameter = new BodyParameter();
            XmlType xmlType = getXmlType(Class.forName(parameterSource.getType().getQualifiedName()));
            String name = xmlType.name().trim();
            bodyParameter.name(name);
            bodyParameter.setRequired(true);
            bodyParameter.setSchema(new RefModel(name));
            operation.parameter(bodyParameter);
            setParamDescription(parameterSource, methodParamDescriptions, bodyParameter);
        } else if (pathVariableAnnotationSource != null) {
            log.debug("Parameter \"" + parameterSource.getName() + "\" is a PathVariable.");
            PathParameter pathParameter = new PathParameter();
            pathParameter.name(pathVariableAnnotationSource.getStringValue("value").trim());
            setParameterType(parameterSource, pathParameter);
            operation.parameter(pathParameter);
            setParamDescription(parameterSource, methodParamDescriptions, pathParameter);
        }
    } catch (ClassNotFoundException e) {
        throw new MojoExecutionException("Unable to instantiate class \"" + parameterSource.getType().getQualifiedName() + "\". Reason: " + e.getMessage(), e);
    }
}
Also used : QueryParameter(io.swagger.models.parameters.QueryParameter) RefModel(io.swagger.models.RefModel) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) BodyParameter(io.swagger.models.parameters.BodyParameter) PathParameter(io.swagger.models.parameters.PathParameter) XmlType(javax.xml.bind.annotation.XmlType)

Example 12 with XmlType

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

the class AnnotationConsistencyCheck method testImplementationAnnotations.

/**
 * Tests the annotations on every SIS implementations of the interfaces enumerated
 * in the {@link #types} array. More specifically this method tests that:
 *
 * <ul>
 *   <li>All implementation classes have {@link XmlRootElement} and {@link XmlType} annotations.</li>
 *   <li>The name declared in the {@code XmlType} annotations matches the
 *       {@link #getExpectedXmlTypeName expected value}.</li>
 *   <li>The name declared in the {@code XmlRootElement} annotations matches the identifier declared
 *       in the {@link UML} annotation of the GeoAPI interfaces, with {@code "Abstract"} prefix added
 *       if needed.</li>
 *   <li>The namespace declared in the {@code XmlRootElement} annotations is not redundant with
 *       the {@link XmlSchema} annotation in the package.</li>
 * </ul>
 *
 * This method does not check the method annotations, since it is {@link #testMethodAnnotations()} job.
 */
@Test
@DependsOnMethod("testInterfaceAnnotations")
public void testImplementationAnnotations() {
    for (final Class<?> type : types) {
        if (CodeList.class.isAssignableFrom(type)) {
            // Skip code lists, since they are not the purpose of this test.
            continue;
        }
        testingClass = type.getCanonicalName();
        /*
             * Get the implementation class, which is mandatory (otherwise the
             * subclass shall not include the interface in the 'types' array).
             */
        final Class<?> impl = getImplementation(type);
        assertNotNull("No implementation found.", impl);
        assertNotSame("No implementation found.", type, impl);
        testingClass = impl.getCanonicalName();
        /*
             * Compare the XmlRootElement with the UML annotation, if any. The UML annotation
             * is mandatory in the default implementation of the 'testInterfaceAnnotations()'
             * method, but we don't require the UML to be non-null here since this is not the
             * job of this test method. This is because subclasses may choose to override the
             * 'testInterfaceAnnotations()' method.
             */
        final XmlRootElement root = impl.getAnnotation(XmlRootElement.class);
        assertNotNull("Missing @XmlRootElement annotation.", root);
        final UML uml = type.getAnnotation(UML.class);
        // More tests on development branch (removed on trunk because test depends on GeoAPI 3.1)
        /*
             * Check that the namespace is the expected one (according subclass)
             * and is not redundant with the package @XmlSchema annotation.
             */
        assertExpectedNamespace(root.namespace(), impl, uml);
        /*
             * Compare the XmlType annotation with the expected value.
             */
        final XmlType xmlType = impl.getAnnotation(XmlType.class);
        assertNotNull("Missing @XmlType annotation.", xmlType);
    // More tests on development branch (removed on trunk because test depends on GeoAPI 3.1)
    }
}
Also used : XmlRootElement(javax.xml.bind.annotation.XmlRootElement) UML(org.opengis.annotation.UML) XmlType(javax.xml.bind.annotation.XmlType) Test(org.junit.Test) DependsOnMethod(org.apache.sis.test.DependsOnMethod)

Example 13 with XmlType

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

the class PackageVerifier method verify.

/**
 * Verifies {@code @XmlType} and {@code @XmlRootElement} on the class. This method verifies naming convention
 * (type name should be same as root element name with {@value SchemaCompliance#TYPE_SUFFIX} suffix appended),
 * ensures that the name exists in the schema, and checks the namespace.
 *
 * @param  type  the class on which to verify annotations.
 */
final void verify(final Class<?> type) throws IOException, ParserConfigurationException, SAXException, SchemaException {
    /*
         * Reinitialize fields to be updated for each class.
         */
    classNS = null;
    currentClass = type;
    isDeprecatedClass = false;
    properties = Collections.emptyMap();
    final XmlType xmlType = type.getDeclaredAnnotation(XmlType.class);
    final XmlRootElement xmlRoot = type.getDeclaredAnnotation(XmlRootElement.class);
    XmlElement codeList = null;
    /*
         * Get the type name and namespace from the @XmlType or @XmlRootElement annotations.
         * If both of them are present, verify that they are consistent (same namespace and
         * same name with "_Type" suffix in @XmlType). If the type name is not declared, we
         * assume that it is the same than the class name (this is what Apache SIS 0.8 does
         * in its org.apache.sis.internal.jaxb.code package for CodeList adapters).
         */
    // ISO class name (not the same than Java class name).
    final String isoName;
    if (xmlRoot != null) {
        classNS = xmlRoot.namespace();
        isoName = xmlRoot.name();
        if (xmlType != null) {
            if (!classNS.equals(xmlType.namespace())) {
                throw new SchemaException(errorInClassMember(null).append("Mismatched namespace in @XmlType and @XmlRootElement."));
            }
            SchemaCompliance.verifyNamingConvention(type.getName(), isoName, xmlType.name(), SchemaCompliance.TYPE_SUFFIX);
        }
    } else if (xmlType != null) {
        classNS = xmlType.namespace();
        final String name = xmlType.name();
        isoName = SchemaCompliance.trim(name, SchemaCompliance.TYPE_SUFFIX);
    } else {
        /*
             * If there is neither @XmlRootElement or @XmlType annotation, it may be a code list as implemented
             * in the org.apache.sis.internal.jaxb.code package. Those adapters have a single @XmlElement which
             * is to be interpreted as if it was the actual type.
             */
        for (final Method method : type.getDeclaredMethods()) {
            final XmlElement e = method.getDeclaredAnnotation(XmlElement.class);
            if (e != null) {
                if (codeList != null)
                    return;
                codeList = e;
            }
        }
        if (codeList == null)
            return;
        classNS = codeList.namespace();
        isoName = codeList.name();
    }
    /*
         * Verify that the namespace declared on the class is not redundant with the namespace
         * declared in the package. Actually redundant namespaces are not wrong, but we try to
         * reduce code size.
         */
    if (classNS.equals(AnnotationConsistencyCheck.DEFAULT)) {
        classNS = packageNS;
    } else if (classNS.equals(packageNS)) {
        throw new SchemaException(errorInClassMember(null).append("Redundant namespace declaration: ").append(classNS));
    }
    /*
         * Verify that the namespace has a prefix associated to it in the package-info file.
         */
    if (namespaceIsUsed.put(classNS, Boolean.TRUE) == null) {
        throw new SchemaException(errorInClassMember(null).append("No prefix in package-info for ").append(classNS));
    }
    /*
         * Properties in the legacy GMD or GMI namespaces may be deprecated, depending if a replacement
         * is already available or not. However properties in other namespaces should not be deprecated.
         * Some validations of deprecated properties are skipped because we didn't loaded their schema.
         */
    isDeprecatedClass = (LEGACY_NAMESPACES.get(classNS) == ALL);
    if (!isDeprecatedClass) {
        if (type.isAnnotationPresent(Deprecated.class)) {
            throw new SchemaException(errorInClassMember(null).append("Unexpected @Deprecated annotation."));
        }
        /*
             * Verify that class name exists, then verify its namespace (associated to the null key by convention).
             */
        properties = schemas.typeDefinition(isoName);
        if (properties == null) {
            throw new SchemaException(errorInClassMember(null).append("Unknown name declared in @XmlRootElement: ").append(isoName));
        }
        final String expectedNS = properties.get(null).namespace;
        if (!classNS.equals(expectedNS)) {
            throw new SchemaException(errorInClassMember(null).append(isoName).append(" shall be associated to namespace ").append(expectedNS));
        }
        // If the class was a code list, we are done.
        if (codeList != null)
            return;
    }
    /*
         * At this point the classNS, className, isDeprecatedClass and properties field have been set.
         * We can now loop over the XML elements, which may be on fields or on methods (public or private).
         */
    for (final Field field : type.getDeclaredFields()) {
        Class<?> valueType = field.getType();
        final boolean isCollection = Collection.class.isAssignableFrom(valueType);
        if (isCollection) {
            valueType = Classes.boundOfParameterizedProperty(field);
        }
        verify(field, field.getName(), valueType, isCollection);
    }
    for (final Method method : type.getDeclaredMethods()) {
        Class<?> valueType = method.getReturnType();
        final boolean isCollection = Collection.class.isAssignableFrom(valueType);
        if (isCollection) {
            valueType = Classes.boundOfParameterizedProperty(method);
        }
        verify(method, method.getName(), valueType, isCollection);
    }
}
Also used : XmlRootElement(javax.xml.bind.annotation.XmlRootElement) Field(java.lang.reflect.Field) XmlElement(javax.xml.bind.annotation.XmlElement) Method(java.lang.reflect.Method) XmlType(javax.xml.bind.annotation.XmlType)

Example 14 with XmlType

use of javax.xml.bind.annotation.XmlType in project tomee 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
    }
    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);
    }
    XmlSchema 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 15 with XmlType

use of javax.xml.bind.annotation.XmlType in project platformlayer by platformlayer.

the class XmlHelper method getXmlElementInfo.

public static ElementInfo getXmlElementInfo(Class<?> clazz) {
    String elementName = null;
    String namespace = null;
    XmlType xmlType = clazz.getAnnotation(XmlType.class);
    if (xmlType != null) {
        elementName = xmlType.name();
        namespace = xmlType.namespace();
    } else {
        XmlRootElement xmlRootElement = clazz.getAnnotation(XmlRootElement.class);
        if (xmlRootElement != null) {
            elementName = xmlRootElement.name();
            namespace = xmlRootElement.namespace();
        }
    }
    if ("##default".equals(elementName)) {
        elementName = StringUtils.uncapitalize(clazz.getSimpleName());
    }
    if ("##default".equals(namespace)) {
        namespace = null;
    }
    if (namespace == null) {
        Package itemPackage = clazz.getPackage();
        XmlSchema xmlSchema = itemPackage.getAnnotation(XmlSchema.class);
        if (xmlSchema != null) {
            namespace = getXmlNamespace(xmlSchema);
        }
    }
    if (elementName != null && namespace != null) {
        return new ElementInfo(namespace, elementName);
    }
    return null;
}
Also used : XmlRootElement(javax.xml.bind.annotation.XmlRootElement) XmlSchema(javax.xml.bind.annotation.XmlSchema) 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