# FILE: SESendSoap.py
#
# SESendSoap - Search External core module
#
# send a request via http to remote host and return the results in return string
# communication error handling must be improved (see below)
# this is based on XMLRPCMethod.py
#
# (C) 2003 by CC Open Computer Systems for the "Neuroinfo" project
# This is free software avaiable under the GPL license, see:
#   LICENSE.txt, README.txt for details.
# ==================================================================

import httplib
import timeoutsocket
from base64 import encodestring
import sys, os, stat, traceback
from threading import Thread


timeout=30



class Request:
    def request(self, host, port, uri, request_body, userpassword=''):
        """ issue XML-RPC request """

        data=''
        timeoutsocket.setDefaultSocketTimeout(timeout)
        try:
            h = httplib.HTTPConnection(host, port)
            h.connect()
            h.putrequest("POST", uri)
            # h.putheader("Host", host)
            h.putheader("User-Agent", 'CC-SOAP-Connector_v01(beta)')
            h.putheader("Content-Type", 'text/xml; charset="UTF-8"' )
            h.putheader("Content-Length", str(len(request_body)))
            h.putheader("SOAPAction", 'http://' + host + ':' + str(port) + uri)
            # basic auth
            if userpassword !='':
                h.putheader("AUTHORIZATION", "Basic %s" % replace(
                    encodestring("%s" % (userpassword)),
                    "\012", ""))
            h.endheaders()

            if request_body:
                h.send(request_body)

            r = h.getresponse();
            errcode = r.status

            if errcode != 200:
                print "Invalid http status =%d received" % errcode
            data = r.read()
#
# TODO: change exeption handling - generate SOAP fault
# or at least more meaningful errors..
#
        except timeoutsocket.Timeout:
            # print 'TIMEOUT'
            data = 'Timeout'
        except Exception, e:
            data = 'other error: ' + str(e)

        h.close()
        return data

