package tutorial.wls70.sample2; 

import java.io.StringWriter;


import weblogic.webservice.encoding.AbstractCodec;
import weblogic.xml.schema.binding.DeserializationContext;
import weblogic.xml.schema.binding.DeserializationException;
import weblogic.xml.schema.binding.Deserializer;
import weblogic.xml.schema.binding.SerializationContext;
import weblogic.xml.schema.binding.SerializationException;
import weblogic.xml.schema.binding.Serializer;
import weblogic.xml.stream.Attribute;
import weblogic.xml.stream.CharacterData;
import weblogic.xml.stream.ElementFactory;
import weblogic.xml.stream.EndElement;
import weblogic.xml.stream.StartElement;
import weblogic.xml.stream.XMLEvent;
import weblogic.xml.stream.XMLInputStream;
import weblogic.xml.stream.XMLName;
import weblogic.xml.stream.XMLOutputStream;
import weblogic.xml.stream.XMLOutputStreamFactory;

import weblogic.xml.stream.XMLStreamException;

public final class XmlStringCodec 
  extends weblogic.webservice.encoding.AbstractCodec {

  public void serialize(Object obj,
                        XMLName name,
                        XMLOutputStream writer,
                        SerializationContext context)
    throws SerializationException
  {
  
    try {
    
      writer.add( ((XmlString)obj).getXmlString() );
     
    } catch(XMLStreamException xse) {
      throw new SerializationException("stream error", xse);
    }
  }

  public Object deserialize(XMLName name,
                            XMLInputStream reader,
                            DeserializationContext context)
    throws DeserializationException
  {
    // extract the desired information out of reader, consuming the
    // entire element representing the type,
    // construct your object, and return it.
    XmlString xmlString = new XmlString();
    
    try {

      XMLInputStream subStream = reader.getSubStream();
      StringWriter sw = new StringWriter();

      XMLOutputStream xos = 
        XMLOutputStreamFactory.newInstance().newOutputStream(sw);

      xos.add(subStream);
      xos.flush();
      xos.close();
      xmlString.setXmlString(sw.toString());

    } catch (XMLStreamException xse) {
      throw new DeserializationException("stream error", xse);
    }

    return xmlString;
  }

  public Object deserialize(XMLName name,
                            Attribute att,
                            DeserializationContext context)
    throws DeserializationException
  {
    //NOTE: not used in this example
    // extract the desired information out of att, consuming the
    // entire element representing the type,
    // construct your object, and return it.

    throw new DeserializationException( "No attributes for this type" );
    
  }

}



