axis-java-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From i..@apache.org
Subject cvs commit: ws-axis/java/src/org/apache/axis/encoding/ser SimpleListSerializerFactory.java SimpleListDeserializer.java SimpleListDeserializerFactory.java SimpleListSerializer.java
Date Fri, 19 Dec 2003 13:50:06 GMT
ias         2003/12/19 05:50:06

  Added:       java/src/org/apache/axis/encoding/ser
                        SimpleListSerializerFactory.java
                        SimpleListDeserializer.java
                        SimpleListDeserializerFactory.java
                        SimpleListSerializer.java
  Log:
  initial check-in
  
  Revision  Changes    Path
  1.1                  ws-axis/java/src/org/apache/axis/encoding/ser/SimpleListSerializerFactory.java
  
  Index: SimpleListSerializerFactory.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2002 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  /**
   * 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);
      }
  }
  
  
  
  1.1                  ws-axis/java/src/org/apache/axis/encoding/ser/SimpleListDeserializer.java
  
  Index: SimpleListDeserializer.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  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.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.Messages;
  import org.xml.sax.Attributes;
  import org.xml.sax.SAXException;
  
  /**
   * Deserializer for 
   * <xsd:simpleType ...>
   *   <xsd:list itemType="...">
   * </xsd:simpleType>
   * based on SimpleDeserializer
   *
   * @author Ias (iasandcb@tmax.co.kr)
   */
  public class SimpleListDeserializer extends DeserializerImpl {
  
      StringBuffer val = new StringBuffer();
      private Constructor constructor = null;
      private Map propertyMap = null;
      private HashMap attributeMap = 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) {
          this.xmlType = xmlType;
          this.javaType = javaType;
      }
      public SimpleListDeserializer(Class javaType, QName xmlType, TypeDesc 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
      }
  
      /**
       * Remove the Value Targets of the Deserializer.
       * Simple deserializers may be re-used, so don't
       * nullify the vector.
       */
      public void removeValueTargets() {
          if (targets != null) {
              targets.clear();
              // targets = null;
          }
      }
  
      /**
       * 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);
              }
          }
          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
      {
  
          // 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);
              }
          }
      }
  
  }
  
  
  
  1.1                  ws-axis/java/src/org/apache/axis/encoding/ser/SimpleListDeserializerFactory.java
  
  Index: SimpleListDeserializerFactory.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  package org.apache.axis.encoding.ser;
  import org.apache.axis.utils.JavaUtils;
  
  import javax.xml.namespace.QName;
  import javax.xml.rpc.JAXRPCException;
  import java.lang.reflect.Constructor;
  
  /**
   * DeserializerFactory for 
   * <xsd:simpleType ...>
   *   <xsd:list itemType="...">
   * </xsd:simpleType>
   * based on SimpleDeserializerFactory
   *
   * @author Ias (iasandcb@tmax.co.kr)
   */
  public class SimpleListDeserializerFactory extends BaseDeserializerFactory {
  
      private Constructor constructor = null;
      /**
       * 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 SimpleListDeserializerFactory(Class javaType, QName xmlType) {
          super(SimpleListDeserializer.class, xmlType, javaType.getComponentType());
          Class componentType = javaType.getComponentType();
          try {
              if (!componentType.isPrimitive()) {
                  constructor = 
                  componentType.getDeclaredConstructor(new Class [] {String.class});
              }
              else {
                  Class wrapper = JavaUtils.getWrapperClass(componentType);
                  if (wrapper != null)
                      constructor = 
                          wrapper.getDeclaredConstructor(new Class [] {String.class});
              }
          } catch (java.lang.NoSuchMethodException e) {
              throw new IllegalArgumentException(e.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;
          }
          SimpleListDeserializer deser = (SimpleListDeserializer) super.getDeserializerAs(mechanismType);
          if (deser != null)
              deser.setConstructor(constructor);
          return deser;
      }
              
  }
  
  
  
  1.1                  ws-axis/java/src/org/apache/axis/encoding/ser/SimpleListSerializer.java
  
  Index: SimpleListSerializer.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  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 
   * <xsd:simpleType ...>
   *   <xsd:list itemType="...">
   * </xsd:simpleType>
   * 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);
  
          context.startElement(name, attributes);
          if (value != null) {
              context.writeSafeString(getValueAsString(value, context));
          }
          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 {
            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;
  
      }
  }
  
  
  

Mime
View raw message