def docomponent(str, loc, toks): global attrs, keyvals, paths, curcontext, themodel, Debug if curcontext == "": print "No context defined for component", toks[1] print "docomponent::", toks[1] sys.stdout.flush() print " \tattrs::", attrs required = ['type', 'description', 'value_type'] for x in required: if x not in attrs[0]: print "one or more of the required keyvals", required, "not found for ", toks[ 1] print attrs[0] return if not Debug: cobj = Personis_base.Component(Identifier=toks[1], component_type=attrs[0]['type'], value_type=attrs[0]['value_type'], value_list=attrs[0].get('value'), resolver=attrs[0].get('resolver'), Description=attrs[0]['description']) try: res = themodel.mkcomponent(context=curcontext, componentobj=cobj) except: print "mkcomponent failed" if res != None: print res print """cobj = Personis_base.Component(Identifier="%s", component_type="%s", value_type="%s", value_list="%s", resolver="%s", Description="%s") """ % (toks[1], attrs[0]['type'], attrs[0]['value_type'], attrs[0].get('value'), attrs[0].get('resolver'), attrs[0]['description']) if 'rule' in attrs[0]: if type(attrs[0]['rule']) != type([]): rules = [attrs[0]['rule']] for rule in rules: if not Debug: themodel.subscribe(context=curcontext, view=[toks[1]], subscription=dict(user="******", password="******", statement=rule)) print "\tsub::", curcontext, [toks[1]], dict(user="******", password="******", statement=rule) print "+++ component created " if len(attrs) > 1: # see if there is some evidence for e in attrs[1:]: print "\tevidence::", e dotells(e, toks[1]) # del attrs[0] attrs = [] keyvals = {} paths = []
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_mkcomponent(self, line): """mkcomponent component_name make a new component""" global um, context, attrs if not loggedin(self.username, self.userpassword, 'mkcomponent'): return if not nomodel(self.umname, line): return line = line.split() if len(line) != 1: print "usage: mkcomponent compname" return contxt = self.context comp = line[0] compdesc = raw_input("Component description? ") print "Component type:" for ct in Personis_base.ComponentTypes: print Personis_base.ComponentTypes.index(ct), ct ctindex = int(raw_input("Index? ")) if (ctindex < 0) or (ctindex > len(Personis_base.ComponentTypes) - 1): print "Index out of range" return comptype = Personis_base.ComponentTypes[ctindex] print "Value type:" for ct in Personis_base.ValueTypes: print Personis_base.ValueTypes.index(ct), ct ctindex = int(raw_input("Index? ")) if (ctindex < 0) or (ctindex > len(Personis_base.ValueTypes) - 1): print "Index out of range" return valtype = Personis_base.ValueTypes[ctindex] print "Creating new component '%s', type '%s', description '%s', value type '%s'" % ( comp, comptype, compdesc, valtype) ok = raw_input("Ok?[N] ") if ok != 'Y': return cobj = Personis_base.Component(Identifier=comp, component_type=comptype, Description=compdesc, value_type=valtype) res = um.mkcomponent(context=contxt, componentobj=cobj)
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 python import Personis import Personis_base from Personis_util import printcomplist um = Personis.Access(model="bob", user='******') sleep = Personis_base.Component(Identifier="sleep", Description="Sleep info", component_type="attribute", value_type="string") um.mkcomponent(context=["Personal", "Health"], componentobj=sleep)
#!/usr/bin/env python import Personis_base from Personis_util import printcomplist, showobj # create a new component um = Personis_base.Access(model="Alice", modeldir='Tests/Models', authType='user', auth='alice:secret') cobj = Personis_base.Component(Identifier="age", component_type="attribute", Description="age", goals=[['Personal', 'Health', 'weight']], value_type="number") showobj(cobj, 1) res = um.mkcomponent(context=["Personal"], componentobj=cobj) print ` res ` # show this age in the Personal context ev = Personis_base.Evidence(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 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, showobj print "Testing goals" print "\tcreate a new component" um = Personis_base.Access(model="Alice", modeldir='Tests/Models', authType='user', auth='alice:secret') cobj = Personis_base.Component(Identifier="fitness", component_type="goal", Description="My overall fitness", goals=[['Personal', 'Health', 'weight']], value_type="number") showobj(cobj, 1) res = um.mkcomponent(context=["Personal"], componentobj=cobj) print ` res ` print "\t show this component in the Personal context" ev = Personis_base.Evidence(evidence_type="explicit", value=17) um.tell(context=["Personal"], componentid='fitness', evidence=ev) reslist = um.ask(context=["Personal"], view=['fitness'], resolver={'evidence_filter': "all"}) printcomplist(reslist, printev="yes") goals = reslist[0].goals print "Old goals are:", goals
#!/usr/bin/env python import Personis import Personis_base from Personis_util import printcomplist um = Personis.Access(model="bob", user='******') weight = Personis_base.Component(Identifier="weight", Description="My weight", component_type="attribute", value_type="number") um.mkcomponent(context=["Personal", "Health"], componentobj=weight)