Example usage for javax.xml.namespace QName getLocalPart

List of usage examples for javax.xml.namespace QName getLocalPart

Introduction

In this page you can find the example usage for javax.xml.namespace QName getLocalPart.

Prototype

public String getLocalPart() 

Source Link

Document

Get the local part of this QName.

Usage

From source file:org.apache.axis.description.TypeDesc.java

/**
 * Get the field name associated with this QName, but only if it's
 * marked as an element.//from w  w  w  .ja v a2s.  c  om
 * 
 * If the "ignoreNS" argument is true, just compare localNames.
 */
public String getFieldNameForElement(QName qname, boolean ignoreNS) {
    // have we already computed the answer to this question?
    if (fieldElementMap != null) {
        String cached = (String) fieldElementMap.get(qname);
        if (cached != null)
            return cached;
    }

    String result = null;

    String localPart = qname.getLocalPart();

    // check fields in this class
    for (int i = 0; fields != null && i < fields.length; i++) {
        FieldDesc field = fields[i];
        if (field.isElement()) {
            QName xmlName = field.getXmlName();
            if (localPart.equals(xmlName.getLocalPart())) {
                if (ignoreNS || qname.getNamespaceURI().equals(xmlName.getNamespaceURI())) {
                    result = field.getFieldName();
                    break;
                }
            }
        }
    }

    // check superclasses if they exist
    // and we are allowed to look
    if (result == null && canSearchParents) {
        if (parentDesc != null) {
            result = parentDesc.getFieldNameForElement(qname, ignoreNS);
        }
    }

    // cache the answer away for quicker retrieval next time.
    if (result != null) {
        if (fieldElementMap == null)
            fieldElementMap = new HashMap();
        fieldElementMap.put(qname, result);
    }

    return result;
}

From source file:org.apache.axis.description.TypeDesc.java

/**
 * Get the field name associated with this QName, but only if it's
 * marked as an attribute.//w  w w  .j a  v  a  2 s .  com
 */
public String getFieldNameForAttribute(QName qname) {
    String possibleMatch = null;

    for (int i = 0; fields != null && i < fields.length; i++) {
        FieldDesc field = fields[i];
        if (!field.isElement()) {
            // It's an attribute, so if we have a solid match, return
            // its name.
            if (qname.equals(field.getXmlName())) {
                return field.getFieldName();
            }
            // Not a solid match, but it's still possible we might match
            // the default (i.e. QName("", fieldName))
            if (qname.getNamespaceURI().equals("") && qname.getLocalPart().equals(field.getFieldName())) {
                possibleMatch = field.getFieldName();
            }
        }
    }

    if (possibleMatch == null && canSearchParents) {
        // check superclasses if they exist
        // and we are allowed to look
        if (parentDesc != null) {
            possibleMatch = parentDesc.getFieldNameForAttribute(qname);
        }
    }

    return possibleMatch;
}

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

/**
 * This method is invoked after startElement when the element requires
 * deserialization (i.e. the element is not an href & the value is not nil)
 * DeserializerImpl provides default behavior, which simply
 * involves obtaining a correct Deserializer and plugging its handler.
 * @param namespace is the namespace of the element
 * @param localName is the name of the element
 * @param prefix is the prefix of the element
 * @param attributes are the attrs on the element...used to get the type
 * @param context is the DeserializationContext
 *//* w ww.j ava2  s . c o m*/
public void onStartElement(String namespace, String localName, String prefix, Attributes attributes,
        DeserializationContext context) throws SAXException {
    // Deserializing the xml array requires processing the
    // xsi:type= attribute, the soapenc:arrayType attribute,
    // and the xsi:type attributes of the individual elements.
    //
    // The xsi:type=<qName> attribute is used to determine the java
    // type of the array to instantiate.  Axis expects it
    // to be set to the generic "soapenc:Array" or to
    // a specific qName.  If the generic "soapenc:Array"
    // specification is used, Axis determines the array
    // type by examining the soapenc:arrayType attribute.
    //
    // The soapenc:arrayType=<qname><dims> is used to determine
    // i) the number of dimensions, 
    // ii) the length of each dimension,
    // iii) the default xsi:type of each of the elements.
    //
    // If the arrayType attribute is missing, Axis assumes
    // a single dimension array with length equal to the number
    // of nested elements.  In such cases, the default xsi:type of 
    // the elements is determined using the array xsi:type.
    //
    // The xsi:type attributes of the individual elements of the
    // array are used to determine the java type of the element.
    // If the xsi:type attribute is missing for an element, the 
    // default xsi:type value is used.

    if (log.isDebugEnabled()) {
        log.debug("Enter: ArrayDeserializer::startElement()");
    }

    soapConstants = context.getSOAPConstants();

    // Get the qname for the array type=, set it to null if
    // the generic type is used.
    QName typeQName = context.getTypeFromAttributes(namespace, localName, attributes);
    if (typeQName == null) {
        typeQName = getDefaultType();
    }

    if (typeQName != null && Constants.equals(Constants.SOAP_ARRAY, typeQName)) {
        typeQName = null;
    }

    // Now get the arrayType value
    QName arrayTypeValue = context.getQNameFromString(
            Constants.getValue(attributes, Constants.URIS_SOAP_ENC, soapConstants.getAttrItemType()));

    // The first part of the arrayType expression is 
    // the default item type qname.
    // The second part is the dimension information
    String dimString = null;
    QName innerQName = null;
    String innerDimString = "";
    if (arrayTypeValue != null) {
        if (soapConstants != SOAPConstants.SOAP12_CONSTANTS) {
            // Doing SOAP 1.1
            // Array dimension noted like this : [][x]
            String arrayTypeValueNamespaceURI = arrayTypeValue.getNamespaceURI();
            String arrayTypeValueLocalPart = arrayTypeValue.getLocalPart();

            int leftBracketIndex = arrayTypeValueLocalPart.lastIndexOf('[');
            int rightBracketIndex = arrayTypeValueLocalPart.lastIndexOf(']');
            if (leftBracketIndex == -1 || rightBracketIndex == -1 || rightBracketIndex < leftBracketIndex) {
                throw new IllegalArgumentException(Messages.getMessage("badArrayType00", "" + arrayTypeValue));
            }

            dimString = arrayTypeValueLocalPart.substring(leftBracketIndex + 1, rightBracketIndex);
            arrayTypeValueLocalPart = arrayTypeValueLocalPart.substring(0, leftBracketIndex);

            // If multi-dim array set to soapenc:Array
            if (arrayTypeValueLocalPart.endsWith("]")) {
                defaultItemType = Constants.SOAP_ARRAY;
                int bracket = arrayTypeValueLocalPart.indexOf("[");
                innerQName = new QName(arrayTypeValueNamespaceURI,
                        arrayTypeValueLocalPart.substring(0, bracket));
                innerDimString = arrayTypeValueLocalPart.substring(bracket);
            } else {
                defaultItemType = new QName(arrayTypeValueNamespaceURI, arrayTypeValueLocalPart);
            }

        } else {
            String arraySizeValue = attributes.getValue(soapConstants.getEncodingURI(),
                    Constants.ATTR_ARRAY_SIZE);
            int leftStarIndex = arraySizeValue.lastIndexOf('*');

            // Skip to num if any
            if (leftStarIndex != -1) {
                // "*" => ""
                if (leftStarIndex == 0 && arraySizeValue.length() == 1) {
                    // "* *" => ""
                } else if (leftStarIndex == (arraySizeValue.length() - 1)) {
                    throw new IllegalArgumentException(
                            Messages.getMessage("badArraySize00", "" + arraySizeValue));
                    // "* N" => "N"
                } else {
                    dimString = arraySizeValue.substring(leftStarIndex + 2);
                    innerQName = arrayTypeValue;
                    innerDimString = arraySizeValue.substring(0, leftStarIndex + 1);
                }
            } else {
                dimString = arraySizeValue;
            }

            if (innerDimString == null || innerDimString.length() == 0) {
                defaultItemType = arrayTypeValue;
            } else {
                defaultItemType = Constants.SOAP_ARRAY12;
            }
        }
    }

    // If no type QName and no defaultItemType qname, use xsd:anyType
    if (defaultItemType == null && typeQName == null) {
        Class destClass = context.getDestinationClass();
        if (destClass != null && destClass.isArray()) {
            // This will get set OK down below...
        } else {
            defaultItemType = Constants.XSD_ANYTYPE;
        }
    }

    // Determine the class type for the array.
    arrayClass = null;
    if (typeQName != null) {
        arrayClass = context.getTypeMapping().getClassForQName(typeQName);
    }

    if (typeQName == null || arrayClass == null) {
        // type= information is not sufficient.
        // Get an array of the default item type.
        Class arrayItemClass = null;
        QName compQName = defaultItemType;

        // Nested array, use the innermost qname
        String dims = "[]";
        if (innerQName != null) {
            compQName = innerQName;

            if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) {
                // With SOAP 1.2 Array, we append [] for each * found
                int offset = 0;
                while ((offset = innerDimString.indexOf('*', offset)) != -1) {
                    dims += "[]";
                    offset++;
                }
            } else {
                // With SOAP 1.1 Array, we can append directly the complete innerDimString
                dims += innerDimString;
            }
        }

        // item Class
        arrayItemClass = context.getTypeMapping().getClassForQName(compQName);
        if (arrayItemClass != null) {
            try {
                // Append the dimension found to the classname computed from the itemClass
                // to form the array classname
                //
                String loadableArrayClassName = JavaUtils
                        .getLoadableClassName(JavaUtils.getTextClassName(arrayItemClass.getName()) + dims);
                arrayClass = ClassUtils.forName(loadableArrayClassName, true, arrayItemClass.getClassLoader());
            } catch (Exception e) {
                throw new SAXException(Messages.getMessage("noComponent00", "" + defaultItemType));
            }
        }
    }
    if (arrayClass == null) {
        arrayClass = context.getDestinationClass();
    }

    if (arrayClass == null) {
        throw new SAXException(Messages.getMessage("noComponent00", "" + defaultItemType));
    }

    if (dimString == null || dimString.length() == 0) {
        // Size determined using length of the members
        value = new ArrayListExtension(arrayClass);
    } else {
        try {
            StringTokenizer tokenizer;
            if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) {
                tokenizer = new StringTokenizer(dimString);
            } else {
                tokenizer = new StringTokenizer(dimString, "[],");
            }

            length = Integer.parseInt(tokenizer.nextToken());
            if (tokenizer.hasMoreTokens()) {
                // If the array is passed as a multi-dimensional array
                // (i.e. int[2][3]) then store all of the 
                // mult-dim lengths.
                // The valueReady method uses this array to set the
                // proper mult-dim element.
                mDimLength = new ArrayList();
                mDimLength.add(new Integer(length));

                while (tokenizer.hasMoreTokens()) {
                    mDimLength.add(new Integer(Integer.parseInt(tokenizer.nextToken())));
                }
            }

            // Create an ArrayListExtension class to store the ArrayList
            // plus converted objects.
            ArrayList list = new ArrayListExtension(arrayClass, length);

            // This is expensive as our array may not grown this big.
            // Prevents problems when XML claims a huge size
            // that it doesn't actually fill.
            //for (int i = 0; i < length; i++) {
            //    list.add(null);
            //}
            value = list;

        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(Messages.getMessage("badInteger00", dimString));
        }
    }

    // If soapenc:offset specified, set the current index accordingly
    String offset = Constants.getValue(attributes, Constants.URIS_SOAP_ENC, Constants.ATTR_OFFSET);
    if (offset != null) {
        if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) {
            throw new SAXException(Messages.getMessage("noSparseArray"));
        }

        int leftBracketIndex = offset.lastIndexOf('[');
        int rightBracketIndex = offset.lastIndexOf(']');

        if (leftBracketIndex == -1 || rightBracketIndex == -1 || rightBracketIndex < leftBracketIndex) {
            throw new SAXException(Messages.getMessage("badOffset00", offset));
        }

        curIndex = convertToIndex(offset.substring(leftBracketIndex + 1, rightBracketIndex), "badOffset00");
    }

    if (log.isDebugEnabled()) {
        log.debug("Exit: ArrayDeserializer::startElement()");
    }
}

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

/**
 * Serialize a bean.  Done simply by serializing each bean property.
 * @param name is the element name//ww w .  j  a  v a2s. com
 * @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 {
    // 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
    Attributes beanAttrs = getObjectAttributes(value, attributes, context);

    // Get the encoding style
    boolean isEncoded = context.isEncoded();

    // check whether we have and xsd:any namespace="##any" type
    boolean suppressElement = !isEncoded && name.getNamespaceURI().equals("")
            && name.getLocalPart().equals("any");

    if (!suppressElement)
        context.startElement(name, beanAttrs);

    // check whether the array is converted to ArrayOfT shema type    
    if (value != null && value.getClass().isArray()) {
        Object newVal = JavaUtils.convert(value, javaType);
        if (newVal != null && javaType.isAssignableFrom(newVal.getClass())) {
            value = newVal;
        }
    }
    try {
        // Serialize each property
        for (int i = 0; i < propertyDescriptor.length; i++) {
            String propName = propertyDescriptor[i].getName();
            if (propName.equals("class"))
                continue;
            QName qname = null;
            QName xmlType = null;
            Class javaType = propertyDescriptor[i].getType();

            boolean isOmittable = false;
            // isNillable default value depends on the field type
            boolean isNillable = Types.isNullable(javaType);
            // isArray
            boolean isArray = false;
            QName itemQName = null;

            // If we have type metadata, check to see what we're doing
            // with this field.  If it's an attribute, skip it.  If it's
            // an element, use whatever qname is in there.  If we can't
            // find any of this info, use the default.
            if (typeDesc != null) {
                FieldDesc field = typeDesc.getFieldByName(propName);
                if (field != null) {
                    if (!field.isElement()) {
                        continue;
                    }

                    ElementDesc element = (ElementDesc) field;

                    // If we're SOAP encoded, just use the local part,
                    // not the namespace.  Otherwise use the whole
                    // QName.
                    if (isEncoded) {
                        qname = new QName(element.getXmlName().getLocalPart());
                    } else {
                        qname = element.getXmlName();
                    }
                    isOmittable = element.isMinOccursZero();
                    isNillable = element.isNillable();
                    isArray = element.isMaxOccursUnbounded();
                    xmlType = element.getXmlType();
                    itemQName = element.getItemQName();
                    context.setItemQName(itemQName);
                }
            }

            if (qname == null) {
                qname = new QName(isEncoded ? "" : name.getNamespaceURI(), propName);
            }

            if (xmlType == null) {
                // look up the type QName using the class
                xmlType = context.getQNameForClass(javaType);
            }

            // Read the value from the property
            if (propertyDescriptor[i].isReadable()) {
                if (itemQName != null || (!propertyDescriptor[i].isIndexed() && !isArray)) {
                    // Normal case: serialize the value
                    Object propValue = propertyDescriptor[i].get(value);

                    if (propValue == null) {
                        // an element cannot be null if nillable property is set to
                        // "false" and the element cannot be omitted
                        if (!isNillable && !isOmittable) {
                            if (Number.class.isAssignableFrom(javaType)) {
                                // If we have a null and it's a number, though,
                                // we might turn it into the appropriate kind of 0.
                                // TODO : Should be caching these constructors?
                                try {
                                    Constructor constructor = javaType
                                            .getConstructor(SimpleDeserializer.STRING_CLASS);
                                    propValue = constructor.newInstance(ZERO_ARGS);
                                } catch (Exception e) {
                                    // If anything goes wrong here, oh well we tried.
                                }
                            }

                            if (propValue == null) {
                                throw new IOException(Messages.getMessage("nullNonNillableElement", propName));
                            }
                        }

                        // if meta data says minOccurs=0, then we can skip
                        // it if its value is null and we aren't doing SOAP
                        // encoding.
                        if (isOmittable && !isEncoded) {
                            continue;
                        }
                    }

                    context.serialize(qname, null, propValue, xmlType, javaType);
                } else {
                    // Collection of properties: serialize each one
                    int j = 0;
                    while (j >= 0) {
                        Object propValue = null;
                        try {
                            propValue = propertyDescriptor[i].get(value, j);
                            j++;
                        } catch (Exception e) {
                            j = -1;
                        }
                        if (j >= 0) {
                            context.serialize(qname, null, propValue, xmlType, propertyDescriptor[i].getType());
                        }
                    }
                }
            }
        }

        BeanPropertyDescriptor anyDesc = typeDesc == null ? null : typeDesc.getAnyDesc();
        if (anyDesc != null) {
            // If we have "extra" content here, it'll be an array
            // of MessageElements.  Serialize each one.
            Object anyVal = anyDesc.get(value);
            if (anyVal != null && anyVal instanceof MessageElement[]) {
                MessageElement[] anyContent = (MessageElement[]) anyVal;
                for (int i = 0; i < anyContent.length; i++) {
                    MessageElement element = anyContent[i];
                    element.output(context);
                }
            }
        }
    } catch (InvocationTargetException ite) {
        Throwable target = ite.getTargetException();
        log.error(Messages.getMessage("exception00"), target);
        throw new IOException(target.toString());
    } catch (Exception e) {
        log.error(Messages.getMessage("exception00"), e);
        throw new IOException(e.toString());
    }

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

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

/**
 * Return XML schema for the specified type, suitable for insertion into
 * the &lt;types&gt; element of a WSDL document, or underneath an
 * &lt;element&gt; or &lt;attribute&gt; declaration.
 *
 * @param javaType the Java Class we're writing out schema for
 * @param types the Java2WSDL Types object which holds the context
 *              for the WSDL being generated.
 * @return a type element containing a schema simpleType/complexType
 * @see org.apache.axis.wsdl.fromJava.Types
 *//*from w  w w .  j  ava2 s .  c  o  m*/
public Element writeSchema(Class javaType, Types types) throws Exception {

    // ComplexType representation of bean class
    Element complexType = types.createElement("complexType");

    // See if there is a super class, stop if we hit a stop class
    Element e = null;
    Class superClass = javaType.getSuperclass();
    BeanPropertyDescriptor[] superPd = null;
    List stopClasses = types.getStopClasses();
    if (superClass != null && superClass != java.lang.Object.class && superClass != java.lang.Exception.class
            && superClass != java.lang.Throwable.class && superClass != java.lang.RuntimeException.class
            && superClass != java.rmi.RemoteException.class && superClass != org.apache.axis.AxisFault.class
            && (stopClasses == null || !(stopClasses.contains(superClass.getName())))) {
        // Write out the super class
        String base = types.writeType(superClass);
        Element complexContent = types.createElement("complexContent");
        complexType.appendChild(complexContent);
        Element extension = types.createElement("extension");
        complexContent.appendChild(extension);
        extension.setAttribute("base", base);
        e = extension;
        // Get the property descriptors for the super class
        TypeDesc superTypeDesc = TypeDesc.getTypeDescForClass(superClass);
        if (superTypeDesc != null) {
            superPd = superTypeDesc.getPropertyDescriptors();
        } else {
            superPd = BeanUtils.getPd(superClass, null);
        }
    } else {
        e = complexType;
    }

    // Add fields under sequence element.
    // Note: In most situations it would be okay
    // to put the fields under an all element.
    // However it is illegal schema to put an
    // element with minOccurs=0 or maxOccurs>1 underneath
    // an all element.  This is the reason why a sequence
    // element is used.
    Element all = types.createElement("sequence");
    e.appendChild(all);

    if (Modifier.isAbstract(javaType.getModifiers())) {
        complexType.setAttribute("abstract", "true");
    }

    // Serialize each property
    for (int i = 0; i < propertyDescriptor.length; i++) {
        String propName = propertyDescriptor[i].getName();

        // Don't serializer properties named class
        boolean writeProperty = true;
        if (propName.equals("class")) {
            writeProperty = false;
        }

        // Don't serialize the property if it is present
        // in the super class property list
        if (superPd != null && writeProperty) {
            for (int j = 0; j < superPd.length && writeProperty; j++) {
                if (propName.equals(superPd[j].getName())) {
                    writeProperty = false;
                }
            }
        }
        if (!writeProperty) {
            continue;
        }

        // If we have type metadata, check to see what we're doing
        // with this field.  If it's an attribute, skip it.  If it's
        // an element, use whatever qname is in there.  If we can't
        // find any of this info, use the default.

        if (typeDesc != null) {
            Class fieldType = propertyDescriptor[i].getType();
            FieldDesc field = typeDesc.getFieldByName(propName);

            if (field != null) {
                QName qname = field.getXmlName();
                QName fieldXmlType = field.getXmlType();
                boolean isAnonymous = fieldXmlType != null && fieldXmlType.getLocalPart().startsWith(">");

                if (qname != null) {
                    // FIXME!
                    // Check to see if this is in the right namespace -
                    // if it's not, we need to use an <element ref="">
                    // to represent it!!!

                    // Use the default...
                    propName = qname.getLocalPart();
                }
                if (!field.isElement()) {
                    writeAttribute(types, propName, fieldType, fieldXmlType, complexType);
                } else {
                    writeField(types, propName, fieldXmlType, fieldType, propertyDescriptor[i].isIndexed(),
                            field.isMinOccursZero(), all, isAnonymous, ((ElementDesc) field).getItemQName());
                }
            } else {
                writeField(types, propName, null, fieldType, propertyDescriptor[i].isIndexed(), false, all,
                        false, null);
            }
        } else {
            boolean done = false;
            if (propertyDescriptor[i] instanceof FieldPropertyDescriptor) {
                FieldPropertyDescriptor fpd = (FieldPropertyDescriptor) propertyDescriptor[i];
                Class clazz = fpd.getField().getType();
                if (types.getTypeQName(clazz) != null) {
                    writeField(types, propName, null, clazz, false, false, all, false, null);

                    done = true;
                }
            }
            if (!done) {
                writeField(types, propName, null, propertyDescriptor[i].getType(),
                        propertyDescriptor[i].isIndexed(), false, all, false, null);
            }

        }
    }

    // done
    return complexType;
}

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

/**
 * write a schema representation of the given Class field and append it to
 * the where Node, recurse on complex types
 * @param fieldName name of the field/*from   w ww.ja  v  a2  s . c  o m*/
 * @param xmlType the schema type of the field
 * @param fieldType type of the field
 * @param isUnbounded causes maxOccurs="unbounded" if set
 * @param where location for the generated schema node
 * @param itemQName
 * @throws Exception
 */
protected void writeField(Types types, String fieldName, QName xmlType, Class fieldType, boolean isUnbounded,
        boolean isOmittable, Element where, boolean isAnonymous, QName itemQName) throws Exception {
    Element elem;
    String elementType = null;

    if (isAnonymous) {
        elem = types.createElementWithAnonymousType(fieldName, fieldType, isOmittable,
                where.getOwnerDocument());
    } else {
        if (!SchemaUtils.isSimpleSchemaType(xmlType) && Types.isArray(fieldType)) {
            xmlType = null;
        }

        if (itemQName != null && SchemaUtils.isSimpleSchemaType(xmlType) && Types.isArray(fieldType)) {
            xmlType = null;
        }

        QName typeQName = types.writeTypeAndSubTypeForPart(fieldType, xmlType);
        elementType = types.getQNameString(typeQName);

        if (elementType == null) {
            // If writeType returns null, then emit an anytype.
            QName anyQN = Constants.XSD_ANYTYPE;
            String prefix = types.getNamespaces().getCreatePrefix(anyQN.getNamespaceURI());
            elementType = prefix + ":" + anyQN.getLocalPart();
        }

        // isNillable default value depends on the field type
        boolean isNillable = Types.isNullable(fieldType);
        if (typeDesc != null) {
            FieldDesc field = typeDesc.getFieldByName(fieldName);
            if (field != null && field.isElement()) {
                isNillable = ((ElementDesc) field).isNillable();
            }
        }

        elem = types.createElement(fieldName, elementType, isNillable, isOmittable, where.getOwnerDocument());
    }

    if (isUnbounded) {
        elem.setAttribute("maxOccurs", "unbounded");
    }

    where.appendChild(elem);
}

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

private void setAttributeProperty(Object propValue, QName qname, QName xmlType, Class javaType,
        AttributesImpl attrs, SerializationContext context) throws Exception {

    String namespace = qname.getNamespaceURI();
    String localName = qname.getLocalPart();

    // org.xml.sax.helpers.AttributesImpl JavaDoc says: "For the
    // sake of speed, this method does no checking to see if the
    // attribute is already in the list: that is the
    // responsibility of the application." check for the existence
    // of the attribute to avoid adding it more than once.
    if (attrs.getIndex(namespace, localName) != -1) {
        return;/* w  ww .  j a v  a2 s . c  o  m*/
    }

    String propString = context.getValueAsString(propValue, xmlType, javaType);

    attrs.addAttribute(namespace, localName, context.attributeQName2String(qname), "CDATA", propString);
}

From source file:org.apache.axis.encoding.ser.castor.CastorSerializer.java

/**
 * Serialize a Castor object./*from   w w w .  java2s .c  o m*/
 *
 * @param name
 * @param attributes
 * @param value      this must be a castor object for marshalling
 * @param context
 * @throws IOException for XML schema noncompliance, bad object type, and any IO
 *                     trouble.
 */
public void serialize(QName name, Attributes attributes, Object value, SerializationContext context)
        throws IOException {
    try {
        AxisContentHandler hand = new AxisContentHandler(context);
        Marshaller marshaller = new Marshaller(hand);

        // Don't include the DOCTYPE, otherwise an exception occurs due to
        //2 DOCTYPE defined in the document. The XML fragment is included in
        //an XML document containing already a DOCTYPE
        marshaller.setMarshalAsDocument(false);
        String localPart = name.getLocalPart();
        int arrayDims = localPart.indexOf('[');
        if (arrayDims != -1) {
            localPart = localPart.substring(0, arrayDims);
        }
        marshaller.setRootElement(localPart);
        // Marshall the Castor object into the stream (sink)
        marshaller.marshal(value);
    } catch (MarshalException me) {
        log.error(Messages.getMessage("castorMarshalException00"), me);
        throw new IOException(Messages.getMessage("castorMarshalException00") + me.getLocalizedMessage());
    } catch (ValidationException ve) {
        log.error(Messages.getMessage("castorValidationException00"), ve);
        throw new IOException(Messages.getMessage("castorValidationException00") + ve.getLocation() + ": "
                + ve.getLocalizedMessage());
    }
}

From source file:org.apache.axis.encoding.SerializationContext.java

/**
 * Convert QName to a string of the form <prefix>:<localpart>
 * @param qName//  w  w w.jav a 2 s . c  o m
 * @return prefixed qname representation for serialization.
 */
public String qName2String(QName qName, boolean writeNS) {
    String prefix = null;
    String namespaceURI = qName.getNamespaceURI();
    String localPart = qName.getLocalPart();

    if (localPart != null && localPart.length() > 0) {
        int index = localPart.indexOf(':');
        if (index != -1) {
            prefix = localPart.substring(0, index);
            if (prefix.length() > 0 && !prefix.equals("urn")) {
                registerPrefixForURI(prefix, namespaceURI);
                localPart = localPart.substring(index + 1);
            } else {
                prefix = null;
            }
        }
        localPart = Utils.getLastLocalPart(localPart);
    }

    if (namespaceURI.length() == 0) {
        if (writeNS) {
            // If this is unqualified (i.e. prefix ""), set the default
            // namespace to ""
            String defaultNS = nsStack.getNamespaceURI("");
            if (defaultNS != null && defaultNS.length() > 0) {
                registerPrefixForURI("", "");
            }
        }
    } else {
        prefix = getPrefixForURI(namespaceURI);
    }

    if ((prefix == null) || (prefix.length() == 0))
        return localPart;

    return prefix + ':' + localPart;
}

From source file:org.apache.axis.encoding.SerializationContext.java

/**
 * Convert attribute QName to a string of the form <prefix>:<localpart>
 * There are slightly different rules for attributes:
 *  - There is no default namespace/* w w w .  j  a v  a  2s .  co m*/
 *  - any attribute in a namespace must have a prefix
 *
 * @param qName QName
 * @return prefixed qname representation for serialization.
 */
public String attributeQName2String(QName qName) {
    String prefix = null;
    String uri = qName.getNamespaceURI();
    if (uri.length() > 0) {
        prefix = getPrefixForURI(uri, null, true);
    }

    if ((prefix == null) || (prefix.length() == 0))
        return qName.getLocalPart();

    return prefix + ':' + qName.getLocalPart();
}