1 # -*- coding: utf-8 -*-
9 """REST client to SLA Manager.
11 Contains a generic rest client and wrappers over this generic client
14 Each resource client implements business-like() functions, but
15 returns a tuple (output, requests.Response)
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:
21 c = Agreements("http://localhost/slagui-service")
23 A Factory facility is provided to create resource client instances. The
24 Factory uses "rooturl" module variable to use as rooturl parameter.
26 restclient.rooturl = "http://localhost/slagui-service"
27 c = restclient.Factory.agreements()
31 _PROVIDERS_PATH = "providers"
32 _AGREEMENTS_PATH = "agreements"
33 _VIOLATIONS_PATH = "violations"
34 _ENFORCEMENTJOBS_PATH = "enforcementjobs"
39 class Factory(object):
42 """Returns aREST client for Agreements
46 return Agreements(rooturl)
50 """Returns aREST client for Providers
54 return Providers(rooturl)
58 """Returns aREST client for Violations
62 return Violations(rooturl)
66 def __init__(self, root_url):
68 """Generic rest client using requests library
70 Each operation mimics the corresponding "requests" operation (arguments
73 :param str root_url: this url is used as prefix in all subsequent
76 self.rooturl = root_url
78 def get(self, path, **kwargs):
79 """Just a wrapper over request.get, just in case.
81 Returns a requests.Response
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
89 c = Client("http://localhost:8080/service")
90 c.get("/resource", headers = { "accept": "application/json" })
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])
98 class _Resource(object):
100 def __init__(self, url, converter):
101 """Provides some common operations over resources.
103 The operations return a structured representation of the resource.
105 :param str url: url to the resource
106 :param Converter converter: resouce xml converter
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
113 self.client = Client(url)
114 self.converter = converter
115 self.listconverter = xmlconverter.ListConverter(self.converter)
118 def _processresult(r, converter):
120 """Generic processing of the REST call.
122 If no errors, tries to convert the result to a destination entity.
125 :param converter Converter:
127 if r.status_code == 404:
130 content_type = r.headers.get('content-type', '')
132 print("content-type = " + content_type)
133 if content_type == 'application/json':
135 elif content_type == 'application/xml':
137 result = xmlconverter.convertstring(converter, xml)
146 r = self.client.get("")
147 resources = self._processresult(r, self.listconverter)
150 def getbyid(self, id):
151 """Get resource 'id'"""
152 r = self.client.get(id)
153 resource = _Resource._processresult(r, self.converter)
156 def get(self, params):
157 """Generic query over resource: GET /resource?q1=v1&q2=v2...
159 :param dict[str,str] params: values to pass as get parameters
161 r = self.client.get("", params=params)
162 resources = self._processresult(r, self.listconverter)
165 class Agreements(object):
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
172 The final url to the resource is root_url + "/" + path
174 resourceurl = _buildpath_(root_url, path)
175 converter = xmlconverter.AgreementConverter()
176 self.res = _Resource(resourceurl, converter)
182 :rtype : list[wsag_model.Agreement]
184 return self.res.getall()
186 def getbyid(self, agreementid):
189 :rtype : wsag_model.Agreement
191 return self.res.getbyid(agreementid)
193 def getbyconsumer(self, consumerid):
194 """Get a consumer's agreements
196 :rtype : list[wsag_model.Agreement]
198 return self.res.get(dict(consumerId=consumerid))
200 def getbyprovider(self, providerid):
201 """Get the agreements served by a provider
203 :rtype : list[wsag_model.Agreement]
205 return self.res.get(dict(providerId=providerid))
207 def getstatus(self, agreementid):
208 """Get guarantee status of an agreement
210 :param str agreementid :
211 :rtype : wsag_model.AgreementStatus
213 path = _buildpath_(agreementid, "guaranteestatus")
214 r = self.res.client.get(path, headers={'accept': 'application/json'})
216 status = wsag_model.AgreementStatus.json_decode(json_obj)
220 class Providers(object):
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
227 The final url to the resource is root_url + "/" + path
229 resourceurl = _buildpath_(root_url, path)
230 converter = xmlconverter.ProviderConverter()
231 self.res = _Resource(resourceurl, converter)
234 """ Get all providers
236 :rtype : list[wsag_model.Provider]
238 return self.res.getall()
240 def getbyid(self, provider_id):
243 :rtype: wsag_model.Provider
245 return self.res.getbyid(provider_id)
247 class Violations(object):
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
254 The final url to the resource is root_url + "/" + path
256 resourceurl = _buildpath_(root_url, path)
257 converter = xmlconverter.ViolationConverter()
258 self.res = _Resource(resourceurl, converter)
261 """ Get all violations
262 :rtype : list[wsag_model.Violation]
264 return self.res.getall()
266 def getbyid(self, violationid):
269 :rtype : wsag_model.Violation
271 return self.res.getbyid(violationid)
273 def getbyagreement(self, agreement_id, term=None):
274 """Get the violations of an agreement.
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]
282 {"agreementId": agreement_id, "guaranteeTerm": term})
285 def _buildpath_(*paths):
286 return "/".join(paths)
294 rooturl = "http://10.0.2.2:8080/sla-service"
296 c = Factory.agreements()
298 #r = c.getbyid("noexiste")
299 #r = c.getstatus("agreement03")
302 #r = c.getbyconsumer('RandomClient')
304 c = Providers(rooturl)
307 c = Violations(rooturl)
309 r_ = c.getbyagreement("agreement03", "GT_Otro")
310 r_ = c.getbyid('cf41011d-9f30-4ebc-a967-30b4ea928192')
315 if __name__ == "__main__":