def dotell_body(str, loc, toks,changed_only=False): model = toks[1] if model == '.': model = defaultmodel context = [x for x in toks[2:-6] if x != '/'] componentid = toks[-5] evidence_type = toks[-3] newval = toks[-1] print "Tell %s/%s/%s, %s:%s" % (model, context, componentid, evidence_type, newval) try: if model!=defaultmodel: global Personis import Personis as pmdns um = pmdns.Access(model=model, user=user, password=password) if changed_only: comp = um.ask(context=context, view=[componentid], resolver='default')[0] if comp.value == newval: return True # don't actually need to do the tell um.tell(context=context, componentid=componentid, evidence=Personis_base.Evidence(evidence_type=evidence_type, value=newval)) else: if changed_only: comp = currentum.ask(context=context, view=[componentid], resolver='default')[0] if comp.value == newval: return True # don't actually need to do the tell currentum.tell(context=context, componentid=componentid, evidence=Personis_base.Evidence(evidence_type=evidence_type, value=newval)) except: print 'tell failed' raise ParseException, (str, loc, "tell failed",0) return True
def dotells(ev, compid): global themodel, curcontext evattrs = [ "flags", "evidence_type", "source", "owner", "value", "comment", "time", "useby" ] if not all([a in evattrs for a in ev]): print "**** evidence attributes %s must be one of %s" % (ev.keys(), ` evattrs `) return if "flags" in ev: if type(ev['flags']) != type([]): print "**** evidence flags %s must be a list" % (ev['flags']) return if not Debug: evobj = Personis_base.Evidence(evidence_type="explicit") for k, v in ev.items(): evobj.__dict__[k] = v themodel.tell(context=curcontext, componentid=compid, evidence=evobj) print """ evobj = Personis_base.Evidence(ev) themodel.tell(context=%s, componentid=%s, evidence=%s) """ % (curcontext, compid, evobj.__dict__) else: print """ evobj = Personis_base.Evidence(ev) themodel.tell(context=%s, componentid=%s, evidence=%s) """ % (curcontext, compid, ev)
def ask(self, context=[], view=None, resolver=None, showcontexts=None): """ arguments: (see Personis_base for details) context is a list giving the path of context identifiers view is either: an identifier of a view in the context specified a list of component identifiers or full path lists None indicating that the values of all components in the context be returned resolver specifies a resolver, default is the builtin resolver returns a list of component objects """ if self.authType == 'app': self.auth = self.app + ":" + Personis_base.generate_app_signature( self.app, self.key) reslist = jsoncall.do_call(self.modelserver, self.modelport, self.ca_certs_file, "ask", {'modelname':self.modelname,\ 'authType':self.authType,\ 'auth':self.auth,\ 'context':context,\ 'view':view,\ 'resolver':resolver,\ 'showcontexts':showcontexts}) complist = [] if showcontexts: cobjlist, contexts, theviews, thesubs = reslist for c in cobjlist: comp = Personis_base.Component(**c) if c["evidencelist"]: comp.evidencelist = [ Personis_base.Evidence(**e) for e in c["evidencelist"] ] complist.append(comp) reslist = [complist, contexts, theviews, thesubs] else: for c in reslist: comp = Personis_base.Component(**c) if c["evidencelist"]: comp.evidencelist = [ Personis_base.Evidence(**e) for e in c["evidencelist"] ] complist.append(comp) reslist = complist return reslist
def do_tell(self, line): """tell component_name will prompt for component value etc""" global um, umname, context, username if not loggedin(self.username, self.userpassword, 'tell'): return if not nomodel(self.umname, line): return line = line.split() if len(line) != 1: print "usage: tell component" return compname = line[0] val = raw_input("Value? ") print "Evidence type:" for et in Personis_base.EvidenceTypes: print Personis_base.EvidenceTypes.index(et), et etindex = raw_input("Index? [0]") if etindex == '': etindex = 0 else: etindex = int(etindex) if (etindex < 0) or (etindex > len(Personis_base.EvidenceTypes) - 1): print "Index out of range" return etype = Personis_base.EvidenceTypes[etindex] source = self.username flags = [] while True: flag = raw_input("Evidence flag? (CR for none)") if flag == '': break flags.append(flag) print "Tell value=%s, type=%s, flags=%s, source=%s, context=%s, component=%s " % ( val, etype, flags, source, self.context, compname) ok = raw_input("Ok?[N] ") if ok != 'Y': return ev = Personis_base.Evidence(source=source, evidence_type=etype, flags=flags, value=val) try: um.tell(context=self.context, componentid=compname, evidence=ev) except ValueError, e: print "tell failed: %s" % (e)
#!/usr/bin/env python import Personis import Personis_base from Personis_util import printcomplist # add some evidence to some components - use example1_asks to see it print ">>>> add evidence of Alice's names to his model" um = Personis.Access(model="Alice", user='******', password='******') # create a piece of evidence with demoex2 as source and Alice as value ev = Personis_base.Evidence(source="demoex2", evidence_type="explicit", value="Alice") # tell this as user Alice's first name um.tell(context=["Personal"], componentid='firstname', evidence=ev) ev = Personis_base.Evidence(source="demoex2", evidence_type="explicit", value="Smith") um.tell(context=["Personal"], componentid='lastname', evidence=ev) print "===================================================================" print ">>>> Now check the evidence list for Alice's names" reslist = um.ask(context=["Personal"], view='fullname') printcomplist(reslist, printev="yes")
def default(self, *args): try: jsonobj = cherrypy.request.body.read() print jsonobj pargs = json.loads(jsonobj) except: print "bad request - cannot decode json - possible access from web browser" return json.dumps( "Personis User Model server. Not accessible using a web browser." ) # dirty kludge to get around unicode for k, v in pargs.items(): if type(v) == type(u''): pargs[k] = str(v) if type(k) == type(u''): del pargs[k] pargs[str(k)] = v try: result = False if args[0] == 'mkmodel': # fixme need to implement security # and error handling # Only users can make models, so authType must be 'user' (user, password) = pargs['auth'].split(":") Personis_base.MkModel(model=pargs['modelname'], modeldir=self.modeldir, \ user=user, password=password, description=pargs['description']) result = True elif args[0] == 'apprequestauth': Personis_base.AppRequestAuth(model=pargs['modelname'], modeldir=self.modeldir, \ app=pargs['app'], key=pargs['key'], description=pargs['description']) result = True else: um = Personis_a.Access(model=pargs['modelname'], modeldir=self.modeldir, authType=pargs['authType'], auth=pargs['auth']) if args[0] == 'access': result = True elif args[0] == 'tell': result = um.tell( context=pargs['context'], componentid=pargs['componentid'], evidence=Personis_base.Evidence(**pargs['evidence'])) elif args[0] == 'ask': reslist = um.ask(context=pargs['context'], view=pargs['view'], resolver=pargs['resolver'], \ showcontexts=pargs['showcontexts']) if pargs['showcontexts']: cobjlist, contexts, theviews, thesubs = reslist cobjlist = [c.__dict__ for c in cobjlist] for c in cobjlist: if c["evidencelist"]: c["evidencelist"] = [e for e in c["evidencelist"]] newviews = {} if theviews != None: for vname, v in theviews.items(): newviews[vname] = v.__dict__ else: newviews = None reslist = [cobjlist, contexts, newviews, thesubs] else: reslist = [c.__dict__ for c in reslist] for c in reslist: if c["evidencelist"]: c["evidencelist"] = [e for e in c["evidencelist"]] result = reslist elif args[0] == 'subscribe': result = um.subscribe(context=pargs['context'], view=pargs['view'], subscription=pargs['subscription']) elif args[0] == 'delete_sub': result = um.delete_sub(context=pargs['context'], componentid=pargs['componentid'], subname=pargs['subname']) elif args[0] == 'list_subs': result = um.list_subs(context=pargs['context'], componentid=pargs['componentid']) elif args[0] == 'export_model': result = um.export_model(context=pargs['context'], resolver=pargs['resolver']) elif args[0] == 'import_model': result = um.import_model(context=pargs['context'], partial_model=pargs['partial_model']) elif args[0] == 'set_goals': result = um.set_goals(context=pargs['context'], componentid=pargs['componentid'], goals=pargs['goals']) elif args[0] == 'registerapp': result = um.registerapp(app=pargs['app'], desc=pargs['description'], fingerprint=pargs['fingerprint']) elif args[0] == 'deleteapp': result = um.deleteapp(app=pargs['app']) elif args[0] == 'getpermission': result = um.getpermission(context=pargs['context'], componentid=pargs['componentid'], app=pargs['app']) elif args[0] == 'setpermission': result = um.setpermission(context=pargs['context'], componentid=pargs['componentid'], app=pargs['app'], permissions=pargs['permissions']) elif args[0] == 'listapps': result = um.listapps() elif args[0] == 'listrequests': result = um.listrequests() elif args[0] == 'mkcomponent': comp = Personis_base.Component(**pargs["componentobj"]) result = um.mkcomponent(pargs["context"], comp) elif args[0] == 'delcomponent': result = um.delcomponent(pargs["context"], pargs["componentid"]) elif args[0] == 'delcontext': result = um.delcontext(pargs["context"]) elif args[0] == 'setresolver': result = um.setresolver(pargs["context"], pargs["componentid"], pargs["resolver"]) elif args[0] == 'getresolvers': result = um.getresolvers() elif args[0] == 'mkview': viewobj = Personis_base.View(**pargs["viewobj"]) result = um.mkview(pargs["context"], viewobj) elif args[0] == 'delview': result = um.delview(pargs["context"], pargs["viewid"]) elif args[0] == 'mkcontext': contextobj = Personis_base.Context(**pargs["contextobj"]) result = um.mkcontext(pargs["context"], contextobj) elif args[0] == 'getcontext': result = um.getcontext(pargs["context"], pargs["getsize"]) # Repackage result code with error values IF there is a version string. if pargs.has_key("version"): new_result = {} new_result["result"] = "ok" new_result["val"] = result result = new_result except Exception, e: print "Exception:", e traceback.print_exc() if pargs.has_key("version"): new_result = {} #new_result["errorType"] = e.__class__.__name__ #new_result["errorData"] = e.__dict__.copy() #new_result["pythonPickel"] = cPickle.dumps(e) new_result["val"] = [ e.__class__.__name__, e.__dict__.copy(), cPickle.dumps(e) ] new_result["result"] = "error" result = new_result else: result = False
#!/usr/bin/env python2.4 # NOTE: this test can only be run locally since # it adds a new resolver. import Personis_base from Personis_util import printcomplist # add some evidence to some components and then use example1 to see it um = Personis_base.Access(model="Alice", modeldir="Tests/Models", authType='user', auth='alice:secret') # create a piece of evidence with Alice as value ev = Personis_base.Evidence(evidence_type="explicit", value="Alice") # tell this as user Alice's first name um.tell(context=["Personal"], componentid='firstname', evidence=ev) ev = Personis_base.Evidence(evidence_type="explicit", value="Smith") um.tell(context=["Personal"], componentid='lastname', evidence=ev) print "===================================================================" print "Now add a new resolver to um" def myresolver(model=None, component=None, context=None, resolver_args=None): """ new resolver function """ print "new resolver called with ", `component` if resolver_args == None: ev_filter = None else: ev_filter = resolver_args.get('evidence_filter') component.evidencelist = component.filterevidence(model=model, context=context, resolver_args=resolver_args) if len(component.evidencelist) > 0:
#!/usr/bin/env python import Personis import Personis_base from urllib2 import urlopen import json, time u = urlopen("http://wbsapi.withings.net/measure?action=getmeas&userid=14044&publickey=a724d144737439b5&limit=1") res = u.read() res = json.jsonToObj(res) mtime = res['body']['measuregrps'][0]['date'] weight = res['body']['measuregrps'][0]['measures'][0]['value']/1000.0 print "Time:", time.ctime(mtime), "Weight:", weight um = Personis.Access(model="bob", user='******') ev = Personis_base.Evidence(source="withings", evidence_type="given", value=weight, time=mtime) um.tell(context=["Personal", "Health"], componentid='weight', evidence=ev)
#!/usr/bin/env python import Personis import Personis_base from Personis_util import printcomplist # add some evidence to a component in the music preferences um = Personis.Access(model="Alice", user='******', password='******') ev = Personis_base.Evidence(source="alice", evidence_type="explicit", value=4) print ">>>> add a preference for Alice for Miles_Davis" um.tell(context=["Preferences", "Music","Jazz","Artists"], componentid='Miles_Davis', evidence=ev) print "===================================================================" print ">>>> Now check the evidence list for that preference" reslist = um.ask(context=["Preferences", "Music", "Jazz", "Artists"], view=['Miles_Davis'], resolver={'evidence_filter':"all"}) printcomplist(reslist, printev = "yes")
#!/usr/bin/env python import Personis import Personis_base from Personis_util import printcomplist print ">>>> add some evidence to some components and then use example1 to see it" um = Personis.Access(model="Alice", user='******', password='******') print ">>>> create a piece of evidence with alice as source and Alice as value" ev = Personis_base.Evidence(source="willy", evidence_type="explicit", value="Fred") print ">>>> tell this as user alice's first name" um.tell(context=["Personal"], componentid='firstname', evidence=ev) ev = Personis_base.Evidence(source="nilly", evidence_type="explicit", value="Smith") um.tell(context=["Personal"], componentid='lastname', evidence=ev) print "===================================================================" print ">>>> Now check the evidence list for Alice's names" reslist = um.ask(context=["Personal"], view='fullname') printcomplist(reslist, printev = "yes")
#!/usr/local/bin/python import Personis_base from Personis_util import printcomplist print "tell new location for Alice" um = Personis_base.Access(model='Alice', modeldir='Tests/Models', authType='user', auth='alice:secret') # create a piece of evidence with home as value ev = Personis_base.Evidence(evidence_type="explicit", value="home") # tell this as user alice's location um.tell(context=['Location'], componentid='location', evidence=ev) print "===================================================================" print "Now check the evidence list for Alice's location" reslist = um.ask(context=['Location'], view=['location'], resolver={'evidence_filter': "all"}) printcomplist(reslist, printev="yes")
#!/usr/bin/env python import Personis import Personis_base from Personis_util import printcomplist, showobj print ">>>> create an 'age' component" um = Personis.Access(model="Alice", user='******', password='******') cobj = Personis_base.Component(Identifier="age", component_type="attribute", Description="age", value_type="number") showobj(cobj, 1) res = um.mkcomponent(context=["Personal"], componentobj=cobj) print `res` print ">>>> show the age component in the Personal context" ev = Personis_base.Evidence(source="example 6", evidence_type="explicit", value=17) um.tell(context=["Personal"], componentid='age', evidence=ev) reslist = um.ask(context=["Personal"], view=['age'], resolver={'evidence_filter':"all"}) printcomplist(reslist, printev = "yes")
#!/usr/bin/env python import Personis_base from Personis_util import printcomplist import json print "add a JSON encoded value to a component" fullname = {'firstname': 'Alice', 'lastname': 'Smith'} um = Personis_base.Access(model="Alice", modeldir='Tests/Models', authType='user', auth='alice:secret') # create a piece of evidence with json encoded value ev = Personis_base.Evidence(evidence_type="explicit", value=json.dumps(fullname)) um.tell(context=["People"], componentid='fullname', evidence=ev) print "===================================================================" print "Now check the evidence list " reslist = um.ask(context=["People"], view=['fullname']) printcomplist(reslist, printev="yes")
#!/usr/bin/env python import Personis import Personis_base um = Personis.Access(model="bob", user='******') ev = Personis_base.Evidence(source="withings", evidence_type="given", value="77.0") um.tell(context=["Personal", "Health"], componentid='weight', evidence=ev)
#!/usr/bin/env python import Personis import Personis_base from Personis_util import printcomplist import json print ">>>> add a JSON encoded value to a component" fullname = {'firstname': 'Judy', 'lastname': 'Kay'} um = Personis.Access(model="Alice", user='******', password='******') # create a piece of evidence with demoex2 as source and json encoded value ev = Personis_base.Evidence(source="demoex2", evidence_type="explicit", value=json.dumps(fullname)) um.tell(context=["People"], componentid='fullname', evidence=ev) print "===================================================================" print ">>>> Now check the evidence list " reslist = um.ask(context=["People"], view=['fullname']) printcomplist(reslist, printev="yes")