SLA and Service Directory code added
[unfold.git] / sla / slaclient / restclient_old.py
1 # -*- coding: utf-8 -*-
2
3 import requests
4
5 import xmlconverter
6 import wsag_model
7
8
9 """REST client to SLA Manager.
10
11 Contains a generic rest client and wrappers over this generic client 
12 for each resource.
13
14 Each resource client implements business-like() functions, but
15 returns a tuple (output, requests.Response)
16
17 The resource clients are initialized with the rooturl and a path, which 
18 are combined to build the resource url. The path is defaulted to the known
19 resource path. So, for example, to create a agreements client:
20
21 c = Agreements("http://localhost/slagui-service")
22
23 A Factory facility is provided to create resource client instances. The
24 Factory uses "rooturl" module variable to use as rooturl parameter.
25
26 restclient.rooturl = "http://localhost/slagui-service"
27 c = restclient.Factory.agreements()
28
29 """
30
31 _PROVIDERS_PATH = "providers"
32 _AGREEMENTS_PATH = "agreements"
33 _VIOLATIONS_PATH = "violations"
34 _ENFORCEMENTJOBS_PATH = "enforcementjobs"
35
36 rooturl = ""
37
38
39 class Factory(object):
40     @staticmethod
41     def agreements():
42         """Returns aREST client for Agreements
43
44         :rtype : Agreements
45         """
46         return Agreements(rooturl)
47
48     @staticmethod
49     def providers():
50         """Returns aREST client for Providers
51
52         :rtype : Providers
53         """
54         return Providers(rooturl)
55
56     @staticmethod
57     def violations():
58         """Returns aREST client for Violations
59
60         :rtype : Violations
61         """
62         return Violations(rooturl)
63
64 class Client(object):
65
66     def __init__(self, root_url):
67
68         """Generic rest client using requests library
69
70         Each operation mimics the corresponding "requests" operation (arguments
71         and return)
72
73         :param str root_url: this url is used as prefix in all subsequent
74             requests
75         """
76         self.rooturl = root_url
77
78     def get(self, path, **kwargs):
79         """Just a wrapper over request.get, just in case.
80
81         Returns a requests.Response
82
83         :rtype : request.Response
84         :param str path: remaining path from root url; 
85             empty if desired path equal to rooturl.
86         :param kwargs: arguments to requests.get
87         
88         Example: 
89             c = Client("http://localhost:8080/service")
90             c.get("/resource", headers = { "accept": "application/json" })
91         """
92         url = _buildpath_(self.rooturl, path)
93         result = requests.get(url, **kwargs)
94         print "GET {} {} {}".format(
95             result.url, result.status_code, result.text[0:70])
96         return result
97
98 class _Resource(object):
99
100     def __init__(self, url, converter):
101         """Provides some common operations over resources.
102
103         The operations return a structured representation of the resource.
104
105         :param str url: url to the resource
106         :param Converter converter: resouce xml converter
107
108         Some attributes are initialized to be used from the owner if needed:
109         * client: Client instance
110         * converter: resource xml converter
111         * listconverter: list of resources xml converter
112         """
113         self.client = Client(url)
114         self.converter = converter
115         self.listconverter = xmlconverter.ListConverter(self.converter)
116
117     @staticmethod
118     def _processresult(r, converter):
119
120         """Generic processing of the REST call.
121
122          If no errors, tries to convert the result to a destination entity.
123
124         :param r requests:
125         :param converter Converter:
126         """
127         if r.status_code == 404:
128             return None
129
130         content_type = r.headers.get('content-type', '')
131
132         print("content-type = " + content_type)
133         if content_type == 'application/json':
134             result = r.json()
135         elif content_type == 'application/xml':
136             xml = r.text
137             result = xmlconverter.convertstring(converter, xml)
138         else:
139             result = r.text
140         return result
141
142     def getall(self):
143         """Get all resources
144
145         """
146         r = self.client.get("")
147         resources = self._processresult(r, self.listconverter)
148         return resources, r
149
150     def getbyid(self, id):
151         """Get resource 'id'"""
152         r = self.client.get(id)
153         resource = _Resource._processresult(r, self.converter)
154         return resource, r
155
156     def get(self, params):
157         """Generic query over resource: GET /resource?q1=v1&q2=v2...
158
159         :param dict[str,str] params: values to pass as get parameters
160         """
161         r = self.client.get("", params=params)
162         resources = self._processresult(r, self.listconverter)
163         return resources, r
164
165 class Agreements(object):
166
167     def __init__(self, root_url, path=_AGREEMENTS_PATH):
168         """Business methods for Agreement resource
169         :param str root_url: url to the root of resources
170         :param str path: path to resource from root_url
171
172         The final url to the resource is root_url + "/" + path
173         """
174         resourceurl = _buildpath_(root_url, path)
175         converter = xmlconverter.AgreementConverter()
176         self.res = _Resource(resourceurl, converter)
177
178     def getall(self):
179         """
180         Get all agreements
181
182         :rtype : list[wsag_model.Agreement]
183         """
184         return self.res.getall()
185
186     def getbyid(self, agreementid):
187         """Get an agreement
188
189         :rtype : wsag_model.Agreement
190         """
191         return self.res.getbyid(agreementid)
192
193     def getbyconsumer(self, consumerid):
194         """Get a consumer's agreements
195
196         :rtype : list[wsag_model.Agreement]
197         """
198         return self.res.get(dict(consumerId=consumerid))
199
200     def getbyprovider(self, providerid):
201         """Get the agreements served by a provider
202
203         :rtype : list[wsag_model.Agreement]
204         """
205         return self.res.get(dict(providerId=providerid))
206
207     def getstatus(self, agreementid):
208         """Get guarantee status of an agreement
209
210         :param str agreementid :
211         :rtype : wsag_model.AgreementStatus
212         """
213         path = _buildpath_(agreementid, "guaranteestatus")
214         r = self.res.client.get(path, headers={'accept': 'application/json'})
215         json_obj = r.json()
216         status = wsag_model.AgreementStatus.json_decode(json_obj)
217
218         return status, r
219
220 class Providers(object):
221
222     def __init__(self, root_url, path=_PROVIDERS_PATH):
223         """Business methods for Providers resource
224         :param str root_url: url to the root of resources
225         :param str path: path to resource from root_url
226
227         The final url to the resource is root_url + "/" + path
228         """
229         resourceurl = _buildpath_(root_url, path)
230         converter = xmlconverter.ProviderConverter()
231         self.res = _Resource(resourceurl, converter)
232
233     def getall(self):
234         """ Get all providers
235
236         :rtype : list[wsag_model.Provider]
237         """
238         return self.res.getall()
239
240     def getbyid(self, provider_id):
241         """Get a provider
242
243         :rtype: wsag_model.Provider
244         """
245         return self.res.getbyid(provider_id)
246
247 class Violations(object):
248
249     def __init__(self, root_url, path=_VIOLATIONS_PATH):
250         """Business methods for Violation resource
251         :param str root_url: url to the root of resources
252         :param str path: path to resource from root_url
253
254         The final url to the resource is root_url + "/" + path
255         """
256         resourceurl = _buildpath_(root_url, path)
257         converter = xmlconverter.ViolationConverter()
258         self.res = _Resource(resourceurl, converter)
259
260     def getall(self):
261         """ Get all violations
262         :rtype : list[wsag_model.Violation]
263         """
264         return self.res.getall()
265
266     def getbyid(self, violationid):
267         """Get a violation
268
269         :rtype : wsag_model.Violation
270         """
271         return self.res.getbyid(violationid)
272
273     def getbyagreement(self, agreement_id, term=None):
274         """Get the violations of an agreement.
275
276         :param str agreement_id:
277         :param str term: optional GuaranteeTerm name. If not specified,
278             violations from all terms will be returned
279         :rtype: list[wsag_model.Violation]
280         """
281         return self.res.get(
282             {"agreementId": agreement_id, "guaranteeTerm": term})
283
284
285 def _buildpath_(*paths):
286     return "/".join(paths)
287
288
289 def main():
290     #
291     # Move to test
292     #
293     global rooturl
294     rooturl = "http://10.0.2.2:8080/sla-service"
295
296     c = Factory.agreements()
297     #r = c.getall()
298     #r = c.getbyid("noexiste")
299     #r = c.getstatus("agreement03")
300     #print r
301
302     #r = c.getbyconsumer('RandomClient')
303
304     c = Providers(rooturl)
305     r = c.getall()
306
307     c = Violations(rooturl)
308     #r = c.getall()
309     r_ = c.getbyagreement("agreement03", "GT_Otro")
310     r_ = c.getbyid('cf41011d-9f30-4ebc-a967-30b4ea928192')
311
312     print r_
313
314
315 if __name__ == "__main__":
316     main()
317
318