index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/QNameDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * A QNameDeserializer Factory */ public class QNameDeserializerFactory extends BaseDeserializerFactory { public QNameDeserializerFactory(Class javaType, QName xmlType) { super(QNameDeserializer.class, xmlType, javaType); } }
7,500
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/BeanDeserializer.java
/* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.ElementDesc; import org.apache.axis.description.FieldDesc; import org.apache.axis.description.TypeDesc; import org.apache.axis.encoding.ConstructorTarget; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.encoding.Target; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.message.MessageElement; import org.apache.axis.message.SOAPHandler; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.io.CharArrayWriter; import java.io.Serializable; import java.lang.reflect.Constructor; import java.util.Map; /** * General purpose deserializer for an arbitrary java bean. * * @author Sam Ruby (rubys@us.ibm.com) * @author Rich Scheuerle (scheu@us.ibm.com) * @author Tom Jordahl (tomj@macromedia.com) */ public class BeanDeserializer extends DeserializerImpl implements Serializable { protected static Log log = LogFactory.getLog(BeanDeserializer.class.getName()); private final CharArrayWriter val = new CharArrayWriter(); QName xmlType; Class javaType; protected Map propertyMap = null; protected QName prevQName; /** * Constructor if no default constructor */ protected Constructor constructorToUse = null; /** * Constructor Target object to use (if constructorToUse != null) */ protected Target constructorTarget = null; /** Type metadata about this class for XML deserialization */ protected TypeDesc typeDesc = null; // This counter is updated to deal with deserialize collection properties protected int collectionIndex = -1; protected SimpleDeserializer cacheStringDSer = null; protected QName cacheXMLType = null; // Construct BeanSerializer for the indicated class/qname public BeanDeserializer(Class javaType, QName xmlType) { this(javaType, xmlType, TypeDesc.getTypeDescForClass(javaType)); } // Construct BeanDeserializer for the indicated class/qname and meta Data public BeanDeserializer(Class javaType, QName xmlType, TypeDesc typeDesc ) { this(javaType, xmlType, typeDesc, BeanDeserializerFactory.getProperties(javaType, typeDesc)); } // Construct BeanDeserializer for the indicated class/qname and meta Data public BeanDeserializer(Class javaType, QName xmlType, TypeDesc typeDesc, Map propertyMap ) { this.xmlType = xmlType; this.javaType = javaType; this.typeDesc = typeDesc; this.propertyMap = propertyMap; // create a value try { value=javaType.newInstance(); } catch (Exception e) { // Don't process the exception at this point. // This is defered until the call to startElement // which will throw the exception. } } /** * startElement * * The ONLY reason that this method is overridden is so that * the object value can be set or a reasonable exception is thrown * indicating that the object cannot be created. This is done * at this point so that it occurs BEFORE href/id processing. * @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 attributes on the element...used to get the * type * @param context is the DeserializationContext */ public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { // Create the bean object if it was not already // created in the constructor. if (value == null) { try { value=javaType.newInstance(); } catch (Exception e) { // Use first found constructor. // Note : the right way is to use XML mapping information // for example JSR 109's constructor-parameter-order Constructor[] constructors = javaType.getConstructors(); if (constructors.length > 0) { constructorToUse = constructors[0]; } // Failed to create an object if no constructor if (constructorToUse == null) { throw new SAXException(Messages.getMessage("cantCreateBean00", javaType.getName(), e.toString())); } } } // Invoke super.startElement to do the href/id processing. super.startElement(namespace, localName, prefix, attributes, context); } /** * Deserializer interface called on each child element encountered in * the XML stream. * @param namespace is the namespace of the child element * @param localName is the local name of the child element * @param prefix is the prefix used on the name of the child element * @param attributes are the attributes of the child element * @param context is the deserialization context. * @return is a Deserializer to use to deserialize a child (must be * a derived class of SOAPHandler) or null if no deserialization should * be performed. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { handleMixedContent(); BeanPropertyDescriptor propDesc = null; FieldDesc fieldDesc = null; SOAPConstants soapConstants = context.getSOAPConstants(); String encodingStyle = context.getEncodingStyle(); boolean isEncoded = Constants.isSOAP_ENC(encodingStyle); QName elemQName = new QName(namespace, localName); if (log.isDebugEnabled()) { log.debug("Start processing child; xmlType=" + xmlType + "; javaType=" + javaType + "; elemQName=" + elemQName + "; isEncoded=" + isEncoded); } // The collectionIndex needs to be reset for Beans with multiple arrays if ((prevQName == null) || (!prevQName.equals(elemQName))) { collectionIndex = -1; } boolean isArray = false; QName itemQName = null; if (typeDesc != null) { // Lookup the name appropriately (assuming an unqualified // name for SOAP encoding, using the namespace otherwise) String fieldName = typeDesc.getFieldNameForElement(elemQName, isEncoded); propDesc = (BeanPropertyDescriptor)propertyMap.get(fieldName); fieldDesc = typeDesc.getFieldByName(fieldName); if (fieldDesc != null) { ElementDesc element = (ElementDesc)fieldDesc; isArray = element.isMaxOccursUnbounded(); itemQName = element.getItemQName(); } } if (propDesc == null) { // look for a field by this name. propDesc = (BeanPropertyDescriptor) propertyMap.get(localName); } // try and see if this is an xsd:any namespace="##any" element before // reporting a problem if (propDesc == null || (((prevQName != null) && prevQName.equals(elemQName) && !(propDesc.isIndexed()||isArray) && getAnyPropertyDesc() != null ))) { // try to put unknown elements into a SOAPElement property, if // appropriate prevQName = elemQName; propDesc = getAnyPropertyDesc(); if (propDesc != null) { try { MessageElement [] curElements = (MessageElement[])propDesc.get(value); int length = 0; if (curElements != null) { length = curElements.length; } MessageElement [] newElements = new MessageElement[length + 1]; if (curElements != null) { System.arraycopy(curElements, 0, newElements, 0, length); } MessageElement thisEl = context.getCurElement(); newElements[length] = thisEl; propDesc.set(value, newElements); // if this is the first pass through the MessageContexts // make sure that the correct any element is set, // that is the child of the current MessageElement, however // on the first pass this child has not been set yet, so // defer it to the child SOAPHandler if (!localName.equals(thisEl.getName())) { return new SOAPHandler(newElements, length); } return new SOAPHandler(); } catch (Exception e) { throw new SAXException(e); } } } if (propDesc == null) { // No such field throw new SAXException( Messages.getMessage("badElem00", javaType.getName(), localName)); } prevQName = elemQName; // Get the child's xsi:type if available QName childXMLType = context.getTypeFromAttributes(namespace, localName, attributes); String href = attributes.getValue(soapConstants.getAttrHref()); Class fieldType = propDesc.getType(); // If no xsi:type or href, check the meta-data for the field if (childXMLType == null && fieldDesc != null && href == null) { childXMLType = fieldDesc.getXmlType(); if (itemQName != null) { // This is actually a wrapped literal array and should be // deserialized with the ArrayDeserializer childXMLType = Constants.SOAP_ARRAY; fieldType = propDesc.getActualType(); } else { childXMLType = fieldDesc.getXmlType(); } } // Get Deserializer for child, default to using DeserializerImpl Deserializer dSer = getDeserializer(childXMLType, fieldType, href, context); // It is an error if the dSer is not found - the only case where we // wouldn't have a deserializer at this point is when we're trying // to deserialize something we have no clue about (no good xsi:type, // no good metadata). if (dSer == null) { dSer = context.getDeserializerForClass(propDesc.getType()); } // Fastpath nil checks... if (context.isNil(attributes)) { if (propDesc != null && (propDesc.isIndexed()||isArray)) { if (!((dSer != null) && (dSer instanceof ArrayDeserializer))) { collectionIndex++; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc, collectionIndex)); addChildDeserializer(dSer); return (SOAPHandler)dSer; } } return null; } if (dSer == null) { throw new SAXException(Messages.getMessage("noDeser00", childXMLType.toString())); } if (constructorToUse != null) { if (constructorTarget == null) { constructorTarget = new ConstructorTarget(constructorToUse, this); } dSer.registerValueTarget(constructorTarget); } else if (propDesc.isWriteable()) { // If this is an indexed property, and the deserializer we found // was NOT the ArrayDeserializer, this is a non-SOAP array: // <bean> // <field>value1</field> // <field>value2</field> // ... // In this case, we want to use the collectionIndex and make sure // the deserialized value for the child element goes into the // right place in the collection. // Register value target if ((itemQName != null || propDesc.isIndexed() || isArray) && !(dSer instanceof ArrayDeserializer)) { collectionIndex++; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc, collectionIndex)); } else { // If we're here, the element maps to a single field value, // whether that be a "basic" type or an array, so use the // normal (non-indexed) BeanPropertyTarget form. collectionIndex = -1; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc)); } } // Let the framework know that we need this deserializer to complete // for the bean to complete. addChildDeserializer(dSer); return (SOAPHandler)dSer; } /** * Get a BeanPropertyDescriptor which indicates where we should * put extensibility elements (i.e. XML which falls under the * auspices of an &lt;xsd:any&gt; declaration in the schema) * * @return an appropriate BeanPropertyDescriptor, or null */ public BeanPropertyDescriptor getAnyPropertyDesc() { if (typeDesc == null) return null; return typeDesc.getAnyDesc(); } /** * Set the bean properties that correspond to element attributes. * * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href and the value is not * nil.) * @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 attributes on the element...used to get the * type * @param context is the DeserializationContext */ public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { // The value should have been created or assigned already. // This code may no longer be needed. if (value == null && constructorToUse == null) { // create a value try { value=javaType.newInstance(); } catch (Exception e) { throw new SAXException(Messages.getMessage("cantCreateBean00", javaType.getName(), e.toString())); } } // If no type description meta data, there are no attributes, // so we are done. if (typeDesc == null) return; // loop through the attributes and set bean properties that // correspond to attributes for (int i=0; i < attributes.getLength(); i++) { QName attrQName = new QName(attributes.getURI(i), attributes.getLocalName(i)); String fieldName = typeDesc.getFieldNameForAttribute(attrQName); if (fieldName == null) continue; FieldDesc fieldDesc = typeDesc.getFieldByName(fieldName); // look for the attribute property BeanPropertyDescriptor bpd = (BeanPropertyDescriptor) propertyMap.get(fieldName); if (bpd != null) { if (constructorToUse == null) { // check only if default constructor if (!bpd.isWriteable() || bpd.isIndexed()) continue ; } // Get the Deserializer for the attribute Deserializer dSer = getDeserializer(fieldDesc.getXmlType(), bpd.getType(), null, context); if (dSer == null) { dSer = context.getDeserializerForClass(bpd.getType()); // The java type is an array, but the context didn't // know that we are an attribute. Better stick with // simple types.. if (dSer instanceof ArrayDeserializer) { SimpleListDeserializerFactory factory = new SimpleListDeserializerFactory(bpd.getType(), fieldDesc.getXmlType()); dSer = (Deserializer) factory.getDeserializerAs(dSer.getMechanismType()); } } if (dSer == null) throw new SAXException( Messages.getMessage("unregistered00", bpd.getType().toString())); if (! (dSer instanceof SimpleDeserializer)) throw new SAXException( Messages.getMessage("AttrNotSimpleType00", bpd.getName(), bpd.getType().toString())); // Success! Create an object from the string and set // it in the bean try { dSer.onStartElement(namespace, localName, prefix, attributes, context); Object val = ((SimpleDeserializer)dSer). makeValue(attributes.getValue(i)); if (constructorToUse == null) { bpd.set(value, val); } else { // add value for our constructor if (constructorTarget == null) { constructorTarget = new ConstructorTarget(constructorToUse, this); } constructorTarget.set(val); } } catch (Exception e) { throw new SAXException(e); } } // if } // attribute loop } /** * Get the Deserializer for the attribute or child element. * @param xmlType QName of the attribute/child element or null if not known. * @param javaType Class of the corresponding property * @param href String is the value of the href attribute, which is used * to determine whether the child element is complete or an * href to another element. * @param context DeserializationContext * @return Deserializer or null if not found. */ protected Deserializer getDeserializer(QName xmlType, Class javaType, String href, DeserializationContext context) { if (log.isDebugEnabled()) { log.debug("Getting deserializer for xmlType=" + xmlType + ", javaType=" + javaType + ", href=" + href); } if (javaType.isArray()) { context.setDestinationClass(javaType); } // See if we have a cached deserializer if (cacheStringDSer != null) { if (String.class.equals(javaType) && href == null && (cacheXMLType == null && xmlType == null || cacheXMLType != null && cacheXMLType.equals(xmlType))) { cacheStringDSer.reset(); return cacheStringDSer; } } Deserializer dSer = null; if (xmlType != null && href == null) { // Use the xmlType to get the deserializer. dSer = context.getDeserializerForType(xmlType); } else { // If the xmlType is not set, get a default xmlType TypeMapping tm = context.getTypeMapping(); QName defaultXMLType = tm.getTypeQName(javaType); // If there is not href, then get the deserializer // using the javaType and default XMLType, // If there is an href, the create the generic // DeserializerImpl and set its default type (the // default type is used if the href'd element does // not have an xsi:type. if (href == null) { dSer = context.getDeserializer(javaType, defaultXMLType); } else { dSer = new DeserializerImpl(); context.setDestinationClass(javaType); dSer.setDefaultType(defaultXMLType); } } if (javaType.equals(String.class) && dSer instanceof SimpleDeserializer) { cacheStringDSer = (SimpleDeserializer) dSer; cacheXMLType = xmlType; } if (log.isDebugEnabled()) { log.debug("Deserializer is " + dSer); } return dSer; } public void characters(char[] chars, int start, int end) throws SAXException { val.write(chars, start, end); } public void onEndElement(String namespace, String localName, DeserializationContext context) throws SAXException { handleMixedContent(); } protected void handleMixedContent() throws SAXException { BeanPropertyDescriptor propDesc = getAnyPropertyDesc(); if (propDesc == null || val.size() == 0) { return; } String textValue = val.toString().trim(); val.reset(); if (textValue.length() == 0) { return; } try { MessageElement[] curElements = (MessageElement[]) propDesc.get(value); int length = 0; if (curElements != null) { length = curElements.length; } MessageElement[] newElements = new MessageElement[length + 1]; if (curElements != null) { System.arraycopy(curElements, 0, newElements, 0, length); } MessageElement thisEl = new MessageElement(new org.apache.axis.message.Text(textValue)); newElements[length] = thisEl; propDesc.set(value, newElements); } catch (Exception e) { throw new SAXException(e); } } }
7,501
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/JAFDataHandlerDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.attachments.AttachmentUtils; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.message.SOAPHandler; import org.apache.axis.utils.Messages; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; /** * JAFDataHandler Serializer * @author Rick Rineholt * Modified by Rich Scheuerle (scheu@us.ibm.com) */ public class JAFDataHandlerDeserializer extends DeserializerImpl { protected static Log log = LogFactory.getLog(JAFDataHandlerDeserializer.class.getName()); public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (!context.isDoneParsing()) { if (myElement == null) { try { myElement = makeNewElement(namespace, localName, prefix, attributes, context); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } context.pushNewElement(myElement); } } populateDataHandler(context, namespace, localName, attributes); } private void populateDataHandler(DeserializationContext context, String namespace, String localName, Attributes attributes) { SOAPConstants soapConstants = context.getSOAPConstants(); QName type = context.getTypeFromAttributes(namespace, localName, attributes); if (log.isDebugEnabled()) { log.debug(Messages.getMessage("gotType00", "Deser", "" + type)); } String href = attributes.getValue(soapConstants.getAttrHref()); if (href != null) { Object ref = context.getObjectByRef(href); try{ ref = AttachmentUtils.getActivationDataHandler((org.apache.axis.Part)ref); }catch(AxisFault e){;} setValue(ref); } } /** * Deserializer interface called on each child element encountered in * the XML stream. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if(namespace.equals(Constants.URI_XOP_INCLUDE) && localName.equals(Constants.ELEM_XOP_INCLUDE)) { populateDataHandler(context, namespace, localName, attributes); return null; } else { throw new SAXException(Messages.getMessage( "noSubElements", namespace + ":" + localName)); } } }
7,502
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/JAFDataHandlerDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.attachments.OctetStream; import org.apache.commons.logging.Log; import javax.mail.internet.MimeMultipart; import javax.xml.namespace.QName; import javax.xml.transform.Source; import java.awt.*; /** * A JAFDataHandlerDeserializer Factory * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class JAFDataHandlerDeserializerFactory extends BaseDeserializerFactory { protected static Log log = LogFactory.getLog(JAFDataHandlerDeserializerFactory.class.getName()); public JAFDataHandlerDeserializerFactory(Class javaType, QName xmlType) { super(getDeserializerClass(javaType, xmlType), xmlType, javaType); log.debug("Enter/Exit: JAFDataHandlerDeserializerFactory(" + javaType + ", " + xmlType + ")"); } public JAFDataHandlerDeserializerFactory() { super(JAFDataHandlerDeserializer.class); log.debug("Enter/Exit: JAFDataHandlerDeserializerFactory()"); } private static Class getDeserializerClass(Class javaType, QName xmlType) { Class deser; if (Image.class.isAssignableFrom(javaType)) { deser = ImageDataHandlerDeserializer.class; } else if (String.class.isAssignableFrom(javaType)) { deser = PlainTextDataHandlerDeserializer.class; } else if (Source.class.isAssignableFrom(javaType)) { deser = SourceDataHandlerDeserializer.class; } else if (MimeMultipart.class.isAssignableFrom(javaType)) { deser = MimeMultipartDataHandlerDeserializer.class; } else if (OctetStream.class.isAssignableFrom(javaType)) { deser = OctetStreamDataHandlerDeserializer.class; } else { deser = JAFDataHandlerDeserializer.class; } return deser; } // getDeserializerClass }
7,503
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/QNameSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SimpleValueSerializer; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; /** * Serializer for QNames. */ public class QNameSerializer implements SimpleValueSerializer { /** * Serialize a QName. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { // NOTE: getValueAsString has the side-effect of priming the context // with the QName's namespace, so it must be called BEFORE context.startElement. String qnameString = getValueAsString(value, context); context.startElement(name, attributes); context.writeString(qnameString); context.endElement(); } public static String qName2String(QName qname, SerializationContext context) { String str = context.qName2String(qname); // work around for default namespace if (str == qname.getLocalPart()) { String namespace = qname.getNamespaceURI(); if (namespace != null && namespace.length() > 0) { String prefix = context.getPrefixForURI(qname.getNamespaceURI(), null, true); return prefix + ":" + str; } } return str; } public String getValueAsString(Object value, SerializationContext context) { return qName2String((QName)value, context); } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,504
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/VectorSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.Serializer; import org.apache.axis.utils.IdentityHashMap; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.fromJava.Types; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; import java.util.Iterator; import java.util.Vector; /** * A <code>VectorSerializer</code> is be used to serialize and * deserialize Vectors using the <code>SOAP-ENC</code> * encoding style.<p> * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class VectorSerializer implements Serializer { protected static Log log = LogFactory.getLog(VectorSerializer.class.getName()); /** Serialize a Vector * * Walk the collection of keys, serializing each key/value pair * inside an &lt;item&gt; element. * * @param name the desired QName for the element * @param attributes the desired attributes for the element * @param value the Object to serialize * @param context the SerializationContext in which to do all this * @exception IOException */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { if (!(value instanceof Vector)) throw new IOException( Messages.getMessage("noVector00", "VectorSerializer", value.getClass().getName())); Vector vector = (Vector)value; // Check for circular references. if(isRecursive(new IdentityHashMap(), vector)){ throw new IOException(Messages.getMessage("badVector00")); } context.startElement(name, attributes); for (Iterator i = vector.iterator(); i.hasNext(); ) { Object item = i.next(); context.serialize(Constants.QNAME_LITERAL_ITEM, null, item); } context.endElement(); } public boolean isRecursive(IdentityHashMap map, Vector vector) { map.add(vector); boolean recursive = false; for(int i=0;i<vector.size() && !recursive;i++) { Object o = vector.get(i); if(o instanceof Vector) { if(map.containsKey(o)) { return true; } else { recursive = isRecursive(map, (Vector)o); } } } return recursive; } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement("complexType"); complexType.setAttribute("name", "Vector"); types.writeSchemaTypeDecl(Constants.SOAP_VECTOR, complexType); Element seq = types.createElement("sequence"); complexType.appendChild(seq); Element element = types.createElement("element"); element.setAttribute("name", "item"); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", "xsd:anyType"); seq.appendChild(element); return complexType; } }
7,505
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/CalendarSerializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * SerializerFactory for Calendar(dateTime) primitives * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class CalendarSerializerFactory extends BaseSerializerFactory { public CalendarSerializerFactory(Class javaType, QName xmlType) { super(CalendarSerializer.class, xmlType, javaType); // true indicates shared class } }
7,506
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/EnumDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * DeserializerFactory for Enumeration. * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class EnumDeserializerFactory extends BaseDeserializerFactory { public EnumDeserializerFactory(Class javaType, QName xmlType) { super(EnumDeserializer.class, xmlType, javaType); // Can't share deserializers } }
7,507
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ElementDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.message.MessageElement; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.SAXException; import java.util.List; /** * Deserializer for DOM elements * * @author Glen Daniels (gdaniels@apache.org) * Modified by @author Rich scheuerle (scheu@us.ibm.com) */ public class ElementDeserializer extends DeserializerImpl { protected static Log log = LogFactory.getLog(ElementDeserializer.class.getName()); public static final String DESERIALIZE_CURRENT_ELEMENT = "DeserializeCurrentElement"; public final void onEndElement(String namespace, String localName, DeserializationContext context) throws SAXException { try { MessageElement msgElem = context.getCurElement(); if ( msgElem != null ) { MessageContext messageContext = context.getMessageContext(); Boolean currentElement = (Boolean) messageContext.getProperty(DESERIALIZE_CURRENT_ELEMENT); if (currentElement != null && currentElement.booleanValue()) { value = msgElem.getAsDOM(); messageContext.setProperty(DESERIALIZE_CURRENT_ELEMENT, Boolean.FALSE); return; } List children = msgElem.getChildren(); if ( children != null ) { msgElem = (MessageElement) children.get(0); if ( msgElem != null ) value = msgElem.getAsDOM(); } } } catch( Exception exp ) { log.error(Messages.getMessage("exception00"), exp); throw new SAXException( exp ); } } }
7,508
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/BeanPropertyTarget.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.Target; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.SAXException; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; /** * Class which knows how to update a bean property */ public class BeanPropertyTarget implements Target { protected static Log log = LogFactory.getLog(BeanPropertyTarget.class.getName()); private Object object; private BeanPropertyDescriptor pd; private int index = -1; /** * This constructor is used for a normal property. * @param object is the bean class * @param pd is the property **/ public BeanPropertyTarget(Object object, BeanPropertyDescriptor pd) { this.object = object; this.pd = pd; this.index = -1; // disable indexing } /** * This constructor is used for an indexed property. * @param object is the bean class * @param pd is the property * @param i is the index **/ public BeanPropertyTarget(Object object, BeanPropertyDescriptor pd, int i) { this.object = object; this.pd = pd; this.index = i; } /** * set the bean property with specified value * @param value is the value. */ public void set(Object value) throws SAXException { try { // Set the value on the bean property. // Use the indexed property method if the // index is set. if (index < 0) { pd.set(object, value); } else { pd.set(object, index, value); } } catch (Exception e) { try { // If an exception occurred, // see it the value can be converted into // the expected type. Class type = pd.getType(); if (value.getClass().isArray() && value.getClass().getComponentType().isPrimitive() && type.isArray() && type.getComponentType().equals(Object.class)) { //we make our own array type here. type = Array.newInstance(JavaUtils.getWrapperClass(value.getClass().getComponentType()),0).getClass(); } if (JavaUtils.isConvertable(value, type)) { value = JavaUtils.convert(value, type); if (index < 0) pd.set(object, value); else pd.set(object, index, value); } else { // It is possible that an indexed // format was expected, but the // entire array was sent. In such // cases traverse the array and // call the setter for each item. if (index == 0 && value.getClass().isArray() && !type.getClass().isArray()) { for (int i=0; i<Array.getLength(value); i++) { Object item = JavaUtils.convert(Array.get(value, i), type); pd.set(object, i, item); } } else { // Can't proceed. Throw an exception that // will be caught in the catch block below. throw e; } } } catch (Exception ex) { // Throw a SAX exception with an informative // message. String field= pd.getName(); if (index >=0) { field += "[" + index + "]"; } if (log.isErrorEnabled()) { //TODO: why is this just logged on the server-side and not thrown back to the client??? String valueType = "null"; if (value != null) valueType = value.getClass().getName(); log.error(Messages.getMessage("cantConvert02", new String[]{ valueType, field, (index >= 0) ? pd.getType().getComponentType().getName() : pd.getType().getName() })); } if(ex instanceof InvocationTargetException) { Throwable t = ((InvocationTargetException)ex).getTargetException(); if( t != null) { String classname = this.object.getClass().getName(); //show the context where this exception occured. throw new SAXException(Messages.getMessage("cantConvert04", new String[] { classname, field, (value==null)?null:value.toString(), t.getMessage()})); } } throw new SAXException(ex); } } } }
7,509
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/Base64Deserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.encoding.Base64; import javax.xml.namespace.QName; /** * Deserializer for Base64 * * @author Sam Ruby (rubys@us.ibm.com) * Modified by @author Rich scheuerle (scheu@us.ibm.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#base64Binary">XML Schema 3.2.16</a> */ public class Base64Deserializer extends SimpleDeserializer { public Base64Deserializer(Class javaType, QName xmlType) { super(javaType, xmlType); } /** * Convert the string that has been accumulated into an Object. Subclasses * may override this. Note that if the javaType is a primitive, the returned * object is a wrapper class. * @param source the serialized value to be deserialized * @throws Exception any exception thrown by this method will be wrapped */ public Object makeValue(String source) throws Exception { byte [] value = Base64.decode(source); if (value == null) { if (javaType == Byte[].class) { return new Byte[0]; } else { return new byte[0]; } } if (javaType == Byte[].class) { Byte[] data = new Byte[ value.length ]; for (int i=0; i<data.length; i++) { byte b = value[i]; data[i] = new Byte(b); } return data; } return value; } }
7,510
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/DateDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.utils.Messages; import javax.xml.namespace.QName; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * The DateSerializer deserializes a Date. Much of the work is done in the * base class. * * @author Sam Ruby (rubys@us.ibm.com) * Modified for JAX-RPC @author Rich Scheuerle (scheu@us.ibm.com) */ public class DateDeserializer extends SimpleDeserializer { private static SimpleDateFormat zulu = new SimpleDateFormat("yyyy-MM-dd"); // 0123456789 0 123456789 private static Calendar calendar = Calendar.getInstance(); /** * The Deserializer is constructed with the xmlType and * javaType */ public DateDeserializer(Class javaType, QName xmlType) { super(javaType, xmlType); } /** * The simple deserializer provides most of the stuff. * We just need to override makeValue(). */ public Object makeValue(String source) { Object result; boolean bc = false; // validate fixed portion of format if ( source != null ) { if (source.length() < 10) throw new NumberFormatException( Messages.getMessage("badDate00")); if (source.charAt(0) == '+') source = source.substring(1); if (source.charAt(0) == '-') { source = source.substring(1); bc = true; } if (source.charAt(4) != '-' || source.charAt(7) != '-') throw new NumberFormatException( Messages.getMessage("badDate00")); } synchronized (calendar) { // convert what we have validated so far try { result = zulu.parse(source == null ? null : (source.substring(0,10)) ); } catch (Exception e) { throw new NumberFormatException(e.toString()); } // support dates before the Christian era if (bc) { calendar.setTime((Date)result); calendar.set(Calendar.ERA, GregorianCalendar.BC); result = calendar.getTime(); } if (javaType == java.util.Date.class) { return result; } else if (javaType == java.sql.Date.class) { result = new java.sql.Date(((Date)result).getTime()); } else { calendar.setTime((Date)result); result = calendar; } } return result; } }
7,511
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SimpleListDeserializer.java
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.xml.namespace.QName; import org.apache.axis.description.TypeDesc; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.SimpleType; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.message.SOAPHandler; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.Messages; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Deserializer for * &lt;xsd:simpleType ...&gt; * &lt;xsd:list itemType="..."&gt; * &lt;/xsd:simpleType&gt; * based on SimpleDeserializer * * @author Ias (iasandcb@tmax.co.kr) */ public class SimpleListDeserializer extends SimpleDeserializer { StringBuffer val = new StringBuffer(); private Constructor constructor = null; private Map propertyMap = null; private HashMap attributeMap = null; private DeserializationContext context = null; public QName xmlType; public Class javaType; private TypeDesc typeDesc = null; protected SimpleListDeserializer cacheStringDSer = null; protected QName cacheXMLType = null; /** * The Deserializer is constructed with the xmlType and * javaType (which could be a java primitive like int.class) */ public SimpleListDeserializer(Class javaType, QName xmlType) { super (javaType, xmlType); this.xmlType = xmlType; this.javaType = javaType; } public SimpleListDeserializer(Class javaType, QName xmlType, TypeDesc typeDesc) { super (javaType, xmlType, typeDesc); this.xmlType = xmlType; this.javaType = javaType; this.typeDesc = typeDesc; } /** * Reset deserializer for re-use */ public void reset() { val.setLength(0); // Reset string buffer back to zero attributeMap = null; // Remove attribute map isNil = false; // Don't know if nil isEnded = false; // Indicate the end of element not yet called } /** * The Factory calls setConstructor. */ public void setConstructor(Constructor c) { constructor = c; } /** * There should not be nested elements, so thow and exception if this occurs. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { throw new SAXException( Messages.getMessage("cantHandle00", "SimpleDeserializer")); } /** * Append any characters received to the value. This method is defined * by Deserializer. */ public void characters(char [] chars, int start, int end) throws SAXException { val.append(chars, start, end); } /** * Append any characters to the value. This method is defined by * Deserializer. */ public void onEndElement(String namespace, String localName, DeserializationContext context) throws SAXException { if (isNil || val == null) { value = null; return; } try { value = makeValue(val.toString()); } catch (InvocationTargetException ite) { Throwable realException = ite.getTargetException(); if (realException instanceof Exception) throw new SAXException((Exception)realException); else throw new SAXException(ite.getMessage()); } catch (Exception e) { throw new SAXException(e); } // If this is a SimpleType, set attributes we have stashed away setSimpleTypeAttributes(); } /** * Convert the string that has been accumulated into an Object. Subclasses * may override this. * @param source the serialized value to be deserialized * @throws Exception any exception thrown by this method will be wrapped */ public Object makeValue(String source) throws Exception { // According to XML Schema Spec Part 0: Primer 2.3.1 - white space delimitor StringTokenizer tokenizer = new StringTokenizer(source.trim()); int length = tokenizer.countTokens(); Object list = Array.newInstance(javaType, length); for (int i = 0; i < length; i++) { String token = tokenizer.nextToken(); Array.set(list, i, makeUnitValue(token)); } return list; } private Object makeUnitValue(String source) throws Exception { // If the javaType is a boolean, except a number of different sources if (javaType == boolean.class || javaType == Boolean.class) { // This is a pretty lame test, but it is what the previous code did. switch (source.charAt(0)) { case '0': case 'f': case 'F': return Boolean.FALSE; case '1': case 't': case 'T': return Boolean.TRUE; default: throw new NumberFormatException( Messages.getMessage("badBool00")); } } // If expecting a Float or a Double, need to accept some special cases. if (javaType == float.class || javaType == java.lang.Float.class) { if (source.equals("NaN")) { return new Float(Float.NaN); } else if (source.equals("INF")) { return new Float(Float.POSITIVE_INFINITY); } else if (source.equals("-INF")) { return new Float(Float.NEGATIVE_INFINITY); } } if (javaType == double.class || javaType == java.lang.Double.class) { if (source.equals("NaN")) { return new Double(Double.NaN); } else if (source.equals("INF")) { return new Double(Double.POSITIVE_INFINITY); } else if (source.equals("-INF")) { return new Double(Double.NEGATIVE_INFINITY); } } if (javaType == QName.class) { int colon = source.lastIndexOf(":"); String namespace = colon < 0 ? "" : context.getNamespaceURI(source.substring(0, colon)); String localPart = colon < 0 ? source : source.substring(colon + 1); return new QName(namespace, localPart); } return constructor.newInstance(new Object [] { source }); } /** * Set the bean properties that correspond to element attributes. * * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href and the value is not nil.) * @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 attributes on the element...used to get the type * @param context is the DeserializationContext */ public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { this.context = context; // If we have no metadata, we have no attributes. Q.E.D. if (typeDesc == null) return; // loop through the attributes and set bean properties that // correspond to attributes for (int i=0; i < attributes.getLength(); i++) { QName attrQName = new QName(attributes.getURI(i), attributes.getLocalName(i)); String fieldName = typeDesc.getFieldNameForAttribute(attrQName); if (fieldName == null) continue; // look for the attribute property BeanPropertyDescriptor bpd = (BeanPropertyDescriptor) propertyMap.get(fieldName); if (bpd != null) { if (!bpd.isWriteable() || bpd.isIndexed() ) continue ; // determine the QName for this child element TypeMapping tm = context.getTypeMapping(); Class type = bpd.getType(); QName qn = tm.getTypeQName(type); if (qn == null) throw new SAXException( Messages.getMessage("unregistered00", type.toString())); // get the deserializer Deserializer dSer = context.getDeserializerForType(qn); if (dSer == null) throw new SAXException( Messages.getMessage("noDeser00", type.toString())); if (! (dSer instanceof SimpleListDeserializer)) throw new SAXException( Messages.getMessage("AttrNotSimpleType00", bpd.getName(), type.toString())); // Success! Create an object from the string and save // it in our attribute map for later. if (attributeMap == null) { attributeMap = new HashMap(); } try { Object val = ((SimpleListDeserializer)dSer). makeValue(attributes.getValue(i)); attributeMap.put(fieldName, val); } catch (Exception e) { throw new SAXException(e); } } // if } // attribute loop } // onStartElement /** * Process any attributes we may have encountered (in onStartElement) */ private void setSimpleTypeAttributes() throws SAXException { // if this isn't a simpleType bean, wont have attributes if (! SimpleType.class.isAssignableFrom(javaType) || attributeMap == null) return; // loop through map Set entries = attributeMap.entrySet(); for (Iterator iterator = entries.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Object val = entry.getValue(); BeanPropertyDescriptor bpd = (BeanPropertyDescriptor) propertyMap.get(name); if (!bpd.isWriteable() || bpd.isIndexed()) continue; try { bpd.set(value, val ); } catch (Exception e) { throw new SAXException(e); } } } }
7,512
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/TimeSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; import javax.xml.namespace.QName; import org.w3c.dom.Element; import org.xml.sax.Attributes; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SimpleValueSerializer; import org.apache.axis.wsdl.fromJava.Types; /** * Serializer for Time. * @author Florent Benoit */ public class TimeSerializer implements SimpleValueSerializer { /** * Parser */ private static SimpleDateFormat zulu = new SimpleDateFormat("HH:mm:ss.SSS'Z'"); // We should always format dates in the GMT timezone static { zulu.setTimeZone(TimeZone.getTimeZone("GMT")); } /** * Serialize a Time. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { context.startElement(name, attributes); context.writeString(getValueAsString(value, context)); context.endElement(); } public String getValueAsString(Object value, SerializationContext context) { StringBuffer buf = new StringBuffer(); // Reset year, month, day ((Calendar) value).set(0,0,0); buf.append(zulu.format(((Calendar)value).getTime())); return buf.toString(); } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,513
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/BaseFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import java.lang.reflect.Method; import javax.xml.namespace.QName; import org.apache.axis.utils.cache.MethodCache; /** * Base Factory for BaseDeserializerFactory and BaseSerializerFactory. * Code Reuse for the method cache * * @author Davanum Srinivas (dims@yahoo.com) */ public abstract class BaseFactory { private static final Class[] STRING_CLASS_QNAME_CLASS = new Class[] { String.class, Class.class, QName.class }; /** * Returns the the specified method - if any. */ protected Method getMethod(Class clazz, String methodName) { Method method = null; try { method = MethodCache.getInstance().getMethod(clazz, methodName, STRING_CLASS_QNAME_CLASS); } catch (NoSuchMethodException e) { } return method; } }
7,514
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/MimeMultipartDataHandlerSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.attachments.MimeMultipartDataSource; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import javax.activation.DataHandler; import javax.mail.internet.MimeMultipart; import javax.xml.namespace.QName; import java.io.IOException; /** * MimeMultipartDataHandler Serializer * @author Russell Butek (butek@us.ibm.com) */ public class MimeMultipartDataHandlerSerializer extends JAFDataHandlerSerializer { protected static Log log = LogFactory.getLog(MimeMultipartDataHandlerSerializer.class.getName()); /** * Serialize a Source DataHandler quantity. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { if (value != null) { DataHandler dh = new DataHandler(new MimeMultipartDataSource("Multipart", (MimeMultipart) value)); super.serialize(name, attributes, dh, context); } } // serialize } // class MimeMultipartDataHandlerSerializer
7,515
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/MapSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.Serializer; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.fromJava.Types; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * A <code>MapSerializer</code> is be used to serialize and * deserialize Maps using the <code>SOAP-ENC</code> * encoding style.<p> * * @author Glen Daniels (gdaniels@apache.org) * Modified by @author Rich Scheuerle (scheu@us.ibm.com) */ public class MapSerializer implements Serializer { protected static Log log = LogFactory.getLog(MapSerializer.class.getName()); // QNames we deal with private static final QName QNAME_KEY = new QName("","key"); private static final QName QNAME_ITEM = new QName("", "item"); private static final QName QNAME_VALUE = new QName("", "value"); private static final QName QNAME_ITEMTYPE = new QName(Constants.NS_URI_XMLSOAP, "item"); /** Serialize a Map * * Walk the collection of keys, serializing each key/value pair * inside an &lt;item&gt; element. * * @param name the desired QName for the element * @param attributes the desired attributes for the element * @param value the Object to serialize * @param context the SerializationContext in which to do all this * @exception IOException */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { if (!(value instanceof Map)) throw new IOException( Messages.getMessage("noMap00", "MapSerializer", value.getClass().getName())); Map map = (Map)value; context.startElement(name, attributes); AttributesImpl itemsAttributes = new AttributesImpl(); String encodingURI = context.getMessageContext().getEncodingStyle(); String encodingPrefix = context.getPrefixForURI(encodingURI); String soapPrefix = context.getPrefixForURI(Constants.SOAP_MAP.getNamespaceURI()); itemsAttributes.addAttribute(encodingURI, "type", encodingPrefix + ":type", "CDATA", encodingPrefix + ":Array"); itemsAttributes.addAttribute(encodingURI, "arrayType", encodingPrefix + ":arrayType", "CDATA", soapPrefix + ":item["+map.size()+"]"); for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry) i.next(); Object key = entry.getKey(); Object val = entry.getValue(); context.startElement(QNAME_ITEM, null); // Since the Key and Value can be any type, send type info context.serialize(QNAME_KEY, null, key, null, null, Boolean.TRUE); context.serialize(QNAME_VALUE, null, val, null, null, Boolean.TRUE); context.endElement(); } context.endElement(); } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement("complexType"); complexType.setAttribute("name", "Map"); Element seq = types.createElement("sequence"); complexType.appendChild(seq); Element element = types.createElement("element"); element.setAttribute("name", "item"); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", types.getQNameString(new QName(Constants.NS_URI_XMLSOAP,"mapItem"))); seq.appendChild(element); Element itemType = types.createElement("complexType"); itemType.setAttribute("name", "mapItem"); Element seq2 = types.createElement("sequence"); itemType.appendChild(seq2); Element element2 = types.createElement("element"); element2.setAttribute("name", "key"); element2.setAttribute("nillable", "true"); element2.setAttribute("type", "xsd:anyType"); seq2.appendChild(element2); Element element3 = types.createElement("element"); element3.setAttribute("name", "value"); element3.setAttribute("nillable", "true"); element3.setAttribute("type", "xsd:anyType"); seq2.appendChild(element3); types.writeSchemaTypeDecl(QNAME_ITEMTYPE, itemType); return complexType; } }
7,516
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/HexSerializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * SerializerFactory for hexBinary. * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class HexSerializerFactory extends BaseSerializerFactory { public HexSerializerFactory(Class javaType, QName xmlType) { super(HexSerializer.class, xmlType, javaType); // Share HexSerializer instance } }
7,517
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/OctetStreamDataHandlerDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.attachments.OctetStream; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.activation.DataHandler; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayOutputStream; /** * application/octet-stream DataHandler Deserializer * Modified by Davanum Srinivas (dims@yahoo.com) */ public class OctetStreamDataHandlerDeserializer extends JAFDataHandlerDeserializer { protected static Log log = LogFactory.getLog(OctetStreamDataHandlerDeserializer.class.getName()); public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { super.startElement(namespace, localName, prefix, attributes, context); if (getValue() instanceof DataHandler) { try { DataHandler dh = (DataHandler) getValue(); InputStream in = dh.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int byte1 = -1; while((byte1 = in.read())!=-1) baos.write(byte1); OctetStream os = new OctetStream(baos.toByteArray()); setValue(os); } catch (IOException ioe) { } } } // startElement } // class OctetStreamDataHandlerDeserializer
7,518
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/TimeDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * A Deserializer Factory for time * @author Florent Benoit */ public class TimeDeserializerFactory extends BaseDeserializerFactory { public TimeDeserializerFactory(Class javaType, QName xmlType) { super(TimeDeserializer.class, xmlType, javaType); } }
7,519
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SimpleListSerializer.java
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import java.io.IOException; import java.lang.reflect.Array; import javax.xml.namespace.QName; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.description.FieldDesc; import org.apache.axis.description.TypeDesc; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SimpleType; import org.apache.axis.encoding.SimpleValueSerializer; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; /** * Serializer for * &lt;xsd:simpleType ...&gt; * &lt;xsd:list itemType="..."&gt; * &lt;/xsd:simpleType&gt; * based on SimpleSerializer * * @author Ias (iasandcb@tmax.co.kr) */ public class SimpleListSerializer implements SimpleValueSerializer { public QName xmlType; public Class javaType; private BeanPropertyDescriptor[] propertyDescriptor = null; private TypeDesc typeDesc = null; public SimpleListSerializer(Class javaType, QName xmlType) { this.xmlType = xmlType; this.javaType = javaType; } public SimpleListSerializer(Class javaType, QName xmlType, TypeDesc typeDesc) { this.xmlType = xmlType; this.javaType = javaType; this.typeDesc = typeDesc; } /** * Serialize a list of primitives or simple values. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { if (value != null && value.getClass() == java.lang.Object.class) { throw new IOException(Messages.getMessage("cantSerialize02")); } // get any attributes if (value instanceof SimpleType) attributes = getObjectAttributes(value, attributes, context); String strValue = null; if (value != null) { strValue = getValueAsString(value, context); } context.startElement(name, attributes); if (strValue != null) { context.writeSafeString(strValue); } context.endElement(); } public String getValueAsString(Object value, SerializationContext context) { // We could have separate serializers/deserializers to take // care of Float/Double cases, but it makes more sence to // put them here with the rest of the java lang primitives. int length = Array.getLength(value); StringBuffer result = new StringBuffer(); for (int i = 0; i < length; i++) { Object object = Array.get(value, i); if (object instanceof Float || object instanceof Double) { double data = 0.0; if (object instanceof Float) { data = ((Float) object).doubleValue(); } else { data = ((Double) object).doubleValue(); } if (Double.isNaN(data)) { result.append("NaN"); } else if (data == Double.POSITIVE_INFINITY) { result.append("INF"); } else if (data == Double.NEGATIVE_INFINITY) { result.append("-INF"); } else { result.append(object.toString()); } } else if (object instanceof QName) { result.append(QNameSerializer.qName2String((QName)object, context)); } else { result.append(object.toString()); } if (i < length - 1) { result.append(' '); } } return result.toString(); } private 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); // 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) { String propString = getValueAsString(propValue, context); String namespace = qname.getNamespaceURI(); String localName = qname.getLocalPart(); attrs.addAttribute(namespace, localName, context.qName2String(qname), "CDATA", propString); } } } } catch (Exception e) { // no attributes return attrs; } return attrs; } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { // Let the caller generate WSDL if this is not a SimpleType if (!SimpleType.class.isAssignableFrom(javaType)) return null; // ComplexType representation of SimpleType bean class Element complexType = types.createElement("complexType"); types.writeSchemaElementDecl(xmlType, complexType); complexType.setAttribute("name", xmlType.getLocalPart()); // Produce simpleContent extending base type. Element simpleContent = types.createElement("simpleContent"); complexType.appendChild(simpleContent); Element extension = types.createElement("extension"); simpleContent.appendChild(extension); // Get the base type from the "value" element of the bean String base = "string"; for (int i=0; i<propertyDescriptor.length; i++) { String propName = propertyDescriptor[i].getName(); if (!propName.equals("value")) { if (typeDesc != null) { FieldDesc field = typeDesc.getFieldByName(propName); if (field != null) { if (field.isElement()) { // throw? } QName qname = field.getXmlName(); if (qname == null) { // Use the default... qname = new QName("", propName); } // write attribute element Class fieldType = propertyDescriptor[i].getType(); // Attribute must be a simple type, enum or SimpleType if (!types.isAcceptableAsAttribute(fieldType)) { throw new AxisFault(Messages.getMessage("AttrNotSimpleType00", propName, fieldType.getName())); } // write attribute element // TODO the attribute name needs to be preserved from the XML Element elem = types.createAttributeElement(propName, fieldType, field.getXmlType(), false, extension.getOwnerDocument()); extension.appendChild(elem); } } continue; } BeanPropertyDescriptor bpd = propertyDescriptor[i]; Class type = bpd.getType(); // Attribute must extend a simple type, enum or SimpleType if (!types.isAcceptableAsAttribute(type)) { throw new AxisFault(Messages.getMessage("AttrNotSimpleType01", type.getName())); } base = types.writeType(type); extension.setAttribute("base", base); } // done return complexType; } }
7,520
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/CalendarSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SimpleValueSerializer; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Serializer for dateTime (Calendar). * * @author Sam Ruby (rubys@us.ibm.com) * Modified by @author Rich scheuerle (scheu@us.ibm.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#dateTime">XML Schema 3.2.16</a> */ public class CalendarSerializer implements SimpleValueSerializer { private static SimpleDateFormat zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // 0123456789 0 123456789 static { zulu.setTimeZone(TimeZone.getTimeZone("GMT")); } /** * Serialize a Date. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { context.startElement(name, attributes); context.writeString(getValueAsString(value, context)); context.endElement(); } public String getValueAsString(Object value, SerializationContext context) { Date date = value instanceof Date ? (Date) value : ((Calendar) value).getTime(); // Serialize including convert to GMT synchronized (zulu) { // Sun JDK bug http://developer.java.sun.com/developer/bugParade/bugs/4229798.html return zulu.format(date); } } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,521
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/TimeDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; import org.apache.axis.types.Time; /** * The TimeSerializer deserializes a time. * Rely on Time of types package * @author Florent Benoit */ public class TimeDeserializer extends SimpleDeserializer { /** * The Deserializer is constructed with the xmlType and * javaType */ public TimeDeserializer(Class javaType, QName xmlType) { super(javaType, xmlType); } /** * The simple deserializer provides most of the stuff. * We just need to override makeValue(). */ public Object makeValue(String source) { Time t = new Time(source); return t.getAsCalendar(); } }
7,522
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ImageDataHandlerSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.attachments.ImageDataSource; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import javax.activation.DataHandler; import javax.xml.namespace.QName; import java.awt.*; import java.io.IOException; /** * ImageDataHandler Serializer * @author Russell Butek (butek@us.ibm.com) */ public class ImageDataHandlerSerializer extends JAFDataHandlerSerializer { protected static Log log = LogFactory.getLog(ImageDataHandlerSerializer.class.getName()); /** * Serialize a Source DataHandler quantity. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { DataHandler dh = new DataHandler( new ImageDataSource("source", (Image) value)); super.serialize(name, attributes, dh, context); } // serialize } // class ImageDataHandlerSerializer
7,523
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SimpleListSerializerFactory.java
/* * Copyright 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * SerializerFactory for * <xsd:simpleType ...> * <xsd:list itemType="..."> * </xsd:simpleType> * based on SimpleSerializerFactory * * @author Ias (iasandcb@tmax.co.kr) */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; public class SimpleListSerializerFactory extends BaseSerializerFactory { /** * Note that the factory is constructed with the QName and xmlType. This is important * to allow distinction between primitive values and java.lang wrappers. **/ public SimpleListSerializerFactory(Class javaType, QName xmlType) { super(SimpleListSerializer.class, xmlType, javaType); } }
7,524
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/HexSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SimpleValueSerializer; import org.apache.axis.types.HexBinary; import org.apache.axis.utils.JavaUtils; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; /** * Serializer for hexBinary. * * @author Davanum Srinivas (dims@yahoo.com) * Modified by @author Rich scheuerle (scheu@us.ibm.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#hexBinary">XML Schema 3.2.16</a> */ public class HexSerializer implements SimpleValueSerializer { public QName xmlType; public Class javaType; public HexSerializer(Class javaType, QName xmlType) { this.xmlType = xmlType; this.javaType = javaType; } /** * Serialize a HexBinary quantity. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { context.startElement(name, attributes); context.writeString(getValueAsString(value, context)); context.endElement(); } public String getValueAsString(Object value, SerializationContext context) { value = JavaUtils.convert(value, javaType); if (javaType == HexBinary.class) { return value.toString(); } else { return HexBinary.encode((byte[]) value); } } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,525
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/VectorDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.encoding.DeserializerTarget; import org.apache.axis.message.SOAPHandler; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.util.Vector; /** * Deserializer for SOAP Vectors for compatibility with SOAP 2.2. * * @author Carsten Ziegeler (cziegeler@apache.org) * Modified by @author Rich scheuerle (scheu@us.ibm.com) */ public class VectorDeserializer extends DeserializerImpl { protected static Log log = LogFactory.getLog(VectorDeserializer.class.getName()); public int curIndex = 0; /** * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href and the value is not nil.) * * Simply creates * @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 attributes on the element...used to get the type * @param context is the DeserializationContext */ public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (log.isDebugEnabled()) { log.debug("Enter: VectorDeserializer::startElement()"); } if (context.isNil(attributes)) { return; } // Create a vector to hold the deserialized values. setValue(new java.util.Vector()); if (log.isDebugEnabled()) { log.debug("Exit: VectorDeserializer::startElement()"); } } /** * onStartChild is called on each child element. * * @param namespace is the namespace of the child element * @param localName is the local name of the child element * @param prefix is the prefix used on the name of the child element * @param attributes are the attributes of the child element * @param context is the deserialization context. * @return is a Deserializer to use to deserialize a child (must be * a derived class of SOAPHandler) or null if no deserialization should * be performed. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (log.isDebugEnabled()) { log.debug("Enter: VectorDeserializer::onStartChild()"); } if (attributes == null) throw new SAXException(Messages.getMessage("noType01")); // If the xsi:nil attribute, set the value to null and return since // there is nothing to deserialize. if (context.isNil(attributes)) { setChildValue(null, new Integer(curIndex++)); return null; } // Get the type QName itemType = context.getTypeFromAttributes(namespace, localName, attributes); // Get the deserializer Deserializer dSer = null; if (itemType != null) { dSer = context.getDeserializerForType(itemType); } if (dSer == null) { dSer = new DeserializerImpl(); } // When the value is deserialized, inform us. // Need to pass the index because multi-ref stuff may // result in the values being deserialized in a different order. dSer.registerValueTarget(new DeserializerTarget(this, new Integer(curIndex))); curIndex++; if (log.isDebugEnabled()) { log.debug("Exit: VectorDeserializer::onStartChild()"); } // Let the framework know that we aren't complete until this guy // is complete. addChildDeserializer(dSer); return (SOAPHandler)dSer; } /** * The registerValueTarget code above causes this set function to be invoked when * each value is known. * @param value is the value of an element * @param hint is an Integer containing the index */ public void setChildValue(Object value, Object hint) throws SAXException { if (log.isDebugEnabled()) { log.debug(Messages.getMessage("gotValue00", "VectorDeserializer", "" + value)); } int offset = ((Integer)hint).intValue(); Vector v = (Vector)this.value; // If the vector is too small, grow it if (offset >= v.size()) { v.setSize(offset+1); } v.setElementAt(value, offset); } }
7,526
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/Base64SerializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * SerializerFactory for hexBinary. * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class Base64SerializerFactory extends BaseSerializerFactory { public Base64SerializerFactory(Class javaType, QName xmlType) { super(Base64Serializer.class, xmlType, javaType); // Share Base64Serializer instance } }
7,527
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/MapDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * A MapDeserializer Factory * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class MapDeserializerFactory extends BaseDeserializerFactory { public MapDeserializerFactory(Class javaType, QName xmlType) { super(MapDeserializer.class, xmlType, javaType); } }
7,528
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/Base64Serializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.encoding.Base64; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SimpleValueSerializer; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; /** * Serializer for Base64 * * @author Sam Ruby (rubys@us.ibm.com) * Modified by @author Rich Scheuerle (scheu@us.ibm.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#base64Binary">XML Schema 3.2.16</a> */ public class Base64Serializer implements SimpleValueSerializer { public QName xmlType; public Class javaType; public Base64Serializer(Class javaType, QName xmlType) { this.xmlType = xmlType; this.javaType = javaType; } /** * Serialize a base64 quantity. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { context.startElement(name, attributes); context.writeString(getValueAsString(value, context)); context.endElement(); } public String getValueAsString(Object value, SerializationContext context) { byte[] data = null; if (javaType == byte[].class) { data = (byte[]) value; } else { data = new byte[ ((Byte[]) value).length ]; for (int i=0; i<data.length; i++) { Byte b = ((Byte[]) value)[i]; if (b != null) data[i] = b.byteValue(); } } return Base64.encode(data, 0, data.length); } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,529
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/MapDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.encoding.DeserializerTarget; import org.apache.axis.message.SOAPHandler; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.util.HashMap; import java.util.Map; /** * A <code>MapSerializer</code> is be used to deserialize * deserialize Maps using the <code>SOAP-ENC</code> * encoding style.<p> * * @author Glen Daniels (gdaniels@apache.org) * Modified by @author Rich scheuerle (scheu@us.ibm.com) */ public class MapDeserializer extends DeserializerImpl { protected static Log log = LogFactory.getLog(MapDeserializer.class.getName()); // Fixed objects to act as hints to the set() callback public static final Object KEYHINT = new Object(); public static final Object VALHINT = new Object(); public static final Object NILHINT = new Object(); /** * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href and the value is not nil.) * * Simply creates map. * @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 attributes on the element...used to get the type * @param context is the DeserializationContext */ public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (log.isDebugEnabled()) { log.debug("Enter MapDeserializer::startElement()"); } if (context.isNil(attributes)) { return; } // Create a hashmap to hold the deserialized values. setValue(new HashMap()); if (log.isDebugEnabled()) { log.debug("Exit: MapDeserializer::startElement()"); } } /** * onStartChild is called on each child element. * * @param namespace is the namespace of the child element * @param localName is the local name of the child element * @param prefix is the prefix used on the name of the child element * @param attributes are the attributes of the child element * @param context is the deserialization context. * @return is a Deserializer to use to deserialize a child (must be * a derived class of SOAPHandler) or null if no deserialization should * be performed. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (log.isDebugEnabled()) { log.debug("Enter: MapDeserializer::onStartChild()"); } if(localName.equals("item")) { ItemHandler handler = new ItemHandler(this); // This item must be complete before we're complete... addChildDeserializer(handler); if (log.isDebugEnabled()) { log.debug("Exit: MapDeserializer::onStartChild()"); } return handler; } return this; } /** * The registerValueTarget code above causes this set function to be invoked when * each value is known. * @param value is the value of an element * @param hint is the key */ public void setChildValue(Object value, Object hint) throws SAXException { if (log.isDebugEnabled()) { log.debug(Messages.getMessage("gotValue00", "MapDeserializer", "" + value)); } ((Map)this.value).put(hint, value); } /** * A deserializer for an &lt;item&gt;. Handles getting the key and * value objects from their own deserializers, and then putting * the values into the HashMap we're building. * */ class ItemHandler extends DeserializerImpl { Object key; Object myValue; int numSet = 0; MapDeserializer md = null; ItemHandler(MapDeserializer md) { this.md = md; } /** * Callback from our deserializers. The hint indicates * whether the passed "val" argument is the key or the value * for this mapping. */ public void setChildValue(Object val, Object hint) throws SAXException { if (hint == KEYHINT) { key = val; } else if (hint == VALHINT) { myValue = val; } else if (hint != NILHINT) { return; } numSet++; if (numSet == 2) md.setChildValue(myValue, key); } public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { QName typeQName = context.getTypeFromAttributes(namespace, localName, attributes); Deserializer dser = context.getDeserializerForType(typeQName); // If no deserializer, use the base DeserializerImpl. if (dser == null) dser = new DeserializerImpl(); // When the child value is ready, we // want our set method to be invoked. // To do this register a DeserializeTarget on the // new Deserializer. DeserializerTarget dt = null; if (context.isNil(attributes)) { dt = new DeserializerTarget(this, NILHINT); } else if (localName.equals("key")) { dt = new DeserializerTarget(this, KEYHINT); } else if (localName.equals("value")) { dt = new DeserializerTarget(this, VALHINT); } else { // Do nothing } if (dt != null) { dser.registerValueTarget(dt); } // We need this guy to complete for us to complete. addChildDeserializer(dser); return (SOAPHandler)dser; } } }
7,530
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/DocumentSerializerFactory.java
package org.apache.axis.encoding.ser; /* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * SerializerFactory for DOM Document * * @author Davanum Srinivas (dims@yahoo.com) */ public class DocumentSerializerFactory extends BaseSerializerFactory { public DocumentSerializerFactory() { super(DocumentSerializer.class); // Share DocumentSerializer instance } }
7,531
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/BeanDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.description.TypeDesc; import org.apache.axis.encoding.Deserializer; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.BeanUtils; import org.apache.axis.utils.JavaUtils; import javax.xml.namespace.QName; import java.util.HashMap; import java.util.Map; import java.io.IOException; /** * DeserializerFactory for Bean * * @author Rich Scheuerle (scheu@us.ibm.com) * @author Sam Ruby (rubys@us.ibm.com) */ public class BeanDeserializerFactory extends BaseDeserializerFactory { /** Type metadata about this class for XML deserialization */ protected transient TypeDesc typeDesc = null; protected transient Map propertyMap = null; public BeanDeserializerFactory(Class javaType, QName xmlType) { super(BeanDeserializer.class, xmlType, javaType); // Sometimes an Enumeration class is registered as a Bean. // If this is the case, silently switch to the EnumDeserializer if (JavaUtils.isEnumClass(javaType)) { deserClass = EnumDeserializer.class; } typeDesc = TypeDesc.getTypeDescForClass(javaType); propertyMap = getProperties(javaType, typeDesc); } /** * Get a list of the bean properties */ public static Map getProperties(Class javaType, TypeDesc typeDesc ) { Map propertyMap = null; if (typeDesc != null) { propertyMap = typeDesc.getPropertyDescriptorMap(); } else { BeanPropertyDescriptor[] pd = BeanUtils.getPd(javaType, null); propertyMap = new HashMap(); // loop through properties and grab the names for later for (int i = 0; i < pd.length; i++) { BeanPropertyDescriptor descriptor = pd[i]; propertyMap.put(descriptor.getName(), descriptor); } } return propertyMap; } /** * Optimize construction of a BeanDeserializer by caching the * type descriptor and property map. */ protected Deserializer getGeneralPurpose(String mechanismType) { if (javaType == null || xmlType == null) { return super.getGeneralPurpose(mechanismType); } if (deserClass == EnumDeserializer.class) { return super.getGeneralPurpose(mechanismType); } return new BeanDeserializer(javaType, xmlType, typeDesc, propertyMap); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); typeDesc = TypeDesc.getTypeDescForClass(javaType); propertyMap = getProperties(javaType, typeDesc); } }
7,532
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/CalendarDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * A CalendarDeserializer Factory * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class CalendarDeserializerFactory extends BaseDeserializerFactory { public CalendarDeserializerFactory(Class javaType, QName xmlType) { super(CalendarDeserializer.class, xmlType, javaType); } }
7,533
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ArrayDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.encoding.DeserializerTarget; import org.apache.axis.message.SOAPHandler; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.SchemaUtils; import org.apache.commons.logging.Log; import org.apache.axis.soap.SOAPConstants; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; /** * An ArrayDeserializer handles deserializing SOAP * arrays. * * Some code borrowed from ApacheSOAP - thanks to Matt Duftler! * * @author Glen Daniels (gdaniels@apache.org) * * Multi-reference stuff: * @author Rich Scheuerle (scheu@us.ibm.com) */ public class ArrayDeserializer extends DeserializerImpl { protected static Log log = LogFactory.getLog(ArrayDeserializer.class.getName()); public QName arrayType = null; public int curIndex = 0; QName defaultItemType; int length; Class arrayClass = null; ArrayList mDimLength = null; // If set, array of multi-dim lengths ArrayList mDimFactor = null; // If set, array of factors for multi-dim [] SOAPConstants soapConstants = SOAPConstants.SOAP11_CONSTANTS; /** * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href &amp; 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 */ 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()"); } } /** * onStartChild is called on each child element. * @param namespace is the namespace of the child element * @param localName is the local name of the child element * @param prefix is the prefix used on the name of the child element * @param attributes are the attributes of the child element * @param context is the deserialization context. * @return is a Deserializer to use to deserialize a child (must be * a derived class of SOAPHandler) or null if no deserialization should * be performed. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (log.isDebugEnabled()) { log.debug("Enter: ArrayDeserializer.onStartChild()"); } // If the position attribute is set, // use it to update the current index if (attributes != null) { String pos = Constants.getValue(attributes, Constants.URIS_SOAP_ENC, Constants.ATTR_POSITION); if (pos != null) { if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { throw new SAXException(Messages.getMessage("noSparseArray")); } int leftBracketIndex = pos.lastIndexOf('['); int rightBracketIndex = pos.lastIndexOf(']'); if (leftBracketIndex == -1 || rightBracketIndex == -1 || rightBracketIndex < leftBracketIndex) { throw new SAXException( Messages.getMessage("badPosition00", pos)); } curIndex = convertToIndex(pos.substring(leftBracketIndex + 1, rightBracketIndex), "badPosition00"); } // If the xsi:nil attribute, set the value to null // and return since there is nothing to deserialize. if (context.isNil(attributes)) { setChildValue(null, new Integer(curIndex++)); return null; } } // Use the xsi:type setting on the attribute if it exists. QName itemType = context.getTypeFromAttributes(namespace, localName, attributes); // Get the deserializer for the type. Deserializer dSer = null; if (itemType != null && (context.getCurElement().getHref() == null)) { dSer = context.getDeserializerForType(itemType); } if (dSer == null) { // No deserializer can be found directly. Need to look harder QName defaultType = defaultItemType; Class javaType = null; if (arrayClass != null && arrayClass.isArray() && defaultType == null) { javaType = arrayClass.getComponentType(); defaultType = context.getTypeMapping().getTypeQName(javaType); } // We don't have a deserializer, the safest thing to do // is to set up using the DeserializerImpl below. // The DeserializerImpl will take care of href/id and // install the appropriate serializer, etc. The problem // is that takes a lot of time and will occur // all the time if no xsi:types are sent. Most of the // time an item is a simple schema type (i.e. String) // so the following shortcut is used to get a Deserializer // for these cases. if (itemType == null && dSer == null) { if (defaultType != null && SchemaUtils.isSimpleSchemaType(defaultType)) { dSer = context.getDeserializer(javaType, defaultType); } } // If no deserializer is // found, the deserializer is set to DeserializerImpl(). // It is possible that the element has an href, thus we // won't know the type until the definitition is encountered. if (dSer == null) { dSer = new DeserializerImpl(); // Determine a default type for the deserializer if (itemType == null) { dSer.setDefaultType(defaultType); } } } // Register the callback value target, and // keep track of this index so we know when it has been set. dSer.registerValueTarget( new DeserializerTarget(this, new Integer(curIndex))); // The framework handles knowing when the value is complete, as // long as we tell it about each child we're waiting on... addChildDeserializer(dSer); curIndex++; // In case of multi-array, we need to specify the destination class // of the children elements of this element array deserializer. context.setDestinationClass(arrayClass.getComponentType()); if (log.isDebugEnabled()) { log.debug("Exit: ArrayDeserializer.onStartChild()"); } return (SOAPHandler)dSer; } public void onEndChild(String namespace, String localName, DeserializationContext context) throws SAXException { // reverse onStartChild operation. context.setDestinationClass(arrayClass); } public void characters(char[] chars, int i, int i1) throws SAXException { for (int idx = i; i < i1; i++) { if (!Character.isWhitespace(chars[idx])) throw new SAXException(Messages.getMessage("charsInArray")); } } /** * set is called during deserialization to assign * the Object value to the array position indicated by hint. * The hint is always a single Integer. If the array being * deserialized is a multi-dimensional array, the hint is * converted into a series of indices to set the correct * nested position. * The array deserializer always deserializes into * an ArrayList, which is converted and copied into the * actual array after completion (by valueComplete). * It is important to wait until all indices have been * processed before invoking valueComplete. * @param value value of the array element * @param hint index of the array element (Integer) **/ public void setChildValue(Object value, Object hint) throws SAXException { if (log.isDebugEnabled()) { log.debug("Enter: ArrayDeserializer::setValue(" + value + ", " + hint + ")"); } ArrayList list = (ArrayList)this.value; int offset = ((Integer)hint).intValue(); if (this.mDimLength == null) { // Normal Case: Set the element in the list // grow the list if necessary to accomodate the new member while (list.size() <= offset) { list.add(null); } list.set(offset, value); } else { // Multi-Dim Array case: Need to find the nested ArrayList // and set the proper element. // Convert the offset into a series of indices ArrayList mDimIndex = toMultiIndex(offset); // Get/Create the nested ArrayList for(int i=0; i < mDimLength.size(); i++) { int length = ((Integer)mDimLength.get(i)).intValue(); int index = ((Integer)mDimIndex.get(i)).intValue(); while (list.size() < length) { list.add(null); } // If not the last dimension, get the nested ArrayList // Else set the value if (i < mDimLength.size()-1) { if (list.get(index) == null) { list.set(index, new ArrayList()); } list = (ArrayList) list.get(index); } else { list.set(index, value); } } } } /** * When valueComplete() is invoked on the array, * first convert the array value into the expected array. * Then call super.valueComplete() to inform referents * that the array value is ready. **/ public void valueComplete() throws SAXException { if (componentsReady()) { try { if (arrayClass != null) { value = JavaUtils.convert(value, arrayClass); } } catch (RuntimeException e) { // We must ignore exceptions from convert for Arrays with null - why? } } super.valueComplete(); } /** * Converts the given string to an index. * Assumes the string consists of a brackets surrounding comma * separated digits. For example "[2]" or [2,3]". * The routine returns a single index. * For example "[2]" returns 2. * For example "[2,3]" depends on the size of the multiple dimensions. * if the dimensions are "[3,5]" then 13 is returned (2*5) + 3. * @param text representing index text * @param exceptKey exception message key * @return index */ private int convertToIndex(String text, String exceptKey) throws SAXException { StringTokenizer tokenizer = new StringTokenizer(text, "[],"); int index = 0; try { if (mDimLength == null) { // Normal Case: Single dimension index = Integer.parseInt(tokenizer.nextToken()); if (tokenizer.hasMoreTokens()) { throw new SAXException( Messages.getMessage(exceptKey, text)); } } else { // Multiple Dimensions: int dim = -1; ArrayList work = new ArrayList(); while(tokenizer.hasMoreTokens()) { // Problem if the number of dimensions specified exceeds // the number of dimensions of arrayType dim++; if (dim >= mDimLength.size()) { throw new SAXException( Messages.getMessage(exceptKey, text)); } // Get the next token and convert to integer int workIndex = Integer.parseInt(tokenizer.nextToken()); // Problem if the index is out of range. if (workIndex < 0 || workIndex >= ((Integer)mDimLength.get(dim)).intValue()) { throw new SAXException( Messages.getMessage(exceptKey, text)); } work.add(new Integer(workIndex)); } index = toSingleIndex(work); // Convert to single index } } catch (SAXException e) { throw e; } catch (Exception e) { throw new SAXException(Messages.getMessage(exceptKey, text)); } return index; } /** * Converts single index to list of multiple indices. * @param single index * @return list of multiple indices or null if not multiple indices. */ private ArrayList toMultiIndex(int single) { if (mDimLength == null) return null; // Calculate the index factors if not already known if (mDimFactor == null) { mDimFactor = new ArrayList(); for (int i=0; i < mDimLength.size(); i++) { int factor = 1; for (int j=i+1; j<mDimLength.size(); j++) { factor *= ((Integer)mDimLength.get(j)).intValue(); } mDimFactor.add(new Integer(factor)); } } ArrayList rc = new ArrayList(); for (int i=0; i < mDimLength.size(); i++) { int factor = ((Integer)mDimFactor.get(i)).intValue(); rc.add(new Integer(single / factor)); single = single % factor; } return rc; } /** * Converts multiple index to single index. * @param indexArray list of multiple indices * @return single index */ private int toSingleIndex(ArrayList indexArray) { if (mDimLength == null || indexArray == null) return -1; // Calculate the index factors if not already known if (mDimFactor == null) { mDimFactor = new ArrayList(); for (int i=0; i < mDimLength.size(); i++) { int factor = 1; for (int j=i+1; j<mDimLength.size(); j++) { factor *= ((Integer)mDimLength.get(j)).intValue(); } mDimFactor.add(new Integer(factor)); } } int single = 0; for (int i=0; i < indexArray.size(); i++) { single += ((Integer)mDimFactor.get(i)).intValue()* ((Integer)indexArray.get(i)).intValue(); } return single; } /** * During processing, the Array Deserializer stores the array in * an ArrayListExtension class. This class contains all of the * normal function of an ArrayList, plus it keeps a list of the * converted array values. This class is essential to support * arrays that are multi-referenced. **/ public class ArrayListExtension extends ArrayList implements JavaUtils.ConvertCache { private HashMap table = null; private Class arrayClass = null; // The array class. /** * Constructors */ ArrayListExtension(Class arrayClass) { super(); this.arrayClass = arrayClass; // Don't use the array class as a hint // if it can't be instantiated if (arrayClass == null || arrayClass.isInterface() || java.lang.reflect.Modifier.isAbstract( arrayClass.getModifiers())) { arrayClass = null; } } ArrayListExtension(Class arrayClass, int length) { // Sanity check the array size, 50K is big enough to start super(length > 50000 ? 50000 : length); this.arrayClass = arrayClass; // Don't use the array class as a hint // if it can't be instantiated if (arrayClass == null || arrayClass.isInterface() || java.lang.reflect.Modifier.isAbstract( arrayClass.getModifiers())) { arrayClass = null; } } /** * Store converted value **/ public void setConvertedValue(Class cls, Object value) { if (table == null) table = new HashMap(); table.put(cls, value); } /** * Get previously converted value **/ public Object getConvertedValue(Class cls) { if (table == null) return null; return table.get(cls); } /** * Get the destination array class described by the xml **/ public Class getDestClass() { return arrayClass; } } }
7,534
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/DateSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.SimpleValueSerializer; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Serializer for Dates. * * @author Sam Ruby (rubys@us.ibm.com) * Modified by @author Rich scheuerle (scheu@us.ibm.com) * @see <a href="http://www.w3.org/TR/xmlschema-2/#dateTime">XML Schema 3.2.16</a> */ public class DateSerializer implements SimpleValueSerializer { private static SimpleDateFormat zulu = new SimpleDateFormat("yyyy-MM-dd"); private static Calendar calendar = Calendar.getInstance(); /** * Serialize a Date. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { context.startElement(name, attributes); context.writeString(getValueAsString(value, context)); context.endElement(); } public String getValueAsString(Object value, SerializationContext context) { StringBuffer buf = new StringBuffer(); synchronized (calendar) { if(value instanceof Calendar) { value = ((Calendar)value).getTime(); } if (calendar.get(Calendar.ERA) == GregorianCalendar.BC) { buf.append("-"); calendar.setTime((Date)value); calendar.set(Calendar.ERA, GregorianCalendar.AD); value = calendar.getTime(); } buf.append(zulu.format((Date)value)); } return buf.toString(); } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,535
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/HexDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * DeserializerFactory for hexBinary. * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class HexDeserializerFactory extends BaseDeserializerFactory { public HexDeserializerFactory(Class javaType, QName xmlType) { super(HexDeserializer.class, xmlType, javaType); } }
7,536
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/BeanSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.FieldDesc; import org.apache.axis.description.TypeDesc; import org.apache.axis.description.ElementDesc; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.Serializer; import org.apache.axis.message.MessageElement; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.BeanUtils; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.FieldPropertyDescriptor; import org.apache.axis.wsdl.fromJava.Types; import org.apache.axis.wsdl.symbolTable.SchemaUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.lang.reflect.Constructor; import java.util.List; /** * General purpose serializer/deserializerFactory for an arbitrary java bean. * * @author Sam Ruby (rubys@us.ibm.com) * @author Rich Scheuerle (scheu@us.ibm.com) * @author Tom Jordahl (tomj@macromedia.com) */ public class BeanSerializer implements Serializer, Serializable { protected static Log log = LogFactory.getLog(BeanSerializer.class.getName()); private static final QName MUST_UNDERSTAND_QNAME = new QName(Constants.URI_SOAP11_ENV, Constants.ATTR_MUST_UNDERSTAND); private static final Object[] ZERO_ARGS = new Object [] { "0" }; QName xmlType; Class javaType; protected BeanPropertyDescriptor[] propertyDescriptor = null; protected TypeDesc typeDesc = null; // Construct BeanSerializer for the indicated class/qname public BeanSerializer(Class javaType, QName xmlType) { this(javaType, xmlType, TypeDesc.getTypeDescForClass(javaType)); } // Construct BeanSerializer for the indicated class/qname public BeanSerializer(Class javaType, QName xmlType, TypeDesc typeDesc) { this(javaType, xmlType, typeDesc, null); if (typeDesc != null) { propertyDescriptor = typeDesc.getPropertyDescriptors(); } else { propertyDescriptor = BeanUtils.getPd(javaType, null); } } // Construct BeanSerializer for the indicated class/qname/propertyDesc public BeanSerializer(Class javaType, QName xmlType, TypeDesc typeDesc, BeanPropertyDescriptor[] propertyDescriptor) { this.xmlType = xmlType; this.javaType = javaType; this.typeDesc = typeDesc; this.propertyDescriptor = propertyDescriptor; } /** * Serialize a bean. Done simply by serializing each bean property. * @param name is the element name * @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(); if (log.isDebugEnabled()) { log.debug("Start serializing bean; xmlType=" + xmlType + "; javaType=" + javaType + "; name=" + name + "; isEncoded=" + 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(); } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ 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; } /** * 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 * @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); } /** * write aa attribute element and append it to the 'where' Node * @param fieldName name of the field * @param fieldType type of the field * @param where location for the generated schema node * @throws Exception */ protected void writeAttribute(Types types, String fieldName, Class fieldType, QName fieldXmlType, Element where) throws Exception { // Attribute must be a simple type. if (!types.isAcceptableAsAttribute(fieldType)) { throw new AxisFault(Messages.getMessage("AttrNotSimpleType00", fieldName, fieldType.getName())); } Element elem = types.createAttributeElement(fieldName, fieldType, fieldXmlType, false, where.getOwnerDocument()); where.appendChild(elem); } /** * 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 * * @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; } 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; } String propString = context.getValueAsString(propValue, xmlType, javaType); attrs.addAttribute(namespace, localName, context.attributeQName2String(qname), "CDATA", propString); } }
7,537
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SimpleDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.description.TypeDesc; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.encoding.SimpleType; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.message.SOAPHandler; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.BeanUtils; import org.apache.axis.utils.Messages; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.io.CharArrayWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * A deserializer for any simple type with a (String) constructor. Note: * this class is designed so that subclasses need only override the makeValue * method in order to construct objects of their own type. * * @author Glen Daniels (gdaniels@apache.org) * @author Sam Ruby (rubys@us.ibm.com) * Modified for JAX-RPC @author Rich Scheuerle (scheu@us.ibm.com) */ public class SimpleDeserializer extends DeserializerImpl { private static final Class[] STRING_STRING_CLASS = new Class [] {String.class, String.class}; public static final Class[] STRING_CLASS = new Class [] {String.class}; private final CharArrayWriter val = new CharArrayWriter(); private Constructor constructor = null; private Map propertyMap = null; private HashMap attributeMap = null; public QName xmlType; public Class javaType; private TypeDesc typeDesc = null; protected DeserializationContext context = null; protected SimpleDeserializer cacheStringDSer = null; protected QName cacheXMLType = null; /** * The Deserializer is constructed with the xmlType and * javaType (which could be a java primitive like int.class) */ public SimpleDeserializer(Class javaType, QName xmlType) { this.xmlType = xmlType; this.javaType = javaType; init(); } public SimpleDeserializer(Class javaType, QName xmlType, TypeDesc typeDesc) { this.xmlType = xmlType; this.javaType = javaType; this.typeDesc = typeDesc; init(); } /** * Initialize the typeDesc, property descriptors and propertyMap. */ private void init() { // The typeDesc and map array are only necessary // if this class extends SimpleType. if (SimpleType.class.isAssignableFrom(javaType)) { // Set the typeDesc if not already set if (typeDesc == null) { typeDesc = TypeDesc.getTypeDescForClass(javaType); } } // Get the cached propertyDescriptor from the type or // generate a fresh one. if (typeDesc != null) { propertyMap = typeDesc.getPropertyDescriptorMap(); } else { BeanPropertyDescriptor[] pd = BeanUtils.getPd(javaType, null); propertyMap = new HashMap(); for (int i = 0; i < pd.length; i++) { BeanPropertyDescriptor descriptor = pd[i]; propertyMap.put(descriptor.getName(), descriptor); } } } /** * Reset deserializer for re-use */ public void reset() { val.reset(); attributeMap = null; // Remove attribute map isNil = false; // Don't know if nil isEnded = false; // Indicate the end of element not yet called } /** * The Factory calls setConstructor. */ public void setConstructor(Constructor c) { constructor = c; } /** * There should not be nested elements, so thow and exception if this occurs. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { throw new SAXException( Messages.getMessage("cantHandle00", "SimpleDeserializer")); } /** * Append any characters received to the value. This method is defined * by Deserializer. */ public void characters(char [] chars, int start, int end) throws SAXException { val.write(chars,start,end); } /** * Append any characters to the value. This method is defined by * Deserializer. */ public void onEndElement(String namespace, String localName, DeserializationContext context) throws SAXException { if (isNil) { value = null; return; } try { value = makeValue(val.toString()); } catch (InvocationTargetException ite) { Throwable realException = ite.getTargetException(); if (realException instanceof Exception) throw new SAXException((Exception)realException); else throw new SAXException(ite.getMessage()); } catch (Exception e) { throw new SAXException(e); } // If this is a SimpleType, set attributes we have stashed away setSimpleTypeAttributes(); } /** * Convert the string that has been accumulated into an Object. Subclasses * may override this. Note that if the javaType is a primitive, the returned * object is a wrapper class. * @param source the serialized value to be deserialized * @throws Exception any exception thrown by this method will be wrapped */ public Object makeValue(String source) throws Exception { if (javaType == java.lang.String.class) { return source; } // Trim whitespace if non-String source = source.trim(); if (source.length() == 0 && typeDesc == null) { return null; } // if constructor is set skip all basic java type checks if (this.constructor == null) { Object value = makeBasicValue(source); if (value != null) { return value; } } Object [] args = null; boolean isQNameSubclass = QName.class.isAssignableFrom(javaType); if (isQNameSubclass) { int colon = source.lastIndexOf(":"); String namespace = colon < 0 ? "" : context.getNamespaceURI(source.substring(0, colon)); String localPart = colon < 0 ? source : source.substring(colon + 1); args = new Object [] {namespace, localPart}; } if (constructor == null) { try { if (isQNameSubclass) { constructor = javaType.getDeclaredConstructor(STRING_STRING_CLASS); } else { constructor = javaType.getDeclaredConstructor(STRING_CLASS); } } catch (Exception e) { return null; } } if(constructor.getParameterTypes().length==0){ try { Object obj = constructor.newInstance(new Object[]{}); obj.getClass().getMethod("set_value", new Class[]{String.class}) .invoke(obj, new Object[]{source}); return obj; } catch (Exception e){ //Ignore exception } } if (args == null) { args = new Object[]{source}; } return constructor.newInstance(args); } private Object makeBasicValue(String source) throws Exception { // If the javaType is a boolean, except a number of different sources if (javaType == boolean.class || javaType == Boolean.class) { // This is a pretty lame test, but it is what the previous code did. switch (source.charAt(0)) { case '0': case 'f': case 'F': return Boolean.FALSE; case '1': case 't': case 'T': return Boolean.TRUE; default: throw new NumberFormatException( Messages.getMessage("badBool00")); } } // If expecting a Float or a Double, need to accept some special cases. if (javaType == float.class || javaType == java.lang.Float.class) { if (source.equals("NaN")) { return new Float(Float.NaN); } else if (source.equals("INF")) { return new Float(Float.POSITIVE_INFINITY); } else if (source.equals("-INF")) { return new Float(Float.NEGATIVE_INFINITY); } else { return new Float(source); } } if (javaType == double.class || javaType == java.lang.Double.class) { if (source.equals("NaN")) { return new Double(Double.NaN); } else if (source.equals("INF")) { return new Double(Double.POSITIVE_INFINITY); } else if (source.equals("-INF")) { return new Double(Double.NEGATIVE_INFINITY); } else { return new Double(source); } } if (javaType == int.class || javaType == java.lang.Integer.class) { return new Integer(source); } if (javaType == short.class || javaType == java.lang.Short.class) { return new Short(source); } if (javaType == long.class || javaType == java.lang.Long.class) { return new Long(source); } if (javaType == byte.class || javaType == java.lang.Byte.class) { return new Byte(source); } if (javaType == org.apache.axis.types.URI.class) { return new org.apache.axis.types.URI(source); } return null; } /** * Set the bean properties that correspond to element attributes. * * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href and the value is not nil.) * @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 attributes on the element...used to get the type * @param context is the DeserializationContext */ public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { this.context = context; // loop through the attributes and set bean properties that // correspond to attributes for (int i=0; i < attributes.getLength(); i++) { QName attrQName = new QName(attributes.getURI(i), attributes.getLocalName(i)); String fieldName = attributes.getLocalName(i); if(typeDesc != null) { fieldName = typeDesc.getFieldNameForAttribute(attrQName); if (fieldName == null) continue; } if (propertyMap == null) continue; // look for the attribute property BeanPropertyDescriptor bpd = (BeanPropertyDescriptor) propertyMap.get(fieldName); if (bpd != null) { if (!bpd.isWriteable() || bpd.isIndexed() ) continue ; // determine the QName for this child element TypeMapping tm = context.getTypeMapping(); Class type = bpd.getType(); QName qn = tm.getTypeQName(type); if (qn == null) throw new SAXException( Messages.getMessage("unregistered00", type.toString())); // get the deserializer Deserializer dSer = context.getDeserializerForType(qn); if (dSer == null) throw new SAXException( Messages.getMessage("noDeser00", type.toString())); if (! (dSer instanceof SimpleDeserializer)) throw new SAXException( Messages.getMessage("AttrNotSimpleType00", bpd.getName(), type.toString())); // Success! Create an object from the string and save // it in our attribute map for later. if (attributeMap == null) { attributeMap = new HashMap(); } try { Object val = ((SimpleDeserializer)dSer). makeValue(attributes.getValue(i)); attributeMap.put(fieldName, val); } catch (Exception e) { throw new SAXException(e); } } // if } // attribute loop } // onStartElement /** * Process any attributes we may have encountered (in onStartElement) */ private void setSimpleTypeAttributes() throws SAXException { if (attributeMap == null) return; // loop through map Set entries = attributeMap.entrySet(); for (Iterator iterator = entries.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); Object val = entry.getValue(); BeanPropertyDescriptor bpd = (BeanPropertyDescriptor) propertyMap.get(name); if (!bpd.isWriteable() || bpd.isIndexed()) continue; try { bpd.set(value, val ); } catch (Exception e) { throw new SAXException(e); } } } }
7,538
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/SimpleDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.utils.BeanUtils; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.JavaUtils; import javax.xml.namespace.QName; import javax.xml.rpc.JAXRPCException; import java.lang.reflect.Constructor; import java.io.IOException; /** * A deserializer for any simple type with a (String) constructor. Note: * this class is designed so that subclasses need only override the makeValue * method in order to construct objects of their own type. * * @author Glen Daniels (gdaniels@apache.org) * @author Sam Ruby (rubys@us.ibm.com) * Modified for JAX-RPC @author Rich Scheuerle (scheu@us.ibm.com) */ public class SimpleDeserializerFactory extends BaseDeserializerFactory { private static final Class[] STRING_STRING_CLASS = new Class [] {String.class, String.class}; private static final Class[] STRING_CLASS = new Class [] {String.class}; private transient Constructor constructor = null; private boolean isBasicType = false; /** * Note that the factory is constructed with the QName and xmlType. This is important * to allow distinction between primitive values and java.lang wrappers. **/ public SimpleDeserializerFactory(Class javaType, QName xmlType) { super(SimpleDeserializer.class, xmlType, javaType); this.isBasicType = JavaUtils.isBasic(javaType); initConstructor(javaType); } private void initConstructor(Class javaType) { if (!this.isBasicType) { // discover the constructor for non basic types try { if (QName.class.isAssignableFrom(javaType)) { constructor = javaType.getDeclaredConstructor(STRING_STRING_CLASS); } else { constructor = javaType.getDeclaredConstructor(STRING_CLASS); } } catch (NoSuchMethodException e) { try { constructor = javaType.getDeclaredConstructor(new Class[]{}); BeanPropertyDescriptor[] pds = BeanUtils.getPd(javaType); if(pds != null) { if(BeanUtils.getSpecificPD(pds,"_value")!=null){ return; } } throw new IllegalArgumentException(e.toString()); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException(ex.toString()); } } } } /** * Get the Deserializer and the set the Constructor so the * deserializer does not have to do introspection. */ public javax.xml.rpc.encoding.Deserializer getDeserializerAs(String mechanismType) throws JAXRPCException { if (javaType == java.lang.Object.class) { return null; } if (this.isBasicType) { return new SimpleDeserializer(javaType, xmlType); } else { // XXX: don't think we can always expect to be SimpleDeserializer // since getSpecialized() might return a different type SimpleDeserializer deser = (SimpleDeserializer) super.getDeserializerAs(mechanismType); if (deser != null) { deser.setConstructor(constructor); } return deser; } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); initConstructor(javaType); } }
7,539
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/EnumSerializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * SerializerFactory for Enum * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class EnumSerializerFactory extends BaseSerializerFactory { public EnumSerializerFactory(Class javaType, QName xmlType) { super(EnumSerializer.class, xmlType, javaType); // Share EnumSerializer instance } }
7,540
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ArraySerializerFactory.java
/* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.encoding.Serializer; import javax.xml.namespace.QName; /** * SerializerFactory for arrays * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class ArraySerializerFactory extends BaseSerializerFactory { public ArraySerializerFactory() { this(Object[].class, Constants.SOAP_ARRAY); } public ArraySerializerFactory(Class javaType, QName xmlType) { super(ArraySerializer.class, xmlType, javaType); } private QName componentType = null; private QName componentQName = null; public ArraySerializerFactory(QName componentType) { super(ArraySerializer.class, Constants.SOAP_ARRAY, Object[].class); this.componentType = componentType; } public ArraySerializerFactory(QName componentType, QName componentQName) { this(componentType); this.componentQName = componentQName; } /** * @param componentQName The componentQName to set. */ public void setComponentQName(QName componentQName) { this.componentQName = componentQName; } /** * @param componentType The componentType to set. */ public void setComponentType(QName componentType) { this.componentType = componentType; } /** * @return Returns the componentQName. */ public QName getComponentQName() { return componentQName; } /** * @return Returns the componentType. */ public QName getComponentType() { return componentType; } /** * Obtains a serializer by invoking &lt;constructor&gt;(javaType, xmlType) * on the serClass. */ protected Serializer getGeneralPurpose(String mechanismType) { // Do something special only if we have an array component type if (componentType == null) return super.getGeneralPurpose(mechanismType); else return new ArraySerializer(javaType, xmlType, componentType, componentQName); } }
7,541
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/DateSerializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * SerializerFactory for Date primitives * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class DateSerializerFactory extends BaseSerializerFactory { public DateSerializerFactory(Class javaType, QName xmlType) { super(DateSerializer.class, xmlType, javaType); // true indicates shared class } }
7,542
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/JAFDataHandlerSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import java.io.IOException; import javax.activation.DataHandler; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.Part; import org.apache.axis.attachments.Attachments; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.Serializer; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.fromJava.Types; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; /** * JAFDataHandler Serializer * @author Rick Rineholt * Modified by Rich Scheuerle (scheu@us.ibm.com) */ public class JAFDataHandlerSerializer implements Serializer { protected static Log log = LogFactory.getLog(JAFDataHandlerSerializer.class.getName()); /** * Serialize a JAF DataHandler quantity. */ 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. } } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,543
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/PlainTextDataHandlerDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.activation.DataHandler; import java.io.IOException; /** * text/plain DataHandler Deserializer * Modified by Russell Butek (butek@us.ibm.com) */ public class PlainTextDataHandlerDeserializer extends JAFDataHandlerDeserializer { protected static Log log = LogFactory.getLog(PlainTextDataHandlerDeserializer.class.getName()); public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { super.startElement(namespace, localName, prefix, attributes, context); if (getValue() instanceof DataHandler) { try { DataHandler dh = (DataHandler) getValue(); setValue(dh.getContent()); } catch (IOException ioe) { } } } // startElement } // class PlainTextDataHandlerDeserializer
7,544
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ElementSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.MessageContext; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.Serializer; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; /** * Serializer for DOM elements * * @author Glen Daniels (gdaniels@apache.org) * Modified by @author Rich scheuerle (scheu@us.ibm.com) */ public class ElementSerializer implements Serializer { /** * Serialize a DOM Element */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { if (!(value instanceof Element)) throw new IOException(Messages.getMessage("cantSerialize01")); MessageContext mc = context.getMessageContext(); context.setWriteXMLType(null); boolean writeWrapper = (mc == null) || mc.isPropertyTrue("writeWrapperForElements", true); if (writeWrapper) context.startElement(name, attributes); context.writeDOMElement((Element)value); if (writeWrapper) context.endElement(); } public String getMechanismType() { return Constants.AXIS_SAX; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,545
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/EnumSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.fromJava.Types; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; /** * Serializer for a JAX-RPC enum. * * @author Rich Scheuerle (scheu@us.ibm.com) * @author Sam Ruby (rubys@us.ibm.com) */ public class EnumSerializer extends SimpleSerializer { protected static Log log = LogFactory.getLog(EnumSerializer.class.getName()); private java.lang.reflect.Method toStringMethod = null; public EnumSerializer(Class javaType, QName xmlType) { super(javaType, xmlType); } /** * Serialize an enumeration */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { context.startElement(name, attributes); context.writeString(getValueAsString(value, context)); context.endElement(); } public String getValueAsString(Object value, SerializationContext context) { // Invoke the toString method on the enumeration class and // write out the result as a string. try { if (toStringMethod == null) { toStringMethod = javaType.getMethod("toString", null); } return (String) toStringMethod.invoke(value, null); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); } return null; } /** * 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 */ public Element writeSchema(Class javaType, Types types) throws Exception { // Use Types helper method. return types.writeEnumType(xmlType, javaType); } }
7,546
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/MapSerializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * A MapSerializer Factory * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class MapSerializerFactory extends BaseSerializerFactory { public MapSerializerFactory(Class javaType, QName xmlType) { super(MapSerializer.class, xmlType, javaType); } }
7,547
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/VectorSerializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import javax.xml.namespace.QName; /** * A VectorSerializer Factory * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class VectorSerializerFactory extends BaseSerializerFactory { public VectorSerializerFactory(Class javaType, QName xmlType) { super(VectorSerializer.class, xmlType, javaType); } }
7,548
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ElementDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; /** * DeserializerFactory for Element. * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class ElementDeserializerFactory extends BaseDeserializerFactory { public ElementDeserializerFactory() { super(ElementDeserializer.class); } }
7,549
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/DocumentDeserializerFactory.java
package org.apache.axis.encoding.ser; /* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * DeserializerFactory for DOM Document. * * @author Davanum Srinivas (dims@yahoo.com) */ public class DocumentDeserializerFactory extends BaseDeserializerFactory { public DocumentDeserializerFactory() { super(DocumentDeserializer.class); } }
7,550
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/BaseDeserializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerFactory; import org.apache.axis.i18n.Messages; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import javax.xml.rpc.JAXRPCException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.Vector; /** * Base class for Axis Deserialization Factory classes for code reuse * * @author Rich Scheuerle (scheu@us.ibm.com) */ public abstract class BaseDeserializerFactory extends BaseFactory implements DeserializerFactory { protected static Log log = LogFactory.getLog(BaseDeserializerFactory.class.getName()); transient static Vector mechanisms = null; protected Class deserClass = null; protected QName xmlType = null; protected Class javaType = null; transient protected Constructor deserClassConstructor = null; transient protected Method getDeserializer = null; /** * Constructor * @param deserClass is the class of the Deserializer */ public BaseDeserializerFactory(Class deserClass) { if (!Deserializer.class.isAssignableFrom(deserClass)) { throw new ClassCastException( Messages.getMessage("BadImplementation00", deserClass.getName(), Deserializer.class.getName())); } this.deserClass = deserClass; } public BaseDeserializerFactory(Class deserClass, QName xmlType, Class javaType) { this(deserClass); this.xmlType = xmlType; this.javaType = javaType; } public javax.xml.rpc.encoding.Deserializer getDeserializerAs(String mechanismType) throws JAXRPCException { Deserializer deser = null; // Need to add code to check against mechanisms vector. // Try getting a specialized Deserializer deser = getSpecialized(mechanismType); // Try getting a general purpose Deserializer via constructor // invocation if (deser == null) { deser = getGeneralPurpose(mechanismType); } try { // If not successfull, try newInstance if (deser == null) { deser = (Deserializer) deserClass.newInstance(); } } catch (Exception e) { throw new JAXRPCException(e); } return deser; } /** * Obtains a deserializer by invoking &lt;constructor&gt;(javaType, xmlType) * on the deserClass. */ protected Deserializer getGeneralPurpose(String mechanismType) { if (javaType != null && xmlType != null) { Constructor deserClassConstructor = getDeserClassConstructor(); if (deserClassConstructor != null) { try { return (Deserializer) deserClassConstructor.newInstance( new Object[] {javaType, xmlType}); } catch (InstantiationException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } catch (IllegalAccessException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } catch (InvocationTargetException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } } } return null; } private static final Class[] CLASS_QNAME_CLASS = new Class[] {Class.class, QName.class}; /** * return constructor for class if any */ private Constructor getConstructor(Class clazz) { try { return clazz.getConstructor(CLASS_QNAME_CLASS); } catch (NoSuchMethodException e) {} return null; } /** * Obtains a deserializer by invoking getDeserializer method in the * javaType class or its Helper class. */ protected Deserializer getSpecialized(String mechanismType) { if (javaType != null && xmlType != null) { Method getDeserializer = getGetDeserializer(); if (getDeserializer != null) { try { return (Deserializer) getDeserializer.invoke( null, new Object[] {mechanismType, javaType, xmlType}); } catch (IllegalAccessException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } catch (InvocationTargetException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } } } return null; } /** * Returns a list of all XML processing mechanism types supported by this DeserializerFactory. * * @return List of unique identifiers for the supported XML processing mechanism types */ public Iterator getSupportedMechanismTypes() { if (mechanisms == null) { mechanisms = new Vector(1); mechanisms.add(Constants.AXIS_SAX); } return mechanisms.iterator(); } /** * Utility method that intospects on a factory class to decide how to * create the factory. Tries in the following order: * public static create(Class javaType, QName xmlType) * public &lt;constructor&gt;(Class javaType, QName xmlType) * public &lt;constructor&gt;() * @param factory class * @param javaType * @param xmlType */ public static DeserializerFactory createFactory(Class factory, Class javaType, QName xmlType) { if (factory == null) { return null; } try { if (factory == BeanDeserializerFactory.class) { return new BeanDeserializerFactory(javaType, xmlType); } else if (factory == SimpleDeserializerFactory.class) { return new SimpleDeserializerFactory(javaType, xmlType); } else if (factory == EnumDeserializerFactory.class) { return new EnumDeserializerFactory(javaType, xmlType); } else if (factory == ElementDeserializerFactory.class) { return new ElementDeserializerFactory(); } else if (factory == SimpleListDeserializerFactory.class) { return new SimpleListDeserializerFactory(javaType, xmlType); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } return null; } DeserializerFactory df = null; try { Method method = factory.getMethod("create", CLASS_QNAME_CLASS); df = (DeserializerFactory) method.invoke(null, new Object[] {javaType, xmlType}); } catch (NoSuchMethodException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } catch (IllegalAccessException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } catch (InvocationTargetException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } if (df == null) { try { Constructor constructor = factory.getConstructor(CLASS_QNAME_CLASS); df = (DeserializerFactory) constructor.newInstance( new Object[] {javaType, xmlType}); } catch (NoSuchMethodException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } catch (InstantiationException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } catch (IllegalAccessException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } catch (InvocationTargetException e) { if(log.isDebugEnabled()) { log.debug(org.apache.axis.utils.Messages.getMessage("exception00"), e); } } } if (df == null) { try { df = (DeserializerFactory) factory.newInstance(); } catch (InstantiationException e) { } catch (IllegalAccessException e) {} } return df; } /** * Returns the deserClassConstructor. * @return Constructor */ protected Constructor getDeserClassConstructor() { if (deserClassConstructor == null) { deserClassConstructor = getConstructor(deserClass); } return deserClassConstructor; } /** * Returns the getDeserializer. * @return Method */ protected Method getGetDeserializer() { if (getDeserializer == null) { getDeserializer = getMethod(javaType,"getDeserializer"); } return getDeserializer; } }
7,551
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/PlainTextDataHandlerSerializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.attachments.PlainTextDataSource; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import javax.activation.DataHandler; import javax.xml.namespace.QName; import java.io.IOException; /** * text/plain DataHandler Serializer * @author Russell Butek (butek@us.ibm.com) */ public class PlainTextDataHandlerSerializer extends JAFDataHandlerSerializer { protected static Log log = LogFactory.getLog(PlainTextDataHandlerSerializer.class.getName()); /** * Serialize a Source DataHandler quantity. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { DataHandler dh = new DataHandler( new PlainTextDataSource("source", (String) value)); super.serialize(name, attributes, dh, context); } // serialize } // class PlainTextDataHandlerSerializer
7,552
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/MimeMultipartDataHandlerDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.activation.DataHandler; import javax.mail.internet.MimeMultipart; /** * MimeMultipartDataHandler Deserializer * @author Russell Butek (butek@us.ibm.com) */ public class MimeMultipartDataHandlerDeserializer extends JAFDataHandlerDeserializer { protected static Log log = LogFactory.getLog(MimeMultipartDataHandlerDeserializer.class.getName()); public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { super.startElement(namespace, localName, prefix, attributes, context); if (getValue() instanceof DataHandler) { try { DataHandler dh = (DataHandler) getValue(); MimeMultipart mmp = new MimeMultipart(dh.getDataSource()); if (mmp.getCount() == 0) { mmp = null; } setValue(mmp); } catch (Exception e) { throw new SAXException(e); } } } // startElement } // class MimeMultipartDataHandlerDeserializer
7,553
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ElementSerializerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; /** * SerializerFactory for Element * * @author Rich Scheuerle (scheu@us.ibm.com) */ public class ElementSerializerFactory extends BaseSerializerFactory { public ElementSerializerFactory() { super(ElementSerializer.class); // Share ElementSerializer instance } }
7,554
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/encoding/ser/ImageDataHandlerDeserializer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.activation.DataHandler; import javax.imageio.ImageIO; import java.awt.*; import java.io.InputStream; /** * ImageDataHandler Deserializer * Modified by Russell Butek (butek@us.ibm.com) */ public class ImageDataHandlerDeserializer extends JAFDataHandlerDeserializer { protected static Log log = LogFactory.getLog(ImageDataHandlerDeserializer.class.getName()); public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { super.startElement(namespace, localName, prefix, attributes, context); if (getValue() instanceof DataHandler) { try { DataHandler dh = (DataHandler) getValue(); InputStream is = dh.getInputStream(); Image image = ImageIO.read(is); setValue(image); } catch (Exception e) { } } } // startElement } // class ImageDataHandlerDeserializer
7,555
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/MessageWithAttachments.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import java.util.Hashtable; /** * @author James Snell (jasnell@us.ibm.com) */ public interface MessageWithAttachments { public boolean hasAttachments(); public Hashtable getAttachments(); public Object getAttachment(String id); public Object getAttachment(int index); }
7,556
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/NullAttributes.java
package org.apache.axis.message; import org.xml.sax.Attributes; /** * Null implementation of the Attributes interface. * * @author David Megginson * @author Sam Ruby (rubys@us.ibm.com) */ public class NullAttributes implements Attributes { public static final NullAttributes singleton = new NullAttributes(); //////////////////////////////////////////////////////////////////// // Implementation of org.xml.sax.Attributes. //////////////////////////////////////////////////////////////////// /** * Return the number of attributes in the list. * * @return The number of attributes in the list. * @see org.xml.sax.Attributes#getLength */ public int getLength () { return 0; } /** * Return an attribute's Namespace URI. * * @param index The attribute's index (zero-based). * @return The Namespace URI, the empty string if none is * available, or null if the index is out of range. * @see org.xml.sax.Attributes#getURI */ public String getURI (int index) { return null; } /** * Return an attribute's local name. * * @param index The attribute's index (zero-based). * @return The attribute's local name, the empty string if * none is available, or null if the index if out of range. * @see org.xml.sax.Attributes#getLocalName */ public String getLocalName (int index) { return null; } /** * Return an attribute's qualified (prefixed) name. * * @param index The attribute's index (zero-based). * @return The attribute's qualified name, the empty string if * none is available, or null if the index is out of bounds. * @see org.xml.sax.Attributes#getQName */ public String getQName (int index) { return null; } /** * Return an attribute's type by index. * * @param index The attribute's index (zero-based). * @return The attribute's type, "CDATA" if the type is unknown, or null * if the index is out of bounds. * @see org.xml.sax.Attributes#getType(int) */ public String getType (int index) { return null; } /** * Return an attribute's value by index. * * @param index The attribute's index (zero-based). * @return The attribute's value or null if the index is out of bounds. * @see org.xml.sax.Attributes#getValue(int) */ public String getValue (int index) { return null; } /** * Look up an attribute's index by Namespace name. * * <p>In many cases, it will be more efficient to look up the name once and * use the index query methods rather than using the name query methods * repeatedly.</p> * * @param uri The attribute's Namespace URI, or the empty * string if none is available. * @param localName The attribute's local name. * @return The attribute's index, or -1 if none matches. * @see org.xml.sax.Attributes#getIndex(java.lang.String,java.lang.String) */ public int getIndex (String uri, String localName) { return -1; } /** * Look up an attribute's index by qualified (prefixed) name. * * @param qName The qualified name. * @return The attribute's index, or -1 if none matches. * @see org.xml.sax.Attributes#getIndex(java.lang.String) */ public int getIndex (String qName) { return -1; } /** * Look up an attribute's type by Namespace-qualified name. * * @param uri The Namespace URI, or the empty string for a name * with no explicit Namespace URI. * @param localName The local name. * @return The attribute's type, or null if there is no * matching attribute. * @see org.xml.sax.Attributes#getType(java.lang.String,java.lang.String) */ public String getType (String uri, String localName) { return null; } /** * Look up an attribute's type by qualified (prefixed) name. * * @param qName The qualified name. * @return The attribute's type, or null if there is no * matching attribute. * @see org.xml.sax.Attributes#getType(java.lang.String) */ public String getType (String qName) { return null; } /** * Look up an attribute's value by Namespace-qualified name. * * @param uri The Namespace URI, or the empty string for a name * with no explicit Namespace URI. * @param localName The local name. * @return The attribute's value, or null if there is no * matching attribute. * @see org.xml.sax.Attributes#getValue(java.lang.String,java.lang.String) */ public String getValue (String uri, String localName) { return null; } /** * Look up an attribute's value by qualified (prefixed) name. * * @param qName The qualified name. * @return The attribute's value, or null if there is no * matching attribute. * @see org.xml.sax.Attributes#getValue(java.lang.String) */ public String getValue (String qName) { return null; } }
7,557
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/Text.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.InternalException; import org.w3c.dom.DOMException; /** * A representation of a node whose value is text. A <CODE> * Text</CODE> object may represent text that is content or text * that is a comment. * * @author Davanum Srinivas (dims@yahoo.com) * @author Heejune Ahn (cityboy@tmax.co.kr) */ public class Text extends NodeImpl implements javax.xml.soap.Text { public Text(org.w3c.dom.CharacterData data) { if ( data == null ) { throw new IllegalArgumentException( "Text value may not be null." ); } textRep = data; } public Text(String s) { try { org.w3c.dom.Document doc = org.apache.axis.utils.XMLUtils.newDocument(); textRep = doc.createTextNode(s); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new InternalException(e); } } public Text() { this((String)null); } /** * Retrieves whether this <CODE>Text</CODE> object * represents a comment. * @return <CODE>true</CODE> if this <CODE>Text</CODE> object is * a comment; <CODE>false</CODE> otherwise */ public boolean isComment() { String temp = textRep.getNodeValue().trim(); if(temp.startsWith("<!--") && temp.endsWith("-->")) return true; return false; } /** * Implementation of DOM TEXT Interface * ************************************************************* */ // Overriding the MessageElement Method, where it throws exeptions. public String getNodeValue() throws DOMException { return textRep.getNodeValue(); } // Overriding the MessageElement Method, where it throws exeptions. public void setNodeValue(String nodeValue) throws DOMException{ setDirty(); textRep.setNodeValue(nodeValue); } /** * Use the textRep, and convert it to org.apache.axis.Text * in order to keep the Axis SOAP strcture after operation * * This work would be easier if constructor, Text(org.w3c.dom.Text) * is defined * * @since SAAJ 1.2 * @param offset * @return * @throws DOMException */ public org.w3c.dom.Text splitText(int offset) throws DOMException { int length = textRep.getLength(); // take the first part, and save the second part for new Text // length check and exception will be thrown here, no need to duplicated check String tailData = textRep.substringData(offset,length); textRep.deleteData(offset,length); // insert the first part again as a new node Text tailText = new Text(tailData); org.w3c.dom.Node myParent = getParentNode(); if(myParent != null){ org.w3c.dom.NodeList brothers = myParent.getChildNodes(); for(int i = 0;i < brothers.getLength(); i++){ if(brothers.item(i).equals(this)){ myParent.insertBefore(tailText, this); return tailText; } } } return tailText; } /** * @since SAAJ 1.2 */ public String getData() throws DOMException { return textRep.getData(); } /** * @since SAAJ 1.2 */ public void setData(String data) throws DOMException { textRep.setData(data); } /** * @since SAAJ 1.2 * * @return */ public int getLength(){ return textRep.getLength(); } /** * @since SAAJ 1.2 * @param offset * @param count * @return * @throws DOMException */ public String substringData(int offset, int count)throws DOMException { return textRep.substringData(offset,count); } /** * * @since SAAJ 1.2 * @param arg * @throws DOMException */ public void appendData(String arg) throws DOMException { textRep.appendData(arg); } /** * @since SAAJ 1.2 * @param offset * @param arg * @throws DOMException */ public void insertData(int offset, String arg)throws DOMException { textRep.insertData(offset, arg); } /** * @since SAAJ 1.2 * @param offset * @param count * @param arg * @throws DOMException */ public void replaceData(int offset, int count, String arg) throws DOMException { textRep.replaceData(offset, count, arg); } /** * @since SAAJ 1.2 * @param offset * @param count * @throws DOMException */ public void deleteData(int offset, int count) throws DOMException { textRep.deleteData(offset, count); } public String toString() { return textRep.getNodeValue(); } public boolean equals( Object obj ) { if ( !( obj instanceof Text ) ) { return false; } return this == obj || hashCode() == obj.hashCode(); } public int hashCode() { if ( textRep == null ) { return -1; } return ( textRep.getData() != null ? textRep.getData().hashCode() : 0 ); } }
7,558
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPFault.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.description.FaultDesc; import org.apache.axis.description.OperationDesc; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import javax.xml.soap.DetailEntry; import javax.xml.soap.Name; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import java.util.List; import java.util.Locale; import java.util.Iterator; /** A Fault body element. * * @author Sam Ruby (rubys@us.ibm.com) * @author Glen Daniels (gdaniels@apache.org) * @author Tom Jordahl (tomj@macromedia.com) */ public class SOAPFault extends SOAPBodyElement implements javax.xml.soap.SOAPFault { protected AxisFault fault; protected String prefix; private java.util.Locale locale; protected Detail detail = null; public SOAPFault(String namespace, String localName, String prefix, Attributes attrs, DeserializationContext context) throws AxisFault { super(namespace, localName, prefix, attrs, context); } public SOAPFault(AxisFault fault) { this.fault = fault; } public void outputImpl(SerializationContext context) throws Exception { SOAPConstants soapConstants = context.getMessageContext() == null ? SOAPConstants.SOAP11_CONSTANTS : context.getMessageContext().getSOAPConstants(); namespaceURI = soapConstants.getEnvelopeURI(); name = Constants.ELEM_FAULT; context.registerPrefixForURI(prefix, soapConstants.getEnvelopeURI()); context.startElement(new QName(this.getNamespaceURI(), this.getName()), attributes); // XXX - Can fault be anything but an AxisFault here? if (fault instanceof AxisFault) { AxisFault axisFault = fault; if (axisFault.getFaultCode() != null) { // Do this BEFORE starting the element, so the prefix gets // registered if needed. if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { String faultCode = context.qName2String(axisFault.getFaultCode()); context.startElement(Constants.QNAME_FAULTCODE_SOAP12, null); context.startElement(Constants.QNAME_FAULTVALUE_SOAP12, null); context.writeSafeString(faultCode); context.endElement(); QName[] subcodes = axisFault.getFaultSubCodes(); if (subcodes != null) { for (int i = 0; i < subcodes.length; i++) { faultCode = context.qName2String(subcodes[i]); context.startElement(Constants.QNAME_FAULTSUBCODE_SOAP12, null); context.startElement(Constants.QNAME_FAULTVALUE_SOAP12, null); context.writeSafeString(faultCode); context.endElement(); } for (int i = 0; i < subcodes.length; i++) context.endElement(); } context.endElement(); } else { String faultCode = context.qName2String(axisFault.getFaultCode()); context.startElement(Constants.QNAME_FAULTCODE, null); context.writeSafeString(faultCode); context.endElement(); } } if (axisFault.getFaultString() != null) { if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { context.startElement(Constants.QNAME_FAULTREASON_SOAP12, null); AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("http://www.w3.org/XML/1998/namespace", "lang", "xml:lang", "CDATA", "en"); context.startElement(Constants.QNAME_TEXT_SOAP12, attrs); } else context.startElement(Constants.QNAME_FAULTSTRING, null); context.writeSafeString(axisFault.getFaultString()); context.endElement(); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { context.endElement(); } } if (axisFault.getFaultActor() != null) { if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) context.startElement(Constants.QNAME_FAULTROLE_SOAP12, null); else context.startElement(Constants.QNAME_FAULTACTOR, null); context.writeSafeString(axisFault.getFaultActor()); context.endElement(); } if (axisFault.getFaultNode() != null) { if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { context.startElement(Constants.QNAME_FAULTNODE_SOAP12, null); context.writeSafeString(axisFault.getFaultNode()); context.endElement(); } } // get the QName for this faults detail element QName qname = getFaultQName(fault.getClass(), context); if (qname == null && fault.detail != null) { qname = getFaultQName(fault.detail.getClass(), context); } if (qname == null) { // not the greatest, but... qname = new QName("", "faultData"); } Element[] faultDetails = axisFault.getFaultDetails(); if (faultDetails != null) { if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) context.startElement(Constants.QNAME_FAULTDETAIL_SOAP12, null); else context.startElement(Constants.QNAME_FAULTDETAILS, null); // Allow the fault to write its data, if any axisFault.writeDetails(qname, context); // Then output any other elements for (int i = 0; i < faultDetails.length; i++) { context.writeDOMElement(faultDetails[i]); } if (detail!= null) { for (Iterator it = detail.getChildren().iterator(); it.hasNext();) { ((NodeImpl)it.next()).output(context); } } context.endElement(); } } context.endElement(); } private QName getFaultQName(Class cls, SerializationContext context) { QName qname = null; if (! cls.equals(AxisFault.class)) { FaultDesc faultDesc = null; if (context.getMessageContext() != null) { OperationDesc op = context.getMessageContext().getOperation(); if (op != null) { faultDesc = op.getFaultByClass(cls); } } if (faultDesc != null) { qname = faultDesc.getQName(); } } return qname; } public AxisFault getFault() { return fault; } public void setFault(AxisFault fault) { this.fault = fault; } /** * Sets this <CODE>SOAPFaultException</CODE> object with the given * fault code. * * <P>Fault codes, which given information about the fault, * are defined in the SOAP 1.1 specification.</P> * @param faultCode a <CODE>String</CODE> giving * the fault code to be set; must be one of the fault codes * defined in the SOAP 1.1 specification * @throws SOAPException if there was an error in * adding the <CODE>faultCode</CODE> to the underlying XML * tree. */ public void setFaultCode(String faultCode) throws SOAPException { fault.setFaultCodeAsString(faultCode); } /** * Gets the fault code for this <CODE>SOAPFaultException</CODE> * object. * @return a <CODE>String</CODE> with the fault code */ public String getFaultCode() { return fault.getFaultCode().getLocalPart(); } /** * Sets this <CODE>SOAPFaultException</CODE> object with the given * fault actor. * * <P>The fault actor is the recipient in the message path who * caused the fault to happen.</P> * @param faultActor a <CODE>String</CODE> * identifying the actor that caused this <CODE> * SOAPFaultException</CODE> object * @throws SOAPException if there was an error in * adding the <CODE>faultActor</CODE> to the underlying XML * tree. */ public void setFaultActor(String faultActor) throws SOAPException { fault.setFaultActor(faultActor); } /** * Gets the fault actor for this <CODE>SOAPFaultException</CODE> * object. * @return a <CODE>String</CODE> giving the actor in the message * path that caused this <CODE>SOAPFaultException</CODE> object * @see #setFaultActor(java.lang.String) setFaultActor(java.lang.String) */ public String getFaultActor() { return fault.getFaultActor(); } /** * Sets the fault string for this <CODE>SOAPFaultException</CODE> * object to the given string. * * @param faultString a <CODE>String</CODE> * giving an explanation of the fault * @throws SOAPException if there was an error in * adding the <CODE>faultString</CODE> to the underlying XML * tree. * @see #getFaultString() getFaultString() */ public void setFaultString(String faultString) throws SOAPException { fault.setFaultString(faultString); } /** * Gets the fault string for this <CODE>SOAPFaultException</CODE> * object. * @return a <CODE>String</CODE> giving an explanation of the * fault */ public String getFaultString() { return fault.getFaultString(); } /** * Returns the detail element for this <CODE>SOAPFaultException</CODE> * object. * * <P>A <CODE>Detail</CODE> object carries * application-specific error information related to <CODE> * SOAPBodyElement</CODE> objects.</P> * @return a <CODE>Detail</CODE> object with * application-specific error information */ public javax.xml.soap.Detail getDetail() { List children = this.getChildren(); if(children==null || children.size()<=0) return null; // find detail element for (int i=0; i < children.size(); i++) { Object obj = children.get(i); if (obj instanceof javax.xml.soap.Detail) { return (javax.xml.soap.Detail) obj; } } return null; } /** * Creates a <CODE>Detail</CODE> object and sets it as the * <CODE>Detail</CODE> object for this <CODE>SOAPFaultException</CODE> * object. * * <P>It is illegal to add a detail when the fault already * contains a detail. Therefore, this method should be called * only after the existing detail has been removed.</P> * @return the new <CODE>Detail</CODE> object * @throws SOAPException if this * <CODE>SOAPFaultException</CODE> object already contains a valid * <CODE>Detail</CODE> object */ public javax.xml.soap.Detail addDetail() throws SOAPException { if(getDetail() != null){ throw new SOAPException(Messages.getMessage("valuePresent")); } Detail detail = convertToDetail(fault); addChildElement(detail); return detail; } public void setFaultCode(Name faultCodeQName) throws SOAPException { String uri = faultCodeQName.getURI(); String local = faultCodeQName.getLocalName(); String prefix = faultCodeQName.getPrefix(); this.prefix = prefix; QName qname = new QName(uri,local); fault.setFaultCode(qname); } public Name getFaultCodeAsName() { QName qname = fault.getFaultCode(); String uri = qname.getNamespaceURI(); String local = qname.getLocalPart(); return new PrefixedQName(uri, local, prefix); } public void setFaultString(String faultString, Locale locale) throws SOAPException { fault.setFaultString(faultString); this.locale = locale; } public Locale getFaultStringLocale() { return locale; } /** * Convert the details in an AxisFault to a Detail object * * @param fault source of the fault details * @return a detail element contructed from the AxisFault details * @throws SOAPException */ private Detail convertToDetail(AxisFault fault) throws SOAPException { detail = new Detail(); Element[] darray = fault.getFaultDetails(); fault.setFaultDetail(new Element[]{}); for (int i = 0; i < darray.length; i++) { Element detailtEntryElem = darray[i]; DetailEntry detailEntry = detail.addDetailEntry( new PrefixedQName(detailtEntryElem.getNamespaceURI(), detailtEntryElem.getLocalName(), detailtEntryElem.getPrefix())); copyChildren(detailEntry, detailtEntryElem); } return detail; } /** * Copy the children of a DOM element to a SOAPElement. * * @param soapElement target of the copy * @param domElement source for the copy * @throws SOAPException */ private static void copyChildren(SOAPElement soapElement, Element domElement) throws SOAPException { org.w3c.dom.NodeList nl = domElement.getChildNodes(); for (int j = 0; j < nl.getLength(); j++) { org.w3c.dom.Node childNode = nl.item(j); if (childNode.getNodeType() == Node.TEXT_NODE) { soapElement.addTextNode(childNode.getNodeValue()); break; // only one text node assmed } if (childNode.getNodeType() == Node.ELEMENT_NODE) { String uri = childNode.getNamespaceURI(); SOAPElement childSoapElement = null; if (uri == null) { childSoapElement = soapElement.addChildElement(childNode.getLocalName ()); } else { childSoapElement = soapElement.addChildElement( childNode.getLocalName(), childNode.getPrefix(), uri); } copyChildren(childSoapElement, (Element) childNode); } } } }
7,559
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPFaultCodeBuilder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.Constants; import org.apache.axis.encoding.Callback; import org.apache.axis.encoding.CallbackTarget; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; /** * Build a Fault body element. * * @author Sam Ruby (rubys@us.ibm.com) * @author Glen Daniels (gdaniels@apache.org) * @author Tom Jordahl (tomj@macromedia.com) */ public class SOAPFaultCodeBuilder extends SOAPHandler implements Callback { // Fault data protected QName faultCode = null; protected SOAPFaultCodeBuilder next = null; public SOAPFaultCodeBuilder() { } public QName getFaultCode() { return faultCode; } public SOAPFaultCodeBuilder getNext() { return next; } public SOAPHandler onStartChild(String namespace, String name, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { QName thisQName = new QName(namespace, name); if (thisQName.equals(Constants.QNAME_FAULTVALUE_SOAP12)) { Deserializer currentDeser = null; currentDeser = context.getDeserializerForType(Constants.XSD_QNAME); if (currentDeser != null) { currentDeser.registerValueTarget(new CallbackTarget(this, thisQName)); } return (SOAPHandler)currentDeser; } else if (thisQName.equals(Constants.QNAME_FAULTSUBCODE_SOAP12)) { return (next = new SOAPFaultCodeBuilder()); } else return null; } /* * Defined by Callback. * This method gets control when the callback is invoked. * @param is the value to set. * @param hint is an Object that provide additional hint information. */ public void setValue(Object value, Object hint) { QName thisQName = (QName)hint; if (thisQName.equals(Constants.QNAME_FAULTVALUE_SOAP12)) { faultCode = (QName)value; } } }
7,560
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/HeaderBuilder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** * * @author Glen Daniels (gdaniels@allaire.com) */ import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class HeaderBuilder extends SOAPHandler { protected static Log log = LogFactory.getLog(HeaderBuilder.class.getName()); private SOAPHeaderElement header; private SOAPEnvelope envelope; HeaderBuilder(SOAPEnvelope envelope) { this.envelope = envelope; } public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { SOAPConstants soapConstants = context.getSOAPConstants(); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS && attributes.getValue(Constants.URI_SOAP12_ENV, Constants.ATTR_ENCODING_STYLE) != null) { AxisFault fault = new AxisFault(Constants.FAULT_SOAP12_SENDER, null, Messages.getMessage("noEncodingStyleAttrAppear", "Header"), null, null, null); throw new SAXException(fault); } if (!context.isDoneParsing()) { if (myElement == null) { try { myElement = new SOAPHeader(namespace, localName, prefix, attributes, context, envelope.getSOAPConstants()); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } envelope.setHeader((SOAPHeader)myElement); } context.pushNewElement(myElement); } } public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { try { header = new SOAPHeaderElement(namespace, localName, prefix, attributes, context); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } SOAPHandler handler = new SOAPHandler(); handler.myElement = header; return handler; } public void onEndChild(String namespace, String localName, DeserializationContext context) { } }
7,561
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/CommentImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import javax.xml.soap.Text; /** * Most of methods are inherited from TEXT, defined for its Interface Marker * only * * @author Heejune Ahn (cityboy@tmax.co.kr) */ public class CommentImpl extends org.apache.axis.message.Text implements Text, Comment { public CommentImpl(String text) { super(text); } public boolean isComment() { return true; } public org.w3c.dom.Text splitText(int offset) throws DOMException { int length = textRep.getLength(); // take the first part, and save the second part for new Text // length check and exception will be thrown here, no need to // duplicated check String tailData = textRep.substringData(offset, length); textRep.deleteData(offset, length); // insert the first part again as a new node Text tailText = new CommentImpl(tailData); org.w3c.dom.Node myParent = (org.w3c.dom.Node) getParentNode(); if (myParent != null) { org.w3c.dom.NodeList brothers = (org.w3c.dom.NodeList) myParent.getChildNodes(); for (int i = 0; i < brothers.getLength(); i++) { if (brothers.item(i).equals(this)) { myParent.insertBefore(tailText, this); return tailText; } } } return tailText; } }
7,562
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/RPCHandler.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** * * @author Glen Daniels (gdaniels@allaire.com) */ import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.constants.Style; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ParameterDesc; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.encoding.XMLType; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; /** * This is the SOAPHandler which is called for each RPC parameter as we're * deserializing the XML for a method call or return. In other words for * this XML: * * <pre> * &lt;methodName&gt; * &lt;param1 xsi:type="xsd:string"&gt;Hello!&lt;/param1&gt; * &lt;param2&gt;3.14159&lt;/param2&gt; * &lt;/methodName&gt; * </pre> * * ...we'll get onStartChild() events for &lt;param1&gt; and &lt;param2&gt;. * * @author Glen Daniels (gdaniels@apache.org) */ public class RPCHandler extends SOAPHandler { protected static Log log = LogFactory.getLog(RPCHandler.class.getName()); private RPCElement rpcElem; private RPCParam currentParam = null; private boolean isResponse; private OperationDesc operation; private boolean isHeaderElement; public RPCHandler(RPCElement rpcElem, boolean isResponse) throws SAXException { this.rpcElem = rpcElem; this.isResponse = isResponse; } public void setOperation(OperationDesc myOperation) { this.operation = myOperation; } /** * Indicate RPCHandler is processing header elements * @param value boolean indicating whether * header elements are being processed. */ public void setHeaderElement(boolean value) { isHeaderElement = true; } /** * This method is invoked when an element start tag is encountered. * The purpose of this method in RPCHandler is to reset variables * (this allows re-use of RPCHandlers) * @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 attributes on the element...used to get the type * @param context is the DeserializationContext */ public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { super.startElement(namespace, localName, prefix, attributes, context); currentParam = null; } /** * Register the start of a parameter (child element of the method call * element). * * Our job here is to figure out a) which parameter this is (based on * the QName of the element or its position), and b) what type it is * (based on the xsi:type attribute or operation metadata) so we can * successfully deserialize it. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (log.isDebugEnabled()) { log.debug("Enter: RPCHandler.onStartChild()"); } if (!context.isDoneParsing()) { try { context.pushNewElement(new MessageElement(namespace, localName, prefix, attributes, context)); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } } MessageElement curEl = context.getCurElement(); QName type = null; QName qname = new QName(namespace, localName); ParameterDesc paramDesc = null; SOAPConstants soapConstants = context.getSOAPConstants(); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS && Constants.QNAME_RPC_RESULT.equals(qname)) { // TODO: fix it ... now we just skip it return new DeserializerImpl(); } // Create a new param if not the same element if (currentParam == null || !currentParam.getQName().getNamespaceURI().equals(namespace) || !currentParam.getQName().getLocalPart().equals(localName)) { currentParam = new RPCParam(namespace, localName, null); rpcElem.addParam(currentParam); } // Grab xsi:type attribute if present, on either this element or // the referent (if it's an href). MessageElement.getType() will // automatically dig through to the referent if necessary. type = curEl.getType(); if (type == null) { type = context.getTypeFromAttributes(namespace, localName, attributes); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("typeFromAttr00", "" + type)); } Class destClass = null; // If we have an operation descriptor, try to associate this parameter // with the appropriate ParameterDesc if (operation != null) { // Try by name first if (isResponse) { paramDesc = operation.getOutputParamByQName(qname); } else { paramDesc = operation.getInputParamByQName(qname); } // If that didn't work, try position // FIXME : Do we need to be in EITHER named OR positional // mode? I.e. will it screw us up to find something // by position if we've already looked something up // by name? I think so... if (paramDesc == null) { if (isResponse) { paramDesc = operation.getReturnParamDesc(); } else { paramDesc = operation.getParameter(rpcElem.getParams().size() - 1); } } if (paramDesc == null) { throw new SAXException(Messages.getMessage("noParmDesc")); } // Make sure that we don't find body parameters that should // be in the header if (!isHeaderElement && ((isResponse && paramDesc.isOutHeader()) || (!isResponse && paramDesc.isInHeader()))) { throw new SAXException( Messages.getMessage("expectedHeaderParam", paramDesc.getQName().toString())); } destClass = paramDesc.getJavaType(); if ((destClass != null) && (destClass.isArray())) { context.setDestinationClass(destClass); } // Keep the association so we can use it later // (see RPCProvider.processMessage()) currentParam.setParamDesc(paramDesc); if (type == null) { type = paramDesc.getTypeQName(); } } if (type != null && type.equals(XMLType.AXIS_VOID)) { Deserializer nilDSer = new DeserializerImpl(); return (SOAPHandler) nilDSer; } // If the nil attribute is set, just // return the base DeserializerImpl. // Register the value target to set the value // on the RPCParam. This is necessary for cases like // <method> // <foo>123</foo> // <foo>456</foo> // <foo xsi:nil="true" /> // </method> // so that a list of 3 items is created. // Failure to register the target would result in the last // item not being added to the list if (context.isNil(attributes)) { Deserializer nilDSer = new DeserializerImpl(); nilDSer.registerValueTarget(new RPCParamTarget(currentParam)); return (SOAPHandler) nilDSer; } Deserializer dser = null; if ((type == null) && (namespace != null) && (!namespace.equals(""))) { dser = context.getDeserializerForType(qname); } else { dser = context.getDeserializer(destClass, type); // !!! if (dser == null && destClass != null && destClass.isArray() && operation.getStyle() == Style.DOCUMENT) { dser = context.getDeserializerForClass(destClass); } // !!! } if (dser == null) { if (type != null) { dser = context.getDeserializerForType(type); if(null != destClass && dser == null && Element.class.isAssignableFrom(destClass)){ //If a DOM element is expected, as last resort always allow direct mapping // of parameter's SOAP xml to a DOM element. Support of literal parms by default. dser = context.getDeserializerForType(Constants.SOAP_ELEMENT); } if (dser == null) { dser = context.getDeserializerForClass(destClass); } if (dser == null) { throw new SAXException(Messages.getMessage( "noDeser01", localName,"" + type)); } if (paramDesc != null && paramDesc.getJavaType() != null) { // If we have an xsi:type, make sure it makes sense // with the current paramDesc type Class xsiClass = context.getTypeMapping().getClassForQName(type); if (null != xsiClass && !JavaUtils.isConvertable(xsiClass, destClass)) { throw new SAXException("Bad types (" + xsiClass + " -> " + destClass + ")"); // FIXME! } } } else { dser = context.getDeserializerForClass(destClass); if (dser == null) { dser = new DeserializerImpl(); } } } dser.setDefaultType(type); dser.registerValueTarget(new RPCParamTarget(currentParam)); if (log.isDebugEnabled()) { log.debug("Exit: RPCHandler.onStartChild()"); } return (SOAPHandler)dser; } public void endElement(String namespace, String localName, DeserializationContext context) throws SAXException { // endElement may not be called in all circumstances. // In addition, onStartChild may be called after endElement // (for header parameter/response processing). // So please don't add important logic to this method. if (log.isDebugEnabled()) { log.debug(Messages.getMessage("setProp00", "MessageContext", "RPCHandler.endElement().")); } context.getMessageContext().setProperty("RPC", rpcElem); } }
7,563
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/RPCParamTarget.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.encoding.Target; import org.xml.sax.SAXException; public class RPCParamTarget implements Target { private RPCParam param; public RPCParamTarget(RPCParam param) { this.param = param; } public void set(Object value) throws SAXException { this.param.set(value); } }
7,564
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/InputStreamBody.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.IOUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.io.IOException; import java.io.InputStream; public class InputStreamBody extends SOAPBodyElement { protected static Log log = LogFactory.getLog(InputStreamBody.class.getName()); protected InputStream inputStream; public InputStreamBody(InputStream inputStream) { this.inputStream = inputStream; } public void outputImpl(SerializationContext context) throws IOException { try { byte[] buf = new byte[ inputStream.available() ]; IOUtils.readFully(inputStream,buf); String contents = new String(buf); context.writeString(contents); } catch( IOException ex ) { throw ex; } catch( Exception e ) { log.error(Messages.getMessage("exception00"), e); } } }
7,565
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPEnvelope.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.client.AxisClient; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.configuration.NullProvider; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.schema.SchemaVersion; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Mapping; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import javax.xml.soap.SOAPException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; import java.util.List; /** * Implementation of a SOAP Envelope */ public class SOAPEnvelope extends MessageElement implements javax.xml.soap.SOAPEnvelope { protected static Log log = LogFactory.getLog(SOAPEnvelope.class.getName()); private SOAPHeader header; private SOAPBody body; public Vector trailers = new Vector(); private SOAPConstants soapConstants; private SchemaVersion schemaVersion = SchemaVersion.SCHEMA_2001; // This is a hint to any service description to tell it what // "type" of message we are. This might be "request", "response", // or anything else your particular service descripton requires. // // This gets passed back into the service description during // deserialization public String messageType; private boolean recorded; public SOAPEnvelope() { this(true, SOAPConstants.SOAP11_CONSTANTS); } public SOAPEnvelope(SOAPConstants soapConstants) { this(true, soapConstants); } public SOAPEnvelope(SOAPConstants soapConstants, SchemaVersion schemaVersion) { this(true, soapConstants, schemaVersion); } public SOAPEnvelope(boolean registerPrefixes, SOAPConstants soapConstants) { this (registerPrefixes, soapConstants, SchemaVersion.SCHEMA_2001); } public SOAPEnvelope(boolean registerPrefixes, SOAPConstants soapConstants, SchemaVersion schemaVersion) { // FIX BUG http://nagoya.apache.org/bugzilla/show_bug.cgi?id=18108 super(Constants.ELEM_ENVELOPE, Constants.NS_PREFIX_SOAP_ENV, (soapConstants != null) ? soapConstants.getEnvelopeURI() : Constants.DEFAULT_SOAP_VERSION.getEnvelopeURI()); if (soapConstants == null) soapConstants = Constants.DEFAULT_SOAP_VERSION; // FIX BUG http://nagoya.apache.org/bugzilla/show_bug.cgi?id=18108 this.soapConstants = soapConstants; this.schemaVersion = schemaVersion; header = new SOAPHeader(this, soapConstants); body = new SOAPBody(this, soapConstants); if (registerPrefixes) { if (namespaces == null) namespaces = new ArrayList(); namespaces.add(new Mapping(soapConstants.getEnvelopeURI(), Constants.NS_PREFIX_SOAP_ENV)); namespaces.add(new Mapping(schemaVersion.getXsdURI(), Constants.NS_PREFIX_SCHEMA_XSD)); namespaces.add(new Mapping(schemaVersion.getXsiURI(), Constants.NS_PREFIX_SCHEMA_XSI)); } setDirty(); } public SOAPEnvelope(InputStream input) throws SAXException { InputSource is = new InputSource(input); // FIX BUG http://nagoya.apache.org/bugzilla/show_bug.cgi?id=18108 //header = new SOAPHeader(this, soapConstants); // soapConstants = null! header = new SOAPHeader(this, Constants.DEFAULT_SOAP_VERSION); // soapConstants = null! // FIX BUG http://nagoya.apache.org/bugzilla/show_bug.cgi?id=18108 DeserializationContext dser = null ; AxisClient tmpEngine = new AxisClient(new NullProvider()); MessageContext msgContext = new MessageContext(tmpEngine); dser = new DeserializationContext(is, msgContext, Message.REQUEST, this ); dser.parse(); } /** * Get the Message Type (REQUEST/RESPONSE) * @return message type */ public String getMessageType() { return messageType; } /** * Set the Message Type (REQUEST/RESPONSE) * @param messageType */ public void setMessageType(String messageType) { this.messageType = messageType; } /** * Get all the BodyElement's in the soap body * @return vector with body elements * @throws AxisFault */ public Vector getBodyElements() throws AxisFault { if (body != null) { return body.getBodyElements(); } else { return new Vector(); } } /** * Return trailers * @return vector of some type */ public Vector getTrailers() { return trailers; } /** * Get the first BodyElement in the SOAP Body * @return first Body Element * @throws AxisFault */ public SOAPBodyElement getFirstBody() throws AxisFault { if (body == null) { return null; } else { return body.getFirstBody(); } } /** * Get Headers * @return Vector containing Header's * @throws AxisFault */ public Vector getHeaders() throws AxisFault { if (header != null) { return header.getHeaders(); } else { return new Vector(); } } /** * Get all the headers targeted at a list of actors. */ public Vector getHeadersByActor(ArrayList actors) { if (header != null) { return header.getHeadersByActor(actors); } else { return new Vector(); } } /** * Add a HeaderElement * @param hdr */ public void addHeader(SOAPHeaderElement hdr) { if (header == null) { header = new SOAPHeader(this, soapConstants); } hdr.setEnvelope(this); header.addHeader(hdr); _isDirty = true; } /** * Add a SOAP Body Element * @param element */ public void addBodyElement(SOAPBodyElement element) { if (body == null) { body = new SOAPBody(this, soapConstants); } element.setEnvelope(this); body.addBodyElement(element); _isDirty = true; } /** * Remove all headers */ public void removeHeaders() { if (header != null) { removeChild(header); } header = null; } /** * Set the SOAP Header * @param hdr */ public void setHeader(SOAPHeader hdr) { if(this.header != null) { removeChild(this.header); } header = hdr; try { header.setParentElement(this); } catch (SOAPException ex) { // class cast should never fail when parent is a SOAPEnvelope log.fatal(Messages.getMessage("exception00"), ex); } } /** * Remove a Header Element from SOAP Header * @param hdr */ public void removeHeader(SOAPHeaderElement hdr) { if (header != null) { header.removeHeader(hdr); _isDirty = true; } } /** * Remove the SOAP Body */ public void removeBody() { if (body != null) { removeChild(body); } body = null; } /** * Set the soap body * @param body */ public void setBody(SOAPBody body) { if(this.body != null) { removeChild(this.body); } this.body = body; try { body.setParentElement(this); } catch (SOAPException ex) { // class cast should never fail when parent is a SOAPEnvelope log.fatal(Messages.getMessage("exception00"), ex); } } /** * Remove a Body Element from the soap body * @param element */ public void removeBodyElement(SOAPBodyElement element) { if (body != null) { body.removeBodyElement(element); _isDirty = true; } } /** * Remove an element from the trailer * @param element */ public void removeTrailer(MessageElement element) { if (log.isDebugEnabled()) log.debug(Messages.getMessage("removeTrailer00")); trailers.removeElement(element); _isDirty = true; } /** * clear the elements in the soap body */ public void clearBody() { if (body != null) { body.clearBody(); _isDirty = true; } } /** * Add an element to the trailer * @param element */ public void addTrailer(MessageElement element) { if (log.isDebugEnabled()) log.debug(Messages.getMessage("removeTrailer00")); element.setEnvelope(this); trailers.addElement(element); _isDirty = true; } /** * Get a header by name (always respecting the currently in-scope * actors list) */ public SOAPHeaderElement getHeaderByName(String namespace, String localPart) throws AxisFault { return getHeaderByName(namespace, localPart, false); } /** * Get a header by name, filtering for headers targeted at this * engine depending on the accessAllHeaders parameter. */ public SOAPHeaderElement getHeaderByName(String namespace, String localPart, boolean accessAllHeaders) throws AxisFault { if (header != null) { return header.getHeaderByName(namespace, localPart, accessAllHeaders); } else { return null; } } /** * Get a body element given its name * @param namespace * @param localPart * @return * @throws AxisFault */ public SOAPBodyElement getBodyByName(String namespace, String localPart) throws AxisFault { if (body == null) { return null; } else { return body.getBodyByName(namespace, localPart); } } /** * Get an enumeration of header elements given the namespace and localpart * @param namespace * @param localPart * @return * @throws AxisFault */ public Enumeration getHeadersByName(String namespace, String localPart) throws AxisFault { return getHeadersByName(namespace, localPart, false); } /** * Return an Enumeration of headers which match the given namespace * and localPart. Depending on the value of the accessAllHeaders * parameter, we will attempt to filter on the current engine's list * of actors. * * !!! NOTE THAT RIGHT NOW WE ALWAYS ASSUME WE'RE THE "ULTIMATE * DESTINATION" (i.e. we match on null actor). IF WE WANT TO FULLY SUPPORT * INTERMEDIARIES WE'LL NEED TO FIX THIS. */ public Enumeration getHeadersByName(String namespace, String localPart, boolean accessAllHeaders) throws AxisFault { if (header != null) { return header.getHeadersByName(namespace, localPart, accessAllHeaders); } else { return new Vector().elements(); } } /** Should make SOAPSerializationException? */ public void outputImpl(SerializationContext context) throws Exception { boolean oldPretty = context.getPretty(); context.setPretty(true); // Register namespace prefixes. if (namespaces != null) { for (Iterator i = namespaces.iterator(); i.hasNext(); ) { Mapping mapping = (Mapping)i.next(); context.registerPrefixForURI(mapping.getPrefix(), mapping.getNamespaceURI()); } } Enumeration enumeration; // Output <SOAP-ENV:Envelope> context.startElement(new QName(soapConstants.getEnvelopeURI(), Constants.ELEM_ENVELOPE), attributes); // Output <SOAP-ENV:Envelope>'s each child as it appears. Iterator i = getChildElements(); while (i.hasNext()) { NodeImpl node = (NodeImpl)i.next(); if (node instanceof SOAPHeader) { header.outputImpl(context); } else if (node instanceof SOAPBody) { body.outputImpl(context); } else if (node instanceof MessageElement) { ((MessageElement)node).output(context); } else { node.output(context); } } // Output trailers enumeration = trailers.elements(); while (enumeration.hasMoreElements()) { MessageElement element = (MessageElement)enumeration.nextElement(); element.output(context); // Output this independent element } // Output </SOAP-ENV:Envelope> context.endElement(); context.setPretty(oldPretty); } /** * Get the soap constants for this envelope * @return */ public SOAPConstants getSOAPConstants() { return soapConstants; } /** * Set the soap constants for this envelope * @param soapConstants */ public void setSoapConstants(SOAPConstants soapConstants) { this.soapConstants = soapConstants; } /** * Get the schema version for this envelope * @return */ public SchemaVersion getSchemaVersion() { return schemaVersion; } /** * Set the schema version for this envelope * @param schemaVersion */ public void setSchemaVersion(SchemaVersion schemaVersion) { this.schemaVersion = schemaVersion; } /** * Add a soap body if one does not exist * @return * @throws SOAPException */ public javax.xml.soap.SOAPBody addBody() throws SOAPException { if (body == null) { body = new SOAPBody(this, soapConstants); _isDirty = true; body.setOwnerDocument(getOwnerDocument()); return body; } else { throw new SOAPException(Messages.getMessage("bodyPresent")); } } /** * Add a soap header if one does not exist * @return * @throws SOAPException */ public javax.xml.soap.SOAPHeader addHeader() throws SOAPException { if (header == null) { header = new SOAPHeader(this, soapConstants); header.setOwnerDocument(getOwnerDocument()); return header; } else { throw new SOAPException(Messages.getMessage("headerPresent")); } } /** * create a Name given the local part * @param localName * @return * @throws SOAPException */ public javax.xml.soap.Name createName(String localName) throws SOAPException { return new PrefixedQName(null, localName, null); } /** * Create a name given local part, prefix and uri * @param localName * @param prefix * @param uri * @return * @throws SOAPException */ public javax.xml.soap.Name createName(String localName, String prefix, String uri) throws SOAPException { return new PrefixedQName(uri, localName, prefix); } /** * Get the soap body * @return * @throws SOAPException */ public javax.xml.soap.SOAPBody getBody() throws SOAPException { return body; } /** * Get the soap header * @return * @throws SOAPException */ public javax.xml.soap.SOAPHeader getHeader() throws SOAPException { return header; } public void setSAAJEncodingCompliance(boolean comply) { this.body.setSAAJEncodingCompliance(comply); } public Node removeChild(Node oldChild) throws DOMException { if(oldChild == header) { header = null; } else if(oldChild == body) { body = null; } return super.removeChild(oldChild); } public Node cloneNode(boolean deep) { SOAPEnvelope envelope = (SOAPEnvelope)super.cloneNode( deep ); if( !deep ) { envelope.body = null; envelope.header = null; } return envelope; } protected void childDeepCloned( NodeImpl oldNode, NodeImpl newNode ) { if( oldNode == body ) { body = (SOAPBody)newNode; try { body.setParentElement(this); } catch (SOAPException ex) { // class cast should never fail when parent is a SOAPEnvelope log.fatal(Messages.getMessage("exception00"), ex); } } else if( oldNode == header ) { header = (SOAPHeader)newNode; } } public void setOwnerDocument(org.apache.axis.SOAPPart sp) { super.setOwnerDocument(sp); if(body != null) { body.setOwnerDocument(sp); setOwnerDocumentForChildren(((NodeImpl)body).children, sp); } if(header != null){ header.setOwnerDocument(sp); setOwnerDocumentForChildren(((NodeImpl)body).children, sp); } } private void setOwnerDocumentForChildren(List children, org.apache.axis.SOAPPart sp) { if (children == null) { return; } int size = children.size(); for (int i = 0; i < size; i++) { NodeImpl node = (NodeImpl) children.get(i); node.setOwnerDocument(sp); setOwnerDocumentForChildren(node.children, sp); // recursively } } public void setRecorded(boolean recorded) { this.recorded = recorded; } public boolean isRecorded() { return recorded; } public void setDirty(boolean dirty) { if (recorder != null && !_isDirty && dirty && isRecorded()){ recorder.clear(); recorder = null; } setDirty(); } }
7,566
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/RPCElement.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.description.OperationDesc; import org.apache.axis.description.ParameterDesc; import org.apache.axis.description.ServiceDesc; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import javax.xml.soap.SOAPElement; import java.util.ArrayList; import java.util.Enumeration; import java.util.Vector; import java.util.Iterator; import java.util.List; import java.util.Collection; public class RPCElement extends SOAPBodyElement { //protected Vector params2 = new Vector(); protected boolean needDeser = false; OperationDesc [] operations = null; public RPCElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context, OperationDesc [] operations) throws AxisFault { super(namespace, localName, prefix, attributes, context); // This came from parsing XML, so we need to deserialize it sometime needDeser = true; // Obtain our possible operations if (operations == null) { updateOperationsByName(); } else { this.operations = operations; } } public RPCElement(String namespace, String methodName, Object [] args) { this.setNamespaceURI(namespace); this.name = methodName; for (int i = 0; args != null && i < args.length; i++) { if (args[i] instanceof RPCParam) { addParam((RPCParam)args[i]); } else { String name = null; if (name == null) name = "arg" + i; addParam(new RPCParam(namespace, name, args[i])); } } } public RPCElement(String methodName) { this.name = methodName; } public void updateOperationsByName() throws AxisFault { if (context == null) { return; } MessageContext msgContext = context.getMessageContext(); if (msgContext == null) { return; } // Obtain our possible operations SOAPService service = msgContext.getService(); if (service == null) { return; } ServiceDesc serviceDesc = service.getInitializedServiceDesc(msgContext); String lc = JavaUtils.xmlNameToJava(name); if (serviceDesc == null) { throw AxisFault.makeFault( new ClassNotFoundException( Messages.getMessage("noClassForService00", lc))); } this.operations = serviceDesc.getOperationsByName(lc); } public void updateOperationsByQName() throws AxisFault { if (context == null) { return; } MessageContext msgContext = context.getMessageContext(); if (msgContext == null) { return; } this.operations = msgContext.getPossibleOperationsByQName(getQName()); } public OperationDesc[] getOperations() { return this.operations; } public String getMethodName() { return name; } public void setNeedDeser(boolean needDeser) { this.needDeser = needDeser; } public void deserialize() throws SAXException { needDeser = false; MessageContext msgContext = context.getMessageContext(); // Figure out if we should be looking for out params or in params // (i.e. is this message a response?) Message msg = msgContext.getCurrentMessage(); SOAPConstants soapConstants = msgContext.getSOAPConstants(); boolean isResponse = ((msg != null) && Message.RESPONSE.equals(msg.getMessageType())); // We're going to need this below, so create one. RPCHandler rpcHandler = new RPCHandler(this, isResponse); if (operations != null) { int numParams = (getChildren() == null) ? 0 : getChildren().size(); SAXException savedException = null; // By default, accept missing parameters as nulls, and // allow the message context to override. boolean acceptMissingParams = msgContext.isPropertyTrue( MessageContext.ACCEPTMISSINGPARAMS, true); // We now have an array of all operations by this name. Try to // find the right one. For each matching operation which has an // equal number of "in" parameters, try deserializing. If we // don't succeed for any of the candidates, punt. for (int i = 0; i < operations.length; i++) { OperationDesc operation = operations[i]; // See if any information is coming from a header boolean needHeaderProcessing = needHeaderProcessing(operation, isResponse); // Make a quick check to determine if the operation // could be a match. // 1) The element is the first param, DOCUMENT, (i.e. // don't know the operation name or the number // of params, so try all operations). // or (2) Style is literal // If the Style is LITERAL, the numParams may be inflated // as in the following case: // <getAttractions xmlns="urn:CityBBB"> // <attname>Christmas</attname> // <attname>Xmas</attname> // </getAttractions> // for getAttractions(String[] attName) // numParams will be 2 and and operation.getNumInParams=1 // or (3) Number of expected params is // >= num params in message if (operation.getStyle() == Style.DOCUMENT || operation.getStyle() == Style.WRAPPED || operation.getUse() == Use.LITERAL || (acceptMissingParams ? (operation.getNumInParams() >= numParams) : (operation.getNumInParams() == numParams))) { boolean isEncoded = operation.getUse() == Use.ENCODED; rpcHandler.setOperation(operation); try { // If no operation name and more than one // parameter is expected, don't // wrap the rpcHandler in an EnvelopeHandler. if ( ( msgContext.isClient() && operation.getStyle() == Style.DOCUMENT ) || ( !msgContext.isClient() && operation.getStyle() == Style.DOCUMENT && operation.getNumInParams() > 0 ) ) { context.pushElementHandler(rpcHandler); context.setCurElement(null); } else { context.pushElementHandler( new EnvelopeHandler(rpcHandler)); context.setCurElement(this); } publishToHandler((org.xml.sax.ContentHandler) context); // If parameter values are located in headers, // get the information and publish the header // elements to the rpc handler. if (needHeaderProcessing) { processHeaders(operation, isResponse, context, rpcHandler); } // Check if the RPCParam's value match the signature of the // param in the operation. boolean match = true; List params = getParams2(); for ( int j = 0 ; j < params.size() && match ; j++ ) { RPCParam rpcParam = (RPCParam)params.get(j); Object value = rpcParam.getObjectValue(); // first check the type on the paramter ParameterDesc paramDesc = rpcParam.getParamDesc(); // if we found some type info try to make sure the value type is // correct. For instance, if we deserialized a xsd:dateTime in // to a Calendar and the service takes a Date, we need to convert if (paramDesc != null && paramDesc.getJavaType() != null) { // Get the type in the signature (java type or its holder) Class sigType = paramDesc.getJavaType(); // if the type is an array but the value is not // an array or Collection, put it into an // ArrayList so that we correctly recognize it // as convertible if (sigType.isArray()) { if (value != null && JavaUtils.isConvertable(value, sigType.getComponentType()) && !(value.getClass().isArray()) && !(value instanceof Collection)) { ArrayList list = new ArrayList(); list.add(value); value = list; rpcParam.setObjectValue(value); } } if(!JavaUtils.isConvertable(value, sigType, isEncoded)) match = false; } } // This is not the right operation, try the next one. if(!match) { children = new ArrayList(); continue; } // Success!! This is the right one... msgContext.setOperation(operation); return; } catch (SAXException e) { // If there was a problem, try the next one. savedException = e; children = new ArrayList(); continue; } catch (AxisFault e) { // Thrown by getHeadersByName... // If there was a problem, try the next one. savedException = new SAXException(e); children = new ArrayList(); continue; } } } // If we're SOAP 1.2, getting to this point means bad arguments. if (!msgContext.isClient() && soapConstants == SOAPConstants.SOAP12_CONSTANTS) { AxisFault fault = new AxisFault(Constants.FAULT_SOAP12_SENDER, "string", null, null); fault.addFaultSubCode(Constants.FAULT_SUBCODE_BADARGS); throw new SAXException(fault); } if (savedException != null) { throw savedException; } else if (!msgContext.isClient()) { QName faultCode = new QName(Constants.FAULT_SERVER_USER); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) faultCode = Constants.FAULT_SOAP12_SENDER; AxisFault fault = new AxisFault(faultCode, null, Messages.getMessage("noSuchOperation", name), null, null, null); throw new SAXException(fault); } } if (operations != null) { rpcHandler.setOperation(operations[0]); } // Same logic as above. Don't wrap rpcHandler // if there is no operation wrapper in the message if (operations != null && operations.length > 0 && (operations[0].getStyle() == Style.DOCUMENT)) { context.pushElementHandler(rpcHandler); context.setCurElement(null); } else { context.pushElementHandler(new EnvelopeHandler(rpcHandler)); context.setCurElement(this); } publishToHandler((org.xml.sax.ContentHandler)context); } private List getParams2() { return getParams(new ArrayList()); } private List getParams(List list) { for (int i = 0; children != null && i < children.size(); i++) { Object child = children.get(i); if (child instanceof RPCParam) { list.add(child); } } return list; } /** This gets the FIRST param whose name matches. * !!! Should it return more in the case of duplicates? */ public RPCParam getParam(String name) throws SAXException { if (needDeser) { deserialize(); } List params = getParams2(); for (int i = 0; i < params.size(); i++) { RPCParam param = (RPCParam)params.get(i); if (param.getName().equals(name)) return param; } return null; } public Vector getParams() throws SAXException { if (needDeser) { deserialize(); } return (Vector)getParams(new Vector()); } public void addParam(RPCParam param) { param.setRPCCall(this); initializeChildren(); children.add(param); } protected void outputImpl(SerializationContext context) throws Exception { MessageContext msgContext = context.getMessageContext(); boolean hasOperationElement = (msgContext == null || msgContext.getOperationStyle() == Style.RPC || msgContext.getOperationStyle() == Style.WRAPPED); // When I have MIME and a no-param document WSDL, if I don't check // for no params here, the server chokes with "can't find Body". // because it will be looking for the enclosing element always // found in an RPC-style (and wrapped) request boolean noParams = getParams2().size() == 0; if (hasOperationElement || noParams) { // Set default namespace if appropriate (to avoid prefix mappings // in literal style). Do this only if there is no encodingStyle. if (encodingStyle != null && encodingStyle.equals("")) { context.registerPrefixForURI("", getNamespaceURI()); } context.startElement(new QName(getNamespaceURI(), name), attributes); } if(noParams) { if (children != null) { for (Iterator it = children.iterator(); it.hasNext();) { ((NodeImpl)it.next()).output(context); } } } else { List params = getParams2(); for (int i = 0; i < params.size(); i++) { RPCParam param = (RPCParam)params.get(i); if (!hasOperationElement && encodingStyle != null && encodingStyle.equals("")) { context.registerPrefixForURI("", param.getQName().getNamespaceURI()); } param.serialize(context); } } if (hasOperationElement || noParams) { context.endElement(); } } /** * needHeaderProcessing * @param operation OperationDesc * @param isResponse boolean indicates if request or response message * @return true if the operation description indicates parameters/results * are located in the soap header. */ private boolean needHeaderProcessing(OperationDesc operation, boolean isResponse) { // Search parameters/return to see if any indicate // that instance data is contained in the header. ArrayList paramDescs = operation.getParameters(); if (paramDescs != null) { for (int j=0; j<paramDescs.size(); j++) { ParameterDesc paramDesc = (ParameterDesc) paramDescs.get(j); if ((!isResponse && paramDesc.isInHeader()) || (isResponse && paramDesc.isOutHeader())) { return true; } } } if (isResponse && operation.getReturnParamDesc() != null && operation.getReturnParamDesc().isOutHeader()) { return true; } return false; } /** * needHeaderProcessing * @param operation OperationDesc * @param isResponse boolean indicates if request or response message * @param context DeserializationContext * @param handler RPCHandler used to deserialize parameters * are located in the soap header. */ private void processHeaders(OperationDesc operation, boolean isResponse, DeserializationContext context, RPCHandler handler) throws AxisFault, SAXException { // Inform handler that subsequent elements come from // the header try { handler.setHeaderElement(true); // Get the soap envelope SOAPElement envelope = getParentElement(); while (envelope != null && !(envelope instanceof SOAPEnvelope)) { envelope = envelope.getParentElement(); } if (envelope == null) return; // Find parameters that have instance // data in the header. ArrayList paramDescs = operation.getParameters(); if (paramDescs != null) { for (int j=0; j<paramDescs.size(); j++) { ParameterDesc paramDesc = (ParameterDesc) paramDescs.get(j); if ((!isResponse && paramDesc.isInHeader()) || (isResponse && paramDesc.isOutHeader())) { // Get the headers that match the parameter's // QName Enumeration headers = ((SOAPEnvelope) envelope). getHeadersByName( paramDesc.getQName().getNamespaceURI(), paramDesc.getQName().getLocalPart(), true); // Publish each of the found elements to the // handler. The pushElementHandler and // setCurElement calls are necessary to // have the message element recognized as a // child of the RPCElement. while(headers != null && headers.hasMoreElements()) { context.pushElementHandler(handler); context.setCurElement(null); ((MessageElement) headers.nextElement()). publishToHandler( (org.xml.sax.ContentHandler)context); } } } } // Now do the same processing for the return parameter. if (isResponse && operation.getReturnParamDesc() != null && operation.getReturnParamDesc().isOutHeader()) { ParameterDesc paramDesc = operation.getReturnParamDesc(); Enumeration headers = ((SOAPEnvelope) envelope). getHeadersByName( paramDesc.getQName().getNamespaceURI(), paramDesc.getQName().getLocalPart(), true); while(headers != null && headers.hasMoreElements()) { context.pushElementHandler(handler); context.setCurElement(null); ((MessageElement) headers.nextElement()). publishToHandler((org.xml.sax.ContentHandler)context); } } } finally { handler.setHeaderElement(false); } } }
7,567
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/RPCHeaderParam.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.MessageContext; import org.apache.axis.encoding.SerializationContext; public class RPCHeaderParam extends SOAPHeaderElement { /** * Create a SOAPHeaderElement that is represented by an RPCParam */ public RPCHeaderParam(RPCParam rpcParam) { super(rpcParam.getQName().getNamespaceURI(), rpcParam.getQName().getLocalPart(), rpcParam); } /** * outputImpl serializes the RPCParam */ protected void outputImpl(SerializationContext context) throws Exception { MessageContext msgContext = context.getMessageContext(); // Get the RPCParam and serialize it RPCParam rpcParam = (RPCParam) getObjectValue(); if (encodingStyle != null && encodingStyle.equals("")) { context.registerPrefixForURI("", rpcParam.getQName().getNamespaceURI()); } rpcParam.serialize(context); } }
7,568
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPHeaderElement.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import javax.xml.soap.Name; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; /** * A simple header element abstraction. Extends MessageElement with * header-specific stuff like mustUnderstand, actor, and a 'processed' flag. * * @author Glen Daniels (gdaniels@apache.org) * @author Glyn Normington (glyn@apache.org) */ public class SOAPHeaderElement extends MessageElement implements javax.xml.soap.SOAPHeaderElement { protected boolean processed = false; protected String actor = "http://schemas.xmlsoap.org/soap/actor/next"; protected boolean mustUnderstand = false; protected boolean relay = false; public SOAPHeaderElement(String namespace, String localPart) { super(namespace, localPart); } public SOAPHeaderElement(Name name) { super(name); } public SOAPHeaderElement(QName qname) { super(qname); } public SOAPHeaderElement(String namespace, String localPart, Object value) { super(namespace, localPart, value); } public SOAPHeaderElement(QName qname, Object value) { super(qname, value); } public SOAPHeaderElement(Element elem) { super(elem); // FIXME : This needs to come from someplace reasonable, perhaps // TLS (SOAPConstants.getCurrentVersion() ?) SOAPConstants soapConstants = getSOAPConstants(); String val = elem.getAttributeNS(soapConstants.getEnvelopeURI(), Constants.ATTR_MUST_UNDERSTAND); try { setMustUnderstandFromString(val, (soapConstants == SOAPConstants.SOAP12_CONSTANTS)); } catch (AxisFault axisFault) { // Log the bad MU value, since this constructor can't throw log.error(axisFault); } QName roleQName = soapConstants.getRoleAttributeQName(); actor = elem.getAttributeNS(roleQName.getNamespaceURI(), roleQName.getLocalPart()); // if (actor == null) { // actor = ""; // } if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { String relayVal = elem.getAttributeNS(soapConstants.getEnvelopeURI(), Constants.ATTR_RELAY); relay = ((relayVal != null) && (relayVal.equals("true") || relayVal.equals("1"))) ? true : false; } } public void setParentElement(SOAPElement parent) throws SOAPException { if(parent == null) { throw new IllegalArgumentException(Messages.getMessage("nullParent00")); } // migration aid if (parent instanceof SOAPEnvelope) { log.warn(Messages.getMessage("bodyHeaderParent")); parent = ((SOAPEnvelope)parent).getHeader(); } if (!(parent instanceof SOAPHeader)) { throw new IllegalArgumentException(Messages.getMessage("illegalArgumentException00")); } super.setParentElement(parent); } public SOAPHeaderElement(String namespace, String localPart, String prefix, Attributes attributes, DeserializationContext context) throws AxisFault { super(namespace, localPart, prefix, attributes, context); SOAPConstants soapConstants = getSOAPConstants(); // Check for mustUnderstand String val = attributes.getValue(soapConstants.getEnvelopeURI(), Constants.ATTR_MUST_UNDERSTAND); setMustUnderstandFromString(val, (soapConstants == SOAPConstants.SOAP12_CONSTANTS)); QName roleQName = soapConstants.getRoleAttributeQName(); actor = attributes.getValue(roleQName.getNamespaceURI(), roleQName.getLocalPart()); // if (actor == null) { // actor = ""; // } if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { String relayVal = attributes.getValue(soapConstants.getEnvelopeURI(), Constants.ATTR_RELAY); relay = ((relayVal != null) && (relayVal.equals("true") || relayVal.equals("1"))) ? true : false; } processed = false; alreadySerialized = true; } private void setMustUnderstandFromString(String val, boolean isSOAP12) throws AxisFault { if (val != null && val.length() > 0) { if ("0".equals(val)) { mustUnderstand = false; } else if ("1".equals(val)) { mustUnderstand = true; } else if (isSOAP12) { if ("true".equalsIgnoreCase(val)) { mustUnderstand = true; } else if ("false".equalsIgnoreCase(val)) { mustUnderstand = false; } else { throw new AxisFault( Messages.getMessage("badMUVal", val, new QName(namespaceURI, name).toString())); } } else { throw new AxisFault( Messages.getMessage("badMUVal", val, new QName(namespaceURI, name).toString())); } } } public boolean getMustUnderstand() { return( mustUnderstand ); } public void setMustUnderstand(boolean b) { mustUnderstand = b ; } public String getActor() { return( actor ); } public void setActor(String a) { actor = a ; } public String getRole() { return( actor ); } public void setRole(String a) { actor = a ; } public boolean getRelay() { return relay; } public void setRelay(boolean relay) { this.relay = relay; } public void setProcessed(boolean value) { processed = value ; } public boolean isProcessed() { return( processed ); } boolean alreadySerialized = false; /** Subclasses can override */ protected void outputImpl(SerializationContext context) throws Exception { if (!alreadySerialized) { SOAPConstants soapVer = getSOAPConstants(); QName roleQName = soapVer.getRoleAttributeQName(); if (actor != null) { setAttribute(roleQName.getNamespaceURI(), roleQName.getLocalPart(), actor); } String val; if (context.getMessageContext() != null && context.getMessageContext().getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) val = mustUnderstand ? "true" : "false"; else val = mustUnderstand ? "1" : "0"; setAttribute(soapVer.getEnvelopeURI(), Constants.ATTR_MUST_UNDERSTAND, val); if (soapVer == SOAPConstants.SOAP12_CONSTANTS && relay) { setAttribute(soapVer.getEnvelopeURI(), Constants.ATTR_RELAY, "true"); } } super.outputImpl(context); } public NamedNodeMap getAttributes() { makeAttributesEditable(); SOAPConstants soapConstants = getSOAPConstants(); String mustUnderstand = attributes.getValue(soapConstants.getEnvelopeURI(), Constants.ATTR_MUST_UNDERSTAND); QName roleQName = soapConstants.getRoleAttributeQName(); String actor = attributes.getValue(roleQName.getNamespaceURI(),roleQName.getLocalPart()); if(mustUnderstand == null){ if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { setAttributeNS(soapConstants.getEnvelopeURI(), Constants.ATTR_MUST_UNDERSTAND,"false"); } else { setAttributeNS(soapConstants.getEnvelopeURI(), Constants.ATTR_MUST_UNDERSTAND,"0"); } } if(actor == null){ setAttributeNS(roleQName.getNamespaceURI(), roleQName.getLocalPart(), this.actor); } return super.getAttributes(); } private SOAPConstants getSOAPConstants() { SOAPConstants soapConstants = null; if (context != null) { return context.getSOAPConstants(); } if (getNamespaceURI() != null && getNamespaceURI().equals(SOAPConstants.SOAP12_CONSTANTS.getEnvelopeURI())) { soapConstants = SOAPConstants.SOAP12_CONSTANTS; } if (soapConstants == null && getEnvelope() != null) { soapConstants = getEnvelope().getSOAPConstants(); } if (soapConstants == null) { soapConstants = SOAPConstants.SOAP11_CONSTANTS; } return soapConstants; } }
7,569
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/MessageElement.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.TextSerializationContext; import org.apache.axis.constants.Style; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Mapping; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.CharacterData; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.w3c.dom.NamedNodeMap; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import javax.xml.rpc.encoding.TypeMapping; import javax.xml.soap.Name; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import javax.xml.parsers.ParserConfigurationException; import java.io.Reader; import java.io.Serializable; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Vector; /** * MessageElement is the base type of nodes of the SOAP message parse tree. * * Note: it was made Serializable to help users of Apache SOAP who had * exploited the serializability of the DOM tree to migrate to Axis. */ // TODO: implement the NodeList methods properly, with tests. public class MessageElement extends NodeImpl implements SOAPElement, Serializable, org.w3c.dom.NodeList, // ADD Nodelist Interfaces for SAAJ 1.2 Cloneable { protected static Log log = LogFactory.getLog(MessageElement.class.getName()); private static final Mapping enc11Mapping = new Mapping(Constants.URI_SOAP11_ENC, "SOAP-ENC"); private static final Mapping enc12Mapping = new Mapping(Constants.URI_SOAP12_ENC, "SOAP-ENC"); protected String id; protected String href; protected boolean _isRoot = true; protected SOAPEnvelope message = null; protected transient DeserializationContext context; protected transient QName typeQName = null; protected Vector qNameAttrs = null; // Some message representations - as recorded SAX events... protected transient SAX2EventRecorder recorder = null; protected int startEventIndex = 0; protected int startContentsIndex = 0; protected int endEventIndex = -1; public ArrayList namespaces = null; /** Our encoding style, if any */ protected String encodingStyle = null; /** Object value, possibly supplied by subclass */ private Object objectValue = null; /** No-arg constructor for building messages? */ public MessageElement() { } /** * constructor * @param namespace namespace of element * @param localPart local name */ public MessageElement(String namespace, String localPart) { namespaceURI = namespace; name = localPart; } /** * constructor. Automatically adds a namespace-prefix mapping to the mapping table * @param localPart local name * @param prefix prefix * @param namespace namespace */ public MessageElement(String localPart, String prefix, String namespace) { this.namespaceURI = namespace; this.name = localPart; this.prefix = prefix; addMapping(new Mapping(namespace, prefix)); } /** * construct using a {@link javax.xml.soap.Name} implementation, * @see #MessageElement(String, String, String) * @param eltName */ public MessageElement(Name eltName) { this(eltName.getLocalName(),eltName.getPrefix(), eltName.getURI()); } /** * constructor binding the internal object value field to the * value parameter * @param namespace namespace of the element * @param localPart local name * @param value value of the node */ public MessageElement(String namespace, String localPart, Object value) { this(namespace, localPart); objectValue = value; } /** * constructor declaring the qualified name of the node * @param name naming information */ public MessageElement(QName name) { this(name.getNamespaceURI(), name.getLocalPart()); } /** * constructor declaring the qualified name of the node * and its value * @param name naming information * @param value value of the node */ public MessageElement(QName name, Object value) { this(name.getNamespaceURI(), name.getLocalPart()); objectValue = value; } /** * create a node through a deep copy of the passed in element. * @param elem name to copy from */ public MessageElement(Element elem) { namespaceURI = elem.getNamespaceURI(); name = elem.getLocalName(); copyNode(elem); } /** * construct a text element. * @param text text data. This is <i>not</i> copied; it is referred to in the MessageElement. */ public MessageElement(CharacterData text) { textRep = text; namespaceURI = text.getNamespaceURI(); name = text.getLocalName(); } /** * Advanced constructor used for deserialization. * <ol> * <li>The context provides the mappings and Sax event recorder * <li>The soap messaging style is determined from the current message context, defaulting * to SOAP1.1 if there is no current context. * <li>if there is an id attribute (any namespace), then the ID is registered * with {@link DeserializationContext#registerElementByID(String, MessageElement)} ;a new recorder is * created if needed. * <li>If there is an attribute "root" in the default SOAP namespace, then it is examined * to see if it marks the element as root (value=="1" or not) * <li>If there is an arrayType attribute then we assume we are an array and set our * {@link #typeQName} field appropriately. * <li>The {@link #href} field is set if there is a relevant href value * </ol> * * @param namespace namespace namespace of element * @param localPart local name local name of element * @param prefix prefix prefix of element * @param attributes attributes to save as our attributes * @param context deserialization context for this message element * @throws AxisFault if the encoding style is not recognized/supported */ public MessageElement(String namespace, String localPart, String prefix, Attributes attributes, DeserializationContext context) throws AxisFault { if (log.isDebugEnabled()) { log.debug(Messages.getMessage("newElem00", super.toString(), "{" + prefix + "}" + localPart)); for (int i = 0; attributes != null && i < attributes.getLength(); i++) { log.debug(" " + attributes.getQName(i) + " = '" + attributes.getValue(i) + "'"); } } this.namespaceURI = namespace; this.name = localPart; this.prefix = prefix; this.context = context; this.startEventIndex = context.getStartOfMappingsPos(); setNSMappings(context.getCurrentNSMappings()); this.recorder = context.getRecorder(); if (attributes != null && attributes.getLength() > 0) { this.attributes = attributes; this.typeQName = context.getTypeFromAttributes(namespace, localPart, attributes); String rootVal = attributes.getValue(Constants.URI_DEFAULT_SOAP_ENC, Constants.ATTR_ROOT); if (rootVal != null) { _isRoot = "1".equals(rootVal); } id = attributes.getValue(Constants.ATTR_ID); // Register this ID with the context..... if (id != null) { context.registerElementByID(id, this); if (recorder == null) { recorder = new SAX2EventRecorder(); context.setRecorder(recorder); } } // Set the encoding style to the attribute value. If null, // we just automatically use our parent's (see getEncodingStyle) MessageContext mc = context.getMessageContext(); SOAPConstants sc = (mc != null) ? mc.getSOAPConstants() : SOAPConstants.SOAP11_CONSTANTS; href = attributes.getValue(sc.getAttrHref()); // If there's an arrayType attribute, we can pretty well guess that we're an Array??? if (attributes.getValue(Constants.URI_DEFAULT_SOAP_ENC, Constants.ATTR_ARRAY_TYPE) != null) { typeQName = Constants.SOAP_ARRAY; } encodingStyle = attributes.getValue(sc.getEncodingURI(), Constants.ATTR_ENCODING_STYLE); // if no-encoding style was defined, we don't define as well if (Constants.URI_SOAP12_NOENC.equals(encodingStyle)) encodingStyle = null; // If we have an encoding style, and are not a MESSAGE style // operation (in other words - we're going to do some data // binding), AND we're SOAP 1.2, check the encoding style against // the ones we've got type mappings registered for. If it isn't // registered, throw a DataEncodingUnknown fault as per the // SOAP 1.2 spec. if (encodingStyle != null && sc.equals(SOAPConstants.SOAP12_CONSTANTS) && (mc.getOperationStyle() != Style.MESSAGE)) { TypeMapping tm = mc.getTypeMappingRegistry(). getTypeMapping(encodingStyle); if (tm == null || (tm.equals(mc.getTypeMappingRegistry(). getDefaultTypeMapping()))) { AxisFault badEncodingFault = new AxisFault( Constants.FAULT_SOAP12_DATAENCODINGUNKNOWN, "bad encoding style", null, null); throw badEncodingFault; } } } } /** * Retrieve the DeserializationContext associated with this MessageElement * * @return The DeserializationContext associated with this MessageElement */ public DeserializationContext getDeserializationContext() { return context; } /** !!! TODO : Make sure this handles multiple targets */ protected Deserializer fixupDeserializer; public void setFixupDeserializer(Deserializer dser) { // !!! Merge targets here if already set? fixupDeserializer = dser; } public Deserializer getFixupDeserializer() { return fixupDeserializer; } /** * record the end index of the SAX recording. * @param endIndex end value */ public void setEndIndex(int endIndex) { endEventIndex = endIndex; //context.setRecorder(null); } /** * get the is-root flag * @return true if the element is considered a document root. */ public boolean isRoot() { return _isRoot; } /** * get a saved ID * @return ID or null for no ID */ public String getID() { return id; } /** * get a saved href * @return href or null */ public String getHref() { return href; } /** * get the attributes * @return attributes. If this equals {@link NullAttributes#singleton} it is null * */ public Attributes getAttributesEx() { return attributes; } /** * Returns a duplicate of this node, i.e., serves as a generic copy * constructor for nodes. The duplicate node has no parent; ( * <code>parentNode</code> is <code>null</code>.). * <br>Cloning an <code>Element</code> copies all attributes and their * values, including those generated by the XML processor to represent * defaulted attributes, but this method does not copy any text it * contains unless it is a deep clone, since the text is contained in a * child <code>Text</code> node. Cloning an <code>Attribute</code> * directly, as opposed to be cloned as part of an <code>Element</code> * cloning operation, returns a specified attribute ( * <code>specified</code> is <code>true</code>). Cloning any other type * of node simply returns a copy of this node. * <br>Note that cloning an immutable subtree results in a mutable copy, * but the children of an <code>EntityReference</code> clone are readonly * . In addition, clones of unspecified <code>Attr</code> nodes are * specified. And, cloning <code>Document</code>, * <code>DocumentType</code>, <code>Entity</code>, and * <code>Notation</code> nodes is implementation dependent. * * @param deep If <code>true</code>, recursively clone the subtree under * the specified node; if <code>false</code>, clone only the node * itself (and its attributes, if it is an <code>Element</code>). * @return The duplicate node. */ public Node cloneNode(boolean deep) { try{ MessageElement clonedSelf = (MessageElement) cloning(); if(deep){ if(children != null){ for(int i =0; i < children.size(); i++){ NodeImpl child = (NodeImpl)children.get(i); if(child != null) { // why child can be null? NodeImpl clonedChild = (NodeImpl)child.cloneNode(deep); // deep == true clonedChild.setParent(clonedSelf); clonedChild.setOwnerDocument(getOwnerDocument()); clonedSelf.childDeepCloned( child, clonedChild ); } } } } return clonedSelf; } catch(Exception e){ return null; } } // Called when a child is cloned from cloneNode(). // // This is used by sub-classes to update internal state when specific elements // are cloned. protected void childDeepCloned( NodeImpl oldNode, NodeImpl newNode ) { } /** * protected clone method (not public) * * copied status * ------------------- * protected String name ; Y * protected String prefix ; Y * protected String namespaceURI ; Y * protected transient Attributes attributes Y * protected String id; Y? * protected String href; Y? * protected boolean _isRoot = true; Y? * protected SOAPEnvelope message = null; N? * protected transient DeserializationContext context; Y? * protected transient QName typeQName = null; Y? * protected Vector qNameAttrs = null; Y? * protected transient SAX2EventRecorder recorder = null; N? * protected int startEventIndex = 0; N? * protected int startContentsIndex = 0; N? * protected int endEventIndex = -1; N? * protected CharacterData textRep = null; Y? * protected MessageElement parent = null; N * public ArrayList namespaces = null; Y * protected String encodingStyle = null; N? * private Object objectValue = null; N? * * @return * @throws CloneNotSupportedException */ protected Object cloning() throws CloneNotSupportedException { try{ MessageElement clonedME = null; clonedME = (MessageElement)this.clone(); clonedME.setName(name); clonedME.setNamespaceURI(namespaceURI); clonedME.setPrefix(prefix); // new AttributesImpl will copy all data not set referencing only clonedME.setAllAttributes(new AttributesImpl(attributes)); // clonedME.addNamespaceDeclaration((namespaces.clone()); // cannot do this. since we cannot access the namepace arraylist clonedME.namespaces = new ArrayList(); if(namespaces != null){ for(int i = 0; i < namespaces.size(); i++){ // jeus.util.Logger.directLog( " Debug : namspace.size() = " + namespaces.size()); Mapping namespace = (Mapping)namespaces.get(i); clonedME.addNamespaceDeclaration(namespace.getPrefix(), namespace.getNamespaceURI()); // why exception here!! } } clonedME.children = new ArrayList(); // clear parents relationship to old parent clonedME.parent = null; // clonedME.setObjectValue(objectValue); // how to copy this??? clonedME.setDirty(this._isDirty); if(encodingStyle != null){ clonedME.setEncodingStyle(encodingStyle); } return clonedME; }catch(Exception ex){ return null; } } /** * set all the attributes of this instance * @param attrs a new attributes list */ public void setAllAttributes(Attributes attrs){ attributes = attrs; } /** * remove all children. */ public void detachAllChildren() { removeContents(); } /** * Obtain an Attributes collection consisting of all attributes * for this MessageElement, including namespace declarations. * * @return Attributes collection */ public Attributes getCompleteAttributes() { if (namespaces == null) { return attributes; } AttributesImpl attrs = null; if (attributes == NullAttributes.singleton) { attrs = new AttributesImpl(); } else { attrs = new AttributesImpl(attributes); } for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { Mapping mapping = (Mapping) iterator.next(); String prefix = mapping.getPrefix(); String nsURI = mapping.getNamespaceURI(); attrs.addAttribute(Constants.NS_URI_XMLNS, prefix, "xmlns:" + prefix, nsURI, "CDATA"); } return attrs; } /** * get the local name of this element * @return name */ public String getName() { return name; } /** * set the local part of this element's name * @param name */ public void setName(String name) { this.name = name; } /** * get the fully qualified name of this element * @return a QName describing the name of thsi element */ public QName getQName() { return new QName(namespaceURI, name); } /** * set the name and namespace of this element * @param qName qualified name */ public void setQName(QName qName) { this.name = qName.getLocalPart(); this.namespaceURI = qName.getNamespaceURI(); } /** * set the namespace URI of the element * @param nsURI new namespace URI */ public void setNamespaceURI(String nsURI) { namespaceURI = nsURI; } /** * get the element's type. * If we are a reference, we look up our target in the context and * return (and cache) its type. * @return */ public QName getType() { // Try to get the type from our target if we're a reference... if (typeQName == null && href != null && context != null) { MessageElement referent = context.getElementByID(href); if (referent != null) { typeQName = referent.getType(); } } return typeQName; } /** * set the element's type * @param qname */ public void setType(QName qname) { typeQName = qname; } /** * get the event recorder * @return recorder or null */ public SAX2EventRecorder getRecorder() { return recorder; } /** * set the event recorder * @param rec */ public void setRecorder(SAX2EventRecorder rec) { recorder = rec; } /** * Get the encoding style. If ours is null, walk up the hierarchy * and use our parent's. Default if we're the root is "". * * @return the currently in-scope encoding style */ public String getEncodingStyle() { if (encodingStyle == null) { if (parent == null) { return ""; } return ((MessageElement) parent).getEncodingStyle(); } return encodingStyle; } /** * remove all chidlren. * All SOAPExceptions which can get thrown in this process are ignored. */ public void removeContents() { // unlink if (children != null) { for (int i = 0; i < children.size(); i++) { try { ((NodeImpl) children.get(i)).setParent(null); } catch (SOAPException e) { log.debug("ignoring", e); } } // empty the collection children.clear(); setDirty(); } } /** * get an iterator over visible prefixes. This includes all declared in * parent elements * @return an iterator. */ public Iterator getVisibleNamespacePrefixes() { Vector prefixes = new Vector(); // Add all parents namespace definitions if(parent !=null){ Iterator parentsPrefixes = ((MessageElement)parent).getVisibleNamespacePrefixes(); if(parentsPrefixes != null){ while(parentsPrefixes.hasNext()){ prefixes.add(parentsPrefixes.next()); } } } Iterator mine = getNamespacePrefixes(); if(mine != null){ while(mine.hasNext()){ prefixes.add(mine.next()); } } return prefixes.iterator(); } /** * Sets the encoding style for this <CODE>SOAPElement</CODE> * object to one specified. The semantics of a null value, * as above in getEncodingStyle() are to just use the parent's value, * but null here means set to "". * * @param encodingStyle a <CODE>String</CODE> * giving the encoding style * @throws java.lang.IllegalArgumentException if * there was a problem in the encoding style being set. * @see #getEncodingStyle() getEncodingStyle() */ public void setEncodingStyle(String encodingStyle) throws SOAPException { if (encodingStyle == null) { encodingStyle = ""; } this.encodingStyle = encodingStyle; // Wherever we set the encoding style, map the SOAP-ENC prefix // just for fun (if it's a known style) if (encodingStyle.equals(Constants.URI_SOAP11_ENC)) { addMapping(enc11Mapping); } else if (encodingStyle.equals(Constants.URI_SOAP12_ENC)) { addMapping(enc12Mapping); } } /** * Note that this method will log a error and no-op if there is * a value (set using setObjectValue) in the MessageElement. */ public void addChild(MessageElement el) throws SOAPException { if (objectValue != null) { IllegalStateException exc = new IllegalStateException(Messages.getMessage("valuePresent")); log.error(Messages.getMessage("valuePresent"), exc); throw exc; } initializeChildren(); children.add(el); el.parent = this; } /** * get a list of children * @return a list, or null if there are no children */ public List getChildren() { return children; } /** * set the index point of our content's starting in the * event recording * @param index index value of the first event of our recorder. */ public void setContentsIndex(int index) { startContentsIndex = index; } /** * set a new namespace mapping list * @param namespaces */ public void setNSMappings(ArrayList namespaces) { this.namespaces = namespaces; } /** * get the prefix for a given namespace URI * @param searchNamespaceURI namespace * @return null for null or emtpy uri, null for no match, and the prefix iff there is a match */ public String getPrefix(String searchNamespaceURI) { if ((searchNamespaceURI == null) || ("".equals(searchNamespaceURI))) return null; if (href != null && getRealElement() != null) { return getRealElement().getPrefix(searchNamespaceURI); } for (int i = 0; namespaces != null && i < namespaces.size(); i++) { Mapping map = (Mapping) namespaces.get(i); if (map.getNamespaceURI().equals(searchNamespaceURI)) { return map.getPrefix(); } } if (parent != null) { return ((MessageElement) parent).getPrefix(searchNamespaceURI); } return null; } /** * map from a prefix to a namespace. * Will recurse <i>upward the element tree</i> until we get a match * @param searchPrefix * @return the prefix, or null for no match */ public String getNamespaceURI(String searchPrefix) { if (searchPrefix == null) { searchPrefix = ""; } if (href != null && getRealElement() != null) { return getRealElement().getNamespaceURI(searchPrefix); } for (int i = 0; namespaces != null && i < namespaces.size(); i++) { Mapping map = (Mapping) namespaces.get(i); if (map.getPrefix().equals(searchPrefix)) { return map.getNamespaceURI(); } } if (parent != null) { return ((MessageElement) parent).getNamespaceURI(searchPrefix); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("noPrefix00", "" + this, searchPrefix)); } return null; } /** * Returns value of the node as an object of registered type. * @return Object of proper type, or null if no mapping could be found. */ public Object getObjectValue() { Object obj = null; try { obj = getObjectValue(null); } catch (Exception e) { log.debug("getValue()", e); } return obj; } /** * Returns value of the node as an object of registered type. * @param cls Class that contains top level deserializer metadata * @return Object of proper type, or null if no mapping could be found. */ public Object getObjectValue(Class cls) throws Exception { if (objectValue == null) { objectValue = getValueAsType(getType(), cls); } return objectValue; } /** * Sets value of this node to an Object. * A serializer needs to be registered for this object class for proper * operation. * <p> * Note that this method will log an error and no-op if there are * any children in the MessageElement or if the MessageElement was * constructed from XML. * @param newValue node's value or null. */ public void setObjectValue(Object newValue) throws SOAPException { if (children != null && !children.isEmpty()) { SOAPException exc = new SOAPException(Messages.getMessage("childPresent")); log.error(Messages.getMessage("childPresent"), exc); throw exc; } if (textRep != null) { SOAPException exc = new SOAPException(Messages.getMessage("xmlPresent")); log.error(Messages.getMessage("xmlPresent"), exc); throw exc; } this.objectValue = newValue; } public Object getValueAsType(QName type) throws Exception { return getValueAsType(type, null); } /** * This is deserialization logic mixed in to our element class. * It is only valid we have a deserializer, which means that we were created * using {@link MessageElement#MessageElement(String, String, String, org.xml.sax.Attributes, org.apache.axis.encoding.DeserializationContext)} * @param type type to look up a deserializer for. * @param cls class to use for looking up the deserializer. This takes precedence over the type field. * @return the value of the deserializer * @throws Exception */ public Object getValueAsType(QName type, Class cls) throws Exception { if (context == null) { throw new Exception(Messages.getMessage("noContext00")); } Deserializer dser = null; if (cls == null) { dser = context.getDeserializerForType(type); } else { dser = context.getDeserializerForClass(cls); } if (dser == null) { throw new Exception(Messages.getMessage("noDeser00", "" + type)); } boolean oldVal = context.isDoneParsing(); context.deserializing(true); context.pushElementHandler(new EnvelopeHandler((SOAPHandler)dser)); publishToHandler((org.xml.sax.ContentHandler) context); context.deserializing(oldVal); return dser.getValue(); } /** * class that represents a qname in a the qNameAttrs vector. */ protected static class QNameAttr { public QName name; public QName value; } /** * add an attribute to the qname vector. This is a separate vector from the * main attribute list. * @param namespace * @param localName * @param value */ public void addAttribute(String namespace, String localName, QName value) { if (qNameAttrs == null) { qNameAttrs = new Vector(); } QNameAttr attr = new QNameAttr(); attr.name = new QName(namespace, localName); attr.value = value; qNameAttrs.addElement(attr); // !!! Add attribute to attributes! } /** * add a normal CDATA/text attribute. * There is no check whether or not the attribute already exists. * @param namespace namespace URI * @param localName local anme * @param value value */ public void addAttribute(String namespace, String localName, String value) { AttributesImpl attributes = makeAttributesEditable(); attributes.addAttribute(namespace, localName, "", "CDATA", value); } /** * add an attribute. * Note that the prefix is not added to our mapping list. * Also, there is no check whether or not the attribute already exists. * @param attrPrefix prefix. * @param namespace namespace URI * @param localName * @param value */ public void addAttribute(String attrPrefix, String namespace, String localName, String value) { AttributesImpl attributes = makeAttributesEditable(); String attrName = localName; if (attrPrefix != null && attrPrefix.length() > 0) { attrName = attrPrefix + ":" + localName; } attributes.addAttribute(namespace, localName, attrName, "CDATA", value); } /** * Set an attribute, adding the attribute if it isn't already present * in this element, and changing the value if it is. Passing null as the * value will cause any pre-existing attribute by this name to go away. */ public void setAttribute(String namespace, String localName, String value) { AttributesImpl attributes = makeAttributesEditable(); int idx = attributes.getIndex(namespace, localName); if (idx > -1) { // Got it, so replace it's value. if (value != null) { attributes.setValue(idx, value); } else { attributes.removeAttribute(idx); } return; } addAttribute(namespace, localName, value); } /** * get the value of an attribute * @param localName * @return the value or null */ public String getAttributeValue(String localName) { if (attributes == null) { return null; } return attributes.getValue(localName); } /** * bind a a new soap envelope. sets the dirty bit. * @param env */ public void setEnvelope(SOAPEnvelope env) { env.setDirty(); message = env; } /** * get our current envelope * @return envelope or null. */ public SOAPEnvelope getEnvelope() { return message; } /** * get the 'real' element -will follow hrefs. * @return the message element or null if there is a href to something * that is not a MessageElemeent. */ public MessageElement getRealElement() { if (href == null) { return this; } Object obj = context.getObjectByRef(href); if (obj == null) { return null; } if (!(obj instanceof MessageElement)) { return null; } return (MessageElement) obj; } /** * get the message element as a document. * This serializes the element to a string and then parses it. * @see #getAsString() * @return * @throws Exception */ public Document getAsDocument() throws Exception { String elementString = getAsString(); Reader reader = new StringReader(elementString); Document doc = XMLUtils.newDocument(new InputSource(reader)); if (doc == null) { throw new Exception( Messages.getMessage("noDoc00", elementString)); } return doc; } /** * get the message element as a string. * This is not a cheap operation, as we have to serialise the * entire message element to the current context, then * convert it to a string. * Nor is it cached; repeated calls repeat the operation. * @return an XML fragment in a string. * @throws Exception if anything went wrong */ public String getAsString() throws Exception { SerializationContext serializeContext = null; StringWriter writer = new StringWriter(); MessageContext msgContext; if (context != null) { msgContext = context.getMessageContext(); } else { msgContext = MessageContext.getCurrentContext(); } serializeContext = new SerializationContext(writer, msgContext); serializeContext.setSendDecl(false); setDirty(false); output(serializeContext); writer.close(); return writer.getBuffer().toString(); } /** * create a DOM from the message element, by * serializing and deserializing the element * @see #getAsString() * @see #getAsDocument() * @return the root document element of the element * @throws Exception */ public Element getAsDOM() throws Exception { return getAsDocument().getDocumentElement(); } /** * replay the sax events to a handler * @param handler * @throws SAXException */ public void publishToHandler(ContentHandler handler) throws SAXException { if (recorder == null) { throw new SAXException(Messages.getMessage("noRecorder00")); } recorder.replay(startEventIndex, endEventIndex, handler); } /** * replay the sax events to a SAX content handles * @param handler * @throws SAXException */ public void publishContents(ContentHandler handler) throws SAXException { if (recorder == null) { throw new SAXException(Messages.getMessage("noRecorder00")); } recorder.replay(startContentsIndex, endEventIndex-1, handler); } /** This is the public output() method, which will always simply use * the recorded SAX stream for this element if it is available. If * not, this method calls outputImpl() to allow subclasses and * programmatically created messages to serialize themselves. * * @param outputContext the SerializationContext we will write to. */ public final void output(SerializationContext outputContext) throws Exception { if ((recorder != null) && (!_isDirty)) { recorder.replay(startEventIndex, endEventIndex, new SAXOutputter(outputContext)); return; } // Turn QName attributes into strings if (qNameAttrs != null) { for (int i = 0; i < qNameAttrs.size(); i++) { QNameAttr attr = (QNameAttr)qNameAttrs.get(i); QName attrName = attr.name; setAttribute(attrName.getNamespaceURI(), attrName.getLocalPart(), outputContext.qName2String(attr.value)); } } /** * Write the encoding style attribute IF it's different from * whatever encoding style is in scope.... */ if (encodingStyle != null) { MessageContext mc = outputContext.getMessageContext(); SOAPConstants soapConstants = (mc != null) ? mc.getSOAPConstants() : SOAPConstants.SOAP11_CONSTANTS; if (parent == null) { // don't emit an encoding style if its "" (literal) if (!"".equals(encodingStyle)) { setAttribute(soapConstants.getEnvelopeURI(), Constants.ATTR_ENCODING_STYLE, encodingStyle); } } else if (!encodingStyle.equals(((MessageElement)parent).getEncodingStyle())) { setAttribute(soapConstants.getEnvelopeURI(), Constants.ATTR_ENCODING_STYLE, encodingStyle); } } outputImpl(outputContext); } /** * override point -output to a serialization context. * @param outputContext destination. * @throws Exception if something went wrong. */ protected void outputImpl(SerializationContext outputContext) throws Exception { if (textRep != null) { boolean oldPretty = outputContext.getPretty(); outputContext.setPretty(false); if (textRep instanceof CDATASection) { outputContext.writeString("<![CDATA["); outputContext.writeString(textRep.getData()); outputContext.writeString("]]>"); } else if (textRep instanceof Comment) { outputContext.writeString("<!--"); outputContext.writeString(textRep.getData()); outputContext.writeString("-->"); } else if (textRep instanceof Text) { outputContext.writeSafeString(textRep.getData()); } outputContext.setPretty(oldPretty); return; } if (prefix != null) outputContext.registerPrefixForURI(prefix, namespaceURI); if (namespaces != null) { for (Iterator i = namespaces.iterator(); i.hasNext();) { Mapping mapping = (Mapping) i.next(); outputContext.registerPrefixForURI(mapping.getPrefix(), mapping.getNamespaceURI()); } } if (objectValue != null) { outputContext.serialize(new QName(namespaceURI, name), attributes, objectValue); return; } outputContext.startElement(new QName(namespaceURI, name), attributes); if (children != null) { for (Iterator it = children.iterator(); it.hasNext();) { ((NodeImpl)it.next()).output(outputContext); } } outputContext.endElement(); } /** * Generate a string representation by serializing our contents * This is not a lightweight operation, and is repeated whenever * you call this method. * If the serialization fails, an error is logged and the classic * {@link Object#toString()} operation invoked instead. * @return a string representing the class */ public String toString() { try { return getAsString(); } catch( Exception exp ) { //couldn't turn to a string. //log it log.error(Messages.getMessage("exception00"), exp); //then hand off to our superclass, which is probably object return super.toString(); } } /** * add a new namespace/prefix mapping * @param map new mapping to add */ // TODO: this code does not verify that the mapping does not exist already; it // is possible to create duplicate mappings. public void addMapping(Mapping map) { if (namespaces == null) { namespaces = new ArrayList(); } namespaces.add(map); } // JAXM SOAPElement methods... /** * add the child element * @param childName uri, prefix and local name of the element to add * @return the child element * @throws SOAPException * @see javax.xml.soap.SOAPElement#addChildElement(javax.xml.soap.Name) */ public SOAPElement addChildElement(Name childName) throws SOAPException { MessageElement child = new MessageElement(childName.getLocalName(), childName.getPrefix(), childName.getURI()); addChild(child); return child; } /** * add a child element in the message element's own namespace * @param localName * @return the child element * @throws SOAPException * @see javax.xml.soap.SOAPElement#addChildElement(String) */ public SOAPElement addChildElement(String localName) throws SOAPException { // Inherit parent's namespace MessageElement child = new MessageElement(getNamespaceURI(), localName); addChild(child); return child; } /** * add a child element * @param localName * @param prefixName * @return the child element * @throws SOAPException * @see javax.xml.soap.SOAPElement#addChildElement(String, String) */ public SOAPElement addChildElement(String localName, String prefixName) throws SOAPException { MessageElement child = new MessageElement(getNamespaceURI(prefixName), localName); child.setPrefix(prefixName); addChild(child); return child; } /** * add a child element * @param localName * @param childPrefix * @param uri * @return the child element * @throws SOAPException * @see javax.xml.soap.SOAPElement#addChildElement(String, String, String) */ public SOAPElement addChildElement(String localName, String childPrefix, String uri) throws SOAPException { MessageElement child = new MessageElement(uri, localName); child.setPrefix(childPrefix); child.addNamespaceDeclaration(childPrefix, uri); addChild(child); return child; } /** * The added child must be an instance of MessageElement rather than * an abitrary SOAPElement otherwise a (wrapped) ClassCastException * will be thrown. * @see javax.xml.soap.SOAPElement#addChildElement(javax.xml.soap.SOAPElement) */ public SOAPElement addChildElement(SOAPElement element) throws SOAPException { try { addChild((MessageElement)element); setDirty(); return element; } catch (ClassCastException e) { throw new SOAPException(e); } } /** * add a text node to the document. * @return ourselves * @see javax.xml.soap.SOAPElement#addTextNode(String) */ public SOAPElement addTextNode(String s) throws SOAPException { try { Text text = getOwnerDocument().createTextNode(s); ((org.apache.axis.message.Text)text).setParentElement(this); return this; } catch (java.lang.IncompatibleClassChangeError e) { Text text = new org.apache.axis.message.Text(s); this.appendChild(text); return this; } catch (ClassCastException e) { throw new SOAPException(e); } } /** * add a new attribute * @param attrName name of the attribute * @param value a string value * @return ourselves * @throws SOAPException * @see javax.xml.soap.SOAPElement#addAttribute(javax.xml.soap.Name, String) */ public SOAPElement addAttribute(Name attrName, String value) throws SOAPException { try { addAttribute(attrName.getPrefix(), attrName.getURI(), attrName.getLocalName(), value); } catch (RuntimeException t) { throw new SOAPException(t); } return this; } /** * create a {@link Mapping} mapping and add to our namespace list. * @param prefix * @param uri * @return * @throws SOAPException for any {@link RuntimeException} caught * @see javax.xml.soap.SOAPElement#addNamespaceDeclaration(String, String) */ // TODO: for some reason this logic catches all rutime exceptions and // rethrows them as SOAPExceptions. This is unusual behavio, and should // be looked at closely. public SOAPElement addNamespaceDeclaration(String prefix, String uri) throws SOAPException { try { Mapping map = new Mapping(uri, prefix); addMapping(map); } catch (RuntimeException t) { //TODO: why is this here? Nowhere else do we turn runtimes into SOAPExceptions. throw new SOAPException(t); } return this; } /** * Get the value of an attribute whose namespace and local name are described. * @param attrName qualified name of the attribute * @return the attribute or null if there was no match * @see SOAPElement#getAttributeValue(javax.xml.soap.Name) */ public String getAttributeValue(Name attrName) { return attributes.getValue(attrName.getURI(), attrName.getLocalName()); } /** * Get an interator to all the attributes of the node. * The iterator is over a static snapshot of the node names; if attributes * are added or deleted during the iteration, this iterator will be not * be updated to follow the changes. * @return an iterator of the attributes. * @see javax.xml.soap.SOAPElement#getAllAttributes() */ public Iterator getAllAttributes() { int num = attributes.getLength(); Vector attrs = new Vector(num); for (int i = 0; i < num; i++) { String q = attributes.getQName(i); String prefix = ""; if (q != null) { int idx = q.indexOf(":"); if (idx > 0) { prefix = q.substring(0, idx); } else { prefix= ""; } } attrs.add(new PrefixedQName(attributes.getURI(i), attributes.getLocalName(i), prefix)); } return attrs.iterator(); } // getNamespaceURI implemented above /** * get an iterator of the prefixes. The iterator * does not get updated in response to changes in the namespace list. * @return an iterator over a vector of prefixes * @see javax.xml.soap.SOAPElement#getNamespacePrefixes() */ public Iterator getNamespacePrefixes() { Vector prefixes = new Vector(); for (int i = 0; namespaces != null && i < namespaces.size(); i++) { prefixes.add(((Mapping)namespaces.get(i)).getPrefix()); } return prefixes.iterator(); } /** * get the full name of the element * @return * @see javax.xml.soap.SOAPElement#getElementName() */ public Name getElementName() { return new PrefixedQName(getNamespaceURI(), getName(), getPrefix()); } /** * remove an element * @param attrName name of the element * @return true if the attribute was found and removed. * @see javax.xml.soap.SOAPElement#removeAttribute(javax.xml.soap.Name) */ public boolean removeAttribute(Name attrName) { AttributesImpl attributes = makeAttributesEditable(); boolean removed = false; for (int i = 0; i < attributes.getLength() && !removed; i++) { if (attributes.getURI(i).equals(attrName.getURI()) && attributes.getLocalName(i).equals(attrName.getLocalName())) { attributes.removeAttribute(i); removed = true; } } return removed; } /** * remove a namespace declaration. * @param namespacePrefix * @return true if the prefix was found and removed. * @see javax.xml.soap.SOAPElement#removeNamespaceDeclaration(String) */ public boolean removeNamespaceDeclaration(String namespacePrefix) { makeAttributesEditable(); boolean removed = false; for (int i = 0; namespaces != null && i < namespaces.size() && !removed; i++) { if (((Mapping)namespaces.get(i)).getPrefix().equals(namespacePrefix)) { namespaces.remove(i); removed = true; } } return removed; } /** * get an iterator over the children * This iterator <i>may</i> get confused if changes are made to the * children while the iteration is in progress. * @return an iterator over child elements. * @see javax.xml.soap.SOAPElement#getChildElements() */ public Iterator getChildElements() { initializeChildren(); return children.iterator(); } /** * Convenience method to get the first matching child for a given QName. * * @param qname * @return child element or null * @see javax.xml.soap.SOAPElement#getChildElements() */ public MessageElement getChildElement(QName qname) { if (children != null) { for (Iterator i = children.iterator(); i.hasNext();) { MessageElement child = (MessageElement) i.next(); if (child.getQName().equals(qname)) return child; } } return null; } /** * get an iterator over child elements * @param qname namespace/element name of parts to find. * This iterator is not (currently) susceptible to change in the element * list during its lifetime, though changes in the contents of the elements * are picked up. * @return an iterator. */ public Iterator getChildElements(QName qname) { initializeChildren(); int num = children.size(); Vector c = new Vector(num); for (int i = 0; i < num; i++) { MessageElement child = (MessageElement)children.get(i); Name cname = child.getElementName(); if (cname.getURI().equals(qname.getNamespaceURI()) && cname.getLocalName().equals(qname.getLocalPart())) { c.add(child); } } return c.iterator(); } /** * get an iterator over child elements * @param childName namespace/element name of parts to find. * This iterator is not (currently) susceptible to change in the element * list during its lifetime, though changes in the contents of the elements * are picked up. * @return an iterator. * @see javax.xml.soap.SOAPElement#getChildElements(javax.xml.soap.Name) */ public Iterator getChildElements(Name childName) { return getChildElements(new QName(childName.getURI(), childName.getLocalName())); } //DOM methods /** * @see org.w3c.dom.Element#getTagName() * @return the name of the element */ public String getTagName() { return prefix == null ? name : prefix + ":" + name; } /** * remove a named attribute. * @see org.w3c.dom.Element#removeAttribute(String) * @param attrName name of the attributes * @throws DOMException */ public void removeAttribute(String attrName) throws DOMException { AttributesImpl impl = (AttributesImpl)attributes; int index = impl.getIndex(attrName); if(index >= 0){ AttributesImpl newAttrs = new AttributesImpl(); // copy except the removed attribute for(int i = 0; i < impl.getLength(); i++){ // shift after removal if(i != index){ String uri = impl.getURI(i); String local = impl.getLocalName(i); String qname = impl.getQName(i); String type = impl.getType(i); String value = impl.getValue(i); newAttrs.addAttribute(uri,local,qname,type,value); } } // replace it attributes = newAttrs; } } /** * test for an attribute existing * @param attrName name of attribute (or null) * @return true if it exists * Note that the behaviour for a null parameter (returns false) is not guaranteed in future * @see org.w3c.dom.Element#hasAttribute(String) */ public boolean hasAttribute(String attrName) { if(attrName == null) // Do I have to send an exception? attrName = ""; for(int i = 0; i < attributes.getLength(); i++){ if(attrName.equals(attributes.getQName(i))) return true; } return false; } /** * get an attribute by name * @param attrName of attribute * @return the attribute value or null * @see org.w3c.dom.Element#getAttribute(String) */ public String getAttribute(String attrName) { return attributes.getValue(attrName); } /** * Remove an attribute. If the removed * attribute has a default value it is immediately replaced. The * replacing attribute has the same namespace URI and local name, as * well as the original prefix. * If there is no matching attribute, the operation is a no-op. * @see org.w3c.dom.Element#removeAttributeNS(String, String) * @param namespace namespace of attr * @param localName local name * @throws DOMException */ public void removeAttributeNS(String namespace, String localName) throws DOMException { makeAttributesEditable(); Name name = new PrefixedQName(namespace, localName, null); removeAttribute(name); } /** * set or update an attribute. * @see org.w3c.dom.Element#setAttribute(String, String) * @param name attribute name * @param value attribute value * @throws DOMException */ public void setAttribute(String name, String value) throws DOMException { AttributesImpl impl = makeAttributesEditable(); int index = impl.getIndex(name); if (index < 0) { // not found String uri = ""; String localname = name; String qname = name; String type = "CDDATA"; impl.addAttribute(uri, localname, qname, type, value); } else { // found impl.setLocalName(index, value); } } /** * Test for an attribute * @see org.w3c.dom.Element#hasAttributeNS(String, String) * @param namespace * @param localName * @return */ public boolean hasAttributeNS(String namespace, String localName) { if (namespace == null) { namespace = ""; } if (localName == null) // Do I have to send an exception? or just return false { localName = ""; } for(int i = 0; i < attributes.getLength(); i++){ if( namespace.equals(attributes.getURI(i)) && localName.equals(attributes.getLocalName(i))) return true; } return false; } /** * This unimplemented operation is meand to return an attribute as a node * @see org.w3c.dom.Element#getAttributeNode(String) * @param attrName * @return null, always. * @deprecated this is not implemented */ // TODO: Fix this for SAAJ 1.2 Implementation. marked as deprecated to warn people // it is broken public Attr getAttributeNode(String attrName) { return null; } /** * remove a an attribue * @param oldAttr * @return oldAttr * @throws DOMException */ public Attr removeAttributeNode(Attr oldAttr) throws DOMException { makeAttributesEditable(); Name name = new PrefixedQName(oldAttr.getNamespaceURI(), oldAttr.getLocalName(), oldAttr.getPrefix()); removeAttribute(name); return oldAttr; } /** * set the attribute node. * @see org.w3c.dom.Element#setAttributeNode(org.w3c.dom.Attr) * @param newAttr * @return newAttr * @throws DOMException * @deprecated this is not implemented */ // TODO: implement public Attr setAttributeNode(Attr newAttr) throws DOMException { return newAttr; } /** * set an attribute as a node * @see org.w3c.dom.Element#setAttributeNodeNS(org.w3c.dom.Attr) * @param newAttr * @return null * @throws DOMException */ // TODO: implement properly. public Attr setAttributeNodeNS(Attr newAttr) throws DOMException { //attributes. AttributesImpl attributes = makeAttributesEditable(); // how to convert to DOM ATTR attributes.addAttribute(newAttr.getNamespaceURI(), newAttr.getLocalName(), newAttr.getLocalName(), "CDATA", newAttr.getValue()); return null; } /** * @see org.w3c.dom.Element#getElementsByTagName(String) * @param tagName tag to look for. * @return a list of elements */ public NodeList getElementsByTagName(String tagName) { NodeListImpl nodelist = new NodeListImpl(); for (int i = 0; children != null && i < children.size(); i++) { if (children.get(i) instanceof Node) { Node el = (Node)children.get(i); if (el.getLocalName() != null && el.getLocalName() .equals(tagName)) nodelist.addNode(el); if (el instanceof Element) { NodeList grandchildren = ((Element)el).getElementsByTagName(tagName); for (int j = 0; j < grandchildren.getLength(); j++) { nodelist.addNode(grandchildren.item(j)); } } } } return nodelist; } /** * get the attribute with namespace/local name match. * @see org.w3c.dom.Element#getAttributeNS(String, String) * @param namespaceURI namespace * @param localName name * @return string value or null if not found */ // TODO: this could be refactored to use getAttributeValue() public String getAttributeNS(String namespaceURI, String localName) { if(namespaceURI == null) { namespaceURI = ""; } for (int i = 0; i < attributes.getLength(); i++) { if (attributes.getURI(i).equals(namespaceURI) && attributes.getLocalName(i).equals(localName)) { return attributes.getValue(i); } } return null; } /** * set an attribute or alter an existing one * @see org.w3c.dom.Element#setAttributeNS(String, String, String) * @param namespaceURI namepsace * @param qualifiedName qualified name of the attribue * @param value value * @throws DOMException */ public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException { AttributesImpl attributes = makeAttributesEditable(); String localName = qualifiedName.substring(qualifiedName.indexOf(":")+1, qualifiedName.length()); if (namespaceURI == null) { namespaceURI = "intentionalNullURI"; } attributes.addAttribute(namespaceURI, localName, qualifiedName, "CDATA", value); } /** * @see org.w3c.dom.Element#getAttributeNS(String, String) * @deprecated not implemented! * @param namespace namespace * @param localName local name * @return null */ public Attr getAttributeNodeNS(String namespace, String localName) { return null; //TODO: Fix this for SAAJ 1.2 Implementation } /** * @see org.w3c.dom.Element#getElementsByTagNameNS(String, String) * @param namespace namespace * @param localName local name of element * @return (potentially empty) list of elements that match the (namespace,localname) tuple */ public NodeList getElementsByTagNameNS(String namespace, String localName) { return getElementsNS(this,namespace,localName); } /** * helper method for recusively getting the element that has namespace URI and localname * @param parentElement parent element * @param namespace namespace * @param localName local name of element * @return (potentially empty) list of elements that match the (namespace,localname) tuple */ protected NodeList getElementsNS(org.w3c.dom.Element parentElement, String namespace, String localName) { NodeList children = parentElement.getChildNodes(); NodeListImpl matches = new NodeListImpl(); for (int i = 0; i < children.getLength(); i++) { if (children.item(i) instanceof Text) { continue; } Element child = (Element) children.item(i); if (namespace.equals(child.getNamespaceURI()) && localName.equals(child.getLocalName())) { matches.addNode(child); } // search the grand-children. matches.addNodeList(child.getElementsByTagNameNS(namespace, localName)); } return matches; } /** * get a child node * @param index index value * @return child or null for out of range value * @see org.w3c.dom.NodeList#item(int) */ public Node item(int index) { if (children != null && children.size() > index) { return (Node) children.get(index); } else { return null; } } /** * The number of nodes in the list. The range of valid child node indices * is 0 to <code>length-1</code> inclusive. * @return number of children * @since SAAJ 1.2 : Nodelist Interface * @see org.w3c.dom.NodeList#getLength() */ public int getLength() { return (children == null) ? 0 : children.size(); } // setEncodingStyle implemented above // getEncodingStyle() implemented above protected MessageElement findElement(Vector vec, String namespace, String localPart) { if (vec.isEmpty()) { return null; } QName qname = new QName(namespace, localPart); Enumeration e = vec.elements(); MessageElement element; while (e.hasMoreElements()) { element = (MessageElement) e.nextElement(); if (element.getQName().equals(qname)) { return element; } } return null; } /** * equality test. Does a string match of the two message elements, * so is fairly brute force. * @see #toString() * @param obj * @return */ public boolean equals(Object obj) { if (obj == null || !(obj instanceof MessageElement)) { return false; } if (this == obj) { return true; } if (!this.getLocalName().equals(((MessageElement) obj).getLocalName())) { return false; } return toString().equals(obj.toString()); } /** * recursively copy. * Note that this does not reset many of our fields, and must be used with caution. * @param element */ private void copyNode(org.w3c.dom.Node element) { copyNode(this, element); } /** * recursive copy * @param dest element to copy into * @param source child element */ private void copyNode(MessageElement dest, org.w3c.dom.Node source) { dest.setPrefix(source.getPrefix()); if(source.getLocalName() != null) { dest.setQName(new QName(source.getNamespaceURI(), source.getLocalName())); } else { dest.setQName(new QName(source.getNamespaceURI(), source.getNodeName())); } NamedNodeMap attrs = source.getAttributes(); for(int i = 0; i < attrs.getLength(); i++){ Node att = attrs.item(i); if (att.getNamespaceURI() != null && att.getPrefix() != null && att.getNamespaceURI().equals(Constants.NS_URI_XMLNS) && "xmlns".equals(att.getPrefix())) { Mapping map = new Mapping(att.getNodeValue(), att.getLocalName()); dest.addMapping(map); } if(att.getLocalName() != null) { dest.addAttribute(att.getPrefix(), (att.getNamespaceURI() != null ? att.getNamespaceURI() : ""), att.getLocalName(), att.getNodeValue()); } else if (att.getNodeName() != null) { dest.addAttribute(att.getPrefix(), (att.getNamespaceURI() != null ? att.getNamespaceURI() : ""), att.getNodeName(), att.getNodeValue()); } } NodeList children = source.getChildNodes(); for(int i = 0; i < children.getLength(); i++){ Node child = children.item(i); if(child.getNodeType()==TEXT_NODE || child.getNodeType()==CDATA_SECTION_NODE || child.getNodeType()==COMMENT_NODE ) { org.apache.axis.message.Text childElement = new org.apache.axis.message.Text((CharacterData)child); dest.appendChild(childElement); } else { MessageElement childElement = new MessageElement(); dest.appendChild(childElement); copyNode(childElement, child); } } } /** * Get the value of the doc as a string. * This uses {@link #getAsDOM()} so is a heavyweight operation. * @return the value of any child node, or null if there is no node/something went * wrong during serialization. If the first child is text, the return value * is the text itself. * @see javax.xml.soap.Node#getValue() ; */ public String getValue() { /*--- Fix for AXIS-1817 if ((recorder != null) && (!_isDirty)) { StringWriter writer = new StringWriter(); TextSerializationContext outputContext = new TextSerializationContext(writer); try { recorder.replay(startEventIndex, endEventIndex, new SAXOutputter(outputContext)); } catch (Exception t) { log.debug("getValue()", t); return null; } String value = writer.toString(); return (value.length() == 0) ? null : value; } ---*/ if (textRep != null) { // weird case: error? return textRep.getNodeValue(); } if (objectValue != null) { return getValueDOM(); } for (Iterator i = getChildElements(); i.hasNext(); ) { org.apache.axis.message.NodeImpl n = (org.apache.axis.message.NodeImpl) i.next(); if (n instanceof org.apache.axis.message.Text) { org.apache.axis.message.Text textNode = (org.apache.axis.message.Text) n; return textNode.getNodeValue(); } } return null; } protected String getValueDOM() { try { Element element = getAsDOM(); if (element.hasChildNodes()) { Node node = element.getFirstChild(); if (node.getNodeType() == Node.TEXT_NODE) { return node.getNodeValue(); } } } catch (Exception t) { log.debug("getValue()", t); } return null; } public void setValue( String value ) { // if possible, get objectValue in sync with Node value if (children==null) { try { setObjectValue(value); } catch ( SOAPException soape ) { log.debug("setValue()", soape); } } super.setValue(value); } public Document getOwnerDocument() { Document doc = null; if (context != null && context.getEnvelope() != null && context.getEnvelope().getOwnerDocument() != null) { doc = context.getEnvelope().getOwnerDocument(); } if(doc == null) { doc = super.getOwnerDocument(); } if (doc == null) { doc = new SOAPDocumentImpl(null); } return doc; } }
7,570
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/NodeImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.i18n.Messages; import org.apache.commons.logging.Log; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.CharacterData; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; /** * This is our implementation of the DOM node */ public class NodeImpl implements org.w3c.dom.Node, javax.xml.soap.Node, Serializable, Cloneable { protected static Log log = LogFactory.getLog(NodeImpl.class.getName()); protected String name; protected String prefix; protected String namespaceURI; protected transient Attributes attributes = NullAttributes.singleton; protected Document document = null; protected NodeImpl parent = null; protected ArrayList children = null; // ...or as DOM protected CharacterData textRep = null; protected boolean _isDirty = false; private static final String NULL_URI_NAME = "intentionalNullURI"; /** * empty constructor */ public NodeImpl() { } /** * constructor which adopts the name and NS of the char data, and its text * @param text */ public NodeImpl(CharacterData text) { textRep = text; namespaceURI = text.getNamespaceURI(); name = text.getLocalName(); } /** * A code representing the type of the underlying object, as defined above. */ public short getNodeType() { if (this.textRep != null) { if (textRep instanceof Comment) { return COMMENT_NODE; } else if (textRep instanceof CDATASection) { return CDATA_SECTION_NODE; } else { return TEXT_NODE; } } else if (false) { return DOCUMENT_FRAGMENT_NODE; } else if (false) { return Node.ELEMENT_NODE; } else { // most often but we cannot give prioeity now return Node.ELEMENT_NODE; } } /** * Puts all <code>Text</code> nodes in the full depth of the sub-tree * underneath this <code>Node</code>, including attribute nodes, into a * "normal" form where only structure (e.g., elements, comments, * processing instructions, CDATA sections, and entity references) * separates <code>Text</code> nodes, i.e., there are neither adjacent * <code>Text</code> nodes nor empty <code>Text</code> nodes. This can * be used to ensure that the DOM view of a document is the same as if * it were saved and re-loaded, and is useful when operations (such as * XPointer lookups) that depend on a particular document tree * structure are to be used.In cases where the document contains * <code>CDATASections</code>, the normalize operation alone may not be * sufficient, since XPointers do not differentiate between * <code>Text</code> nodes and <code>CDATASection</code> nodes. */ public void normalize() { //TODO: Fix this for SAAJ 1.2 Implementation } /** * Returns whether this node (if it is an element) has any attributes. * * @return <code>true</code> if this node has any attributes, * <code>false</code> otherwise. * @since DOM Level 2 */ public boolean hasAttributes() { return attributes.getLength() > 0; } /** * Returns whether this node has any children. * * @return <code>true</code> if this node has any children, * <code>false</code> otherwise. */ public boolean hasChildNodes() { return (children != null && !children.isEmpty()); } /** * Returns the local part of the qualified name of this node. * <br>For nodes of any type other than <code>ELEMENT_NODE</code> and * <code>ATTRIBUTE_NODE</code> and nodes created with a DOM Level 1 * method, such as <code>createElement</code> from the * <code>Document</code> interface, this is always <code>null</code>. * * @since DOM Level 2 */ public String getLocalName() { return name; } /** * The namespace URI of this node, or <code>null</code> if it is * unspecified. * <br>This is not a computed value that is the result of a namespace * lookup based on an examination of the namespace declarations in * scope. It is merely the namespace URI given at creation time. * <br>For nodes of any type other than <code>ELEMENT_NODE</code> and * <code>ATTRIBUTE_NODE</code> and nodes created with a DOM Level 1 * method, such as <code>createElement</code> from the * <code>Document</code> interface, this is always <code>null</code>.Per * the Namespaces in XML Specification an attribute does not inherit * its namespace from the element it is attached to. If an attribute is * not explicitly given a namespace, it simply has no namespace. * * @since DOM Level 2 */ public String getNamespaceURI() { return (namespaceURI); } /** * The name of this node, depending on its type; see the table above. */ public String getNodeName() { return (prefix != null && prefix.length() > 0) ? prefix + ":" + name : name; } /** * The value of this node, depending on its type; see the table above. * When it is defined to be <code>null</code>, setting it has no effect. * * @throws org.w3c.dom.DOMException NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly. * @throws org.w3c.dom.DOMException DOMSTRING_SIZE_ERR: Raised when it would return more characters than * fit in a <code>DOMString</code> variable on the implementation * platform. */ public String getNodeValue() throws DOMException { if (textRep == null) { return null; } else { return textRep.getData(); } } /** * The namespace prefix of this node, or <code>null</code> if it is * unspecified. * <br>Note that setting this attribute, when permitted, changes the * <code>nodeName</code> attribute, which holds the qualified name, as * well as the <code>tagName</code> and <code>name</code> attributes of * the <code>Element</code> and <code>Attr</code> interfaces, when * applicable. * <br>Note also that changing the prefix of an attribute that is known to * have a default value, does not make a new attribute with the default * value and the original prefix appear, since the * <code>namespaceURI</code> and <code>localName</code> do not change. * <br>For nodes of any type other than <code>ELEMENT_NODE</code> and * <code>ATTRIBUTE_NODE</code> and nodes created with a DOM Level 1 * method, such as <code>createElement</code> from the * <code>Document</code> interface, this is always <code>null</code>. * * @throws org.w3c.dom.DOMException INVALID_CHARACTER_ERR: Raised if the specified prefix contains an * illegal character, per the XML 1.0 specification . * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly. * <br>NAMESPACE_ERR: Raised if the specified <code>prefix</code> is * malformed per the Namespaces in XML specification, if the * <code>namespaceURI</code> of this node is <code>null</code>, if the * specified prefix is "xml" and the <code>namespaceURI</code> of this * node is different from "http://www.w3.org/XML/1998/namespace", if * this node is an attribute and the specified prefix is "xmlns" and * the <code>namespaceURI</code> of this node is different from " * http://www.w3.org/2000/xmlns/", or if this node is an attribute and * the <code>qualifiedName</code> of this node is "xmlns" . * @since DOM Level 2 */ public String getPrefix() { return (prefix); } /** * The value of this node, depending on its type; see the table above. * When it is defined to be <code>null</code>, setting it has no effect. * * @throws org.w3c.dom.DOMException NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly. * @throws org.w3c.dom.DOMException DOMSTRING_SIZE_ERR: Raised when it would return more characters than * fit in a <code>DOMString</code> variable on the implementation * platform. */ public void setNodeValue(String nodeValue) throws DOMException { throw new DOMException(DOMException.NO_DATA_ALLOWED_ERR, "Cannot use TextNode.set in " + this); } /** * The namespace prefix of this node, or <code>null</code> if it is * unspecified. * <br>Note that setting this attribute, when permitted, changes the * <code>nodeName</code> attribute, which holds the qualified name, as * well as the <code>tagName</code> and <code>name</code> attributes of * the <code>Element</code> and <code>Attr</code> interfaces, when * applicable. * <br>Note also that changing the prefix of an attribute that is known to * have a default value, does not make a new attribute with the default * value and the original prefix appear, since the * <code>namespaceURI</code> and <code>localName</code> do not change. * <br>For nodes of any type other than <code>ELEMENT_NODE</code> and * <code>ATTRIBUTE_NODE</code> and nodes created with a DOM Level 1 * method, such as <code>createElement</code> from the * <code>Document</code> interface, this is always <code>null</code>. * * @throws org.w3c.dom.DOMException INVALID_CHARACTER_ERR: Raised if the specified prefix contains an * illegal character, per the XML 1.0 specification . * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly. * <br>NAMESPACE_ERR: Raised if the specified <code>prefix</code> is * malformed per the Namespaces in XML specification, if the * <code>namespaceURI</code> of this node is <code>null</code>, if the * specified prefix is "xml" and the <code>namespaceURI</code> of this * node is different from "http://www.w3.org/XML/1998/namespace", if * this node is an attribute and the specified prefix is "xmlns" and * the <code>namespaceURI</code> of this node is different from " * http://www.w3.org/2000/xmlns/", or if this node is an attribute and * the <code>qualifiedName</code> of this node is "xmlns" . * @since DOM Level 2 */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * Set the owner document * * @param doc */ public void setOwnerDocument(Document doc) { document = doc; } /** * The <code>Document</code> object associated with this node. This is * also the <code>Document</code> object used to create new nodes. When * this node is a <code>Document</code> or a <code>DocumentType</code> * which is not used with any <code>Document</code> yet, this is * <code>null</code>. */ public Document getOwnerDocument() { if(document == null) { NodeImpl node = getParent(); if (node != null) { return node.getOwnerDocument(); } } return document; } /** * A <code>NamedNodeMap</code> containing the attributes of this node (if * it is an <code>Element</code>) or <code>null</code> otherwise. */ public NamedNodeMap getAttributes() { // make first it is editable. makeAttributesEditable(); return convertAttrSAXtoDOM(attributes); } /** * The first child of this node. If there is no such node, this returns * <code>null</code>. */ public Node getFirstChild() { if (children != null && !children.isEmpty()) { return (Node) children.get(0); } else { return null; } } /** * The last child of this node. If there is no such node, this returns * <code>null</code>. */ public Node getLastChild() { if (children != null && !children.isEmpty()) { return (Node) children.get(children.size() - 1); } else { return null; } } /** * The node immediately following this node. If there is no such node, * this returns <code>null</code>. */ public Node getNextSibling() { SOAPElement parent = getParentElement(); if (parent == null) { return null; } Iterator iter = parent.getChildElements(); Node nextSibling = null; while (iter.hasNext()) { if (iter.next() == this) { if (iter.hasNext()) { return (Node) iter.next(); } else { return null; } } } return nextSibling; // should be null. } /** * The parent of this node. All nodes, except <code>Attr</code>, * <code>Document</code>, <code>DocumentFragment</code>, * <code>Entity</code>, and <code>Notation</code> may have a parent. * However, if a node has just been created and not yet added to the * tree, or if it has been removed from the tree, this is * <code>null</code>. */ public Node getParentNode() { return (Node) getParent(); } /** * The node immediately preceding this node. If there is no such node, * this returns <code>null</code>. */ public Node getPreviousSibling() { SOAPElement parent = getParentElement(); if (parent == null) { return null; } NodeList nl = parent.getChildNodes(); int len = nl.getLength(); int i = 0; Node previousSibling = null; while (i < len) { if (nl.item(i) == this) { return previousSibling; } previousSibling = nl.item(i); i++; } return previousSibling; // should be null. } /** * Returns a duplicate of this node, i.e., serves as a generic copy * constructor for nodes. The duplicate node has no parent; ( * <code>parentNode</code> is <code>null</code>.). * <br>Cloning an <code>Element</code> copies all attributes and their * values, including those generated by the XML processor to represent * defaulted attributes, but this method does not copy any text it * contains unless it is a deep clone, since the text is contained in a * child <code>Text</code> node. Cloning an <code>Attribute</code> * directly, as opposed to be cloned as part of an <code>Element</code> * cloning operation, returns a specified attribute ( * <code>specified</code> is <code>true</code>). Cloning any other type * of node simply returns a copy of this node. * <br>Note that cloning an immutable subtree results in a mutable copy, * but the children of an <code>EntityReference</code> clone are readonly * . In addition, clones of unspecified <code>Attr</code> nodes are * specified. And, cloning <code>Document</code>, * <code>DocumentType</code>, <code>Entity</code>, and * <code>Notation</code> nodes is implementation dependent. * * @param deep If <code>true</code>, recursively clone the subtree under * the specified node; if <code>false</code>, clone only the node * itself (and its attributes, if it is an <code>Element</code>). * @return The duplicate node. */ public Node cloneNode(boolean deep) { return new NodeImpl(textRep); } /** * A <code>NodeList</code> that contains all children of this node. If * there are no children, this is a <code>NodeList</code> containing no * nodes. */ public NodeList getChildNodes() { if (children == null) { return NodeListImpl.EMPTY_NODELIST; } else { return new NodeListImpl(children); } } /** * Tests whether the DOM implementation implements a specific feature and * that feature is supported by this node. * * @param feature The name of the feature to test. This is the same name * which can be passed to the method <code>hasFeature</code> on * <code>DOMImplementation</code>. * @param version This is the version number of the feature to test. In * Level 2, version 1, this is the string "2.0". If the version is not * specified, supporting any version of the feature will cause the * method to return <code>true</code>. * @return Returns <code>true</code> if the specified feature is * supported on this node, <code>false</code> otherwise. * @since DOM Level 2 */ public boolean isSupported(String feature, String version) { return false; //TODO: Fix this for SAAJ 1.2 Implementation } /** * Adds the node <code>newChild</code> to the end of the list of children * of this node. If the <code>newChild</code> is already in the tree, it * is first removed. * * @param newChild The node to add.If it is a * <code>DocumentFragment</code> object, the entire contents of the * document fragment are moved into the child list of this node * @return The node added. * @throws org.w3c.dom.DOMException HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not * allow children of the type of the <code>newChild</code> node, or if * the node to append is one of this node's ancestors or this node * itself. * <br>WRONG_DOCUMENT_ERR: Raised if <code>newChild</code> was created * from a different document than the one that created this node. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly or * if the previous parent of the node being inserted is readonly. * */ public Node appendChild(Node newChild) throws DOMException { if (newChild == null) { throw new DOMException (DOMException.HIERARCHY_REQUEST_ERR, "Can't append a null node."); } initializeChildren(); // per DOM spec - must remove from tree. If newChild.parent == null, // detachNode() does nothing. So this shouldn't hurt performace of // serializers. ((NodeImpl) newChild).detachNode(); children.add(newChild); ((NodeImpl) newChild).parent = this; setDirty(); return newChild; } /** * Removes the child node indicated by <code>oldChild</code> from the list * of children, and returns it. * * @param oldChild The node being removed. * @return The node removed. * @throws org.w3c.dom.DOMException NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly. * <br>NOT_FOUND_ERR: Raised if <code>oldChild</code> is not a child of * this node. */ public Node removeChild(Node oldChild) throws DOMException { if (removeNodeFromChildList((NodeImpl) oldChild)) { setDirty(); return oldChild; } throw new DOMException(DOMException.NOT_FOUND_ERR, "NodeImpl Not found"); } private boolean removeNodeFromChildList(NodeImpl n) { boolean removed = false; initializeChildren(); final Iterator itr = children.iterator(); while (itr.hasNext()) { final NodeImpl node = (NodeImpl) itr.next(); if (node == n) { removed = true; itr.remove(); } } return removed; } /** * Inserts the node <code>newChild</code> before the existing child node * <code>refChild</code>. If <code>refChild</code> is <code>null</code>, * insert <code>newChild</code> at the end of the list of children. * <br>If <code>newChild</code> is a <code>DocumentFragment</code> object, * all of its children are inserted, in the same order, before * <code>refChild</code>. If the <code>newChild</code> is already in the * tree, it is first removed. * * @param newChild The node to insert. * @param refChild The reference node, i.e., the node before which the * new node must be inserted. * @return The node being inserted. * @throws org.w3c.dom.DOMException HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not * allow children of the type of the <code>newChild</code> node, or if * the node to insert is one of this node's ancestors or this node * itself. * <br>WRONG_DOCUMENT_ERR: Raised if <code>newChild</code> was created * from a different document than the one that created this node. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly or * if the parent of the node being inserted is readonly. * <br>NOT_FOUND_ERR: Raised if <code>refChild</code> is not a child of * this node. */ public Node insertBefore(Node newChild, Node refChild) throws DOMException { initializeChildren(); int position = children.indexOf(refChild); if (position < 0) { position = 0; } children.add(position, newChild); setDirty(); return newChild; } /** * Replaces the child node <code>oldChild</code> with <code>newChild</code> * in the list of children, and returns the <code>oldChild</code> node. * <br>If <code>newChild</code> is a <code>DocumentFragment</code> object, * <code>oldChild</code> is replaced by all of the * <code>DocumentFragment</code> children, which are inserted in the * same order. If the <code>newChild</code> is already in the tree, it * is first removed. * * @param newChild The new node to put in the child list. * @param oldChild The node being replaced in the list. * @return The node replaced. * @throws org.w3c.dom.DOMException HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not * allow children of the type of the <code>newChild</code> node, or if * the node to put in is one of this node's ancestors or this node * itself. * <br>WRONG_DOCUMENT_ERR: Raised if <code>newChild</code> was created * from a different document than the one that created this node. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node or the parent of * the new node is readonly. * <br>NOT_FOUND_ERR: Raised if <code>oldChild</code> is not a child of * this node. */ public Node replaceChild(Node newChild, Node oldChild) throws DOMException { initializeChildren(); int position = children.indexOf(oldChild); if (position < 0) { throw new DOMException(DOMException.NOT_FOUND_ERR, "NodeImpl Not found"); } children.remove(position); children.add(position, newChild); setDirty(); return oldChild; } /** * Returns the the value of the immediate child of this <code>Node</code> * object if a child exists and its value is text. * * @return a <code>String</code> with the text of the immediate child of * this <code>Node</code> object if (1) there is a child and * (2) the child is a <code>Text</code> object; * <code>null</code> otherwise */ public String getValue() { return textRep.getNodeValue(); } /** * Sets the parent of this <code>Node</code> object to the given * <code>SOAPElement</code> object. * * @param parent the <code>SOAPElement</code> object to be set as * the parent of this <code>Node</code> object * @throws javax.xml.soap.SOAPException if there is a problem in setting the * parent to the given element * @see #getParentElement() getParentElement() */ public void setParentElement(SOAPElement parent) throws SOAPException { if (parent == null) throw new IllegalArgumentException( Messages.getMessage("nullParent00")); try { setParent((NodeImpl) parent); } catch (Throwable t) { throw new SOAPException(t); } } /** * Returns the parent element of this <code>Node</code> object. * This method can throw an <code>UnsupportedOperationException</code> * if the tree is not kept in memory. * * @return the <code>SOAPElement</code> object that is the parent of * this <code>Node</code> object or <code>null</code> if this * <code>Node</code> object is root * @throws UnsupportedOperationException if the whole tree is not kept in memory * @see #setParentElement(javax.xml.soap.SOAPElement) setParentElement(javax.xml.soap.SOAPElement) */ public SOAPElement getParentElement() { return (SOAPElement) getParent(); } /** * Removes this <code>Node</code> object from the tree. Once * removed, this node can be garbage collected if there are no * application references to it. */ public void detachNode() { setDirty(); if (parent != null) { parent.removeChild(this); parent = null; } } /** * Notifies the implementation that this <code>Node</code> * object is no longer being used by the application and that the * implementation is free to reuse this object for nodes that may * be created later. * <P> * Calling the method <code>recycleNode</code> implies that the method * <code>detachNode</code> has been called previously. */ public void recycleNode() { //TODO: Fix this for SAAJ 1.2 Implementation } /** * If this is a Text node then this method will set its value, otherwise it * sets the value of the immediate (Text) child of this node. The value of * the immediate child of this node can be set only if, there is one child * node and that node is a Text node, or if there are no children in which * case a child Text node will be created. * * @param value the text to set * @throws IllegalStateException if the node is not a Text node and * either has more than one child node or has a child node that * is not a Text node */ public void setValue(String value) { if (this instanceof org.apache.axis.message.Text) { setNodeValue(value); } else if (children != null) { if (children.size() != 1) { throw new IllegalStateException( "setValue() may not be called on a non-Text node with more than one child." ); } javax.xml.soap.Node child = (javax.xml.soap.Node) children.get(0); if (!(child instanceof org.apache.axis.message.Text)) { throw new IllegalStateException( "setValue() may not be called on a non-Text node with a non-Text child." ); } ((javax.xml.soap.Text)child).setNodeValue(value); } else { appendChild(new org.apache.axis.message.Text(value)); } } /** * make the attributes editable * * @return AttributesImpl */ protected AttributesImpl makeAttributesEditable() { if (attributes == null || attributes instanceof NullAttributes) { attributes = new AttributesImpl(); } else if (!(attributes instanceof AttributesImpl)) { attributes = new AttributesImpl(attributes); } return (AttributesImpl) attributes; } /** * The internal representation of Attributes cannot help being changed * It is because Attribute is not immutible Type, so if we keep out value and * just return it in another form, the application may chnae it, which we cannot * detect without some kind back track method (call back notifying the chnage.) * I am not sure which approach is better. */ protected NamedNodeMap convertAttrSAXtoDOM(Attributes saxAttr) { try { org.w3c.dom.Document doc = org.apache.axis.utils.XMLUtils.newDocument(); AttributesImpl saxAttrs = (AttributesImpl) saxAttr; NamedNodeMap domAttributes = new NamedNodeMapImpl(); for (int i = 0; i < saxAttrs.getLength(); i++) { String uri = saxAttrs.getURI(i); String qname = saxAttrs.getQName(i); String value = saxAttrs.getValue(i); if (uri != null && uri.trim().length() > 0) { // filterring out the tricky method to differentiate the null namespace // -ware case if (NULL_URI_NAME.equals(uri)) { uri = null; } Attr attr = doc.createAttributeNS(uri, qname); attr.setValue(value); domAttributes.setNamedItemNS(attr); } else { Attr attr = doc.createAttribute(qname); attr.setValue(value); domAttributes.setNamedItem(attr); } } return domAttributes; } catch (Exception ex) { log.error(Messages.getMessage("saxToDomFailed00"),ex); return null; } } /** * Initialize the children array */ protected void initializeChildren() { if (children == null) { children = new ArrayList(); } } /** * get the parent node * @return parent node */ protected NodeImpl getParent() { return parent; } /** * Set the parent node and invoke appendChild(this) to * add this node to the parent's list of children. * @param parent * @throws SOAPException */ protected void setParent(NodeImpl parent) throws SOAPException { if (this.parent == parent) { return; } if (this.parent != null) { this.parent.removeChild(this); } if (parent != null) { parent.appendChild(this); } this.setDirty(); this.parent = parent; } /** * print the contents of this node * @param context * @throws Exception */ public void output(SerializationContext context) throws Exception { if (textRep == null) return; boolean oldPretty = context.getPretty(); context.setPretty(false); if (textRep instanceof CDATASection) { context.writeString("<![CDATA["); context.writeString(((org.w3c.dom.Text) textRep).getData()); context.writeString("]]>"); } else if (textRep instanceof Comment) { context.writeString("<!--"); context.writeString(((CharacterData) textRep).getData()); context.writeString("-->"); } else if (textRep instanceof Text) { context.writeSafeString(((Text) textRep).getData()); } context.setPretty(oldPretty); } /** * get the dirty bit * @return */ public boolean isDirty() { return _isDirty; } /** * set the dirty bit. will also set our parent as dirty, if there is one. * Note that clearing the dirty bit does <i>not</i> propagate upwards. * @param dirty new value of the dirty bit */ public void setDirty(boolean dirty) { _isDirty = dirty; if (_isDirty && parent != null) { ((NodeImpl) parent).setDirty(); } } public void setDirty() { _isDirty = true; if (parent != null) { ((NodeImpl) parent).setDirty(); } } /* clear dirty flag recursively */ public void reset() { if (children != null) { for (int i=0; i<children.size(); i++) { ((NodeImpl) children.get(i)).reset(); } } this._isDirty = false; } }
7,571
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPBody.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import javax.xml.soap.Name; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Vector; /** * Holder for body elements. * * @author Glyn Normington (glyn@apache.org) */ public class SOAPBody extends MessageElement implements javax.xml.soap.SOAPBody { private static Log log = LogFactory.getLog(SOAPBody.class.getName()); private SOAPConstants soapConstants; private boolean disableFormatting = false; private boolean doSAAJEncodingCompliance = false; private static ArrayList knownEncodingStyles = new ArrayList(); static { knownEncodingStyles.add(Constants.URI_SOAP11_ENC); knownEncodingStyles.add(Constants.URI_SOAP12_ENC); knownEncodingStyles.add(""); knownEncodingStyles.add(Constants.URI_SOAP12_NOENC); } SOAPBody(SOAPEnvelope env, SOAPConstants soapConsts) { super(soapConsts.getEnvelopeURI(), Constants.ELEM_BODY); soapConstants = soapConsts; try { setParentElement(env); } catch (SOAPException ex) { // class cast should never fail when parent is a SOAPEnvelope log.fatal(Messages.getMessage("exception00"), ex); } } public SOAPBody(String namespace, String localPart, String prefix, Attributes attributes, DeserializationContext context, SOAPConstants soapConsts) throws AxisFault { super(namespace, localPart, prefix, attributes, context); soapConstants = soapConsts; } public void setParentElement(SOAPElement parent) throws SOAPException { if(parent == null) { throw new IllegalArgumentException(Messages.getMessage("nullParent00")); } try { SOAPEnvelope env = (SOAPEnvelope)parent; super.setParentElement(env); setEnvelope(env); } catch (Throwable t) { throw new SOAPException(t); } } public void disableFormatting() { this.disableFormatting = true; } public void setEncodingStyle(String encodingStyle) throws SOAPException { if (encodingStyle == null) { encodingStyle = ""; } if (doSAAJEncodingCompliance) { // Make sure this matches a known encodingStyle. This is if (!knownEncodingStyles.contains(encodingStyle)) throw new IllegalArgumentException(Messages.getMessage("badEncodingStyle1", encodingStyle)); } super.setEncodingStyle(encodingStyle); } protected void outputImpl(SerializationContext context) throws Exception { boolean oldPretty = context.getPretty(); if (!disableFormatting) { context.setPretty(true); } else { context.setPretty(false); } List bodyElements = getChildren(); if (bodyElements == null || bodyElements.isEmpty()) { // This is a problem. // throw new Exception("No body elements!"); // If there are no body elements just return - it's ok that // the body is empty } // Output <SOAP-ENV:Body> context.startElement(new QName(soapConstants.getEnvelopeURI(), Constants.ELEM_BODY), getAttributesEx()); if (bodyElements != null) { Iterator e = bodyElements.iterator(); while (e.hasNext()) { MessageElement body = (MessageElement)e.next(); body.output(context); // Output this body element. } } // Output multi-refs if appropriate context.outputMultiRefs(); // Output </SOAP-ENV:Body> context.endElement(); context.setPretty(oldPretty); } Vector getBodyElements() throws AxisFault { initializeChildren(); return new Vector(getChildren()); } SOAPBodyElement getFirstBody() throws AxisFault { if (!hasChildNodes()) return null; return (SOAPBodyElement)getChildren().get(0); } void addBodyElement(SOAPBodyElement element) { if (log.isDebugEnabled()) log.debug(Messages.getMessage("addBody00")); try { addChildElement(element); } catch (SOAPException ex) { // class cast should never fail when parent is a SOAPBody log.fatal(Messages.getMessage("exception00"), ex); } } void removeBodyElement(SOAPBodyElement element) { if (log.isDebugEnabled()) log.debug(Messages.getMessage("removeBody00")); removeChild( (MessageElement)element ); } void clearBody() { removeContents(); } SOAPBodyElement getBodyByName(String namespace, String localPart) throws AxisFault { QName name = new QName(namespace, localPart); return (SOAPBodyElement)getChildElement(name); } // JAXM methods public javax.xml.soap.SOAPBodyElement addBodyElement(Name name) throws SOAPException { SOAPBodyElement bodyElement = new SOAPBodyElement(name); addChildElement(bodyElement); return bodyElement; } public javax.xml.soap.SOAPFault addFault(Name name, String s, Locale locale) throws SOAPException { AxisFault af = new AxisFault(new QName(name.getURI(), name.getLocalName()), s, "", new Element[0]); SOAPFault fault = new SOAPFault(af); addChildElement(fault); return fault; } public javax.xml.soap.SOAPFault addFault(Name name, String s) throws SOAPException { AxisFault af = new AxisFault(new QName(name.getURI(), name.getLocalName()), s, "", new Element[0]); SOAPFault fault = new SOAPFault(af); addChildElement(fault); return fault; } public javax.xml.soap.SOAPBodyElement addDocument(Document document) throws SOAPException { SOAPBodyElement bodyElement = new SOAPBodyElement(document.getDocumentElement()); addChildElement(bodyElement); return bodyElement; } public javax.xml.soap.SOAPFault addFault() throws SOAPException { AxisFault af = new AxisFault(new QName(Constants.NS_URI_AXIS, Constants.FAULT_SERVER_GENERAL), "", "", new Element[0]); SOAPFault fault = new SOAPFault(af); addChildElement(fault); return fault; } public javax.xml.soap.SOAPFault getFault() { List bodyElements = getChildren(); if (bodyElements != null) { Iterator e = bodyElements.iterator(); while (e.hasNext()) { Object element = e.next(); if(element instanceof javax.xml.soap.SOAPFault) { return (javax.xml.soap.SOAPFault) element; } } } return null; } public boolean hasFault() { return (getFault() != null); } // overwrite the one in MessageElement and set envelope public void addChild(MessageElement element) throws SOAPException { // Commented out for SAAJ compatibility - gdaniels, 05/19/2003 // if (!(element instanceof javax.xml.soap.SOAPBodyElement)) { // throw new SOAPException(Messages.getMessage("badSOAPBodyElement00")); // } element.setEnvelope(getEnvelope()); super.addChild(element); } // overwrite the one in MessageElement and sets dirty flag public SOAPElement addChildElement(SOAPElement element) throws SOAPException { // Commented out for SAAJ compatibility - gdaniels, 05/19/2003 // if (!(element instanceof javax.xml.soap.SOAPBodyElement)) { // throw new SOAPException(Messages.getMessage("badSOAPBodyElement00")); // } SOAPElement child = super.addChildElement(element); setDirty(); return child; } public SOAPElement addChildElement(Name name) throws SOAPException { SOAPBodyElement child = new SOAPBodyElement(name); addChildElement(child); return child; } public SOAPElement addChildElement(String localName) throws SOAPException { // Inherit parent's namespace SOAPBodyElement child = new SOAPBodyElement(getNamespaceURI(), localName); addChildElement(child); return child; } public SOAPElement addChildElement(String localName, String prefix) throws SOAPException { SOAPBodyElement child = new SOAPBodyElement(getNamespaceURI(prefix), localName); child.setPrefix(prefix); addChildElement(child); return child; } public SOAPElement addChildElement(String localName, String prefix, String uri) throws SOAPException { SOAPBodyElement child = new SOAPBodyElement(uri, localName); child.setPrefix(prefix); child.addNamespaceDeclaration(prefix, uri); addChildElement(child); return child; } public void setSAAJEncodingCompliance(boolean comply) { this.doSAAJEncodingCompliance = true; } }
7,572
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPFaultReasonBuilder.java
package org.apache.axis.message; import org.apache.axis.Constants; import org.apache.axis.encoding.Callback; import org.apache.axis.encoding.CallbackTarget; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.util.ArrayList; /* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Parser for the fault Reason element and its associated Text elements. * * @author Glen Daniels (gdaniels@apache.org) */ public class SOAPFaultReasonBuilder extends SOAPHandler implements Callback { /** Storage for the actual text */ private ArrayList text = new ArrayList(); private SOAPFaultBuilder faultBuilder; public SOAPFaultReasonBuilder(SOAPFaultBuilder faultBuilder) { this.faultBuilder = faultBuilder; } public SOAPHandler onStartChild(String namespace, String name, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { QName thisQName = new QName(namespace, name); if (thisQName.equals(Constants.QNAME_TEXT_SOAP12)) { Deserializer currentDeser = null; currentDeser = context.getDeserializerForType(Constants.XSD_STRING); if (currentDeser != null) { currentDeser.registerValueTarget( new CallbackTarget(faultBuilder, thisQName)); } return (SOAPHandler)currentDeser; } else { return null; } } /** * Defined by Callback. * This method gets control when the callback is invoked, which happens * each time we get a deserialized Text string. * * @param value the deserialized value * @param hint (unused) provides additional hint information. */ public void setValue(Object value, Object hint) { text.add(value); } public ArrayList getText() { return text; } }
7,573
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPHeader.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.w3c.dom.Node; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import javax.xml.namespace.QName; import javax.xml.soap.Name; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Vector; /** * Holder for header elements. * * @author Glyn Normington (glyn@apache.org) */ public class SOAPHeader extends MessageElement implements javax.xml.soap.SOAPHeader { private static Log log = LogFactory.getLog(SOAPHeader.class.getName()); private SOAPConstants soapConstants; SOAPHeader(SOAPEnvelope env, SOAPConstants soapConsts) { super(Constants.ELEM_HEADER, Constants.NS_PREFIX_SOAP_ENV, (soapConsts != null) ? soapConsts.getEnvelopeURI() : Constants.DEFAULT_SOAP_VERSION.getEnvelopeURI()); soapConstants = (soapConsts != null) ? soapConsts : Constants.DEFAULT_SOAP_VERSION; try { setParentElement(env); } catch (SOAPException ex) { // class cast should never fail when parent is a SOAPEnvelope log.fatal(Messages.getMessage("exception00"), ex); } } public SOAPHeader(String namespace, String localPart, String prefix, Attributes attributes, DeserializationContext context, SOAPConstants soapConsts) throws AxisFault { super(namespace, localPart, prefix, attributes, context); soapConstants = (soapConsts != null) ? soapConsts : Constants.DEFAULT_SOAP_VERSION; } public void setParentElement(SOAPElement parent) throws SOAPException { if(parent == null) { throw new IllegalArgumentException(Messages.getMessage("nullParent00")); } try { // cast to force exception if wrong type SOAPEnvelope env = (SOAPEnvelope)parent; super.setParentElement(env); setEnvelope(env); } catch (Throwable t) { throw new SOAPException(t); } } public javax.xml.soap.SOAPHeaderElement addHeaderElement(Name name) throws SOAPException { SOAPHeaderElement headerElement = new SOAPHeaderElement(name); addChildElement(headerElement); return headerElement; } private Vector findHeaderElements(String actor) { ArrayList actors = new ArrayList(); actors.add(actor); return getHeadersByActor(actors); } public Iterator examineHeaderElements(String actor) { return findHeaderElements(actor).iterator(); } public Iterator extractHeaderElements(String actor) { Vector results = findHeaderElements(actor); Iterator iterator = results.iterator(); // Detach the header elements from the header while (iterator.hasNext()) { ((SOAPHeaderElement)iterator.next()).detachNode(); } return results.iterator(); } public Iterator examineMustUnderstandHeaderElements(String actor) { if (actor == null) return null; Vector result = new Vector(); List headers = getChildren(); if (headers != null) { for(int i = 0; i < headers.size(); i++) { SOAPHeaderElement she = (SOAPHeaderElement)headers.get(i); if (she.getMustUnderstand()) { String candidate = she.getActor(); if (actor.equals(candidate)) { result.add(headers.get(i)); } } } } return result.iterator(); } public Iterator examineAllHeaderElements() { return getChildElements(); } public Iterator extractAllHeaderElements() { Vector result = new Vector(); List headers = getChildren(); if (headers != null) { for(int i = 0; i < headers.size(); i++) { result.add(headers.get(i)); } headers.clear(); } return result.iterator(); } Vector getHeaders() { initializeChildren(); return new Vector(getChildren()); } /** * Get all the headers targeted at a list of actors. */ Vector getHeadersByActor(ArrayList actors) { Vector results = new Vector(); List headers = getChildren(); if (headers == null) { return results; } Iterator i = headers.iterator(); SOAPConstants soapVer = getEnvelope().getSOAPConstants(); boolean isSOAP12 = soapVer == SOAPConstants.SOAP12_CONSTANTS; String nextActor = soapVer.getNextRoleURI(); while (i.hasNext()) { SOAPHeaderElement header = (SOAPHeaderElement)i.next(); String actor = header.getActor(); // Skip it if we're SOAP 1.2 and it's the "none" role. if (isSOAP12 && Constants.URI_SOAP12_NONE_ROLE.equals(actor)) { continue; } // Always process NEXT's, and then anything else in our list // For now, also always process ultimateReceiver role if SOAP 1.2 if (actor == null || nextActor.equals(actor) || (isSOAP12 && Constants.URI_SOAP12_ULTIMATE_ROLE.equals(actor)) || (actors != null && actors.contains(actor))) { results.add(header); } } return results; } void addHeader(SOAPHeaderElement header) { if (log.isDebugEnabled()) log.debug(Messages.getMessage("addHeader00")); try { addChildElement(header); } catch (SOAPException ex) { // class cast should never fail when parent is a SOAPHeader log.fatal(Messages.getMessage("exception00"), ex); } } void removeHeader(SOAPHeaderElement header) { if (log.isDebugEnabled()) log.debug(Messages.getMessage("removeHeader00")); removeChild(header); } /** * Get a header by name, filtering for headers targeted at this * engine depending on the accessAllHeaders parameter. */ SOAPHeaderElement getHeaderByName(String namespace, String localPart, boolean accessAllHeaders) { QName name = new QName(namespace, localPart); SOAPHeaderElement header = (SOAPHeaderElement)getChildElement(name); // If we're operating within an AxisEngine, respect its actor list // unless told otherwise if (!accessAllHeaders) { MessageContext mc = MessageContext.getCurrentContext(); if (mc != null) { if (header != null) { String actor = header.getActor(); // Always respect "next" role String nextActor = getEnvelope().getSOAPConstants().getNextRoleURI(); if (nextActor.equals(actor)) return header; SOAPService soapService = mc.getService(); if (soapService != null) { ArrayList actors = mc.getService().getActors(); if ((actor != null) && (actors == null || !actors.contains(actor))) { header = null; } } } } } return header; } /** * Return an Enumeration of headers which match the given namespace * and localPart. Depending on the value of the accessAllHeaders * parameter, we will attempt to filter on the current engine's list * of actors. * * !!! NOTE THAT RIGHT NOW WE ALWAYS ASSUME WE'RE THE "ULTIMATE * DESTINATION" (i.e. we match on null actor). IF WE WANT TO FULLY SUPPORT * INTERMEDIARIES WE'LL NEED TO FIX THIS. */ Enumeration getHeadersByName(String namespace, String localPart, boolean accessAllHeaders) { ArrayList actors = null; boolean firstTime = false; /** This might be optimizable by creating a custom Enumeration * which moves through the headers list (parsing on demand, again), * returning only the next one each time.... this is Q&D for now. */ Vector v = new Vector(); List headers = getChildren(); if (headers == null) { return v.elements(); } Iterator e = headers.iterator(); SOAPHeaderElement header; String nextActor = getEnvelope().getSOAPConstants().getNextRoleURI(); while (e.hasNext()) { header = (SOAPHeaderElement)e.next(); if (header.getNamespaceURI().equals(namespace) && header.getName().equals(localPart)) { if (!accessAllHeaders) { if (firstTime) { // Do one-time setup MessageContext mc = MessageContext.getCurrentContext(); if (mc != null && mc.getAxisEngine() != null) { actors = mc.getAxisEngine().getActorURIs(); } firstTime = false; } String actor = header.getActor(); if ((actor != null) && !nextActor.equals(actor) && (actors == null || !actors.contains(actor))) { continue; } } v.addElement(header); } } return v.elements(); } protected void outputImpl(SerializationContext context) throws Exception { List headers = getChildren(); if (headers == null) { return; } boolean oldPretty = context.getPretty(); context.setPretty(true); if (log.isDebugEnabled()) log.debug(headers.size() + " " + Messages.getMessage("headers00")); if (!headers.isEmpty()) { // Output <SOAP-ENV:Header> context.startElement(new QName(soapConstants.getEnvelopeURI(), Constants.ELEM_HEADER), null); Iterator enumeration = headers.iterator(); while (enumeration.hasNext()) { // Output this header element ((NodeImpl)enumeration.next()).output(context); } // Output </SOAP-ENV:Header> context.endElement(); } context.setPretty(oldPretty); } // overwrite the one in MessageElement and set envelope public void addChild(MessageElement element) throws SOAPException { if (!(element instanceof SOAPHeaderElement)) { throw new SOAPException(Messages.getMessage("badSOAPHeader00")); } element.setEnvelope(getEnvelope()); super.addChild(element); } // overwrite the one in MessageElement and sets dirty flag public SOAPElement addChildElement(SOAPElement element) throws SOAPException { if (!(element instanceof SOAPHeaderElement)) { throw new SOAPException(Messages.getMessage("badSOAPHeader00")); } SOAPElement child = super.addChildElement(element); setDirty(); return child; } public SOAPElement addChildElement(Name name) throws SOAPException { SOAPHeaderElement child = new SOAPHeaderElement(name); addChildElement(child); return child; } public SOAPElement addChildElement(String localName) throws SOAPException { // Inherit parent's namespace SOAPHeaderElement child = new SOAPHeaderElement(getNamespaceURI(), localName); addChildElement(child); return child; } public SOAPElement addChildElement(String localName, String prefix) throws SOAPException { SOAPHeaderElement child = new SOAPHeaderElement(getNamespaceURI(prefix), localName); child.setPrefix(prefix); addChildElement(child); return child; } public SOAPElement addChildElement(String localName, String prefix, String uri) throws SOAPException { SOAPHeaderElement child = new SOAPHeaderElement(uri, localName); child.setPrefix(prefix); child.addNamespaceDeclaration(prefix, uri); addChildElement(child); return child; } public Node appendChild(Node newChild) throws DOMException { SOAPHeaderElement headerElement = null; if(newChild instanceof SOAPHeaderElement) headerElement = (SOAPHeaderElement)newChild; else headerElement = new SOAPHeaderElement((Element)newChild); try { addChildElement(headerElement); } catch (SOAPException e) { throw new DOMException(DOMException.INVALID_STATE_ERR,e.toString()); } return headerElement; } }
7,574
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SAXOutputter.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.DefaultHandler; import javax.xml.namespace.QName; import java.io.IOException; public class SAXOutputter extends DefaultHandler implements LexicalHandler { protected static Log log = LogFactory.getLog(SAXOutputter.class.getName()); SerializationContext context; boolean isCDATA = false; public SAXOutputter(SerializationContext context) { this.context = context; } public void startDocument() throws SAXException { context.setSendDecl(true); } public void endDocument() throws SAXException { if (log.isDebugEnabled()) { log.debug("SAXOutputter.endDocument"); } } public void startPrefixMapping(String p1, String p2) throws SAXException { context.registerPrefixForURI(p1,p2); } public void endPrefixMapping(String p1) throws SAXException { // !!! } public void characters(char[] p1, int p2, int p3) throws SAXException { if (log.isDebugEnabled()) { log.debug("SAXOutputter.characters ['" + new String(p1, p2, p3) + "']"); } try { if(!isCDATA) { context.writeChars(p1, p2, p3); } else { context.writeString(new String(p1, p2, p3)); } } catch (IOException e) { throw new SAXException(e); } } public void ignorableWhitespace(char[] p1, int p2, int p3) throws SAXException { try { context.writeChars(p1, p2, p3); } catch (IOException e) { throw new SAXException(e); } } public void skippedEntity(String p1) throws SAXException { } public void startElement(String namespace, String localName, String qName, Attributes attributes) throws SAXException { if (log.isDebugEnabled()) { log.debug("SAXOutputter.startElement ['" + namespace + "' " + localName + "]"); } try { context.startElement(new QName(namespace,localName), attributes); } catch (IOException e) { throw new SAXException(e); } } public void endElement(String namespace, String localName, String qName) throws SAXException { if (log.isDebugEnabled()) { log.debug("SAXOutputter.endElement ['" + namespace + "' " + localName + "]"); } try { context.endElement(); } catch (IOException e) { throw new SAXException(e); } } public void startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId) throws SAXException { } public void endDTD() throws SAXException { } public void startEntity(java.lang.String name) throws SAXException { } public void endEntity(java.lang.String name) throws SAXException { } public void startCDATA() throws SAXException { try { isCDATA = true; context.writeString("<![CDATA["); } catch (IOException e) { throw new SAXException(e); } } public void endCDATA() throws SAXException { try { isCDATA = false; context.writeString("]]>"); } catch (IOException e) { throw new SAXException(e); } } public void comment(char[] ch, int start, int length) throws SAXException { if (log.isDebugEnabled()) { log.debug("SAXOutputter.comment ['" + new String(ch, start, length) + "']"); } try { context.writeString("<!--"); context.writeChars(ch, start, length); context.writeString("-->"); } catch (IOException e) { throw new SAXException(e); } } }
7,575
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/PrefixedQName.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import javax.xml.namespace.QName; import javax.xml.soap.Name; public class PrefixedQName implements Name { /** comment/shared empty string */ private static final String emptyString = "".intern(); private String prefix; private QName qName; public PrefixedQName(String uri, String localName, String pre) { qName = new QName(uri, localName); prefix = (pre == null) ? emptyString : pre.intern(); } public PrefixedQName(QName qname) { this.qName = qname; prefix = emptyString; } public String getLocalName() { return qName.getLocalPart(); } public String getQualifiedName() { StringBuffer buf = new StringBuffer(prefix); if(prefix != emptyString) buf.append(':'); buf.append(qName.getLocalPart()); return buf.toString(); } public String getURI() { return qName.getNamespaceURI(); } public String getPrefix() { return prefix; } public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PrefixedQName)) { return false; } if (!qName.equals(((PrefixedQName)obj).qName)) { return false; } if (prefix == ((PrefixedQName) obj).prefix) { return true; } return false; } public int hashCode() { return prefix.hashCode() + qName.hashCode(); } public String toString() { return qName.toString(); } }
7,576
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/BodyBuilder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** * * @author Glen Daniels (gdaniels@allaire.com) */ import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.MessageContext; import org.apache.axis.Message; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.OperationDesc; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.constants.Style; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; public class BodyBuilder extends SOAPHandler { protected static Log log = LogFactory.getLog(BodyBuilder.class.getName()); boolean gotRPCElement = false; private SOAPEnvelope envelope; BodyBuilder(SOAPEnvelope envelope) { this.envelope = envelope; } public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { SOAPConstants soapConstants = context.getSOAPConstants(); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS && attributes.getValue(Constants.URI_SOAP12_ENV, Constants.ATTR_ENCODING_STYLE) != null) { AxisFault fault = new AxisFault(Constants.FAULT_SOAP12_SENDER, null, Messages.getMessage("noEncodingStyleAttrAppear", "Body"), null, null, null); throw new SAXException(fault); } // make a new body element if (!context.isDoneParsing()) { if (!context.isProcessingRef()) { if (myElement == null) { try { myElement = new SOAPBody(namespace, localName, prefix, attributes, context, envelope.getSOAPConstants()); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } } context.pushNewElement(myElement); } envelope.setBody((SOAPBody)myElement); } } // FIX: do we need this method ? public MessageElement makeNewElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws AxisFault { return new SOAPBody(namespace, localName, prefix, attributes, context, context.getSOAPConstants()); } public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { SOAPBodyElement element = null; if (log.isDebugEnabled()) { log.debug("Enter: BodyBuilder::onStartChild()"); } QName qname = new QName(namespace, localName); SOAPHandler handler = null; /** We're about to create a body element. So we really need * to know at this point if this is an RPC service or not. It's * possible that no one has set the service up until this point, * so if that's the case we should attempt to set it based on the * namespace of the first root body element. Setting the * service may (should?) result in setting the service * description, which can then tell us what to create. */ boolean isRoot = true; String root = attributes.getValue(Constants.URI_DEFAULT_SOAP_ENC, Constants.ATTR_ROOT); if ((root != null) && root.equals("0")) isRoot = false; MessageContext msgContext = context.getMessageContext(); OperationDesc [] operations = null; try { if(msgContext != null) { operations = msgContext.getPossibleOperationsByQName(qname); } // If there's only one match, set it in the MC now if ((operations != null) && (operations.length == 1)) msgContext.setOperation(operations[0]); } catch (org.apache.axis.AxisFault e) { // SAXException is already known to this method, so I // don't have an exception-handling propogation explosion. throw new SAXException(e); } Style style = operations == null ? Style.RPC : operations[0].getStyle(); SOAPConstants soapConstants = context.getSOAPConstants(); /** Now we make a plain SOAPBodyElement IF we either: * a) have an non-root element, or * b) have a non-RPC service */ if (localName.equals(Constants.ELEM_FAULT) && namespace.equals(soapConstants.getEnvelopeURI())) { try { element = new SOAPFault(namespace, localName, prefix, attributes, context); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } element.setEnvelope(context.getEnvelope()); handler = new SOAPFaultBuilder((SOAPFault)element, context); } else if (!gotRPCElement) { if (isRoot && (style != Style.MESSAGE)) { gotRPCElement = true; try { element = new RPCElement(namespace, localName, prefix, attributes, context, operations); } catch (org.apache.axis.AxisFault e) { // SAXException is already known to this method, so I // don't have an exception-handling propogation explosion. // throw new SAXException(e); } // Only deserialize this way if there is a unique operation // for this QName. If there are overloads, // we'll need to start recording. If we're making a high- // fidelity recording anyway, don't bother (for now). if (msgContext != null && !msgContext.isHighFidelity() && (operations == null || operations.length == 1)) { ((RPCElement)element).setNeedDeser(false); boolean isResponse = false; if (msgContext.getCurrentMessage() != null && Message.RESPONSE.equals(msgContext.getCurrentMessage().getMessageType())) isResponse = true; handler = new RPCHandler((RPCElement)element, isResponse); if (operations != null) { ((RPCHandler)handler).setOperation(operations[0]); msgContext.setOperation(operations[0]); } } } } if (element == null) { if ((style == Style.RPC) && soapConstants == SOAPConstants.SOAP12_CONSTANTS) { throw new SAXException(Messages.getMessage("onlyOneBodyFor12")); } try { element = new SOAPBodyElement(namespace, localName, prefix, attributes, context); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } if (element.getFixupDeserializer() != null) handler = (SOAPHandler)element.getFixupDeserializer(); } if (handler == null) handler = new SOAPHandler(); handler.myElement = element; //context.pushNewElement(element); if (log.isDebugEnabled()) { log.debug("Exit: BodyBuilder::onStartChild()"); } return handler; } public void onEndChild(String namespace, String localName, DeserializationContext context) { } }
7,577
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPHandler.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** A <code>SOAPHandler</code> * * @author Glen Daniels (gdaniels@allaire.com) */ import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.axis.utils.StringUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.soap.SOAPException; import java.io.CharArrayWriter; public class SOAPHandler extends DefaultHandler { public MessageElement myElement = null; private MessageElement[] myElements; private int myIndex = 0; private CharArrayWriter val; public SOAPHandler() { } /** * This constructor allows deferred setting of any elements * @param elements array of message elements to be populated * @param index position in array where the message element is to be created */ public SOAPHandler(MessageElement[] elements, int index) { myElements = elements; myIndex = index; } public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { SOAPConstants soapConstants = context.getSOAPConstants(); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { String encodingStyle = attributes.getValue(Constants.URI_SOAP12_ENV, Constants.ATTR_ENCODING_STYLE); if (encodingStyle != null && !encodingStyle.equals("") && !encodingStyle.equals(Constants.URI_SOAP12_NOENC) && !Constants.isSOAP_ENC(encodingStyle)) { TypeMappingRegistry tmr = context.getTypeMappingRegistry(); // TODO: both soap encoding style is registered ? if (tmr.getTypeMapping(encodingStyle) == tmr.getDefaultTypeMapping()) { AxisFault fault = new AxisFault(Constants.FAULT_SOAP12_DATAENCODINGUNKNOWN, null, Messages.getMessage("invalidEncodingStyle"), null, null, null); throw new SAXException(fault); } } } // By default, make a new element if (!context.isDoneParsing() && !context.isProcessingRef()) { if (myElement == null) { try { myElement = makeNewElement(namespace, localName, prefix, attributes, context); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } } context.pushNewElement(myElement); } } public MessageElement makeNewElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws AxisFault { return new MessageElement(namespace, localName, prefix, attributes, context); } public void endElement(String namespace, String localName, DeserializationContext context) throws SAXException { if (myElement != null) { addTextNode(); if (myElements != null) { myElements[myIndex] = myElement; } myElement.setEndIndex(context.getCurrentRecordPos()); } } public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { addTextNode(); SOAPHandler handler = new SOAPHandler(); return handler; } private void addTextNode() throws SAXException { if (myElement != null) { if (val != null && val.size() > 0) { String s = StringUtils.strip(val.toString()); val.reset(); // we need to check the length of STRIPPED string // to avoid appending ignorable white spaces as // message elmenet's child. // (SOAPHeader and others does not accept text children... // but in SAAJ 1.2's DOM view, this could be incorrect. // we need to keep the ignorable white spaces later) if(s.length()>0){ try { // add unstripped string as text child. myElement.addTextNode(s); } catch (SOAPException e) { throw new SAXException(e); } } } } } public void onEndChild(String namespace, String localName, DeserializationContext context) throws SAXException { } public void characters(char[] chars, int start, int end) throws SAXException { if (val == null) { val = new CharArrayWriter(); } val.write(chars, start, end); } }
7,578
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/CDATAImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** * * @author Heejune Ahn (cityboy@tmax.co.kr) */ public class CDATAImpl extends org.apache.axis.message.Text implements org.w3c.dom.CDATASection { public CDATAImpl(String text) { super(text); } public boolean isComment() { return false; } static final String cdataUC = "<![CDATA["; static final String cdataLC = "<![cdata["; }
7,579
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/Detail.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import javax.xml.soap.DetailEntry; import javax.xml.soap.Name; import javax.xml.soap.SOAPException; import java.util.Iterator; /** * Detail Container implementation * * @author Davanum Srinivas (dims@yahoo.com) */ public class Detail extends SOAPFaultElement implements javax.xml.soap.Detail { public Detail() { } /** * Creates a new <code>DetailEntry</code> object with the given * name and adds it to this <code>Detail</code> object. * @param name a <code>Name</code> object identifying the new <code>DetailEntry</code> object * @return DetailEntry. * @throws SOAPException thrown when there is a problem in adding a DetailEntry object to this Detail object. */ public DetailEntry addDetailEntry(Name name) throws SOAPException { org.apache.axis.message.DetailEntry entry = new org.apache.axis.message.DetailEntry(name); addChildElement(entry); return entry; } /** * Gets a list of the detail entries in this <code>Detail</code> object. * @return an <code>Iterator</code> object over the <code>DetailEntry</code> * objects in this <code>Detail</code> object */ public Iterator getDetailEntries() { return this.getChildElements(); } }
7,580
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/NamedNodeMapImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import java.util.Iterator; import java.util.Vector; /** * A W3C simple DOM NameNodeMap implementation * * @author Heejune Ahn (cityboy@tmax.co.kr) */ public class NamedNodeMapImpl implements NamedNodeMap { /** Nodes. */ protected Vector nodes; static private Document doc = null; static{ try { org.w3c.dom.Document doc = org.apache.axis.utils.XMLUtils.newDocument(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new org.apache.axis.InternalException(e); } } public NamedNodeMapImpl() { nodes = new Vector(); } /** * Retrieves a node specified by name. * @param name The <code>nodeName</code> of a node to retrieve. * @return A <code>Node</code> (of any type) with the specified * <code>nodeName</code>, or <code>null</code> if it does not identify * any node in this map. */ public Node getNamedItem(String name){ if(name == null ){ Thread.dumpStack(); throw new java.lang.IllegalArgumentException("local name = null"); } for(Iterator iter = nodes.iterator(); iter.hasNext();){ Attr attr = (Attr)iter.next(); if(name.equals(attr.getName())){ return attr; } } return null; } /** * Adds a node using its <code>nodeName</code> attribute. If a node with * that name is already present in this map, it is replaced by the new * one. * <br>As the <code>nodeName</code> attribute is used to derive the name * which the node must be stored under, multiple nodes of certain types * (those that have a "special" string value) cannot be stored as the * names would clash. This is seen as preferable to allowing nodes to be * aliased. * @param arg A node to store in this map. The node will later be * accessible using the value of its <code>nodeName</code> attribute. * @return If the new <code>Node</code> replaces an existing node the * replaced <code>Node</code> is returned, otherwise <code>null</code> * is returned. * @exception DOMException * WRONG_DOCUMENT_ERR: Raised if <code>arg</code> was created from a * different document than the one that created this map. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly. * <br>INUSE_ATTRIBUTE_ERR: Raised if <code>arg</code> is an * <code>Attr</code> that is already an attribute of another * <code>Element</code> object. The DOM user must explicitly clone * <code>Attr</code> nodes to re-use them in other elements. * <br>HIERARCHY_REQUEST_ERR: Raised if an attempt is made to add a node * doesn't belong in this NamedNodeMap. Examples would include trying * to insert something other than an Attr node into an Element's map * of attributes, or a non-Entity node into the DocumentType's map of * Entities. */ public Node setNamedItem(Node arg) throws DOMException { String name = arg.getNodeName(); if(name == null ){ Thread.dumpStack(); throw new java.lang.IllegalArgumentException("local name = null"); } for(int i = 0; i < nodes.size(); i++){ Attr attr = (Attr)nodes.get(i); // search if we have already if(name.equals(attr.getName())){ nodes.remove(i); nodes.add(i, arg); return attr; // return old one } } // if cannot found nodes.add(arg); return null; } /** * Removes a node specified by name. When this map contains the attributes * attached to an element, if the removed attribute is known to have a * default value, an attribute immediately appears containing the * default value as well as the corresponding namespace URI, local name, * and prefix when applicable. * @param name The <code>nodeName</code> of the node to remove. * @return The node removed from this map if a node with such a name * exists. * @exception DOMException * NOT_FOUND_ERR: Raised if there is no node named <code>name</code> in * this map. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly. */ public Node removeNamedItem(String name) throws DOMException { if(name == null ){ Thread.dumpStack(); throw new java.lang.IllegalArgumentException("local name = null"); } for(int i = 0; i < nodes.size(); i++){ Attr attr = (Attr)nodes.get(i); // search if we have already if(name.equals(attr.getLocalName())){ nodes.remove(i); return attr; // return old one } } return null; } /** * Returns the <code>index</code>th item in the map. If <code>index</code> * is greater than or equal to the number of nodes in this map, this * returns <code>null</code>. * @param index Index into this map. * @return The node at the <code>index</code>th position in the map, or * <code>null</code> if that is not a valid index. */ public Node item(int index){ return (nodes != null && index < nodes.size()) ? (Node)(nodes.elementAt(index)) : null; } /** * The number of nodes in this map. The range of valid child node indices * is <code>0</code> to <code>length-1</code> inclusive. */ public int getLength(){ return (nodes != null) ? nodes.size() : 0; } /** * Retrieves a node specified by local name and namespace URI. * <br>Documents which do not support the "XML" feature will permit only * the DOM Level 1 calls for creating/setting elements and attributes. * Hence, if you specify a non-null namespace URI, these DOMs will never * find a matching node. * @param namespaceURI The namespace URI of the node to retrieve. * @param localName The local name of the node to retrieve. * @return A <code>Node</code> (of any type) with the specified local * name and namespace URI, or <code>null</code> if they do not * identify any node in this map. * @since DOM Level 2 */ public Node getNamedItemNS(String namespaceURI, String localName){ if(namespaceURI == null) namespaceURI = ""; if(localName == null ){ Thread.dumpStack(); throw new java.lang.IllegalArgumentException("local name = null"); } for(Iterator iter = nodes.iterator(); iter.hasNext();){ Attr attr = (Attr)iter.next(); if(namespaceURI.equals(attr.getNamespaceURI()) && localName.equals(attr.getLocalName())){ return attr; } } return null; } /** * Adds a node using its <code>namespaceURI</code> and * <code>localName</code>. If a node with that namespace URI and that * local name is already present in this map, it is replaced by the new * one. * @param arg A node to store in this map. The node will later be * accessible using the value of its <code>namespaceURI</code> and * <code>localName</code> attributes. * @return If the new <code>Node</code> replaces an existing node the * replaced <code>Node</code> is returned, otherwise <code>null</code> * is returned. * @exception DOMException * WRONG_DOCUMENT_ERR: Raised if <code>arg</code> was created from a * different document than the one that created this map. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly. * <br>INUSE_ATTRIBUTE_ERR: Raised if <code>arg</code> is an * <code>Attr</code> that is already an attribute of another * <code>Element</code> object. The DOM user must explicitly clone * <code>Attr</code> nodes to re-use them in other elements. * <br>HIERARCHY_REQUEST_ERR: Raised if an attempt is made to add a node * doesn't belong in this NamedNodeMap. Examples would include trying * to insert something other than an Attr node into an Element's map * of attributes, or a non-Entity node into the DocumentType's map of * Entities. * <br>NOT_SUPPORTED_ERR: Always thrown if the current document does not * support the <code>"XML"</code> feature, since namespaces were * defined by XML. * @since DOM Level 2 */ public Node setNamedItemNS(Node arg) throws DOMException { String namespaceURI = arg.getNamespaceURI(); String localName = arg.getLocalName(); if(namespaceURI == null) namespaceURI = ""; if(localName == null ){ Thread.dumpStack(); throw new java.lang.IllegalArgumentException("local name = null"); } for(int i = 0; i < nodes.size(); i++){ Attr attr = (Attr)nodes.get(i); // search if we have already if(namespaceURI.equals(attr.getNamespaceURI()) && namespaceURI.equals(attr.getLocalName())){ nodes.remove(i); nodes.add(i, arg); return attr; // return old one } } // if cannot found nodes.add(arg); return null; } /** * Removes a node specified by local name and namespace URI. A removed * attribute may be known to have a default value when this map contains * the attributes attached to an element, as returned by the attributes * attribute of the <code>Node</code> interface. If so, an attribute * immediately appears containing the default value as well as the * corresponding namespace URI, local name, and prefix when applicable. * <br>Documents which do not support the "XML" feature will permit only * the DOM Level 1 calls for creating/setting elements and attributes. * Hence, if you specify a non-null namespace URI, these DOMs will never * find a matching node. * @param namespaceURI The namespace URI of the node to remove. * @param localName The local name of the node to remove. * @return The node removed from this map if a node with such a local * name and namespace URI exists. * @exception DOMException * NOT_FOUND_ERR: Raised if there is no node with the specified * <code>namespaceURI</code> and <code>localName</code> in this map. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly. * @since DOM Level 2 */ public Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException{ if(namespaceURI == null) namespaceURI = ""; if(localName == null ){ Thread.dumpStack(); throw new java.lang.IllegalArgumentException("local name = null"); } for(int i = 0; i < nodes.size(); i++){ Attr attr = (Attr)nodes.get(i); // search if we have already if(namespaceURI.equals(attr.getNamespaceURI()) && localName.equals(attr.getLocalName())){ nodes.remove(i); return attr; // return old one } } return null; } }
7,581
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPDocumentImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import javax.xml.namespace.QName; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.SOAPPart; import org.apache.axis.utils.Mapping; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.SOAPException; /** * SOAPDcoumentImpl implements the Document API for SOAPPART. At the moment, it * again delgate the XERCES DOM Implementation Here is my argument on it: I * guess that there is 3 way to implement this. - fully implement the DOM API * here myself. =&gt; This is too much and duplicated work. - extends XERCES * Implementation =&gt; this makes we are fixed to one Implementation - choose * delgate depends on the user's parser preference =&gt; This is the practically * best solution I have now * * @author Heejune Ahn (cityboy@tmax.co.kr) * */ public class SOAPDocumentImpl implements org.w3c.dom.Document, java.io.Serializable { // Depending on the user's parser preference protected Document delegate = null; protected SOAPPart soapPart = null; /** * Construct the Document * * @param sp the soap part */ public SOAPDocumentImpl(SOAPPart sp) { try { delegate = XMLUtils.newDocument(); } catch (ParserConfigurationException e) { // Do nothing } soapPart = sp; } /** * TODO: link with SOAP * * @return */ public DocumentType getDoctype() { return delegate.getDoctype(); } public DOMImplementation getImplementation() { return delegate.getImplementation(); } /** * should not be called, the method will be handled in SOAPPart * * @return */ public Element getDocumentElement() { return soapPart.getDocumentElement(); } /** * based on the tagName, we will make different kind SOAP Elements Instance * Is really we can determine the Type by the Tagname??? * * TODO: verify this method * * @param tagName * @return @throws * DOMException */ public org.w3c.dom.Element createElement(String tagName) throws DOMException { int index = tagName.indexOf(":"); String prefix, localname; if (index < 0) { prefix = ""; localname = tagName; } else { prefix = tagName.substring(0, index); localname = tagName.substring(index + 1); } try { SOAPEnvelope soapenv = (org.apache.axis.message.SOAPEnvelope) soapPart.getEnvelope(); if (soapenv != null) { if (tagName.equalsIgnoreCase(Constants.ELEM_ENVELOPE)) new SOAPEnvelope(); if (tagName.equalsIgnoreCase(Constants.ELEM_HEADER)) return new SOAPHeader(soapenv, soapenv.getSOAPConstants()); if (tagName.equalsIgnoreCase(Constants.ELEM_BODY)) return new SOAPBody(soapenv, soapenv.getSOAPConstants()); if (tagName.equalsIgnoreCase(Constants.ELEM_FAULT)) return new SOAPEnvelope(); if (tagName.equalsIgnoreCase(Constants.ELEM_FAULT_DETAIL)) return new SOAPFault(new AxisFault(tagName)); else { return new MessageElement("", prefix, localname); } } else { return new MessageElement("", prefix, localname); } } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * * Creates an empty <code>DocumentFragment</code> object. * * @return A new <code>DocumentFragment</code>. */ // TODO: not implemented yet public DocumentFragment createDocumentFragment() { return delegate.createDocumentFragment(); } /** * Creates a <code>Text</code> node given the specified string. * * @param data * The data for the node. * @return The new <code>Text</code> object. */ public org.w3c.dom.Text createTextNode(String data) { org.apache.axis.message.Text me = new org.apache.axis.message.Text(delegate.createTextNode(data)); me.setOwnerDocument(soapPart); return me; } /** * Creates a <code>Comment</code> node given the specified string. * * @param data * The data for the node. * @return The new <code>Comment</code> object. */ public Comment createComment(String data) { return new org.apache.axis.message.CommentImpl(data); } /** * Creates a <code>CDATASection</code> node whose value is the specified * string. * * @param data * The data for the <code>CDATASection</code> contents. * @return The new <code>CDATASection</code> object. * @exception DOMException * NOT_SUPPORTED_ERR: Raised if this document is an HTML * document. */ public CDATASection createCDATASection(String data) throws DOMException { return new CDATAImpl(data); } /** * Creates a <code>ProcessingInstruction</code> node given the specified * name and data strings. * * @param target * The target part of the processing instruction. * @param data * The data for the node. * @return The new <code>ProcessingInstruction</code> object. * @exception DOMException * INVALID_CHARACTER_ERR: Raised if the specified target * contains an illegal character. <br>NOT_SUPPORTED_ERR: * Raised if this document is an HTML document. */ public ProcessingInstruction createProcessingInstruction( String target, String data) throws DOMException { throw new java.lang.UnsupportedOperationException( "createProcessingInstruction"); } /** * TODO: How Axis will maintain the Attribute representation ? */ public Attr createAttribute(String name) throws DOMException { return delegate.createAttribute(name); } /** * @param name * @return @throws * DOMException */ public EntityReference createEntityReference(String name) throws DOMException { throw new java.lang.UnsupportedOperationException( "createEntityReference"); } // implemented by yoonforh 2004-07-30 02:48:50 public Node importNode(Node importedNode, boolean deep) throws DOMException { Node targetNode = null; int type = importedNode.getNodeType(); switch (type) { case ELEMENT_NODE : Element el = (Element) importedNode; if (deep) { targetNode = new SOAPBodyElement(el); break; } SOAPBodyElement target = new SOAPBodyElement(); org.w3c.dom.NamedNodeMap attrs = el.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { org.w3c.dom.Node att = attrs.item(i); if (att.getNamespaceURI() != null && att.getPrefix() != null && att.getNamespaceURI().equals(Constants.NS_URI_XMLNS) && att.getPrefix().equals("xmlns")) { Mapping map = new Mapping(att.getNodeValue(), att.getLocalName()); target.addMapping(map); } if (att.getLocalName() != null) { target.addAttribute(att.getPrefix(), att.getNamespaceURI(), att.getLocalName(), att.getNodeValue()); } else if (att.getNodeName() != null) { target.addAttribute(att.getPrefix(), att.getNamespaceURI(), att.getNodeName(), att.getNodeValue()); } } if (el.getLocalName() == null) { target.setName(el.getNodeName()); } else { target.setQName(new QName(el.getNamespaceURI(), el.getLocalName())); } targetNode = target; break; case ATTRIBUTE_NODE : if (importedNode.getLocalName() == null) { targetNode = createAttribute(importedNode.getNodeName()); } else { targetNode = createAttributeNS(importedNode.getNamespaceURI(), importedNode.getLocalName()); } break; case TEXT_NODE : targetNode = createTextNode(importedNode.getNodeValue()); break; case CDATA_SECTION_NODE : targetNode = createCDATASection(importedNode.getNodeValue()); break; case COMMENT_NODE : targetNode = createComment(importedNode.getNodeValue()); break; case DOCUMENT_FRAGMENT_NODE : targetNode = createDocumentFragment(); if (deep) { org.w3c.dom.NodeList children = importedNode.getChildNodes(); for (int i = 0; i < children.getLength(); i++){ targetNode.appendChild(importNode(children.item(i), true)); } } break; case ENTITY_REFERENCE_NODE : targetNode = createEntityReference(importedNode.getNodeName()); break; case PROCESSING_INSTRUCTION_NODE : ProcessingInstruction pi = (ProcessingInstruction) importedNode; targetNode = createProcessingInstruction(pi.getTarget(), pi.getData()); break; case ENTITY_NODE : // TODO : ... throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Entity nodes are not supported."); case NOTATION_NODE : // TODO : any idea? throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Notation nodes are not supported."); case DOCUMENT_TYPE_NODE : throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "DocumentType nodes cannot be imported."); case DOCUMENT_NODE : throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Document nodes cannot be imported."); default : throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Node type (" + type + ") cannot be imported."); } return targetNode; } /** * Return SOAPElements (what if they want SOAPEnvelope or Header/Body?) * * @param namespaceURI * @param qualifiedName * @return @throws * DOMException */ public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException { org.apache.axis.soap.SOAPConstants soapConstants = null; if (Constants.URI_SOAP11_ENV.equals(namespaceURI)) { soapConstants = org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS; } else if (Constants.URI_SOAP12_ENV.equals(namespaceURI)) { soapConstants = org.apache.axis.soap.SOAPConstants.SOAP12_CONSTANTS; } // For special SOAP Element MessageElement me = null; if (soapConstants != null) { if (qualifiedName.equals(Constants.ELEM_ENVELOPE)) { // TODO: confirm SOAP 1.1! me = new SOAPEnvelope(soapConstants); } else if (qualifiedName.equals(Constants.ELEM_HEADER)) { me = new SOAPHeader(null, soapConstants); // Dummy SOAPEnv required? } else if (qualifiedName.equals(Constants.ELEM_BODY)) { me = new SOAPBody(null, soapConstants); } else if (qualifiedName.equals(Constants.ELEM_FAULT)) { me = null; } else if (qualifiedName.equals(Constants.ELEM_FAULT_DETAIL)) { // TODO: me = null; } else { throw new DOMException( DOMException.INVALID_STATE_ERR, "No such Localname for SOAP URI"); } // TODO: return null; // general Elements } else { me = new MessageElement(namespaceURI, qualifiedName); } if (me != null) me.setOwnerDocument(soapPart); return me; } /** * Attribute is not particularly dealt with in SAAJ. * */ public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException { return delegate.createAttributeNS(namespaceURI, qualifiedName); } /** * search the SOAPPart in order of SOAPHeader and SOAPBody for the * requested Element name * */ public NodeList getElementsByTagNameNS( String namespaceURI, String localName) { try { NodeListImpl list = new NodeListImpl(); if (soapPart != null) { SOAPEnvelope soapEnv = (org.apache.axis.message.SOAPEnvelope) soapPart .getEnvelope(); SOAPHeader header = (org.apache.axis.message.SOAPHeader) soapEnv.getHeader(); if (header != null) { list.addNodeList(header.getElementsByTagNameNS( namespaceURI, localName)); } SOAPBody body = (org.apache.axis.message.SOAPBody) soapEnv.getBody(); if (body != null) { list.addNodeList(body.getElementsByTagNameNS( namespaceURI, localName)); } } return list; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * search the SOAPPart in order of SOAPHeader and SOAPBody for the * requested Element name * */ public NodeList getElementsByTagName(String localName) { try { NodeListImpl list = new NodeListImpl(); if (soapPart != null) { SOAPEnvelope soapEnv = (org.apache.axis.message.SOAPEnvelope) soapPart .getEnvelope(); SOAPHeader header = (org.apache.axis.message.SOAPHeader) soapEnv.getHeader(); if (header != null) { list.addNodeList(header.getElementsByTagName(localName)); } SOAPBody body = (org.apache.axis.message.SOAPBody) soapEnv.getBody(); if (body != null) { list.addNodeList(body.getElementsByTagName(localName)); } } return list; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * Returns the <code>Element</code> whose <code>ID</code> is given by * <code>elementId</code>. If no such element exists, returns <code>null</code>. * Behavior is not defined if more than one element has this <code>ID</code>. * The DOM implementation must have information that says which attributes * are of type ID. Attributes with the name "ID" are not of type ID unless * so defined. Implementations that do not know whether attributes are of * type ID or not are expected to return <code>null</code>. * * @param elementId * The unique <code>id</code> value for an element. * @return The matching element. * @since DOM Level 2 */ public Element getElementById(String elementId) { return delegate.getElementById(elementId); } /** * Node Implementation * */ public String getNodeName() { return null; } public String getNodeValue() throws DOMException { throw new DOMException( DOMException.NO_DATA_ALLOWED_ERR, "Cannot use TextNode.get in " + this); } public void setNodeValue(String nodeValue) throws DOMException { throw new DOMException( DOMException.NO_DATA_ALLOWED_ERR, "Cannot use TextNode.set in " + this); } /** * override it in sub-classes * * @return */ public short getNodeType() { return Node.DOCUMENT_NODE; } public Node getParentNode() { return null; } public NodeList getChildNodes() { try { if (soapPart != null) { NodeListImpl children = new NodeListImpl(); children.addNode(soapPart.getEnvelope()); return children; } else { return NodeListImpl.EMPTY_NODELIST; } } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * Do we have to count the Attributes as node ???? * * @return */ public Node getFirstChild() { try { if (soapPart != null) return (org.apache.axis.message.SOAPEnvelope) soapPart .getEnvelope(); else return null; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * @return */ public Node getLastChild() { try { if (soapPart != null) return (org.apache.axis.message.SOAPEnvelope) soapPart .getEnvelope(); else return null; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } public Node getPreviousSibling() { return null; } public Node getNextSibling() { return null; } public NamedNodeMap getAttributes() { return null; } /** * * we have to have a link to them... */ public Document getOwnerDocument() { return null; } /** */ public Node insertBefore(Node newChild, Node refChild) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public Node replaceChild(Node newChild, Node oldChild) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public Node removeChild(Node oldChild) throws DOMException { try { Node envNode; if (soapPart != null) { envNode = soapPart.getEnvelope(); if (envNode.equals(oldChild)) { return envNode; } } throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } public Node appendChild(Node newChild) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public boolean hasChildNodes() { try { if (soapPart != null) { if (soapPart.getEnvelope() != null) { return true; } } return false; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * TODO: Study it more.... to implement the deep mode correctly. * */ public Node cloneNode(boolean deep) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } /** * TODO: is it OK to simply call the superclass? * */ public void normalize() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } // TODO: fill appropriate features private String[] features = { "foo", "bar" }; private String version = "version 2.0"; public boolean isSupported(String feature, String version) { if (!version.equalsIgnoreCase(version)) return false; else return true; } public String getPrefix() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public void setPrefix(String prefix) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public String getNamespaceURI() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public void setNamespaceURI(String nsURI) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public String getLocalName() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public boolean hasAttributes() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } }
7,582
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPFaultBuilder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.encoding.Callback; import org.apache.axis.encoding.CallbackTarget; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.List; import java.util.Vector; /** * Build a Fault body element. * * @author Sam Ruby (rubys@us.ibm.com) * @author Glen Daniels (gdaniels@apache.org) * @author Tom Jordahl (tomj@macromedia.com) */ public class SOAPFaultBuilder extends SOAPHandler implements Callback { boolean waiting = false; boolean passedEnd = false; protected SOAPFault element; protected DeserializationContext context; static HashMap fields_soap11 = new HashMap(); static HashMap fields_soap12 = new HashMap(); // Fault data protected QName faultCode = null; protected QName[] faultSubCode = null; protected String faultString = null; protected String faultActor = null; protected Element[] faultDetails; protected String faultNode = null; protected SOAPFaultCodeBuilder code; protected Class faultClass = null; protected Object faultData = null; static { fields_soap11.put(Constants.ELEM_FAULT_CODE, Constants.XSD_QNAME); fields_soap11.put(Constants.ELEM_FAULT_STRING, Constants.XSD_STRING); fields_soap11.put(Constants.ELEM_FAULT_ACTOR, Constants.XSD_STRING); fields_soap11.put(Constants.ELEM_FAULT_DETAIL, null); } static { fields_soap12.put(Constants.ELEM_FAULT_REASON_SOAP12, null); fields_soap12.put(Constants.ELEM_FAULT_ROLE_SOAP12, Constants.XSD_STRING); fields_soap12.put(Constants.ELEM_FAULT_NODE_SOAP12, Constants.XSD_STRING); fields_soap12.put(Constants.ELEM_FAULT_DETAIL_SOAP12, null); } public SOAPFaultBuilder(SOAPFault element, DeserializationContext context) { this.element = element; this.context = context; } public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { SOAPConstants soapConstants = context.getSOAPConstants(); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS && attributes.getValue(Constants.URI_SOAP12_ENV, Constants.ATTR_ENCODING_STYLE) != null) { AxisFault fault = new AxisFault(Constants.FAULT_SOAP12_SENDER, null, Messages.getMessage("noEncodingStyleAttrAppear", "Fault"), null, null, null); throw new SAXException(fault); } super.startElement(namespace, localName, prefix, attributes, context); } void setFaultData(Object data) { faultData = data; if (waiting && passedEnd) { // This happened after the end of the <soap:Fault>, so make // sure we set up the fault. createFault(); } waiting = false; } public void setFaultClass(Class faultClass) { this.faultClass = faultClass; } /** * Final call back where we can populate the exception with data. */ public void endElement(String namespace, String localName, DeserializationContext context) throws SAXException { super.endElement(namespace, localName, context); if (!waiting) { createFault(); } else { passedEnd = true; } } void setWaiting(boolean waiting) { this.waiting = waiting; } /** * When we're sure we have everything, this gets called. */ private void createFault() { AxisFault f = null; SOAPConstants soapConstants = context.getMessageContext() == null ? SOAPConstants.SOAP11_CONSTANTS : context.getMessageContext().getSOAPConstants(); if (faultClass != null) { // Custom fault handling try { // If we have an element which is fault data, It can be: // 1. A simple type that needs to be passed in to the constructor // 2. A complex type that is the exception itself if (faultData != null) { if (faultData instanceof AxisFault) { // This is our exception class f = (AxisFault) faultData; } else { // We need to create the exception, // passing the data to the constructor. Class argClass = ConvertWrapper(faultData.getClass()); try { Constructor con = faultClass.getConstructor( new Class[] { argClass }); f = (AxisFault) con.newInstance(new Object[] { faultData }); } catch(Exception e){ // Don't do anything here, since a problem above means // we'll just fall through and use a plain AxisFault. } if (f == null && faultData instanceof Exception) { f = AxisFault.makeFault((Exception)faultData); } } } // If we have an AxisFault, set the fields if (AxisFault.class.isAssignableFrom(faultClass)) { if (f == null) { // this is to support the <exceptionName> detail f = (AxisFault) faultClass.newInstance(); } if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { f.setFaultCode(code.getFaultCode()); SOAPFaultCodeBuilder c = code; while ((c = c.getNext()) != null) { f.addFaultSubCode(c.getFaultCode()); } } else { f.setFaultCode(faultCode); } f.setFaultString(faultString); f.setFaultActor(faultActor); f.setFaultNode(faultNode); f.setFaultDetail(faultDetails); } } catch (Exception e) { // Don't do anything here, since a problem above means // we'll just fall through and use a plain AxisFault. } } if (f == null) { if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { faultCode = code.getFaultCode(); if (code.getNext() != null) { Vector v = new Vector(); SOAPFaultCodeBuilder c = code; while ((c = c.getNext()) != null) v.add(c.getFaultCode()); faultSubCode = (QName[])v.toArray(new QName[v.size()]); } } f = new AxisFault(faultCode, faultSubCode, faultString, faultActor, faultNode, faultDetails); try { Vector headers = element.getEnvelope().getHeaders(); for (int i = 0; i < headers.size(); i++) { SOAPHeaderElement header = (SOAPHeaderElement) headers.elementAt(i); f.addHeader(header); } } catch (AxisFault axisFault) { // What to do here? } } element.setFault(f); } public SOAPHandler onStartChild(String namespace, String name, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { SOAPHandler retHandler = null; SOAPConstants soapConstants = context.getMessageContext() == null ? SOAPConstants.SOAP11_CONSTANTS : context.getMessageContext().getSOAPConstants(); QName qName; // If we found the type for this field, get the deserializer // otherwise, if this is the details element, use the special // SOAPFaultDetailsBuilder handler to take care of custom fault data if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { qName = (QName)fields_soap12.get(name); if (qName == null) { QName thisQName = new QName(namespace, name); if (thisQName.equals(Constants.QNAME_FAULTCODE_SOAP12)) return (code = new SOAPFaultCodeBuilder()); else if (thisQName.equals(Constants.QNAME_FAULTREASON_SOAP12)) return new SOAPFaultReasonBuilder(this); else if (thisQName.equals(Constants.QNAME_FAULTDETAIL_SOAP12)) return new SOAPFaultDetailsBuilder(this); } } else { qName = (QName)fields_soap11.get(name); if (qName == null && name.equals(Constants.ELEM_FAULT_DETAIL)) return new SOAPFaultDetailsBuilder(this); } if (qName != null) { Deserializer currentDeser = context.getDeserializerForType(qName); if (currentDeser != null) { currentDeser.registerValueTarget(new CallbackTarget(this, new QName(namespace, name))); } retHandler = (SOAPHandler) currentDeser; } return retHandler; } public void onEndChild(String namespace, String localName, DeserializationContext context) throws SAXException { if (Constants.ELEM_FAULT_DETAIL.equals(localName)) { MessageElement el = context.getCurElement(); List children = el.getChildren(); if (children != null) { Element [] elements = new Element [children.size()]; for (int i = 0; i < elements.length; i++) { try { Node node = (Node) children.get(i); if (node instanceof MessageElement) { elements[i] = ((MessageElement) node).getAsDOM(); } else if(node instanceof Text){ Document tempDoc = XMLUtils.newDocument(); elements[i] = tempDoc.createElement("text"); elements[i].appendChild(tempDoc.importNode(node,true)); } } catch (Exception e) { throw new SAXException(e); } } faultDetails = elements; } } } /* * Defined by Callback. * This method gets control when the callback is invoked. * @param is the value to set. * @param hint is an Object that provide additional hint information. */ public void setValue(Object value, Object hint) { String local = ((QName)hint).getLocalPart(); if (((QName)hint).getNamespaceURI().equals(Constants.URI_SOAP12_ENV)) { if (local.equals(Constants.ELEM_FAULT_ROLE_SOAP12)) { faultActor = (String) value; } else if (local.equals(Constants.ELEM_TEXT_SOAP12)) { faultString = (String) value; } else if (local.equals(Constants.ELEM_FAULT_NODE_SOAP12)) { faultNode = (String) value; } } else { if (local.equals(Constants.ELEM_FAULT_CODE)) { faultCode = (QName)value; } else if (local.equals(Constants.ELEM_FAULT_STRING)) { faultString = (String) value; } else if (local.equals(Constants.ELEM_FAULT_ACTOR)) { faultActor = (String) value; } } } /** * A simple map of holder objects and their primitive types */ private static HashMap TYPES = new HashMap(7); static { TYPES.put(java.lang.Integer.class, int.class); TYPES.put(java.lang.Float.class, float.class); TYPES.put(java.lang.Boolean.class, boolean.class); TYPES.put(java.lang.Double.class, double.class); TYPES.put(java.lang.Byte.class, byte.class); TYPES.put(java.lang.Short.class, short.class); TYPES.put(java.lang.Long.class, long.class); } /** * Internal method to convert wrapper classes to their base class */ private Class ConvertWrapper(Class cls) { Class ret = (Class) TYPES.get(cls); if (ret != null) { return ret; } return cls; } }
7,583
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPFaultDetailsBuilder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.MessageContext; import org.apache.axis.description.FaultDesc; import org.apache.axis.description.OperationDesc; import org.apache.axis.encoding.Callback; import org.apache.axis.encoding.CallbackTarget; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.util.Iterator; /** * Handle deserializing fault details. * * @author Glen Daniels (gdaniels@apache.org) * @author Tom Jordahl (tomj@macromedia.com) */ public class SOAPFaultDetailsBuilder extends SOAPHandler implements Callback { protected SOAPFaultBuilder builder; public SOAPFaultDetailsBuilder(SOAPFaultBuilder builder) { this.builder = builder; } public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { SOAPConstants soapConstants = context.getSOAPConstants(); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS && attributes.getValue(Constants.URI_SOAP12_ENV, Constants.ATTR_ENCODING_STYLE) != null) { AxisFault fault = new AxisFault(Constants.FAULT_SOAP12_SENDER, null, Messages.getMessage("noEncodingStyleAttrAppear", "Detail"), null, null, null); throw new SAXException(fault); } super.startElement(namespace, localName, prefix, attributes, context); } public SOAPHandler onStartChild(String namespace, String name, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { // Get QName of element QName qn = new QName(namespace, name); // Look for <exceptionName> element and create a class // with that name - this is Axis specific and is // replaced by the Exception map if (name.equals("exceptionName")) { // Set up deser of exception name string Deserializer dser = context.getDeserializerForType(Constants.XSD_STRING); dser.registerValueTarget(new CallbackTarget(this, "exceptionName")); return (SOAPHandler)dser; } // Look up this element in our faultMap // if we find a match, this element is the fault data MessageContext msgContext = context.getMessageContext(); SOAPConstants soapConstants = Constants.DEFAULT_SOAP_VERSION; OperationDesc op = null; if (msgContext != null) { soapConstants = msgContext.getSOAPConstants(); op = msgContext.getOperation(); } Class faultClass = null; QName faultXmlType = null; if (op != null) { FaultDesc faultDesc = null; // allow fault type to be denoted in xsi:type faultXmlType = context.getTypeFromAttributes(namespace, name, attributes); if (faultXmlType != null) { faultDesc = op.getFaultByXmlType(faultXmlType); } // If we didn't get type information, look up QName of fault if (faultDesc == null) { faultDesc = op.getFaultByQName(qn); if ((faultXmlType == null) && (faultDesc != null)) { faultXmlType = faultDesc.getXmlType(); } } if (faultDesc == null && op.getFaults() != null) { Iterator i = op.getFaults().iterator(); while(i.hasNext()) { FaultDesc fdesc = (FaultDesc) i.next(); if(fdesc.getClassName().equals(name)) { faultDesc = fdesc; faultXmlType = fdesc.getXmlType(); break; } } } // Set the class if we found a description if (faultDesc != null) { try { faultClass = ClassUtils.forName(faultDesc.getClassName()); } catch (ClassNotFoundException e) { // Just create an AxisFault, no custom exception } } } else { faultXmlType = context.getTypeFromAttributes(namespace, name, attributes); } if (faultClass == null) { faultClass = context.getTypeMapping().getClassForQName(faultXmlType); } if(faultClass != null && faultXmlType != null) { builder.setFaultClass(faultClass); builder.setWaiting(true); // register callback for the data, use the xmlType from fault info Deserializer dser = null; if (attributes.getValue(soapConstants.getAttrHref()) == null) { dser = context.getDeserializerForType(faultXmlType); } else { dser = new DeserializerImpl(); dser.setDefaultType(faultXmlType); } if (dser != null) { dser.registerValueTarget(new CallbackTarget(this, "faultData")); } return (SOAPHandler)dser; } return null; } /* * Defined by Callback. * This method gets control when the callback is invoked. * @param is the value to set. * @param hint is an Object that provide additional hint information. */ public void setValue(Object value, Object hint) { if ("faultData".equals(hint)) { builder.setFaultData(value); } else if ("exceptionName".equals(hint)) { String faultClassName = (String) value; try { Class faultClass = ClassUtils.forName(faultClassName); builder.setFaultClass(faultClass); } catch (ClassNotFoundException e) { // Just create an AxisFault, no custom exception } } } }
7,584
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPBodyElement.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.AxisFault; import org.apache.axis.InternalException; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import javax.xml.soap.Name; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import java.io.InputStream; /** * A Body element. */ public class SOAPBodyElement extends MessageElement implements javax.xml.soap.SOAPBodyElement { private static Log log = LogFactory.getLog(SOAPBodyElement.class.getName()); public SOAPBodyElement(String namespace, String localPart, String prefix, Attributes attributes, DeserializationContext context) throws AxisFault { super(namespace, localPart, prefix, attributes, context); } public SOAPBodyElement(Name name) { super(name); } public SOAPBodyElement(QName qname) { super(qname); } public SOAPBodyElement(QName qname, Object value) { super(qname, value); } public SOAPBodyElement(Element elem) { super(elem); } public SOAPBodyElement() { } public SOAPBodyElement(InputStream input) { super( getDocumentElement(input) ); } public SOAPBodyElement(String namespace, String localPart) { super(namespace, localPart); } private static Element getDocumentElement(InputStream input) { try { return XMLUtils.newDocument(input).getDocumentElement(); } catch (Exception e) { throw new InternalException(e); } } public void setParentElement(SOAPElement parent) throws SOAPException { if(parent == null) { throw new IllegalArgumentException(Messages.getMessage("nullParent00")); } // migration aid if (parent instanceof SOAPEnvelope) { log.warn(Messages.getMessage("bodyElementParent")); parent = ((SOAPEnvelope)parent).getBody(); } if (!(parent instanceof SOAPBody) && !(parent instanceof RPCElement)) { throw new IllegalArgumentException(Messages.getMessage("illegalArgumentException00")); } super.setParentElement(parent); } }
7,585
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/IDResolver.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** * * @author Glen Daniels (gdaniels@allaire.com) */ public interface IDResolver { /** * Get the object refereced by the href */ public Object getReferencedObject(String href); /** * Store the object associated with id */ public void addReferencedObject(String id, Object referent); }
7,586
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/RPCParam.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.ParameterDesc; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.constants.Style; import org.apache.axis.Constants; import org.apache.axis.MessageContext; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; /** An RPC parameter * * @author Glen Daniels (gdaniels@apache.org) */ public class RPCParam extends MessageElement implements Serializable { protected static Log log = LogFactory.getLog(RPCParam.class.getName()); private Object value = null; private int countSetCalls = 0; // counts number of calls to set private ParameterDesc paramDesc; /** * Do we definitely want (or don't want) to send xsi:types? If null * (the default), just do whatever our SerializationContext is configured * to do. If TRUE or FALSE, the SerializationContext will do what we * want. */ private Boolean wantXSIType = null; private static Method valueSetMethod; static { Class cls = RPCParam.class; try { valueSetMethod = cls.getMethod("set", new Class[] {Object.class}); } catch (NoSuchMethodException e) { log.error(Messages.getMessage("noValue00", "" + e)); throw new RuntimeException(e.getMessage()); } } /** Constructor for building up messages. */ public RPCParam(String name, Object value) { this(new QName("", name), value); } public RPCParam(QName qname, Object value) { super(qname); if (value instanceof java.lang.String) { try { this.addTextNode((String) value); } catch (SOAPException e) { throw new RuntimeException(Messages.getMessage("cannotCreateTextNode00")); } } else { this.value = value; } } public RPCParam(String namespace, String name, Object value) { this(new QName(namespace, name), value); } public void setRPCCall(RPCElement call) { parent = call; } public Object getObjectValue() { return value; } public void setObjectValue(Object value) { this.value = value; } /** * This set method is registered during deserialization * to set the deserialized value. * If the method is called multiple times, the * value is automatically changed into a container to * hold all of the values. * @param newValue is the deserialized object */ public void set(Object newValue) { countSetCalls++; // If this is the first call, // simply set the value. if (countSetCalls==1) { this.value = newValue; return; } // If this is the second call, create an // ArrayList to hold all the values else if (countSetCalls==2) { ArrayList list = new ArrayList(); list.add(this.value); this.value = list; } // Add the new value to the list ((ArrayList) this.value).add(newValue); } public static Method getValueSetMethod() { return valueSetMethod; } public ParameterDesc getParamDesc() { return paramDesc; } public void setParamDesc(ParameterDesc paramDesc) { this.paramDesc = paramDesc; } public void setXSITypeGeneration(Boolean value) { this.wantXSIType = value; } public Boolean getXSITypeGeneration() { return this.wantXSIType; } public void serialize(SerializationContext context) throws IOException { // Set the javaType to value's class unless // parameter description information exists. // Set the xmlType using the parameter description // information. (an xmlType=null causes the // serialize method to search for a compatible xmlType) Class javaType = value == null ? null: value.getClass(); QName xmlType = null; // we'll send a null unless our description tells us // that we may be omitted Boolean sendNull = Boolean.TRUE; if (paramDesc != null) { if (javaType == null) { javaType = paramDesc.getJavaType() != null ? paramDesc.getJavaType(): javaType; } else if (!(javaType.equals(paramDesc.getJavaType()))) { Class clazz = JavaUtils.getPrimitiveClass(javaType); if(clazz == null || !clazz.equals(paramDesc.getJavaType())) { if (!(javaType.equals( JavaUtils.getHolderValueType(paramDesc.getJavaType())))) { // This must (assumedly) be a polymorphic type - in ALL // such cases, we must send an xsi:type attribute. wantXSIType = Boolean.TRUE; } } } xmlType = paramDesc.getTypeQName(); QName itemQName = paramDesc.getItemQName(); if (itemQName == null) { MessageContext mc = context.getMessageContext(); if (mc != null && mc.getOperation() != null && mc.getOperation().getStyle() == Style.DOCUMENT) { itemQName = Constants.QNAME_LITERAL_ITEM; } } context.setItemQName(itemQName); QName itemType = paramDesc.getItemType(); context.setItemType(itemType); // don't send anything if we're able to be omitted, // although we'll prefer to send xsi:nill if possible if (paramDesc.isOmittable() && !paramDesc.isNillable()) sendNull = Boolean.FALSE; } context.serialize(getQName(), // element qname null, // no extra attrs value, // value xmlType, // java/xml type sendNull, wantXSIType); } private void writeObject(ObjectOutputStream out) throws IOException { if (getQName() == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeObject(getQName().getNamespaceURI()); out.writeObject(getQName().getLocalPart()); } out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { if (in.readBoolean()) { setQName(new QName((String)in.readObject(), (String)in.readObject())); } in.defaultReadObject(); } protected void outputImpl(SerializationContext context) throws Exception { serialize(context); } public String getValue() { return getValueDOM(); } /** * @see javax.xml.soap.SOAPElement#addTextNode(java.lang.String) */ public SOAPElement addTextNode(String s) throws SOAPException { value = s; return super.addTextNode(s); } /** * @see javax.xml.soap.Node#setValue(java.lang.String) */ public void setValue(String value) { this.value = value; super.setValue(value); } }
7,587
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SAX2EventRecorder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.encoding.DeserializationContext; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; /** * This class records SAX2 Events and allows * the events to be replayed by start and stop index */ public class SAX2EventRecorder { private static final Integer Z = new Integer(0); private static final Integer STATE_START_DOCUMENT = new Integer(1); private static final Integer STATE_END_DOCUMENT = new Integer(2); private static final Integer STATE_START_PREFIX_MAPPING = new Integer(3); private static final Integer STATE_END_PREFIX_MAPPING = new Integer(4); private static final Integer STATE_START_ELEMENT = new Integer(5); private static final Integer STATE_END_ELEMENT = new Integer(6); private static final Integer STATE_CHARACTERS = new Integer(7); private static final Integer STATE_IGNORABLE_WHITESPACE = new Integer(8); private static final Integer STATE_PROCESSING_INSTRUCTION = new Integer(9); private static final Integer STATE_SKIPPED_ENTITY = new Integer(10); // This is a "custom" event which tells DeserializationContexts // that the current element is moving down the stack... private static final Integer STATE_NEWELEMENT = new Integer(11); // Lexical handler events... private static final Integer STATE_START_DTD = new Integer(12); private static final Integer STATE_END_DTD = new Integer(13); private static final Integer STATE_START_ENTITY = new Integer(14); private static final Integer STATE_END_ENTITY = new Integer(15); private static final Integer STATE_START_CDATA = new Integer(16); private static final Integer STATE_END_CDATA = new Integer(17); private static final Integer STATE_COMMENT = new Integer(18); objArrayVector events = new objArrayVector(); public void clear() { events = new objArrayVector(); } public int getLength() { return events.getLength(); } public int startDocument() { return events.add(STATE_START_DOCUMENT, Z,Z,Z,Z); } public int endDocument() { return events.add(STATE_END_DOCUMENT, Z,Z,Z,Z); } public int startPrefixMapping(String p1, String p2) { return events.add(STATE_START_PREFIX_MAPPING, p1, p2, Z,Z); } public int endPrefixMapping(String p1) { return events.add(STATE_END_PREFIX_MAPPING, p1,Z,Z,Z); } public int startElement(String p1, String p2, String p3, org.xml.sax.Attributes p4) { return events.add(STATE_START_ELEMENT, p1, p2, p3, p4); } public int endElement(String p1, String p2, String p3) { return events.add(STATE_END_ELEMENT, p1, p2, p3, Z); } public int characters(char[] p1, int p2, int p3) { return events.add(STATE_CHARACTERS, (Object)clone(p1, p2, p3), Z, Z, Z); } public int ignorableWhitespace(char[] p1, int p2, int p3) { return events.add(STATE_IGNORABLE_WHITESPACE, (Object)clone(p1, p2, p3), Z, Z, Z); } public int processingInstruction(String p1, String p2) { return events.add(STATE_PROCESSING_INSTRUCTION, p1, p2, Z,Z); } public int skippedEntity(String p1) { return events.add(STATE_SKIPPED_ENTITY, p1, Z,Z,Z); } public void startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId) { events.add(STATE_START_DTD, name, publicId, systemId, Z); } public void endDTD() { events.add(STATE_END_DTD, Z, Z, Z, Z); } public void startEntity(java.lang.String name) { events.add(STATE_START_ENTITY, name, Z, Z, Z); } public void endEntity(java.lang.String name) { events.add(STATE_END_ENTITY, name, Z, Z, Z); } public void startCDATA() { events.add(STATE_START_CDATA, Z, Z, Z, Z); } public void endCDATA() { events.add(STATE_END_CDATA, Z, Z, Z, Z); } public void comment(char[] ch, int start, int length) { events.add(STATE_COMMENT, (Object)clone(ch, start, length), Z, Z, Z); } public int newElement(MessageElement elem) { return events.add(STATE_NEWELEMENT, elem, Z,Z,Z); } public void replay(ContentHandler handler) throws SAXException { if (events.getLength() > 0) { replay(0, events.getLength() - 1, handler); } } public void replay(int start, int stop, ContentHandler handler) throws SAXException { // Special case : play the whole thing for [0, -1] if ((start == 0) && (stop == -1)) { replay(handler); return; } if (stop + 1 > events.getLength() || stop < start) { return; // should throw an error here } LexicalHandler lexicalHandler = null; if (handler instanceof LexicalHandler) { lexicalHandler = (LexicalHandler) handler; } for (int n = start; n <= stop; n++) { Object event = events.get(n,0); if (event == STATE_START_ELEMENT) { handler.startElement((String)events.get(n,1), (String)events.get(n,2), (String)events.get(n,3), (org.xml.sax.Attributes)events.get(n,4)); } else if (event == STATE_END_ELEMENT) { handler.endElement((String)events.get(n,1), (String)events.get(n,2), (String)events.get(n,3)); } else if (event == STATE_CHARACTERS) { char[] data = (char[])events.get(n,1); handler.characters(data, 0, data.length); } else if (event == STATE_IGNORABLE_WHITESPACE) { char[] data = (char[])events.get(n,1); handler.ignorableWhitespace(data, 0, data.length); } else if (event == STATE_PROCESSING_INSTRUCTION) { handler.processingInstruction((String)events.get(n,1), (String)events.get(n,2)); } else if (event == STATE_SKIPPED_ENTITY) { handler.skippedEntity((String)events.get(n,1)); } else if (event == STATE_START_DOCUMENT) { handler.startDocument(); } else if (event == STATE_END_DOCUMENT) { handler.endDocument(); } else if (event == STATE_START_PREFIX_MAPPING) { handler.startPrefixMapping((String)events.get(n, 1), (String)events.get(n, 2)); } else if (event == STATE_END_PREFIX_MAPPING) { handler.endPrefixMapping((String)events.get(n, 1)); } else if (event == STATE_START_DTD && lexicalHandler != null) { lexicalHandler.startDTD((String)events.get(n,1), (String)events.get(n,2), (String)events.get(n,3)); } else if (event == STATE_END_DTD && lexicalHandler != null) { lexicalHandler.endDTD(); } else if (event == STATE_START_ENTITY && lexicalHandler != null) { lexicalHandler.startEntity((String)events.get(n,1)); } else if (event == STATE_END_ENTITY && lexicalHandler != null) { lexicalHandler.endEntity((String)events.get(n,1)); } else if (event == STATE_START_CDATA && lexicalHandler != null) { lexicalHandler.startCDATA(); } else if (event == STATE_END_CDATA && lexicalHandler != null) { lexicalHandler.endCDATA(); } else if (event == STATE_COMMENT && lexicalHandler != null) { char[] data = (char[])events.get(n,1); lexicalHandler.comment(data, 0, data.length); } else if (event == STATE_NEWELEMENT) { if (handler instanceof DeserializationContext) { DeserializationContext context = (DeserializationContext)handler; context.setCurElement( (MessageElement)(events.get(n,1))); } } } } private static char[] clone(char[] in, int off, int len) { char[] out = new char[len]; System.arraycopy(in, off, out, 0, len); return out; } ///////////////////////////////////////////// class objArrayVector { private int RECORD_SIZE = 5; private int currentSize = 0; private Object[] objarray = new Object[50 * RECORD_SIZE]; // default to 50 5 field records public int add(Object p1, Object p2, Object p3, Object p4, Object p5) { if (currentSize == objarray.length) { Object[] newarray = new Object[currentSize * 2]; System.arraycopy(objarray, 0, newarray, 0, currentSize); objarray = newarray; } int pos = currentSize / RECORD_SIZE; objarray[currentSize++] = p1; objarray[currentSize++] = p2; objarray[currentSize++] = p3; objarray[currentSize++] = p4; objarray[currentSize++] = p5; return pos; } public Object get(int pos, int fld) { return objarray[(pos * RECORD_SIZE) + fld]; } public int getLength() { return (currentSize / RECORD_SIZE); } } ///////////////////////////////////////////// }
7,588
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/DetailEntry.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** * Detail Entry implementation * * @author Davanum Srinivas (dims@yahoo.com) */ public class DetailEntry extends MessageElement implements javax.xml.soap.DetailEntry { public DetailEntry(javax.xml.soap.Name name){ super(name); } }
7,589
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/EnvelopeHandler.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** * * @author Glen Daniels (gdaniels@allaire.com) */ import org.apache.axis.encoding.DeserializationContext; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class EnvelopeHandler extends SOAPHandler { SOAPHandler realHandler; public EnvelopeHandler(SOAPHandler realHandler) { this.realHandler = realHandler; } public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { return realHandler; } }
7,590
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/SOAPFaultElement.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; /** * SOAP Fault implementation * * @author Davanum Srinivas (dims@yahoo.com) */ public class SOAPFaultElement extends MessageElement implements javax.xml.soap.SOAPFaultElement { }
7,591
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/NodeListImpl.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A simple implementation for Nodelist Support in AXIS * * @author Heejune Ahn (cityboy@tmax.co.kr) * */ class NodeListImpl implements NodeList { List mNodes; public static final NodeList EMPTY_NODELIST = new NodeListImpl(Collections.EMPTY_LIST); /** * Constructor and Setter is intensionally made package access only. * */ NodeListImpl() { mNodes = new ArrayList(); } NodeListImpl(List nodes) { this(); mNodes.addAll(nodes); } void addNode(org.w3c.dom.Node node) { mNodes.add(node); } void addNodeList(org.w3c.dom.NodeList nodes) { for (int i = 0; i < nodes.getLength(); i++) { mNodes.add(nodes.item(i)); } } /** * Interface Implemented * * @param index * @return */ public Node item(int index) { if (mNodes != null && mNodes.size() > index) { return (Node) mNodes.get(index); } else { return null; } } public int getLength() { return mNodes.size(); } }
7,592
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/EnvelopeBuilder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import org.apache.axis.Constants; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import javax.xml.namespace.QName; /** * The EnvelopeBuilder is responsible for parsing the top-level * SOAP envelope stuff (Envelope, Body, Header), and spawning off * HeaderBuilder and BodyBuilders. * * @author Glen Daniels (gdaniels@allaire.com) * @author Andras Avar (andras.avar@nokia.com) */ public class EnvelopeBuilder extends SOAPHandler { private SOAPEnvelope envelope; private SOAPConstants soapConstants = SOAPConstants.SOAP11_CONSTANTS; private boolean gotHeader = false; private boolean gotBody = false; public EnvelopeBuilder(String messageType, SOAPConstants soapConstants) { envelope = new SOAPEnvelope(false, soapConstants); envelope.setMessageType(messageType); myElement = envelope; } public EnvelopeBuilder(SOAPEnvelope env, String messageType) { envelope = env ; envelope.setMessageType(messageType); myElement = envelope; } public SOAPEnvelope getEnvelope() { return envelope; } public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (!localName.equals(Constants.ELEM_ENVELOPE)) throw new SAXException( Messages.getMessage("badTag00", localName)); // See if we're only supporting a single SOAP version at this endpoint MessageContext msgContext = context.getMessageContext(); SOAPConstants singleVersion = null; if (msgContext != null) { singleVersion = (SOAPConstants)msgContext.getProperty( Constants.MC_SINGLE_SOAP_VERSION); } if (namespace.equals(Constants.URI_SOAP11_ENV)) { // SOAP 1.1 soapConstants = SOAPConstants.SOAP11_CONSTANTS; } else if (namespace.equals(Constants.URI_SOAP12_ENV)) { // SOAP 1.2 soapConstants = SOAPConstants.SOAP12_CONSTANTS; } else { soapConstants = null; } if ((soapConstants == null) || (singleVersion != null && soapConstants != singleVersion)) { // Mismatch of some sort, either an unknown namespace or not // the one we want. Send back an appropriate fault. // Right now we only send back SOAP 1.1 faults for this case. Do // we want to send SOAP 1.2 faults back to SOAP 1.2 endpoints? soapConstants = SOAPConstants.SOAP11_CONSTANTS; if (singleVersion == null) singleVersion = soapConstants; try { AxisFault fault = new AxisFault(soapConstants.getVerMismatchFaultCodeQName(), null, Messages.getMessage("versionMissmatch00"), null, null, null); SOAPHeaderElement newHeader = new SOAPHeaderElement(soapConstants.getEnvelopeURI(), Constants.ELEM_UPGRADE); // TODO: insert soap 1.1 upgrade header in case of soap 1.2 response if // axis supports both simultaneously MessageElement innerHeader = new MessageElement(soapConstants.getEnvelopeURI(), Constants.ELEM_SUPPORTEDENVELOPE); innerHeader.addAttribute(null, Constants.ATTR_QNAME, new QName(singleVersion.getEnvelopeURI(), Constants.ELEM_ENVELOPE)); newHeader.addChildElement(innerHeader); fault.addHeader(newHeader); throw new SAXException(fault); } catch (javax.xml.soap.SOAPException e) { throw new SAXException(e); } } // Indicate what version of SOAP we're using to anyone else involved // in processing this message. if(context.getMessageContext() != null) context.getMessageContext().setSOAPConstants(soapConstants); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS && attributes.getValue(Constants.URI_SOAP12_ENV, Constants.ATTR_ENCODING_STYLE) != null) { AxisFault fault = new AxisFault(Constants.FAULT_SOAP12_SENDER, null, Messages.getMessage("noEncodingStyleAttrAppear", "Envelope"), null, null, null); throw new SAXException(fault); } envelope.setPrefix(prefix); envelope.setNamespaceURI(namespace); envelope.setNSMappings(context.getCurrentNSMappings()); envelope.setSoapConstants(soapConstants); context.pushNewElement(envelope); } public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { QName thisQName = new QName(namespace, localName); if (thisQName.equals(soapConstants.getHeaderQName())) { if (gotHeader) throw new SAXException(Messages.getMessage("only1Header00")); gotHeader = true; return new HeaderBuilder(envelope); } if (thisQName.equals(soapConstants.getBodyQName())) { if (gotBody) throw new SAXException(Messages.getMessage("only1Body00")); gotBody = true; return new BodyBuilder(envelope); } if (!gotBody) throw new SAXException(Messages.getMessage("noCustomElems00")); if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { throw new SAXException(Messages.getMessage("noElemAfterBody12")); } try { MessageElement element = new MessageElement(namespace, localName, prefix, attributes, context); if (element.getFixupDeserializer() != null) return (SOAPHandler)element.getFixupDeserializer(); } catch (AxisFault axisFault) { throw new SAXException(axisFault); } return null; } public void onEndChild(String namespace, String localName, DeserializationContext context) { } public void endElement(String namespace, String localName, DeserializationContext context) throws SAXException { // Envelope isn't dirty yet by default... envelope.setDirty(false); envelope.setRecorded(true); envelope.reset(); } }
7,593
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/message/MimeHeaders.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.message; import javax.xml.soap.MimeHeader; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Iterator; /** * wraps javax.xml.soap.MimeHeaders and implements java.io.Serializable interface */ public class MimeHeaders extends javax.xml.soap.MimeHeaders implements java.io.Externalizable { public MimeHeaders() { } public MimeHeaders(javax.xml.soap.MimeHeaders h) { Iterator iterator = h.getAllHeaders(); while (iterator.hasNext()) { MimeHeader hdr = (MimeHeader) iterator.next(); addHeader(hdr.getName(), hdr.getValue()); } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int size = in.readInt(); for (int i = 0; i < size; i++) { Object key = in.readObject(); Object value = in.readObject(); addHeader((String)key, (String)value); } } public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(getHeaderSize()); Iterator iterator = getAllHeaders(); while (iterator.hasNext()) { MimeHeader hdr = (MimeHeader) iterator.next(); out.writeObject(hdr.getName()); out.writeObject(hdr.getValue()); } } private int getHeaderSize() { int size = 0; Iterator iterator = getAllHeaders(); while (iterator.hasNext()) { iterator.next(); size++; } return size; } }
7,594
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/server/JNDIAxisServerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.server; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.utils.Messages; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletContext; import java.util.Map; /** * Helper class for obtaining AxisServers, which hides the complexity * of JNDI accesses, etc. * * !!! QUESTION : Does this class need to play any ClassLoader tricks? * * @author Glen Daniels (gdaniels@apache.org) */ public class JNDIAxisServerFactory extends DefaultAxisServerFactory { /** * Obtain an AxisServer reference, using JNDI if possible, otherwise * creating one using the standard Axis configuration pattern. If we * end up creating one and do have JNDI access, bind it to the passed * name so we find it next time. * * NOTE : REQUIRES SERVLET 2.3 FOR THE GetServletContextName() CALL! * * @param environment The following is used, in addition to * the keys used by the parent class: * AxisEngine.ENV_SERVLET_CONTEXT * [required, else default/parent behavior] * - Instance of ServletContext */ public AxisServer getServer(Map environment) throws AxisFault { log.debug("Enter: JNDIAxisServerFactory::getServer"); InitialContext context = null; // First check to see if JNDI works // !!! Might we need to set up context parameters here? try { context = new InitialContext(); } catch (NamingException e) { log.warn(Messages.getMessage("jndiNotFound00"), e); } ServletContext servletContext = null; try { servletContext = (ServletContext)environment.get(AxisEngine.ENV_SERVLET_CONTEXT); } catch (ClassCastException e) { log.warn(Messages.getMessage("servletContextWrongClass00"), e); // Fall through } AxisServer server = null; if (context != null && servletContext != null) { // Figure out the name by looking in the servlet context (for now) /** * !!! WARNING - THIS CLASS NEEDS TO FIGURE OUT THE CORRECT * NAMING SCHEME FOR GETTING/PUTTING SERVERS FROM/TO JNDI! * */ // For servlet 2.3....? // String name = servletContext.getServletContextName(); // THIS IS NOT ACCEPTABLE JNDI NAMING... String name = servletContext.getRealPath("/WEB-INF/Server"); // The following was submitted as a patch, but I don't believe this // is going to produce a valid JNDI name of ANY sort... yuck. // This would produce a URL, not a path name. // // Since it appears, from comments above, that this entire scheme is // broken, then for now I'll simply check for a null-name to prevent // possible NPE on WebLogic. // // What ARE we doing here?!?! // // if (name == null) { // try { // name = servletContext.getResource("/WEB-INF/Server").toString(); // } catch (Exception e) { // // ignore // } // } // We've got JNDI, so try to find an AxisServer at the // specified name. if (name != null) { try { server = (AxisServer)context.lookup(name); } catch (NamingException e) { // Didn't find it. server = super.getServer(environment); try { context.bind(name, server); } catch (NamingException e1) { // !!! Couldn't do it, what should we do here? } } } } if (server == null) { server = super.getServer(environment); } log.debug("Exit: JNDIAxisServerFactory::getServer"); return server; } }
7,595
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/server/ParamList.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.server; import java.util.Collection; import java.util.Vector; public class ParamList extends Vector { public ParamList () { super (); } public ParamList (Collection c) { super (c); } public ParamList (int initialCapacity) { super (initialCapacity); } public ParamList (int initialCapacity, int capacityIncrement) { super (initialCapacity, capacityIncrement); } }
7,596
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/server/AxisServerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.server; import org.apache.axis.AxisFault; import java.util.Map; /** * @author Glen Daniels (gdaniels@apache.org) */ public interface AxisServerFactory { public AxisServer getServer(Map environment) throws AxisFault; }
7,597
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/server/AxisServer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.server ; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.AxisProperties; import org.apache.axis.Constants; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.SimpleTargetedChain; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.client.AxisClient; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.configuration.EngineConfigurationFactoryFinder; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.util.Map; /** * * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@allaire.com) */ public class AxisServer extends AxisEngine { protected static Log log = LogFactory.getLog(AxisServer.class.getName()); private static Log tlog = LogFactory.getLog("org.apache.axis.TIME"); private static AxisServerFactory factory = null; public static AxisServer getServer(Map environment) throws AxisFault { if (factory == null) { String factoryClassName = AxisProperties.getProperty("axis.ServerFactory"); if (factoryClassName != null) { try { Class factoryClass = ClassUtils.forName(factoryClassName); if (AxisServerFactory.class.isAssignableFrom(factoryClass)) factory = (AxisServerFactory)factoryClass.newInstance(); } catch (Exception e) { // If something goes wrong here, should we just fall // through and use the default one? log.error(Messages.getMessage("exception00"), e); } } if (factory == null) { factory = new DefaultAxisServerFactory(); } } return factory.getServer(environment); } /** * the AxisClient to be used by outcalling Services */ private AxisEngine clientEngine; public AxisServer() { this(EngineConfigurationFactoryFinder.newFactory().getServerEngineConfig()); } public AxisServer(EngineConfiguration config) { super(config); // Server defaults to persisting configuration setShouldSaveConfig(true); } /** Is this server active? If this is false, any requests will * cause a SOAP Server fault to be generated. */ private boolean running = true; public boolean isRunning() { return running; } /** Start the server. */ public void start() { // re-init... init(); running = true; } /** Stop the server. */ public void stop() { running = false; } /** * Get this server's client engine. Create it if it does * not yet exist. */ public synchronized AxisEngine getClientEngine () { if (clientEngine == null) { clientEngine = new AxisClient(); // !!!! } return clientEngine; } /** * Main routine of the AXIS server. In short we locate the appropriate * handler for the desired service and invoke() it. */ public void invoke(MessageContext msgContext) throws AxisFault { long t0=0, t1=0, t2=0, t3=0, t4=0, t5=0; if( tlog.isDebugEnabled() ) { t0=System.currentTimeMillis(); } if (log.isDebugEnabled()) { log.debug("Enter: AxisServer::invoke"); } if (!isRunning()) { throw new AxisFault("Server.disabled", Messages.getMessage("serverDisabled00"), null, null); } String hName = null ; Handler h = null ; // save previous context MessageContext previousContext = getCurrentMessageContext(); try { // set active context setCurrentMessageContext(msgContext); hName = msgContext.getStrProp( MessageContext.ENGINE_HANDLER ); if ( hName != null ) { if ( (h = getHandler(hName)) == null ) { ClassLoader cl = msgContext.getClassLoader(); try { log.debug( Messages.getMessage("tryingLoad00", hName) ); Class cls = ClassUtils.forName(hName, true, cl); h = (Handler) cls.newInstance(); } catch( Exception e ) { h = null ; } } if( tlog.isDebugEnabled() ) { t1=System.currentTimeMillis(); } if ( h != null ) h.invoke(msgContext); else throw new AxisFault( "Server.error", Messages.getMessage("noHandler00", hName), null, null ); if( tlog.isDebugEnabled() ) { t2=System.currentTimeMillis(); tlog.debug( "AxisServer.invoke " + hName + " invoke=" + ( t2-t1 ) + " pre=" + (t1-t0 )); } } else { // This really should be in a handler - but we need to discuss it // first - to make sure that's what we want. /* Now we do the 'real' work. The flow is basically: */ /* Transport Specific Request Handler/Chain */ /* Global Request Handler/Chain */ /* Protocol Specific-Handler(ie. SOAP, XP) */ /* ie. For SOAP Handler: */ /* - Service Specific Request Handler/Chain */ /* - SOAP Semantic Checks */ /* - Service Specific Response Handler/Chain */ /* Global Response Handler/Chain */ /* Transport Specific Response Handler/Chain */ /**************************************************************/ // When do we call init/cleanup?? if (log.isDebugEnabled()) { log.debug(Messages.getMessage("defaultLogic00") ); } /* This is what the entirety of this logic might evolve to: hName = msgContext.getStrProp(MessageContext.TRANSPORT); if ( hName != null ) { if ((h = hr.find( hName )) != null ) { h.invoke(msgContext); } else { log.error(Messages.getMessage("noTransport02", hName)); } } else { // No transport set, so use the default (probably just // calls the global->service handlers) defaultTransport.invoke(msgContext); } */ /* Process the Transport Specific Request Chain */ /**********************************************/ hName = msgContext.getTransportName(); SimpleTargetedChain transportChain = null; if (log.isDebugEnabled()) log.debug(Messages.getMessage("transport01", "AxisServer.invoke", hName)); if( tlog.isDebugEnabled() ) { t1=System.currentTimeMillis(); } if ( hName != null && (h = getTransport( hName )) != null ) { if (h instanceof SimpleTargetedChain) { transportChain = (SimpleTargetedChain)h; h = transportChain.getRequestHandler(); if (h != null) h.invoke(msgContext); } } if( tlog.isDebugEnabled() ) { t2=System.currentTimeMillis(); } /* Process the Global Request Chain */ /**********************************/ if ((h = getGlobalRequest()) != null ) { h.invoke(msgContext); } /** * At this point, the service should have been set by someone * (either the originator of the MessageContext, or one of the * transport or global Handlers). If it hasn't been set, we * fault. */ h = msgContext.getService(); if (h == null) { // It's possible that we haven't yet parsed the // message at this point. This is a kludge to // make sure we have. There probably wants to be // some kind of declarative "parse point" on the handler // chain instead.... Message rm = msgContext.getRequestMessage(); rm.getSOAPEnvelope().getFirstBody(); h = msgContext.getService(); if (h == null) throw new AxisFault("Server.NoService", Messages.getMessage("noService05", "" + msgContext.getTargetService()), null, null ); } if( tlog.isDebugEnabled() ) { t3=System.currentTimeMillis(); } initSOAPConstants(msgContext); try { h.invoke(msgContext); } catch (AxisFault ae) { if ((h = getGlobalRequest()) != null ) { h.onFault(msgContext); } throw ae; } if( tlog.isDebugEnabled() ) { t4=System.currentTimeMillis(); } /* Process the Global Response Chain */ /***********************************/ if ((h = getGlobalResponse()) != null) h.invoke(msgContext); /* Process the Transport Specific Response Chain */ /***********************************************/ if (transportChain != null) { h = transportChain.getResponseHandler(); if (h != null) h.invoke(msgContext); } if( tlog.isDebugEnabled() ) { t5=System.currentTimeMillis(); tlog.debug( "AxisServer.invoke2 " + " preTr=" + ( t1-t0 ) + " tr=" + (t2-t1 ) + " preInvoke=" + ( t3-t2 ) + " invoke=" + ( t4-t3 ) + " postInvoke=" + ( t5-t4 ) + " " + msgContext.getTargetService() + "." + ((msgContext.getOperation( ) == null) ? "" : msgContext.getOperation().getName()) ); } } } catch (AxisFault e) { throw e; } catch (Exception e) { // Should we even bother catching it ? throw AxisFault.makeFault(e); } finally { // restore previous state setCurrentMessageContext(previousContext); } if (log.isDebugEnabled()) { log.debug("Exit: AxisServer::invoke"); } } /** * Extract ans store soap constants info from the envelope * @param msgContext * @throws AxisFault */ private void initSOAPConstants(MessageContext msgContext) throws AxisFault { Message msg = msgContext.getRequestMessage(); if (msg == null) return; SOAPEnvelope env = msg.getSOAPEnvelope(); if (env == null) return; SOAPConstants constants = env.getSOAPConstants(); if (constants == null) return; // Ensure that if we get SOAP1.2, then reply using SOAP1.2 msgContext.setSOAPConstants(constants); } /** * */ public void generateWSDL(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: AxisServer::generateWSDL"); } if (!isRunning()) { throw new AxisFault("Server.disabled", Messages.getMessage("serverDisabled00"), null, null); } String hName = null ; Handler h = null ; // save previous context MessageContext previousContext = getCurrentMessageContext(); try { // set active context setCurrentMessageContext(msgContext); hName = msgContext.getStrProp( MessageContext.ENGINE_HANDLER ); if ( hName != null ) { if ( (h = getHandler(hName)) == null ) { ClassLoader cl = msgContext.getClassLoader(); try { log.debug( Messages.getMessage("tryingLoad00", hName) ); Class cls = ClassUtils.forName(hName, true, cl); h = (Handler) cls.newInstance(); } catch( Exception e ) { throw new AxisFault( "Server.error", Messages.getMessage("noHandler00", hName), null, null ); } } h.generateWSDL(msgContext); } else { // This really should be in a handler - but we need to discuss it // first - to make sure that's what we want. /* Now we do the 'real' work. The flow is basically: */ /* Transport Specific Request Handler/Chain */ /* Global Request Handler/Chain */ /* Protocol Specific-Handler(ie. SOAP, XP) */ /* ie. For SOAP Handler: */ /* - Service Specific Request Handler/Chain */ /* - SOAP Semantic Checks */ /* - Service Specific Response Handler/Chain */ /* Global Response Handler/Chain */ /* Transport Specific Response Handler/Chain */ /**************************************************************/ // When do we call init/cleanup?? log.debug( Messages.getMessage("defaultLogic00") ); /* This is what the entirety of this logic might evolve to: hName = msgContext.getStrProp(MessageContext.TRANSPORT); if ( hName != null ) { if ((h = hr.find( hName )) != null ) { h.generateWSDL(msgContext); } else { log.error(Messages.getMessage("noTransport02", hName)); } } else { // No transport set, so use the default (probably just // calls the global->service handlers) defaultTransport.generateWSDL(msgContext); } */ /* Process the Transport Specific Request Chain */ /**********************************************/ hName = msgContext.getTransportName(); SimpleTargetedChain transportChain = null; if (log.isDebugEnabled()) log.debug(Messages.getMessage("transport01", "AxisServer.generateWSDL", hName)); if ( hName != null && (h = getTransport( hName )) != null ) { if (h instanceof SimpleTargetedChain) { transportChain = (SimpleTargetedChain)h; h = transportChain.getRequestHandler(); if (h != null) { h.generateWSDL(msgContext); } } } /* Process the Global Request Chain */ /**********************************/ if ((h = getGlobalRequest()) != null ) h.generateWSDL(msgContext); /** * At this point, the service should have been set by someone * (either the originator of the MessageContext, or one of the * transport or global Handlers). If it hasn't been set, we * fault. */ h = msgContext.getService(); if (h == null) { // It's possible that we haven't yet parsed the // message at this point. This is a kludge to // make sure we have. There probably wants to be // some kind of declarative "parse point" on the handler // chain instead.... Message rm = msgContext.getRequestMessage(); if (rm != null) { rm.getSOAPEnvelope().getFirstBody(); h = msgContext.getService(); } if (h == null) { throw new AxisFault(Constants.QNAME_NO_SERVICE_FAULT_CODE, Messages.getMessage("noService05", "" + msgContext.getTargetService()), null, null ); } } h.generateWSDL(msgContext); /* Process the Global Response Chain */ /***********************************/ if ((h = getGlobalResponse()) != null ) h.generateWSDL(msgContext); /* Process the Transport Specific Response Chain */ /***********************************************/ if (transportChain != null) { h = transportChain.getResponseHandler(); if (h != null) { h.generateWSDL(msgContext); } } } } catch (AxisFault e) { throw e; } catch(Exception e) { // Should we even bother catching it ? throw AxisFault.makeFault(e); } finally { // restore previous state setCurrentMessageContext(previousContext); } if (log.isDebugEnabled()) { log.debug("Exit: AxisServer::generateWSDL"); } } }
7,598
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/server/Transport.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.server; import org.apache.axis.SimpleTargetedChain; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; /** * Transport is a targeted chain that knows it's a transport. * * This is purely for deployment naming at this point. * * @author Glen Daniels (gdaniels@apache.org) */ public class Transport extends SimpleTargetedChain { protected static Log log = LogFactory.getLog(Transport.class.getName()); }
7,599