/**
 * Abstracts how parameters are passed on the RPC protocol
 */

package org.bucksch.zeipis.all;
import org.bucksch.httpserver.*;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;

public class SimpleRFCParams
{
  public SimpleRFCParams()
  {
    myParams = Util.newMap();
  }
  public SimpleRFCParams parseFromXML(HTTPRequest request)
    throws HTTPException
  {
    Document doc;
    try {
      doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(request.getRequestBody());
    } catch (Exception e) {
      throw new HTTPException(400, "Could not parse the call parameter XML");
    }
    Element root = (Element) doc.getChildNodes().item(0);
    NodeList els = root.getChildNodes();
    for (int i = 0; i < els.getLength(); i++)
    {
      Element el = (Element) els.item(i);
      String elname = el.getLocalName();
      if (el.getNodeType() == Node.TEXT_NODE)
      {
        myParams.put(elname, el.getNodeValue());
        continue;
      }
      NamedNodeMap attrs = el.getAttributes();
      for (int i2 = 0; i < attrs.getLength(); i++)
      {
        Attr attr = (Attr) attrs.item(i2);
        String attrname = attr.getLocalName();
        myParams.put(elname + "-" + attrname, attr.getNodeValue());
      }
    }
    return this;
  }
  public SimpleRFCParams parseFromHeaders(HTTPRequest request)
    throws HTTPException
  {
    myParams.putAll(request.getRequestHeaders());
    return this;
  }
  public SimpleRFCParams parseFromURL(URL url)
    throws HTTPException
  {
    try {
      String paramsStr = url.getQuery();
      if (paramsStr == null)
        return this;
      String[] params = paramsStr.split("&");
      for (String param : params)
      {
        String[] namevalue = param.split("=", 2);
        if (namevalue.length < 2)
          throw new Exception("param does not have name=value syntax: " + param);
        String name = namevalue[0];
        String value;
        try {
          value = URLDecoder.decode(namevalue[1], "UTF-8");
        } catch (UnsupportedEncodingException e) {
          throw new Exception("value cannot be URL decoded: " + namevalue[1], e);
        }
        Util.debug("param " + name + " = " + value);
        myParams.put(name, value);
      }
      return this;
    } catch (Exception e) {
      throw new HTTPException(400, "Could not parse the URL query parameters", e);
    }
  }
  public String param(String name)
  {
    return myParams.get(name);
  }
  protected Map<String, String> myParams;
}
