Example usage for javax.xml.bind.annotation XmlAccessType FIELD

List of usage examples for javax.xml.bind.annotation XmlAccessType FIELD

Introduction

In this page you can find the example usage for javax.xml.bind.annotation XmlAccessType FIELD.

Prototype

XmlAccessType FIELD

To view the source code for javax.xml.bind.annotation XmlAccessType FIELD.

Click Source Link

Document

Every non static, non transient field in a JAXB-bound class will be automatically bound to XML, unless annotated by XmlTransient .

Usage

From source file:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java

/**
 * @param field/*www.java 2  s .co m*/
 * @param class1
 */
private <P> void doWithPropertySafe(PropertyMetadata<T, P> metadata)
        throws IllegalArgumentException, IllegalAccessException {

    AnnotatedElement[] accessors = metadata.getAccessors();

    if (this.findJaxbAnnotation(accessors, XmlTransient.class) != null)
        return;

    XmlSchemaType xmlSchemaType = this.findJaxbAnnotation(accessors, XmlSchemaType.class);
    // a pattern for property's class - force creating
    TypedPattern<P> pattern = null;
    if (xmlSchemaType != null) {
        // the schema type determines the pattern - if it is not present in the registry, it will be present after determining it on the basis of Java class
        // of the property
        QName typeName = new QName(xmlSchemaType.namespace(), xmlSchemaType.name());
        pattern = this.patternRegistry.findPatternByType(typeName, metadata.getPropertyClass());
        if (log.isTraceEnabled() && pattern != null)
            log.trace("-- @XmlSchemaType points to {}", pattern.toString());
    }

    if (pattern == null)
        pattern = this.patternRegistry.determineAndCacheXmlPattern(metadata.getPropertyClass());

    // is it value or list?
    XmlValue xmlValue = this.findJaxbAnnotation(accessors, XmlValue.class);
    XmlList xmlList = this.findJaxbAnnotation(accessors, XmlList.class);
    if (xmlValue != null || xmlList != null) {
        // the field's class must be a simpleType, i.e., a type convertible to String, which is either:
        //  - a type registered in org.javelin.sws.ext.bind.internal.BuiltInMappings.initialize()
        //  - a type which has only one property annotated with @XmlValue
        // a type with one @XmlValue property + non-zero @XmlAttribute properties is complex type with simple content, not a simple type
        if (!(pattern.isSimpleType() && pattern instanceof SimpleContentPattern))
            throw new RuntimeException("TODO: should be simpleType");

        if (log.isTraceEnabled())
            log.trace("-- @XmlValue property \"{}\" of type {} mapped to {}", metadata.getPropertyName(),
                    pattern.getJavaType().getName(), pattern.toString());

        metadata.setPattern(pattern);
        if (this.valueMetadata != null)
            throw new RuntimeException("TODO: Only one @XmlValue allowed!");

        this.valueMetadata = metadata;
        return;
    }

    // is it an attribute?
    XmlAttribute xmlAttribute = this.findJaxbAnnotation(accessors, XmlAttribute.class);
    if (xmlAttribute != null) {
        String namespace = XMLConstants.NULL_NS_URI;
        if (this.attributeFormDefault == XmlNsForm.QUALIFIED) {
            // the attribute MUST have namespace
            namespace = "##default".equals(xmlAttribute.namespace()) ? this.typeName.getNamespaceURI()
                    : xmlAttribute.namespace();
        } else {
            // the attribute MAY have namespace
            // TODO: handle org.javelin.sws.ext.bind.annotations.XmlAttribute
            if (!"##default".equals(xmlAttribute.namespace()))
                namespace = xmlAttribute.namespace();
        }
        String name = "##default".equals(xmlAttribute.name()) ? metadata.getPropertyName()
                : xmlAttribute.name();

        if (!(pattern.isSimpleType() && pattern instanceof SimpleContentPattern))
            throw new RuntimeException("TODO: should be simpleType");

        QName attributeQName = new QName(namespace, name);

        if (log.isTraceEnabled())
            log.trace("-- @XmlAttribute property \"{}\" of type {} mapped to {} attribute {}",
                    metadata.getPropertyName(), pattern.getJavaType().getName(), attributeQName,
                    pattern.toString());

        metadata.setPattern(
                AttributePattern.newAttributePattern(attributeQName, (SimpleContentPattern<P>) pattern));
        this.childAttributeMetadata.add(metadata);
        return;
    }

    // is it an element?
    XmlElement xmlElement = this.findJaxbAnnotation(accessors, XmlElement.class);

    // field is also an element when told so using XmlAccessorType
    boolean isElement = false;

    if (accessors[0] instanceof Field) {
        if (this.accessType == XmlAccessType.FIELD)
            isElement = true;
        else if (this.accessType == XmlAccessType.PUBLIC_MEMBER
                && Modifier.isPublic(((Field) accessors[0]).getModifiers()))
            isElement = true;
    } else if (accessors[0] instanceof Method) {
        if (this.accessType == XmlAccessType.PROPERTY)
            isElement = true;
        else if (this.accessType == XmlAccessType.PUBLIC_MEMBER
                && Modifier.isPublic(((Method) accessors[0]).getModifiers())) {
            // TODO: what if getter is private and setter is public?
            isElement = true;
        }
    }

    if (xmlElement != null || isElement) {
        String namespace = XMLConstants.NULL_NS_URI;
        if (this.elementFormDefault == XmlNsForm.QUALIFIED) {
            // the element MUST have namespace
            namespace = xmlElement == null || "##default".equals(xmlElement.namespace())
                    ? this.typeName.getNamespaceURI()
                    : xmlElement.namespace();
        } else {
            // the element MAY have namespace
            if (xmlElement != null && !"##default".equals(xmlElement.namespace()))
                namespace = xmlElement.namespace();
        }
        String name = xmlElement == null || "##default".equals(xmlElement.name()) ? metadata.getPropertyName()
                : xmlElement.name();
        QName elementQName = new QName(namespace, name);

        if (log.isTraceEnabled())
            log.trace("-- @XmlElement property \"{}\" of type {} mapped to {} element with {}",
                    metadata.getPropertyName(), pattern.getJavaType().getName(), elementQName,
                    pattern.toString());

        ElementPattern<?> elementPattern = ElementPattern.newElementPattern(elementQName, pattern);
        XmlElementWrapper xmlElementWrapper = this.findJaxbAnnotation(accessors, XmlElementWrapper.class);
        if (xmlElementWrapper != null) {
            if (!"##default".equals(xmlElementWrapper.namespace()))
                namespace = xmlElementWrapper.namespace();
            name = !"##default".equals(xmlElementWrapper.name()) ? xmlElementWrapper.name()
                    : metadata.getPropertyName();

            // XmlElementWrapper creates (in XSD Category) a new complex, anonymous, nested (inside element declaration) type
            // DESIGNFLAW: XmlElementWrapper works, but not as clean as it should
            PropertyMetadata<T, ?> md = PropertyMetadata.newPropertyMetadata(this.clazz,
                    metadata.getCollectionClass(), "", PropertyKind.PASSTHROUGH);
            md.setPattern(elementPattern);
            ComplexTypePattern<T> newAnonymousType = ComplexTypePattern.newContentModelPattern(null, this.clazz,
                    md);
            // TODO: Handle @XmlElementWrapper for collection properties
            // TODO: JAXB2 doesn't allow this, but maybe it's a good idea to be able to wrap non-collection properties also?
            // TODO: maybe it's a good idea to create @XmlElementWrappers class (aggregating multime @XmlElementWrapper annotations?)
            elementPattern = ElementPattern.newElementPattern(new QName(namespace, name), newAnonymousType);
            metadata.setWrappedCollection(true);
        }

        metadata.setPattern(elementPattern);
        this.childElementMetadata.add(metadata);
        return;
    }
}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

/**
* @param value the object needing to be detached/scrubbed.
* @param checkedObjectMap This maps identityHashCodes to Objects we've already detached. In that way we can
* quickly determine if we've already done the work for the incoming value and avoid taversing it again. This
* works well almost all of the time, but it is possible that two different objects can have the same identity hash
* (conflicts are always possible with a hash). In that case we utilize the checkedObjectCollisionMap (see below).
* @param checkedObjectCollisionMap checkedObjectMap maps the identityhash to the *first* object with that hash. In
* most cases there will only be mapping for one hash, but it is possible to encounter the same hash for multiple
* objects, especially on 32bit or IBM JVMs. It is important to know if an object has already been detached
* because if it is somehow self-referencing, we have to stop the recursion. This map holds the 2nd..Nth mapping
* for a single hash and is used to ensure we never try to detach an object already processed.
* @param depth used to stop infinite recursion, defaults to a depth we don't expectto see, but it is configurable.
* @param serializationType/*from ww w . ja v a2 s .c  o m*/
* @throws Exception if a problem occurs
* @throws IllegalStateException if the recursion depth limit is reached
*/
private static void nullOutUninitializedFields(Object value, Map<Integer, Object> checkedObjectMap,
        Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType)
        throws Exception {
    if (depth > depthAllowed) {
        String warningMessage = "Recursed too deep [" + depth + " > " + depthAllowed
                + "], will not attempt to detach object of type ["
                + ((value != null) ? value.getClass().getName() : "N/A")
                + "]. This may cause serialization errors later. "
                + "You can try to work around this by setting the system property [" + DEPTH_ALLOWED_SYSPROP
                + "] to a value higher than [" + depth + "] or you can set the system property ["
                + THROW_EXCEPTION_ON_DEPTH_LIMIT_SYSPROP + "] to 'false'";
        LOG.warn(warningMessage);
        if (throwExceptionOnDepthLimit) {
            throw new IllegalStateException(warningMessage);
        }
        return;
    }

    if (null == value) {
        return;
    }

    // System.identityHashCode is a hash code, and therefore not guaranteed to be unique. And we've seen this
    // be the case.  So, we use it to try and avoid duplicating work, but handle the case when two objects may
    // have an identity crisis.
    Integer valueIdentity = hashCodeGenerator.getHashCode(value);
    Object checkedObject = checkedObjectMap.get(valueIdentity);

    if (null == checkedObject) {
        // if we have not yet encountered an object with this hash, store it in our map and start scrubbing            
        checkedObjectMap.put(valueIdentity, value);

    } else if (value == checkedObject) {
        // if we have scrubbed this already, no more work to be done            
        return;

    } else {
        // we have a situation where multiple objects have the same identity hashcode, work with our
        // collision map to decide whether it needs to be scrubbed and add if necessary.
        // Note that this code block is infrequently hit, it is by design that we've pushed the extra
        // work, map, etc, involved for this infrequent case into its own block. The standard cases must
        // be as fast and lean as possible.

        boolean alreadyDetached = false;
        List<Object> collisionObjects = checkedObjectCollisionMap.get(valueIdentity);

        if (null == collisionObjects) {
            // if this is the 2nd occurrence for this hash, create a new map entry                
            collisionObjects = new ArrayList<Object>(1);
            checkedObjectCollisionMap.put(valueIdentity, collisionObjects);

        } else {
            // if we have scrubbed this already, no more work to be done                
            for (Object collisionObject : collisionObjects) {
                if (value == collisionObject) {
                    alreadyDetached = true;
                    break;
                }
            }
        }

        if (LOG.isDebugEnabled()) {
            StringBuilder message = new StringBuilder("\n\tIDENTITY HASHCODE COLLISION [hash=");
            message.append(valueIdentity);
            message.append(", alreadyDetached=");
            message.append(alreadyDetached);
            message.append("]");
            message.append("\n\tCurrent  : ");
            message.append(value.getClass().getName());
            message.append("\n\t    ");
            message.append(value);
            message.append("\n\tPrevious : ");
            message.append(checkedObject.getClass().getName());
            message.append("\n\t    ");
            message.append(checkedObject);
            for (Object collisionObject : collisionObjects) {
                message.append("\n\tPrevious : ");
                message.append(collisionObject.getClass().getName());
                message.append("\n\t    ");
                message.append(collisionObject);
            }

            LOG.debug(message);
        }

        // now that we've done our logging, if already detached we're done. Otherwise add to the list of collision
        // objects for this hash, and start scrubbing
        if (alreadyDetached) {
            return;
        }

        collisionObjects.add(value);
    }

    // Perform the detaching
    if (value instanceof Object[]) {
        Object[] objArray = (Object[]) value;
        for (int i = 0; i < objArray.length; i++) {
            Object listEntry = objArray[i];
            Object replaceEntry = replaceObject(listEntry);
            if (replaceEntry != null) {
                objArray[i] = replaceEntry;
            }
            nullOutUninitializedFields(objArray[i], checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
    } else if (value instanceof List) {
        // Null out any entries in initialized collections
        ListIterator i = ((List) value).listIterator();
        while (i.hasNext()) {
            Object val = i.next();
            Object replace = replaceObject(val);
            if (replace != null) {
                val = replace;
                i.set(replace);
            }
            nullOutUninitializedFields(val, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }

    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        Collection itemsToBeReplaced = new ArrayList();
        Collection replacementItems = new ArrayList();
        for (Object item : collection) {
            Object replacementItem = replaceObject(item);
            if (replacementItem != null) {
                itemsToBeReplaced.add(item);
                replacementItems.add(replacementItem);
                item = replacementItem;
            }
            nullOutUninitializedFields(item, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
        collection.removeAll(itemsToBeReplaced);
        collection.addAll(replacementItems); // watch out! if this collection is a Set, HashMap$MapSet doesn't support addAll. See BZ 688000
    } else if (value instanceof Map) {
        Map originalMap = (Map) value;
        HashMap<Object, Object> replaceMap = new HashMap<Object, Object>();
        for (Iterator i = originalMap.keySet().iterator(); i.hasNext();) {
            // get original key and value - these might be hibernate proxies
            Object originalKey = i.next();
            Object originalKeyValue = originalMap.get(originalKey);

            // replace with non-hibernate classes, if appropriate (will be null otherwise)
            Object replaceKey = replaceObject(originalKey);
            Object replaceValue = replaceObject(originalKeyValue);

            // if either original key or original value was a hibernate proxy object, we have to 
            // remove it from the original map, and remember the replacement objects for later
            if (replaceKey != null || replaceValue != null) {
                Object newKey = (replaceKey != null) ? replaceKey : originalKey;
                Object newValue = (replaceValue != null) ? replaceValue : originalKeyValue;
                replaceMap.put(newKey, newValue);
                i.remove();
            }
        }

        // all hibernate proxies have been removed, we need to replace them with their
        // non-proxy object representations that we got from replaceObject() calls
        originalMap.putAll(replaceMap);

        // now go through each item in the map and null out their internal fields
        for (Object key : originalMap.keySet()) {
            nullOutUninitializedFields(originalMap.get(key), checkedObjectMap, checkedObjectCollisionMap,
                    depth + 1, serializationType);
            nullOutUninitializedFields(key, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
    } else if (value instanceof Enum) {
        // don't need to detach enums, treat them as special objects
        return;
    }

    if (serializationType == SerializationType.JAXB) {
        XmlAccessorType at = value.getClass().getAnnotation(XmlAccessorType.class);
        if (at != null && at.value() == XmlAccessType.FIELD) {
            nullOutFieldsByFieldAccess(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                    serializationType);
        } else {
            nullOutFieldsByAccessors(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                    serializationType);
        }
    } else if (serializationType == SerializationType.SERIALIZATION) {
        nullOutFieldsByFieldAccess(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                serializationType);
    }

}

From source file:ch.flashcard.HibernateDetachUtility.java

/**
 * @param value the object needing to be detached/scrubbed.
 * @param checkedObjectMap This maps identityHashCodes to Objects we've already detached. In that way we can
 * quickly determine if we've already done the work for the incoming value and avoid taversing it again. This
 * works well almost all of the time, but it is possible that two different objects can have the same identity hash
 * (conflicts are always possible with a hash). In that case we utilize the checkedObjectCollisionMap (see below).
 * @param checkedObjectCollisionMap checkedObjectMap maps the identityhash to the *first* object with that hash. In
 * most cases there will only be mapping for one hash, but it is possible to encounter the same hash for multiple
 * objects, especially on 32bit or IBM JVMs. It is important to know if an object has already been detached
 * because if it is somehow self-referencing, we have to stop the recursion. This map holds the 2nd..Nth mapping
 * for a single hash and is used to ensure we never try to detach an object already processed.
 * @param depth used to stop infinite recursion, defaults to a depth we don't expectto see, but it is configurable.
 * @param serializationType/*from  ww w. j  a  v  a 2s  .c om*/
 * @throws Exception if a problem occurs
 * @throws IllegalStateException if the recursion depth limit is reached
 */
private static void nullOutUninitializedFields(Object value, Map<Integer, Object> checkedObjectMap,
        Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType)
        throws Exception {
    if (depth > depthAllowed) {
        String warningMessage = "Recursed too deep [" + depth + " > " + depthAllowed
                + "], will not attempt to detach object of type ["
                + ((value != null) ? value.getClass().getName() : "N/A")
                + "]. This may cause serialization errors later. "
                + "You can try to work around this by setting the system property [" + DEPTH_ALLOWED_SYSPROP
                + "] to a value higher than [" + depth + "] or you can set the system property ["
                + THROW_EXCEPTION_ON_DEPTH_LIMIT_SYSPROP + "] to 'false'";
        LOG.warn(warningMessage);
        if (throwExceptionOnDepthLimit) {
            throw new IllegalStateException(warningMessage);
        }
        return;
    }

    if (null == value) {
        return;
    }

    // System.identityHashCode is a hash code, and therefore not guaranteed to be unique. And we've seen this
    // be the case.  So, we use it to try and avoid duplicating work, but handle the case when two objects may
    // have an identity crisis.
    Integer valueIdentity = hashCodeGenerator.getHashCode(value);
    Object checkedObject = checkedObjectMap.get(valueIdentity);

    if (null == checkedObject) {
        // if we have not yet encountered an object with this hash, store it in our map and start scrubbing            
        checkedObjectMap.put(valueIdentity, value);

    } else if (value == checkedObject) {
        // if we have scrubbed this already, no more work to be done            
        return;

    } else {
        // we have a situation where multiple objects have the same identity hashcode, work with our
        // collision map to decide whether it needs to be scrubbed and add if necessary.
        // Note that this code block is infrequently hit, it is by design that we've pushed the extra
        // work, map, etc, involved for this infrequent case into its own block. The standard cases must
        // be as fast and lean as possible.

        boolean alreadyDetached = false;
        List<Object> collisionObjects = checkedObjectCollisionMap.get(valueIdentity);

        if (null == collisionObjects) {
            // if this is the 2nd occurrence for this hash, create a new map entry                
            collisionObjects = new ArrayList<Object>(1);
            checkedObjectCollisionMap.put(valueIdentity, collisionObjects);

        } else {
            // if we have scrubbed this already, no more work to be done                
            for (Object collisionObject : collisionObjects) {
                if (value == collisionObject) {
                    alreadyDetached = true;
                    break;
                }
            }
        }

        if (LOG.isDebugEnabled()) {
            StringBuilder message = new StringBuilder("\n\tIDENTITY HASHCODE COLLISION [hash=");
            message.append(valueIdentity);
            message.append(", alreadyDetached=");
            message.append(alreadyDetached);
            message.append("]");
            message.append("\n\tCurrent  : ");
            message.append(value.getClass().getName());
            message.append("\n\t    ");
            message.append(value);
            message.append("\n\tPrevious : ");
            message.append(checkedObject.getClass().getName());
            message.append("\n\t    ");
            message.append(checkedObject);
            for (Object collisionObject : collisionObjects) {
                message.append("\n\tPrevious : ");
                message.append(collisionObject.getClass().getName());
                message.append("\n\t    ");
                message.append(collisionObject);
            }

            LOG.debug(message);
        }

        // now that we've done our logging, if already detached we're done. Otherwise add to the list of collision
        // objects for this hash, and start scrubbing
        if (alreadyDetached) {
            return;
        }

        collisionObjects.add(value);
    }

    // Perform the detaching
    if (value instanceof Object[]) {
        Object[] objArray = (Object[]) value;
        for (int i = 0; i < objArray.length; i++) {
            Object listEntry = objArray[i];
            Object replaceEntry = replaceObject(listEntry);
            if (replaceEntry != null) {
                objArray[i] = replaceEntry;
            }
            nullOutUninitializedFields(objArray[i], checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
    } else if (value instanceof List) {
        // Null out any entries in initialized collections
        ListIterator i = ((List) value).listIterator();
        while (i.hasNext()) {
            Object val = i.next();
            Object replace = replaceObject(val);
            if (replace != null) {
                val = replace;
                i.set(replace);
            }
            nullOutUninitializedFields(val, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }

    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        Collection itemsToBeReplaced = new ArrayList();
        Collection replacementItems = new ArrayList();
        for (Object item : collection) {
            Object replacementItem = replaceObject(item);
            if (replacementItem != null) {
                itemsToBeReplaced.add(item);
                replacementItems.add(replacementItem);
                item = replacementItem;
            }
            nullOutUninitializedFields(item, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
        collection.removeAll(itemsToBeReplaced);
        collection.addAll(replacementItems); // watch out! if this collection is a Set, HashMap$MapSet doesn't support addAll. See BZ 688000
    } else if (value instanceof Map) {
        Map originalMap = (Map) value;
        HashMap<Object, Object> replaceMap = new HashMap<Object, Object>();
        for (Iterator i = originalMap.keySet().iterator(); i.hasNext();) {
            // get original key and value - these might be hibernate proxies
            Object originalKey = i.next();
            Object originalKeyValue = originalMap.get(originalKey);

            // replace with non-hibernate classes, if appropriate (will be null otherwise)
            Object replaceKey = replaceObject(originalKey);
            Object replaceValue = replaceObject(originalKeyValue);

            // if either original key or original value was a hibernate proxy object, we have to 
            // remove it from the original map, and remember the replacement objects for later
            if (replaceKey != null || replaceValue != null) {
                Object newKey = (replaceKey != null) ? replaceKey : originalKey;
                Object newValue = (replaceValue != null) ? replaceValue : originalKeyValue;
                replaceMap.put(newKey, newValue);
                i.remove();
            }
        }

        // all hibernate proxies have been removed, we need to replace them with their
        // non-proxy object representations that we got from replaceObject() calls
        originalMap.putAll(replaceMap);

        // now go through each item in the map and null out their internal fields
        for (Object key : originalMap.keySet()) {
            nullOutUninitializedFields(originalMap.get(key), checkedObjectMap, checkedObjectCollisionMap,
                    depth + 1, serializationType);
            nullOutUninitializedFields(key, checkedObjectMap, checkedObjectCollisionMap, depth + 1,
                    serializationType);
        }
    } else if (value instanceof Enum) {
        // don't need to detach enums, treat them as special objects
        return;
    }

    if (serializationType == SerializationType.JAXB) {
        XmlAccessorType at = (XmlAccessorType) value.getClass().getAnnotation(XmlAccessorType.class);
        if (at != null && at.value() == XmlAccessType.FIELD) {
            nullOutFieldsByFieldAccess(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                    serializationType);
        } else {
            nullOutFieldsByAccessors(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                    serializationType);
        }
    } else if (serializationType == SerializationType.SERIALIZATION) {
        nullOutFieldsByFieldAccess(value, checkedObjectMap, checkedObjectCollisionMap, depth,
                serializationType);
    }

}