/* Copyright (c) 2002, Oracle Corportation. All rights reserved */
package oracle.portal.provider.v2.webservice;

import java.io.Reader;
import java.io.StringReader;
import java.io.IOException;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import oracle.portal.utils.xml.v2.XMLUtil;

/**
 * <code>XMLStringWebServiceRenderer</code> is a specialized {@link
 * RPCWebServiceRenderer} for invoking 'RPC style' web services that return XML
 * as a string. <code>XMLStringWebServiceRenderer</code> extends 
 * <code>oracle.portal.provider.v2.webservice.RPCWebserviceRenderer</code>. If
 * the response contains xml in string form, then the string is expanded to XML.
 * Otherwise, if the response contains other data types, the control is 
 * delegated to the super class.
**/

public class XMLStringWebServiceRenderer extends RPCWebServiceRenderer
{

    // Assume strings can be parsed into XML. If the result contains a XML in 
    // string format, the string is expanded to XML.
    protected void expandResult (Document doc, Element el, Object result)
    {
        // Let the superclass handle all non-string results.
        if (result == null || !(result instanceof String))
        {
            super.expandResult(doc, el, result);
        }
        else
        {
            try
            {
                //parse the result into a new document.
                Reader in = new StringReader((String)result);
                Element newResult = 
                    XMLUtil.parseDocument(in, null).getDocumentElement();
                // Import the result into our document.
                Node resultEl = doc.importNode(newResult, true);
                el.appendChild(resultEl);
            }
            catch(SAXException se)
            {
                // If we can't parse the String as XML, let the superclass treat
                // it as a normal string.
                super.expandResult(doc, el, result); 
            }
            catch(IOException ie)
            {
                // If we can't parse the String as XML, let the superclass treat
                // it as a normal string.
                super.expandResult(doc, el, result); 
            }            
        }
    }
}