/* $Id: XMLRPC.java,v 1.2 2003/03/19 09:44:12 tsm Exp $

Copyright (c) 2003 Tienshiao Ma

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject to 
the following conditions:

The above copyright notice and this permission notice shall be included 
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.

 */
package org.tienshiao.XMLLite;

import java.io.*;
import java.util.*;
/**
 *
 * @author  Tienshiao Ma
 */
public class XMLRPC {
    public static final int PARAMS = 0;
    public static final int FAULT = 1;
    
    Object returnValue;
    int faultCode;
    String faultString;
    
    /** Creates a new instance of XMLRPCParser */
    public XMLRPC() {
    }
    
    public Object getReturnValue() {
        return returnValue;
    }
    
    public int getFaultCode() {
        return faultCode;
    }
    
    public String getFaultString() {
        return faultString;
    }

    private static String doValue(Object value) {
        StringBuffer temp = new StringBuffer();
        if (value instanceof Integer) {
            temp.append("<i4>").append(value.toString()).append("</i4>");
        } else if (value instanceof String) {
            temp.append(value);
        } else if (value instanceof Boolean) {
            temp.append("<boolean>").append(value.toString()).append("</boolean");
        } else if (value instanceof Hashtable) {
            temp.append("<struct>");
            for (Enumeration e = ((Hashtable)value).keys(); e.hasMoreElements();) {
                temp.append("<member><name>");
                Object key = e.nextElement();
                temp.append(key);
                temp.append("</name><value>");
                temp.append(doValue(((Hashtable)value).get(key)));
                temp.append("</value></member>");
            }
            temp.append("</struct>");
        } else if (value instanceof Vector) {
            temp.append("<array><data>");
            for (int i = 0; i < ((Vector)value).size(); i++) {
                temp.append("<value>");
                doValue(((Vector)value).elementAt(i));
                temp.append("</value>");
            }
            temp.append("</data></array>");
        }
        return temp.toString();
    }
    
    public static String makeRequest(String procName, Vector params) {
        StringBuffer temp = new StringBuffer();
        temp.append("<?xml version=\"1.0\"?><methodCall><methodName>");
        temp.append(procName);
        temp.append("</methodName><params>");
        for (int i = 0 ; i < params.size(); i++) {
            temp.append("<param><value>");
            temp.append(doValue(params.elementAt(i)));
            temp.append("</value></param>");
        }
        temp.append("</params></methodCall>");
        return temp.toString();
    }

    private void getNextTag(XMLPullParser x) throws IOException, XMLParserException {
    	do {
    		x.getNextToken();
    	} while ((x.getType() != XMLPullParser.START_TAG) ||
    	          (x.getType() != XMLPullParser.END_TAG));
    }
    
    private void expectTag(int type, String name, XMLPullParser x)
        throws IOException, XMLParserException, XMLRPCException {
        getNextTag(x);
        if ((x.getType() != type) || (x.getName().compareTo(name) != 0)) {
        	throw new XMLRPCException("Unexpected Tag :" + x.getName());
        }
    }
    
    private String getTextAndAdvance(XMLPullParser x) throws IOException, XMLParserException {
        StringBuffer sb = new StringBuffer();
        x.getNextToken();
        while ((x.getType() == XMLPullParser.TEXT) ||
               (x.getType() == XMLPullParser.COMMENT)) {
            sb.append(x.getText());
        }
        return sb.toString().trim();
    }
    
    private Object finishValue(XMLPullParser x) throws IOException, XMLParserException, XMLRPCException {
        Object retval = null;
        do {
            x.getNextToken();
        } while ((x.getType() != XMLPullParser.START_TAG) ||
                 (x.getType() != XMLPullParser.END_TAG) ||
                 ((x.getType() != XMLPullParser.TEXT) && 
                  (x.getText().trim().length() == 0)));
        if (x.getType() == XMLPullParser.START_TAG) {
            if (x.getName().compareTo("struct") == 0) {
                Hashtable struct = new Hashtable();
                String key = null;
                getNextTag(x);
                while ((x.getType() == XMLPullParser.START_TAG) &&
                       (x.getName().compareTo("member") == 0)) {
                    expectTag(XMLPullParser.START_TAG, "name", x);
                    key = getTextAndAdvance(x);
                    if ((x.getType() != XMLPullParser.END_TAG) ||
                        (x.getName().compareTo("name") == 0)) {
                        throw new XMLRPCException("Unexpected tag: " + x.getName());
                    }
                    expectTag(XMLPullParser.START_TAG, "value", x);
                    struct.put(key, finishValue(x));
                    expectTag(XMLPullParser.END_TAG, "member", x);
                    getNextTag(x);
                }
                if ((x.getType() != XMLPullParser.END_TAG) ||
                    (x.getName().compareTo("struct") == 0)) {
                    throw new XMLRPCException("Unexpected tag: " + x.getName());
                }
                if (struct.size() > 0) {
                    retval = struct;
                }
            } else if (x.getName().compareTo("array") == 0) {
                expectTag(XMLPullParser.START_TAG, "data", x);
                Vector array = new Vector();
                getNextTag(x);
                while ((x.getType() == XMLPullParser.START_TAG) &&
                       (x.getName().compareTo("value") == 0)) {
                    array.addElement(finishValue(x));
                    getNextTag(x);
                }
                if ((x.getType() != XMLPullParser.END_TAG) || 
                    (x.getName().compareTo("data") != 0)) {
                    throw new XMLRPCException("Unexpected tag: " + x.getName());
                }
                if (array.size() > 0) {
                    retval = array;
                }
                expectTag(XMLPullParser.END_TAG, "array", x);
            } else {
                String name = x.getName();
                String text = getTextAndAdvance(x);
                if ((name.compareTo("i4") == 0) || 
                    (name.compareTo("int") == 0)) {
                    try {
                        retval = Integer.valueOf(text);
                    } catch (NumberFormatException e) {
                        throw new XMLRPCException("Invalid integer: " + text);
                    }
                } else if (name.compareTo("boolean") == 0) {
                    try {
                       if (Integer.parseInt(text) == 0) {
                           retval = new Boolean(false);
                       } else {
                           retval = new Boolean(true);
                       }
                    } catch (NumberFormatException e) {
                        if (text.compareTo("true") == 0) {
                            retval = new Boolean(true);
                        } else if (text.compareTo("false") == 0) {
                            retval = new Boolean(false);
                        } else {
                            throw new XMLRPCException("Invalid boolean: " + text);
                        }
                    }                    
                } else { // double, string, date, base64
                    retval = text;
                }
                if ((x.getType() != XMLPullParser.END_TAG) ||
                    (x.getName().compareTo(name) != 0)) {
                    throw new XMLRPCException("Unexpected Tag: " + x.getName());
                }
            }
        } else if (x.getType() == XMLPullParser.END_TAG) {
            if (x.getName().compareTo("value") != 0) {
                throw new XMLRPCException("Unexpected Tag: " + x.getName());
            }
        } else {
            retval = x.getText().trim();
        }
        expectTag(XMLPullParser.END_TAG, "value", x);
        return retval;
    }
    
    public int parseResponse(Reader r) throws XMLRPCException {
        XMLPullParser xpp = new XMLPullParser(r);
        returnValue = null;
        try {
            expectTag(XMLPullParser.START_TAG, "methodResponse", xpp);
            getNextTag(xpp);
            if (xpp.getType() != XMLPullParser.START_TAG) {
                throw new XMLRPCException("Unexpected Tag :" + xpp.getName());
            }
            if (xpp.getName().compareTo("params") == 0) {
                expectTag(XMLPullParser.START_TAG, "param", xpp);
                expectTag(XMLPullParser.START_TAG, "value", xpp);                
                returnValue = finishValue(xpp);
                expectTag(XMLPullParser.END_TAG, "param", xpp);
                expectTag(XMLPullParser.END_TAG, "params", xpp);
                expectTag(XMLPullParser.END_TAG, "methodResponse", xpp);
                return PARAMS;
            } else if (xpp.getName().compareTo("fault") == 0) {
                expectTag(XMLPullParser.END_TAG, "methodResponse", xpp);
                return FAULT;
            }
            throw new XMLRPCException("Unexpected Tag :" + xpp.getName());
        } catch (XMLParserException e) {
            throw new XMLRPCException("XML parsing error");
        } catch (IOException e) {
            throw new XMLRPCException("Error reading data");
        }
    }
}
