Example usage for org.xml.sax.helpers AttributesImpl AttributesImpl

List of usage examples for org.xml.sax.helpers AttributesImpl AttributesImpl

Introduction

In this page you can find the example usage for org.xml.sax.helpers AttributesImpl AttributesImpl.

Prototype

public AttributesImpl() 

Source Link

Document

Construct a new, empty AttributesImpl object.

Usage

From source file:org.alfresco.repo.exporter.ViewXMLExporter.java

public void permission(NodeRef nodeRef, AccessPermission permission) {
    try {/*  www  .j ava 2s . c  o  m*/
        // output access control entry
        AttributesImpl attrs = new AttributesImpl();
        attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_1_0_URI, ACCESS_LOCALNAME,
                ACCESS_QNAME.toPrefixString(), null, permission.getAccessStatus().toString());
        contentHandler.startElement(ACE_QNAME.getNamespaceURI(), ACE_QNAME.getLocalName(),
                toPrefixString(ACE_QNAME), attrs);

        // output authority
        contentHandler.startElement(AUTHORITY_QNAME.getNamespaceURI(), AUTHORITY_QNAME.getLocalName(),
                toPrefixString(AUTHORITY_QNAME), EMPTY_ATTRIBUTES);
        String authority = permission.getAuthority();
        contentHandler.characters(authority.toCharArray(), 0, authority.length());
        contentHandler.endElement(AUTHORITY_QNAME.getNamespaceURI(), AUTHORITY_QNAME.getLocalName(),
                toPrefixString(AUTHORITY_QNAME));

        // output permission
        contentHandler.startElement(PERMISSION_QNAME.getNamespaceURI(), PERMISSION_QNAME.getLocalName(),
                toPrefixString(PERMISSION_QNAME), EMPTY_ATTRIBUTES);
        String strPermission = permission.getPermission();
        contentHandler.characters(strPermission.toCharArray(), 0, strPermission.length());
        contentHandler.endElement(PERMISSION_QNAME.getNamespaceURI(), PERMISSION_QNAME.getLocalName(),
                toPrefixString(PERMISSION_QNAME));

        // end access control entry
        contentHandler.endElement(ACE_QNAME.getNamespaceURI(), ACE_QNAME.getLocalName(),
                toPrefixString(ACE_QNAME));
    } catch (SAXException e) {
        throw new ExporterException("Failed to process permission event - node ref " + nodeRef.toString()
                + "; permission " + permission);
    }
}

From source file:org.alfresco.repo.exporter.ViewXMLExporter.java

public void value(NodeRef nodeRef, QName property, Object value, int index) {
    try {//  w  w  w .j  av  a 2  s.co m
        // determine data type of value
        QName valueDataType = null;
        PropertyDefinition propDef = dictionaryService.getProperty(property);
        DataTypeDefinition dataTypeDef = (propDef == null) ? null : propDef.getDataType();
        if (dataTypeDef == null || dataTypeDef.getName().equals(DataTypeDefinition.ANY)) {
            dataTypeDef = (value == null) ? null : dictionaryService.getDataType(value.getClass());
            if (dataTypeDef != null) {
                valueDataType = dataTypeDef.getName();
            }
        }

        boolean isMLText = (dataTypeDef != null && dataTypeDef.getName().equals(DataTypeDefinition.MLTEXT));

        // convert node references to paths
        if (value instanceof NodeRef && referenceType.equals(ReferenceType.PATHREF)) {
            NodeRef valueNodeRef = (NodeRef) value;
            if (nodeRef.getStoreRef().equals(valueNodeRef.getStoreRef())) {
                Path nodeRefPath = null;
                if (property.equals(ContentModel.PROP_CATEGORIES)) {
                    // Special case for categories - use the full path so that categories
                    // can be successfully assigned to imported content (provided the same store
                    // was used for both import and export and the categories still exist).
                    nodeRefPath = nodeService.getPath(valueNodeRef);
                } else {
                    nodeRefPath = createPath(context.getExportParent(), nodeRef, valueNodeRef);
                }
                value = (nodeRefPath == null) ? null : nodeRefPath.toPrefixString(namespaceService);
            }
        }

        // output value wrapper if value is null or property data type is ANY or value is part of collection
        if (value == null || valueDataType != null || index != -1) {
            AttributesImpl attrs = new AttributesImpl();
            if (value == null) {
                attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_PREFIX, ISNULL_LOCALNAME,
                        ISNULL_QNAME.toPrefixString(), null, "true");
            }
            if (valueDataType != null) {
                attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_PREFIX, DATATYPE_LOCALNAME,
                        DATATYPE_QNAME.toPrefixString(), null, toPrefixString(valueDataType));
            }
            if (!isMLText) {
                // only output for non MLTEXT values
                contentHandler.startElement(NamespaceService.REPOSITORY_VIEW_PREFIX, VALUE_LOCALNAME,
                        toPrefixString(VALUE_QNAME), attrs);
            }
        }

        // output value
        String strValue = (String) DefaultTypeConverter.INSTANCE.convert(String.class, value);
        if (strValue != null) {
            for (int i = 0; i < strValue.length(); i++) {
                char[] temp = new char[] { strValue.charAt(i) };
                contentHandler.characters(temp, 0, 1);
            }
        }

        // output value wrapper if property data type is any
        if ((value == null || valueDataType != null || index != -1) && !isMLText) {
            // only output for non MLTEXT values
            contentHandler.endElement(NamespaceService.REPOSITORY_VIEW_PREFIX, VALUE_LOCALNAME,
                    toPrefixString(VALUE_QNAME));
        }
    } catch (SAXException e) {
        throw new ExporterException("Failed to process value event - nodeRef " + nodeRef + "; property "
                + toPrefixString(property) + "; value " + value, e);
    }
}

From source file:org.alfresco.repo.exporter.ViewXMLExporter.java

public void startReference(NodeRef nodeRef, QName childName) {
    try {/*from   www  . j a v a  2 s  . co m*/
        // determine format of reference e.g. node or path based
        ReferenceType referenceFormat = referenceType;
        if (nodeRef.equals(nodeService.getRootNode(nodeRef.getStoreRef()))) {
            referenceFormat = ReferenceType.PATHREF;
        }

        // output reference
        AttributesImpl attrs = new AttributesImpl();
        if (referenceFormat.equals(ReferenceType.PATHREF)) {
            Path path = createPath(context.getExportParent(), context.getExportParent(), nodeRef);
            attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_1_0_URI, PATHREF_LOCALNAME,
                    PATHREF_QNAME.toPrefixString(), null, path.toPrefixString(namespaceService));
        } else {
            attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_1_0_URI, NODEREF_LOCALNAME,
                    NODEREF_QNAME.toPrefixString(), null, nodeRef.toString());
        }
        if (childName != null) {
            attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_1_0_URI, CHILDNAME_LOCALNAME,
                    CHILDNAME_QNAME.toPrefixString(), null, childName.toPrefixString(namespaceService));
        }
        contentHandler.startElement(REFERENCE_QNAME.getNamespaceURI(), REFERENCE_LOCALNAME,
                toPrefixString(REFERENCE_QNAME), attrs);
    } catch (SAXException e) {
        throw new ExporterException("Failed to process start reference", e);
    }
}

From source file:org.alfresco.repo.exporter.ViewXMLExporter.java

public void startValueMLText(NodeRef nodeRef, Locale locale, boolean isNull) {
    AttributesImpl attrs = new AttributesImpl();
    attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_PREFIX, LOCALE_LOCALNAME, LOCALE_QNAME.toPrefixString(),
            null, locale.toString());/*from  w  ww .j  a v a  2  s.c  o  m*/
    if (isNull) {
        attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_PREFIX, ISNULL_LOCALNAME,
                ISNULL_QNAME.toPrefixString(), null, "true");
    }
    try {
        contentHandler.startElement(NamespaceService.REPOSITORY_VIEW_PREFIX, MLVALUE_LOCALNAME,
                MLVALUE_QNAME.toPrefixString(), attrs);
    } catch (SAXException e) {
        throw new ExporterException("Failed to process start mlvalue", e);
    }
}

From source file:org.alfresco.repo.transfer.requisite.XMLTransferRequsiteWriter.java

public void missingContent(NodeRef node, QName qname, String name) {
    log.debug("write missing content");
    try {//  w w  w  . j  ava  2s .c  o  m
        AttributesImpl attributes = new AttributesImpl();
        attributes.addAttribute("uri", "nodeRef", "nodeRef", "String", node.toString());
        attributes.addAttribute("uri", "qname", "qname", "String", qname.toString());
        attributes.addAttribute("uri", "name", "name", "String", name.toString());

        // Start Missing Content
        this.writer.startElement(TransferModel.TRANSFER_MODEL_1_0_URI, RequsiteModel.LOCALNAME_ELEMENT_CONTENT,
                PREFIX + ":" + RequsiteModel.LOCALNAME_ELEMENT_CONTENT, attributes);

        // Missing Content
        writer.endElement(TransferModel.TRANSFER_MODEL_1_0_URI, RequsiteModel.LOCALNAME_ELEMENT_CONTENT,
                PREFIX + ":" + RequsiteModel.LOCALNAME_ELEMENT_CONTENT);
    } catch (SAXException se) {
        log.debug("error", se);
    }
}

From source file:org.apache.axis.deployment.wsdd.WSDDDeployableItem.java

public void writeParamsToContext(SerializationContext context) throws IOException {
    if (parameters == null)
        return;// w  w  w .  j av  a2  s.  c  om

    Set entries = parameters.entrySet();
    Iterator i = entries.iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        String name = (String) entry.getKey();
        AttributesImpl attrs = new AttributesImpl();

        attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", name);
        attrs.addAttribute("", ATTR_VALUE, ATTR_VALUE, "CDATA", entry.getValue().toString());
        if (parameters.isKeyLocked(name)) {
            attrs.addAttribute("", ATTR_LOCKED, ATTR_LOCKED, "CDATA", "true");
        }

        context.startElement(QNAME_PARAM, attrs);
        context.endElement();
    }
}

From source file:org.apache.axis.deployment.wsdd.WSDDJAXRPCHandlerInfoChain.java

/**
 * Write this element out to a SerializationContext
 *//* w  w w . ja  v a 2  s . c  om*/
public void writeToContext(SerializationContext context) throws IOException {
    context.startElement(QNAME_JAXRPC_HANDLERINFOCHAIN, null);

    List his = _hiList;
    Iterator iter = his.iterator();
    while (iter.hasNext()) {
        WSDDJAXRPCHandlerInfo hi = (WSDDJAXRPCHandlerInfo) iter.next();
        hi.writeToContext(context);
    }

    if (_roles != null) {
        for (int i = 0; i < _roles.length; i++) {
            AttributesImpl attrs1 = new AttributesImpl();
            attrs1.addAttribute("", ATTR_SOAPACTORNAME, ATTR_SOAPACTORNAME, "CDATA", _roles[i]);
            context.startElement(QNAME_JAXRPC_ROLE, attrs1);
            context.endElement();
        }
    }

    context.endElement();
}

From source file:org.apache.axis.encoding.ser.ArraySerializer.java

/**
 * Serialize an element that is an array.
 * @param name is the element name//w  w  w. j  av a2 s. c om
 * @param attributes are the attributes...serialize is free to add more.
 * @param value is the value
 * @param context is the SerializationContext
 */
public void serialize(QName name, Attributes attributes, Object value, SerializationContext context)
        throws IOException {
    if (value == null)
        throw new IOException(Messages.getMessage("cantDoNullArray00"));

    MessageContext msgContext = context.getMessageContext();
    SchemaVersion schema = SchemaVersion.SCHEMA_2001;
    SOAPConstants soap = SOAPConstants.SOAP11_CONSTANTS;
    boolean encoded = context.isEncoded();

    if (msgContext != null) {
        schema = msgContext.getSchemaVersion();
        soap = msgContext.getSOAPConstants();
    }

    Class cls = value.getClass();
    Collection list = null;

    if (!cls.isArray()) {
        if (!(value instanceof Collection)) {
            throw new IOException(Messages.getMessage("cantSerialize00", cls.getName()));
        }
        list = (Collection) value;
    }

    // Get the componentType of the array/list
    Class componentClass;
    if (list == null) {
        componentClass = cls.getComponentType();
    } else {
        componentClass = Object.class;
    }

    // Get the QName of the componentType
    // if it wasn't passed in from the constructor
    QName componentTypeQName = this.componentType;

    // Check to see if componentType is also an array.
    // If so, set the componentType to the most nested non-array
    // componentType.  Increase the dims string by "[]"
    // each time through the loop.
    // Note from Rich Scheuerle:
    //    This won't handle Lists of Lists or
    //    arrays of Lists....only arrays of arrays.
    String dims = "";

    if (componentTypeQName != null) {
        // if we have a Type QName at this point,
        // this is because ArraySerializer has been instanciated with it
        TypeMapping tm = context.getTypeMapping();
        SerializerFactory factory = (SerializerFactory) tm.getSerializer(componentClass, componentTypeQName);
        while (componentClass.isArray() && factory instanceof ArraySerializerFactory) {
            ArraySerializerFactory asf = (ArraySerializerFactory) factory;
            componentClass = componentClass.getComponentType();
            QName componentType = null;
            if (asf.getComponentType() != null) {
                componentType = asf.getComponentType();
                if (encoded) {
                    componentTypeQName = componentType;
                }
            }
            // update factory with the new values
            factory = (SerializerFactory) tm.getSerializer(componentClass, componentType);
            if (soap == SOAPConstants.SOAP12_CONSTANTS)
                dims += "* ";
            else
                dims += "[]";
        }
    } else {
        // compatibility mode
        while (componentClass.isArray()) {
            componentClass = componentClass.getComponentType();
            if (soap == SOAPConstants.SOAP12_CONSTANTS)
                dims += "* ";
            else
                dims += "[]";
        }
    }

    // Try the current XML type from the context
    if (componentTypeQName == null) {
        componentTypeQName = context.getCurrentXMLType();
        if (componentTypeQName != null) {
            if ((componentTypeQName.equals(xmlType) || componentTypeQName.equals(Constants.XSD_ANYTYPE)
                    || componentTypeQName.equals(soap.getArrayType()))) {
                componentTypeQName = null;
            }
        }
    }

    if (componentTypeQName == null) {
        componentTypeQName = context.getItemType();
    }

    // Then check the type mapping for the class
    if (componentTypeQName == null) {
        componentTypeQName = context.getQNameForClass(componentClass);
    }

    // If still not found, look at the super classes
    if (componentTypeQName == null) {
        Class searchCls = componentClass;
        while (searchCls != null && componentTypeQName == null) {
            searchCls = searchCls.getSuperclass();
            componentTypeQName = context.getQNameForClass(searchCls);
        }
        if (componentTypeQName != null) {
            componentClass = searchCls;
        }
    }

    // Still can't find it?  Throw an error.
    if (componentTypeQName == null) {
        throw new IOException(Messages.getMessage("noType00", componentClass.getName()));
    }

    int len = (list == null) ? Array.getLength(value) : list.size();
    String arrayType = "";
    int dim2Len = -1;
    if (encoded) {
        if (soap == SOAPConstants.SOAP12_CONSTANTS) {
            arrayType = dims + len;
        } else {
            arrayType = dims + "[" + len + "]";
        }

        // Discover whether array can be serialized directly as a two-dimensional
        // array (i.e. arrayType=int[2,3]) versus an array of arrays.
        // Benefits:
        //   - Less text passed on the wire.
        //   - Easier to read wire format
        //   - Tests the deserialization of multi-dimensional arrays.
        // Drawbacks:
        //   - Is not safe!  It is possible that the arrays are multiply
        //     referenced.  Transforming into a 2-dim array will cause the
        //     multi-referenced information to be lost.  Plus there is no
        //     way to determine whether the arrays are multi-referenced.
        //   - .NET currently (Dec 2002) does not support 2D SOAP-encoded arrays
        //
        // OLD Comment as to why this was ENABLED:
        // It is necessary for
        // interoperability (echo2DStringArray).  It is 'safe' for now
        // because Axis treats arrays as non multi-ref (see the note
        // in SerializationContext.isPrimitive(...) )
        // More complicated processing is necessary for 3-dim arrays, etc.
        //
        // Axis 1.1 - December 2002
        // Turned this OFF because Microsoft .NET can not deserialize
        // multi-dimensional SOAP-encoded arrays, and this interopability
        // is pretty high visibility. Make it a global configuration parameter:
        //  <parameter name="enable2DArrayEncoding" value="true"/>    (tomj)
        //

        // Check the message context to see if we should turn 2D processing ON
        // Default is OFF
        boolean enable2Dim = false;

        // Vidyanand : added this check
        if (msgContext != null) {
            enable2Dim = JavaUtils
                    .isTrueExplicitly(msgContext.getProperty(AxisEngine.PROP_TWOD_ARRAY_ENCODING));
        }

        if (enable2Dim && !dims.equals("")) {
            if (cls.isArray() && len > 0) {
                boolean okay = true;
                // Make sure all of the component arrays are the same size
                for (int i = 0; i < len && okay; i++) {

                    Object elementValue = Array.get(value, i);
                    if (elementValue == null)
                        okay = false;
                    else if (dim2Len < 0) {
                        dim2Len = Array.getLength(elementValue);
                        if (dim2Len <= 0) {
                            okay = false;
                        }
                    } else if (dim2Len != Array.getLength(elementValue)) {
                        okay = false;
                    }
                }
                // Update the arrayType to use mult-dim array encoding
                if (okay) {
                    dims = dims.substring(0, dims.length() - 2);
                    if (soap == SOAPConstants.SOAP12_CONSTANTS)
                        arrayType = dims + len + " " + dim2Len;
                    else
                        arrayType = dims + "[" + len + "," + dim2Len + "]";
                } else {
                    dim2Len = -1;
                }
            }
        }
    }

    // Need to distinguish if this is array processing for an
    // actual schema array or for a maxOccurs usage.
    // For the maxOccurs case, the currentXMLType of the context is
    // the same as the componentTypeQName.
    QName itemQName = context.getItemQName();
    boolean maxOccursUsage = !encoded && itemQName == null
            && componentTypeQName.equals(context.getCurrentXMLType());

    if (encoded) {
        AttributesImpl attrs;
        if (attributes == null) {
            attrs = new AttributesImpl();
        } else if (attributes instanceof AttributesImpl) {
            attrs = (AttributesImpl) attributes;
        } else {
            attrs = new AttributesImpl(attributes);
        }

        String compType = context.attributeQName2String(componentTypeQName);

        if (attrs.getIndex(soap.getEncodingURI(), soap.getAttrItemType()) == -1) {
            String encprefix = context.getPrefixForURI(soap.getEncodingURI());

            if (soap != SOAPConstants.SOAP12_CONSTANTS) {
                compType = compType + arrayType;

                attrs.addAttribute(soap.getEncodingURI(), soap.getAttrItemType(), encprefix + ":arrayType",
                        "CDATA", compType);

            } else {
                attrs.addAttribute(soap.getEncodingURI(), soap.getAttrItemType(), encprefix + ":itemType",
                        "CDATA", compType);

                attrs.addAttribute(soap.getEncodingURI(), "arraySize", encprefix + ":arraySize", "CDATA",
                        arrayType);
            }
        }

        // Force type to be SOAP_ARRAY for all array serialization.
        //
        // There are two choices here:
        // Force the type to type=SOAP_ARRAY
        //   Pros:  More interop test successes.
        //   Cons:  Since we have specific type information it
        //          is more correct to use it.  Plus the specific
        //          type information may be important on the
        //          server side to disambiguate overloaded operations.
        // Use the specific type information:
        //   Pros:  The specific type information is more correct
        //          and may be useful for operation overloading.
        //   Cons:  More interop test failures (as of 2/6/2002).
        //
        String qname = context.getPrefixForURI(schema.getXsiURI(), "xsi") + ":type";
        QName soapArray;
        if (soap == SOAPConstants.SOAP12_CONSTANTS) {
            soapArray = Constants.SOAP_ARRAY12;
        } else {
            soapArray = Constants.SOAP_ARRAY;
        }

        int typeI = attrs.getIndex(schema.getXsiURI(), "type");
        if (typeI != -1) {
            attrs.setAttribute(typeI, schema.getXsiURI(), "type", qname, "CDATA",
                    context.qName2String(soapArray));
        } else {
            attrs.addAttribute(schema.getXsiURI(), "type", qname, "CDATA", context.qName2String(soapArray));
        }

        attributes = attrs;
    }

    // For the maxOccurs case, each item is named with the QName
    // we got in the arguments.  For normal array case, we write an element with
    // that QName, and then serialize each item as <item>
    QName elementName = name;
    Attributes serializeAttr = attributes;
    if (!maxOccursUsage) {
        serializeAttr = null; // since we are putting them here
        context.startElement(name, attributes);
        if (itemQName != null)
            elementName = itemQName;
        else if (componentQName != null)
            elementName = componentQName;
    }

    if (dim2Len < 0) {
        // Normal case, serialize each array element
        if (list == null) {
            for (int index = 0; index < len; index++) {
                Object aValue = Array.get(value, index);

                // Serialize the element.
                context.serialize(elementName,
                        (serializeAttr == null ? serializeAttr : new AttributesImpl(serializeAttr)), aValue,
                        componentTypeQName, componentClass); // prefered type QName
            }
        } else {
            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                Object aValue = iterator.next();

                // Serialize the element.
                context.serialize(elementName,
                        (serializeAttr == null ? serializeAttr : new AttributesImpl(serializeAttr)), aValue,
                        componentTypeQName, componentClass); // prefered type QName
            }
        }
    } else {
        // Serialize as a 2 dimensional array
        for (int index = 0; index < len; index++) {
            for (int index2 = 0; index2 < dim2Len; index2++) {
                Object aValue = Array.get(Array.get(value, index), index2);
                context.serialize(elementName, null, aValue, componentTypeQName, componentClass);
            }
        }
    }

    if (!maxOccursUsage)
        context.endElement();
}

From source file:org.apache.axis.encoding.ser.BeanSerializer.java

/**
 * Check for meta-data in the bean that will tell us if any of the
 * properties are actually attributes, add those to the element
 * attribute list//from  w  w w  .  j a  v a2s.c o m
 *
 * @param value the object we are serializing
 * @return attributes for this element, null if none
 */
protected Attributes getObjectAttributes(Object value, Attributes attributes, SerializationContext context) {

    if (typeDesc == null || !typeDesc.hasAttributes())
        return attributes;

    AttributesImpl attrs;
    if (attributes == null) {
        attrs = new AttributesImpl();
    } else if (attributes instanceof AttributesImpl) {
        attrs = (AttributesImpl) attributes;
    } else {
        attrs = new AttributesImpl(attributes);
    }

    try {
        // Find each property that is an attribute
        // and add it to our attribute list
        for (int i = 0; i < propertyDescriptor.length; i++) {
            String propName = propertyDescriptor[i].getName();
            if (propName.equals("class"))
                continue;

            FieldDesc field = typeDesc.getFieldByName(propName);
            // skip it if its not an attribute
            if (field == null || field.isElement())
                continue;

            QName qname = field.getXmlName();
            if (qname == null) {
                qname = new QName("", propName);
            }

            if (propertyDescriptor[i].isReadable() && !propertyDescriptor[i].isIndexed()) {
                // add to our attributes
                Object propValue = propertyDescriptor[i].get(value);
                // Convert true/false to 1/0 in case of soapenv:mustUnderstand
                if (qname.equals(MUST_UNDERSTAND_QNAME)) {
                    if (propValue.equals(Boolean.TRUE)) {
                        propValue = "1";
                    } else if (propValue.equals(Boolean.FALSE)) {
                        propValue = "0";
                    }
                }
                // If the property value does not exist, don't serialize
                // the attribute.  In the future, the decision to serializer
                // the attribute may be more sophisticated.  For example, don't
                // serialize if the attribute matches the default value.
                if (propValue != null) {
                    setAttributeProperty(propValue, qname, field.getXmlType(), field.getJavaType(), attrs,
                            context);
                }
            }
        }
    } catch (Exception e) {
        // no attributes
        return attrs;
    }

    return attrs;
}

From source file:org.apache.axis.encoding.ser.JAFDataHandlerSerializer.java

/**
 * Serialize a JAF DataHandler quantity.
 *//* w ww .java2 s.com*/
public void serialize(QName name, Attributes attributes, Object value, SerializationContext context)
        throws IOException {
    DataHandler dh = (DataHandler) value;
    //Add the attachment content to the message.
    Attachments attachments = context.getCurrentMessage().getAttachmentsImpl();

    if (attachments == null) {
        // Attachments apparently aren't supported.
        // Instead of throwing NullPointerException like
        // we used to do, throw something meaningful.
        throw new IOException(Messages.getMessage("noAttachments"));
    }
    SOAPConstants soapConstants = context.getMessageContext().getSOAPConstants();
    Part attachmentPart = attachments.createAttachmentPart(dh);

    AttributesImpl attrs = new AttributesImpl();
    if (attributes != null && 0 < attributes.getLength())
        attrs.setAttributes(attributes); //copy the existing ones.

    int typeIndex = -1;
    if ((typeIndex = attrs.getIndex(Constants.URI_DEFAULT_SCHEMA_XSI, "type")) != -1) {

        //Found a xsi:type which should not be there for attachments.
        attrs.removeAttribute(typeIndex);
    }

    if (attachments.getSendType() == Attachments.SEND_TYPE_MTOM) {
        context.setWriteXMLType(null);
        context.startElement(name, attrs);
        AttributesImpl attrs2 = new AttributesImpl();
        attrs2.addAttribute("", soapConstants.getAttrHref(), soapConstants.getAttrHref(), "CDATA",
                attachmentPart.getContentIdRef());
        context.startElement(new QName(Constants.URI_XOP_INCLUDE, Constants.ELEM_XOP_INCLUDE), attrs2);
        context.endElement();
        context.endElement();
    } else {
        boolean doTheDIME = false;
        if (attachments.getSendType() == Attachments.SEND_TYPE_DIME)
            doTheDIME = true;

        attrs.addAttribute("", soapConstants.getAttrHref(), soapConstants.getAttrHref(), "CDATA",
                doTheDIME ? attachmentPart.getContentId() : attachmentPart.getContentIdRef());

        context.startElement(name, attrs);
        context.endElement(); //There is no data to so end the element.
    }
}