# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import requests
import json
import xml.dom.minidom

#
# Minimalistic/hardcoded serializer/deserializer framework.
#
def Object2Xml(o):
    clz = o.__class__.__name__
    if clz == 'T1':
        return '<t1><f1>%d</f1><f2>%s</f2></t1>' % (o.f1, o.f2)
    if clz == 'T1Array':
        return '<t1array>' + ''.join(map(lambda o1 : Object2Xml(o1), o.array)) + '</t1array>'
    raise Exception('Unknown class: ' + clz)

def Object2Json(o):
    clz = o.__class__.__name__
    if clz == 'T1':
        return json.dumps(o.__dict__)
    if clz == 'T1Array':
        return '[' + ','.join(map(lambda o1 : Object2Json(o1), o.array)) + ']'
    raise Exception('Unknown class: ' + clz)

def Object2String(o, typ):
    if typ == 'application/xml':
        return Object2Xml(o)
    if typ == 'application/json':
        return Object2Json(o)
    else:
        raise Exception('Unknown type: ' + typ)

def Xml2Object(clz, s):
    doc = xml.dom.minidom.parseString(s)
    if clz == 'T1':
        return T1(doc.getElementsByTagName('f1')[0].firstChild.data, doc.getElementsByTagName('f2')[0].firstChild.data)
    if clz == 'T1Array':
        res = T1Array()
        for elm in doc.getElementsByTagName('t1'):
            res.array.append(T1(elm.getElementsByTagName('f1')[0].firstChild.data, elm.getElementsByTagName('f2')[0].firstChild.data))
        return res
    raise Exception('Unknown class: ' + clz)

def Json2Object(clz, s):
    o = json.loads(s)
    if clz == 'T1':
        return T1(o['f1'], o['f2'])
    if clz == 'T1Array':
        res = T1Array()
        for o1 in o:
            res.array.append(T1(o1['f1'], o1['f2']))
        return res
    raise Exception('Unknown class: ' + clz)

def String2Object(clz, s, typ):
    if typ == 'application/xml':
        return Xml2Object(clz, s)
    if typ == 'application/json':
        return Json2Object(clz, s)
    else:
        raise Exception('Unknown type: ' + typ)

#
# Data classes.
#
class T1(object):
    def __init__(self, _f1 = 0, _f2 = ''):
        self.f1 = _f1
        self.f2 = _f2
    def __str__(self):
        return '{%s,%s}' % (self.f1, self.f2)

class T1Array(object):
    def __init__(self):
        self.array = []

#
# Web service calls.
#
def testGetOne(url, f1, acctyp):
    resp = requests.get(url + '/t1/' + str(f1), headers = { 'Accept': acctyp})
    print(int(resp.status_code / 100) == 2)
    contyp = resp.headers['Content-Type'].split(';')[0]
    o = String2Object('T1', resp.text, contyp)
    print(str(o))

def testGetAll(url, acctyp):
    resp = requests.get(url + '/t1', headers = { 'Accept': acctyp})
    print(int(resp.status_code / 100) == 2)
    contyp = resp.headers['Content-Type'].split(';')[0]
    a = String2Object('T1Array', resp.text, contyp)
    for o in a.array:
        print(str(o))

def testGetSome(url, start, finish, acctyp):
    resp = requests.get(url + '/t1?start=' + str(start) + '&finish=' + str(finish), headers = { 'Accept': acctyp})
    print(int(resp.status_code / 100) == 2)
    contyp = resp.headers['Content-Type'].split(';')[0]
    a = String2Object('T1Array', resp.text, contyp)
    for o in a.array:
        print(str(o))

def testPost(url, contyp, o, acctyp):
    resp = requests.post(url + '/t1', headers = { 'Content-Type': contyp, 'Accept': acctyp}, data = Object2String(o, contyp))
    print(int(resp.status_code / 100) == 2)
    contyp2 = resp.headers['Content-Type'].split(';')[0]
    o = String2Object('T1', resp.text, contyp2)
    print(str(o))

def testPut(url, contyp, o):
    resp = requests.put(url + '/t1/' + str(o.f1), headers = { 'Content-Type': contyp}, data = Object2String(o, contyp))
    print(int(resp.status_code / 100) == 2)

def testDelete(url, f1):
    resp = requests.delete(url + '/t1/' + str(f1))
    print(int(resp.status_code / 100) == 2)

def test2(url, acctyp):
    print('**** %s (%s) ****' % (url, acctyp))
    testGetOne(url, 123, acctyp)
    testGetAll(url, acctyp)
    testGetSome(url, 10, 12, acctyp)
    testPost(url, acctyp, T1(123, 'ABC'), acctyp)
    testPut(url, acctyp, T1(123, 'ABC'))
    testDelete(url, 123)

def test(url):
    test2(url, 'application/xml')
    test2(url, 'application/json')

test('http://localhost:8080/wsrest/testapi1');
test('http://localhost:8080/wsrest/testapi2');
test('http://localhost:8080/wsrest/testapi3');
test('http://localhost/testapi.ashx');
test('http://localhost/testapi.svc');
test('http://localhost/testapi');
test('http://localhost:81/testapi.php')

