Search in sources :

Example 26 with XmlRootElement

use of javax.xml.bind.annotation.XmlRootElement in project swagger-core by swagger-api.

the class ModelResolver method resolve.

public Model resolve(JavaType type, ModelConverterContext context, Iterator<ModelConverter> next) {
    if (type.isEnumType() || PrimitiveType.fromType(type) != null) {
        // We don't build models for primitive types
        return null;
    }
    final BeanDescription beanDesc = _mapper.getSerializationConfig().introspect(type);
    // Couple of possibilities for defining
    String name = _typeName(type, beanDesc);
    if ("Object".equals(name)) {
        return new ModelImpl();
    }
    /**
         * --Preventing parent/child hierarchy creation loops - Comment 1--
         * Creating a parent model will result in the creation of child models. Creating a child model will result in
         * the creation of a parent model, as per the second If statement following this comment.
         *
         * By checking whether a model has already been resolved (as implemented below), loops of parents creating
         * children and children creating parents can be short-circuited. This works because currently the
         * ModelConverterContextImpl will return null for a class that already been processed, but has not yet been
         * defined. This logic works in conjunction with the early immediate definition of model in the context
         * implemented later in this method (See "Preventing parent/child hierarchy creation loops - Comment 2") to
         * prevent such
         */
    Model resolvedModel = context.resolve(type.getRawClass());
    if (resolvedModel != null) {
        if (!(resolvedModel instanceof ModelImpl || resolvedModel instanceof ComposedModel) || (resolvedModel instanceof ModelImpl && ((ModelImpl) resolvedModel).getName().equals(name))) {
            return resolvedModel;
        } else if (resolvedModel instanceof ComposedModel) {
            Model childModel = ((ComposedModel) resolvedModel).getChild();
            if (childModel != null && (!(childModel instanceof ModelImpl) || ((ModelImpl) childModel).getName().equals(name))) {
                return resolvedModel;
            }
        }
    }
    final ModelImpl model = new ModelImpl().type(ModelImpl.OBJECT).name(name).description(_description(beanDesc.getClassInfo()));
    if (!type.isContainerType()) {
        // define the model here to support self/cyclic referencing of models
        context.defineModel(name, model, type, null);
    }
    if (type.isContainerType()) {
        // We treat collections as primitive types, just need to add models for values (if any)
        context.resolve(type.getContentType());
        return null;
    }
    // if XmlRootElement annotation, construct an Xml object and attach it to the model
    XmlRootElement rootAnnotation = beanDesc.getClassAnnotations().get(XmlRootElement.class);
    if (rootAnnotation != null && !"".equals(rootAnnotation.name()) && !"##default".equals(rootAnnotation.name())) {
        LOGGER.debug("{}", rootAnnotation);
        Xml xml = new Xml().name(rootAnnotation.name());
        if (rootAnnotation.namespace() != null && !"".equals(rootAnnotation.namespace()) && !"##default".equals(rootAnnotation.namespace())) {
            xml.namespace(rootAnnotation.namespace());
        }
        model.xml(xml);
    }
    final XmlAccessorType xmlAccessorTypeAnnotation = beanDesc.getClassAnnotations().get(XmlAccessorType.class);
    // see if @JsonIgnoreProperties exist
    Set<String> propertiesToIgnore = new HashSet<String>();
    JsonIgnoreProperties ignoreProperties = beanDesc.getClassAnnotations().get(JsonIgnoreProperties.class);
    if (ignoreProperties != null) {
        propertiesToIgnore.addAll(Arrays.asList(ignoreProperties.value()));
    }
    final ApiModel apiModel = beanDesc.getClassAnnotations().get(ApiModel.class);
    String disc = (apiModel == null) ? "" : apiModel.discriminator();
    if (apiModel != null && StringUtils.isNotEmpty(apiModel.reference())) {
        model.setReference(apiModel.reference());
    }
    if (disc.isEmpty()) {
        // longer method would involve AnnotationIntrospector.findTypeResolver(...) but:
        JsonTypeInfo typeInfo = beanDesc.getClassAnnotations().get(JsonTypeInfo.class);
        if (typeInfo != null) {
            disc = typeInfo.property();
        }
    }
    if (!disc.isEmpty()) {
        model.setDiscriminator(disc);
    }
    List<Property> props = new ArrayList<Property>();
    for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
        Property property = null;
        String propName = propDef.getName();
        Annotation[] annotations = null;
        // it's ugly but gets around https://github.com/swagger-api/swagger-core/issues/415
        if (propDef.getPrimaryMember() != null) {
            java.lang.reflect.Member member = propDef.getPrimaryMember().getMember();
            if (member != null) {
                String altName = member.getName();
                if (altName != null) {
                    final int length = altName.length();
                    for (String prefix : Arrays.asList("get", "is")) {
                        final int offset = prefix.length();
                        if (altName.startsWith(prefix) && length > offset && !Character.isUpperCase(altName.charAt(offset))) {
                            propName = altName;
                            break;
                        }
                    }
                }
            }
        }
        PropertyMetadata md = propDef.getMetadata();
        boolean hasSetter = false, hasGetter = false;
        try {
            if (propDef.getSetter() == null) {
                hasSetter = false;
            } else {
                hasSetter = true;
            }
        } catch (IllegalArgumentException e) {
            //com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder would throw IllegalArgumentException
            // if there are overloaded setters. If we only want to know whether a set method exists, suppress the exception
            // is reasonable.
            // More logs might be added here
            hasSetter = true;
        }
        if (propDef.getGetter() != null) {
            JsonProperty pd = propDef.getGetter().getAnnotation(JsonProperty.class);
            if (pd != null) {
                hasGetter = true;
            }
        }
        Boolean isReadOnly = null;
        if (!hasSetter & hasGetter) {
            isReadOnly = Boolean.TRUE;
        } else {
            isReadOnly = Boolean.FALSE;
        }
        final AnnotatedMember member = propDef.getPrimaryMember();
        Boolean allowEmptyValue = null;
        if (member != null && !ignore(member, xmlAccessorTypeAnnotation, propName, propertiesToIgnore)) {
            List<Annotation> annotationList = new ArrayList<Annotation>();
            for (Annotation a : member.annotations()) {
                annotationList.add(a);
            }
            annotations = annotationList.toArray(new Annotation[annotationList.size()]);
            ApiModelProperty mp = member.getAnnotation(ApiModelProperty.class);
            if (mp != null && mp.readOnly()) {
                isReadOnly = mp.readOnly();
            }
            if (mp != null && mp.allowEmptyValue()) {
                allowEmptyValue = mp.allowEmptyValue();
            } else {
                allowEmptyValue = null;
            }
            JavaType propType = member.getType(beanDesc.bindingsForBeanType());
            // allow override of name from annotation
            if (mp != null && !mp.name().isEmpty()) {
                propName = mp.name();
            }
            if (mp != null && !mp.dataType().isEmpty()) {
                String or = mp.dataType();
                JavaType innerJavaType = null;
                LOGGER.debug("overriding datatype from {} to {}", propType, or);
                if (or.toLowerCase().startsWith("list[")) {
                    String innerType = or.substring(5, or.length() - 1);
                    ArrayProperty p = new ArrayProperty();
                    Property primitiveProperty = PrimitiveType.createProperty(innerType);
                    if (primitiveProperty != null) {
                        p.setItems(primitiveProperty);
                    } else {
                        innerJavaType = getInnerType(innerType);
                        p.setItems(context.resolveProperty(innerJavaType, annotations));
                    }
                    property = p;
                } else if (or.toLowerCase().startsWith("map[")) {
                    int pos = or.indexOf(",");
                    if (pos > 0) {
                        String innerType = or.substring(pos + 1, or.length() - 1);
                        MapProperty p = new MapProperty();
                        Property primitiveProperty = PrimitiveType.createProperty(innerType);
                        if (primitiveProperty != null) {
                            p.setAdditionalProperties(primitiveProperty);
                        } else {
                            innerJavaType = getInnerType(innerType);
                            p.setAdditionalProperties(context.resolveProperty(innerJavaType, annotations));
                        }
                        property = p;
                    }
                } else {
                    Property primitiveProperty = PrimitiveType.createProperty(or);
                    if (primitiveProperty != null) {
                        property = primitiveProperty;
                    } else {
                        innerJavaType = getInnerType(or);
                        property = context.resolveProperty(innerJavaType, annotations);
                    }
                }
                if (innerJavaType != null) {
                    context.resolve(innerJavaType);
                }
            }
            // no property from override, construct from propType
            if (property == null) {
                if (mp != null && StringUtils.isNotEmpty(mp.reference())) {
                    property = new RefProperty(mp.reference());
                } else if (member.getAnnotation(JsonIdentityInfo.class) != null) {
                    property = GeneratorWrapper.processJsonIdentity(propType, context, _mapper, member.getAnnotation(JsonIdentityInfo.class), member.getAnnotation(JsonIdentityReference.class));
                }
                if (property == null) {
                    JsonUnwrapped uw = member.getAnnotation(JsonUnwrapped.class);
                    if (uw != null && uw.enabled()) {
                        handleUnwrapped(props, context.resolve(propType), uw.prefix(), uw.suffix());
                    } else {
                        property = context.resolveProperty(propType, annotations);
                    }
                }
            }
            if (property != null) {
                property.setName(propName);
                if (mp != null && !mp.access().isEmpty()) {
                    property.setAccess(mp.access());
                }
                Boolean required = md.getRequired();
                if (required != null) {
                    property.setRequired(required);
                }
                String description = _intr.findPropertyDescription(member);
                if (description != null && !"".equals(description)) {
                    property.setDescription(description);
                }
                Integer index = _intr.findPropertyIndex(member);
                if (index != null) {
                    property.setPosition(index);
                }
                property.setDefault(_findDefaultValue(member));
                property.setExample(_findExampleValue(member));
                property.setReadOnly(_findReadOnly(member));
                if (allowEmptyValue != null) {
                    property.setAllowEmptyValue(allowEmptyValue);
                }
                if (property.getReadOnly() == null) {
                    if (isReadOnly) {
                        property.setReadOnly(isReadOnly);
                    }
                }
                if (mp != null) {
                    final AllowableValues allowableValues = AllowableValuesUtils.create(mp.allowableValues());
                    if (allowableValues != null) {
                        final Map<PropertyBuilder.PropertyId, Object> args = allowableValues.asPropertyArguments();
                        PropertyBuilder.merge(property, args);
                    }
                }
                JAXBAnnotationsHelper.apply(member, property);
                applyBeanValidatorAnnotations(property, annotations);
                props.add(property);
            }
        }
    }
    Collections.sort(props, getPropertyComparator());
    Map<String, Property> modelProps = new LinkedHashMap<String, Property>();
    for (Property prop : props) {
        modelProps.put(prop.getName(), prop);
    }
    model.setProperties(modelProps);
    /**
         * --Preventing parent/child hierarchy creation loops - Comment 2--
         * Creating a parent model will result in the creation of child models, as per the first If statement following
         * this comment. Creating a child model will result in the creation of a parent model, as per the second If
         * statement following this comment.
         *
         * The current model must be defined in the context immediately. This done to help prevent repeated
         * loops where  parents create children and children create parents when a hierarchy is present. This logic
         * works in conjunction with the "early checking" performed earlier in this method
         * (See "Preventing parent/child hierarchy creation loops - Comment 1"), to prevent repeated creation loops.
         *
         *
         * As an aside, defining the current model in the context immediately also ensures that child models are
         * available for modification by resolveSubtypes, when their parents are created.
         */
    Class<?> currentType = type.getRawClass();
    context.defineModel(name, model, currentType, null);
    /**
         * This must be done after model.setProperties so that the model's set
         * of properties is available to filter from any subtypes
         **/
    if (!resolveSubtypes(model, beanDesc, context)) {
        model.setDiscriminator(null);
    }
    if (apiModel != null) {
        /**
             * Check if the @ApiModel annotation has a parent property containing a value that should not be ignored
             */
        Class<?> parentClass = apiModel.parent();
        if (parentClass != null && !parentClass.equals(Void.class) && !this.shouldIgnoreClass(parentClass)) {
            JavaType parentType = _mapper.constructType(parentClass);
            final BeanDescription parentBeanDesc = _mapper.getSerializationConfig().introspect(parentType);
            /**
                 * Retrieve all the sub-types of the parent class and ensure that the current type is one of those types
                 */
            boolean currentTypeIsParentSubType = false;
            List<NamedType> subTypes = _intr.findSubtypes(parentBeanDesc.getClassInfo());
            if (subTypes != null) {
                for (NamedType subType : subTypes) {
                    if (subType.getType().equals(currentType)) {
                        currentTypeIsParentSubType = true;
                        break;
                    }
                }
            }
            /**
                 Retrieve the subTypes from the parent class @ApiModel annotation and ensure that the current type
                 is one of those types.
                 */
            boolean currentTypeIsParentApiModelSubType = false;
            final ApiModel parentApiModel = parentBeanDesc.getClassAnnotations().get(ApiModel.class);
            if (parentApiModel != null) {
                Class<?>[] apiModelSubTypes = parentApiModel.subTypes();
                if (apiModelSubTypes != null) {
                    for (Class<?> subType : apiModelSubTypes) {
                        if (subType.equals(currentType)) {
                            currentTypeIsParentApiModelSubType = true;
                            break;
                        }
                    }
                }
            }
            /**
                 If the current type is a sub-type of the parent class and is listed in the subTypes property of the
                 parent class @ApiModel annotation, then do the following:
                 1. Resolve the model for the parent class. This will result in the parent model being created, and the
                 current child model being updated to be a ComposedModel referencing the parent.
                 2. Resolve and return the current child type again. This will return the new ComposedModel from the
                 context, which was created in step 1 above. Admittedly, there is a small chance that this may result
                 in a stack overflow, if the context does not correctly cache the model for the current type. However,
                 as context caching is assumed elsewhere to avoid cyclical model creation, this was deemed to be
                 sufficient.
                 */
            if (currentTypeIsParentSubType && currentTypeIsParentApiModelSubType) {
                context.resolve(parentClass);
                return context.resolve(currentType);
            }
        }
    }
    return model;
}
Also used : ApiModelProperty(io.swagger.annotations.ApiModelProperty) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) ComposedModel(io.swagger.models.ComposedModel) MapProperty(io.swagger.models.properties.MapProperty) ArrayList(java.util.ArrayList) AnnotatedMember(com.fasterxml.jackson.databind.introspect.AnnotatedMember) AllowableValues(io.swagger.util.AllowableValues) LinkedHashMap(java.util.LinkedHashMap) PropertyMetadata(com.fasterxml.jackson.databind.PropertyMetadata) HashSet(java.util.HashSet) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) ArrayProperty(io.swagger.models.properties.ArrayProperty) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) JsonIdentityReference(com.fasterxml.jackson.annotation.JsonIdentityReference) JavaType(com.fasterxml.jackson.databind.JavaType) XmlAccessorType(javax.xml.bind.annotation.XmlAccessorType) NamedType(com.fasterxml.jackson.databind.jsontype.NamedType) ApiModel(io.swagger.annotations.ApiModel) JsonIgnoreProperties(com.fasterxml.jackson.annotation.JsonIgnoreProperties) RefProperty(io.swagger.models.properties.RefProperty) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) ModelImpl(io.swagger.models.ModelImpl) JsonUnwrapped(com.fasterxml.jackson.annotation.JsonUnwrapped) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) MapProperty(io.swagger.models.properties.MapProperty) UUIDProperty(io.swagger.models.properties.UUIDProperty) ApiModelProperty(io.swagger.annotations.ApiModelProperty) AbstractNumericProperty(io.swagger.models.properties.AbstractNumericProperty) RefProperty(io.swagger.models.properties.RefProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) Annotation(java.lang.annotation.Annotation) JsonIdentityInfo(com.fasterxml.jackson.annotation.JsonIdentityInfo) Xml(io.swagger.models.Xml) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) ComposedModel(io.swagger.models.ComposedModel) ApiModel(io.swagger.annotations.ApiModel)

Example 27 with XmlRootElement

use of javax.xml.bind.annotation.XmlRootElement in project camel by apache.

the class TypeNameStrategy method findQNameForSoapActionOrType.

/**
     * @return determine element name by using the XmlType.name() of the type to
     *         be marshalled and the XmlSchema.namespace() of the package-info
     */
public QName findQNameForSoapActionOrType(String soapAction, Class<?> type) {
    XmlType xmlType = type.getAnnotation(XmlType.class);
    if (xmlType == null || xmlType.name() == null) {
        throw new RuntimeException("The type " + type.getName() + " needs to have an XmlType annotation with name");
    }
    String nameSpace = xmlType.namespace();
    if ("##default".equals(nameSpace)) {
        XmlSchema xmlSchema = type.getPackage().getAnnotation(XmlSchema.class);
        if (xmlSchema != null) {
            nameSpace = xmlSchema.namespace();
        }
    }
    // prefer name from the XmlType, and fallback to XmlRootElement
    String localName = xmlType.name();
    if (ObjectHelper.isEmpty(localName)) {
        XmlRootElement root = type.getAnnotation(XmlRootElement.class);
        if (root != null) {
            localName = root.name();
        }
    }
    return new QName(nameSpace, localName);
}
Also used : XmlRootElement(javax.xml.bind.annotation.XmlRootElement) XmlSchema(javax.xml.bind.annotation.XmlSchema) QName(javax.xml.namespace.QName) XmlType(javax.xml.bind.annotation.XmlType)

Example 28 with XmlRootElement

use of javax.xml.bind.annotation.XmlRootElement in project camel by apache.

the class XmlRootElementPreferringElementNameStrategy method findQNameForSoapActionOrType.

@Override
public QName findQNameForSoapActionOrType(String soapAction, Class<?> type) {
    XmlType xmlType = type.getAnnotation(XmlType.class);
    if (xmlType == null || xmlType.name() == null) {
        throw new RuntimeException("The type " + type.getName() + " needs to have an XmlType annotation with name");
    }
    // prefer name+ns from the XmlRootElement, and fallback to XmlType
    String localName = null;
    String nameSpace = null;
    XmlRootElement root = type.getAnnotation(XmlRootElement.class);
    if (root != null) {
        localName = ObjectHelper.isEmpty(localName) ? root.name() : localName;
        nameSpace = isInValidNamespace(nameSpace) ? root.namespace() : nameSpace;
    }
    if (ObjectHelper.isEmpty(localName)) {
        localName = xmlType.name();
    }
    if (isInValidNamespace(nameSpace)) {
        XmlSchema xmlSchema = type.getPackage().getAnnotation(XmlSchema.class);
        if (xmlSchema != null) {
            nameSpace = xmlSchema.namespace();
        }
    }
    if (isInValidNamespace(nameSpace)) {
        nameSpace = xmlType.namespace();
    }
    if (ObjectHelper.isEmpty(localName) || isInValidNamespace(nameSpace)) {
        throw new IllegalStateException("Unable to determine localName or namespace for type <" + type.getName() + ">");
    }
    return new QName(nameSpace, localName);
}
Also used : XmlRootElement(javax.xml.bind.annotation.XmlRootElement) XmlSchema(javax.xml.bind.annotation.XmlSchema) QName(javax.xml.namespace.QName) XmlType(javax.xml.bind.annotation.XmlType)

Example 29 with XmlRootElement

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

the class ModelXmlWriter method getElementName.

protected String getElementName(Object o) {
    Class<?> c = o.getClass();
    String name = ELEMENT_NAME_CACHE.get(c);
    if (name != null) {
        return name;
    }
    XmlRootElement xre = c.getAnnotation(XmlRootElement.class);
    String namespace = null;
    if (xre != null) {
        Package p = c.getPackage();
        if (p != null) {
            XmlSchema schema = p.getAnnotation(XmlSchema.class);
            if (schema != null && schema.xmlns() != null) {
                if (usedNamespacePrefixs == null) {
                    usedNamespacePrefixs = new HashMap<>();
                }
                for (XmlNs xns : schema.xmlns()) {
                    if (!usedNamespacePrefixs.containsKey(xns.namespaceURI())) {
                        usedNamespacePrefixs.put(xns.namespaceURI(), xns.prefix());
                    }
                }
            }
        }
        namespace = xre.namespace();
        if (!"##default".equals(xre.name())) {
            name = getTagName(namespace, xre.name());
        }
    } else {
        XmlElement x = c.getAnnotation(XmlElement.class);
        if (x != null) {
            namespace = x.namespace();
            if (!"##default".equals(x.name())) {
                name = getTagName(namespace, x.name());
            }
        }
    }
    if (name == null) {
        String oname = o.getClass().getSimpleName();
        if (oname.endsWith("[]")) {
            oname = oname.substring(0, oname.length() - 2);
        }
        if (Character.isUpperCase(oname.charAt(0))) {
            char[] namechars = oname.toCharArray();
            int stop = 1;
            for (int i = 1; i < namechars.length; i++) {
                if (Character.isUpperCase(namechars[i])) {
                    stop++;
                    continue;
                }
                if (stop > 1) {
                    stop--;
                }
                break;
            }
            for (int i = 0; i < stop; i++) {
                namechars[i] = Character.toLowerCase(namechars[i]);
            }
            oname = new String(namechars);
        }
        name = getTagName(namespace, oname);
    }
    ELEMENT_NAME_CACHE.put(c, name);
    return name;
}
Also used : XmlRootElement(javax.xml.bind.annotation.XmlRootElement) XmlSchema(javax.xml.bind.annotation.XmlSchema) XmlNs(javax.xml.bind.annotation.XmlNs) XmlElement(javax.xml.bind.annotation.XmlElement)

Example 30 with XmlRootElement

use of javax.xml.bind.annotation.XmlRootElement in project jaffa-framework by jaffa-projects.

the class AttachmentService method createAttachmentData.

/**
 * Converts the input attachment into an array of bytes.
 * The following algorithm is used for conversion
 *   - If the input is an array of bytes, then it is returned as is.
 *   - If the input is a String, then its getBytes() method is used to generate the output.
 *   - If the input is a File, then its contents are loaded to generate the output.
 *   - If the input carries the JAXB annotation, then it is marshalled into XML using JAXB.
 *   - If none of the above are satisfied, the attachment is marshalled into XML using the XMLEncoder.
 * @param attachment the attachment to be converted
 * @throws FrameworkException If any system error occurs.
 * @throws ApplicationExceptions If any application error occurs.
 * @return the attachment as an array of bytes.
 */
public static byte[] createAttachmentData(Object attachment) throws FrameworkException, ApplicationExceptions {
    try {
        byte[] data = null;
        if (attachment.getClass().isArray() && attachment.getClass().getComponentType() == Byte.TYPE) {
            if (log.isDebugEnabled())
                log.debug("A byte[] has been passed in. Will be used as is");
            data = (byte[]) attachment;
        } else if (attachment instanceof String) {
            if (log.isDebugEnabled())
                log.debug("A String has been passed in. The getBytes() method will be used to create attachment data");
            data = ((String) attachment).getBytes();
        } else if (attachment instanceof File) {
            if (log.isDebugEnabled())
                log.debug("A File has been passed in. The File contents will be used to create attachment data");
            InputStream is = null;
            ByteArrayOutputStream bos = null;
            try {
                // Write the file contents to a ByteArrayOutputStream
                is = new BufferedInputStream(new FileInputStream((File) attachment));
                bos = new ByteArrayOutputStream();
                int b;
                while ((b = is.read()) != -1) bos.write(b);
                bos.flush();
                data = bos.toByteArray();
            } finally {
                try {
                    if (bos != null)
                        bos.close();
                } catch (IOException e) {
                // do nothing
                }
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                // do nothing
                }
            }
        } else if (attachment.getClass().isAnnotationPresent(XmlRootElement.class)) {
            if (log.isDebugEnabled())
                log.debug(attachment.getClass().getName() + " has the 'XmlRootElement' JAXB annotation, and hence will be marshalled using JAXB");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            JAXBContext jc = JAXBHelper.obtainJAXBContext(attachment.getClass());
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(attachment, new BufferedOutputStream(os));
            data = os.toByteArray();
        } else {
            if (log.isDebugEnabled())
                log.debug(attachment.getClass().getName() + " does not have the 'XmlRootElement' JAXB annotation, and hence will be marshalled using XMLEncoder");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            XMLEncoder e = new XMLEncoder(new BufferedOutputStream(os));
            e.writeObject(attachment);
            e.close();
            data = os.toByteArray();
        }
        return data;
    } catch (Exception e) {
        throw ExceptionHelper.throwAFR(e);
    }
}
Also used : XmlRootElement(javax.xml.bind.annotation.XmlRootElement) Marshaller(javax.xml.bind.Marshaller) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JAXBContext(javax.xml.bind.JAXBContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FrameworkException(org.jaffa.exceptions.FrameworkException) IOException(java.io.IOException) XMLEncoder(java.beans.XMLEncoder) BufferedInputStream(java.io.BufferedInputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

XmlRootElement (javax.xml.bind.annotation.XmlRootElement)39 XmlSchema (javax.xml.bind.annotation.XmlSchema)11 XmlType (javax.xml.bind.annotation.XmlType)9 QName (javax.xml.namespace.QName)9 LinkedHashSet (java.util.LinkedHashSet)6 TreeSet (java.util.TreeSet)6 TypeElement (javax.lang.model.element.TypeElement)6 AnnotationProcessorHelper.findTypeElement (org.apache.camel.tools.apt.AnnotationProcessorHelper.findTypeElement)6 Method (java.lang.reflect.Method)5 TypeMirror (javax.lang.model.type.TypeMirror)5 Elements (javax.lang.model.util.Elements)5 XmlElements (javax.xml.bind.annotation.XmlElements)5 Metadata (org.apache.camel.spi.Metadata)5 HashSet (java.util.HashSet)4 Test (org.junit.Test)4 XmlAccessorType (javax.xml.bind.annotation.XmlAccessorType)3 JsonIgnoreProperties (com.fasterxml.jackson.annotation.JsonIgnoreProperties)2 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)2 JsonTypeInfo (com.fasterxml.jackson.annotation.JsonTypeInfo)2 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)2