[server] fix unicode conversion capability in UndoException
By overriding the __unicode__ method, we ensure unicode builtin will return
Unicode object even for python versions that don't have a __unicode__ method by
default (python < 2.6)
In previous versions, when this method is not defined, string conversion is
attempted, and the result of string conversion is converted to Unicode using
the system default encoding which is ascii the most of the time.
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr## This file is part of CubicWeb.## CubicWeb is free software: you can redistribute it and/or modify it under the# terms of the GNU Lesser General Public License as published by the Free# Software Foundation, either version 2.1 of the License, or (at your option)# any later version.## CubicWeb is distributed in the hope that it will be useful, but WITHOUT# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more# details.## You should have received a copy of the GNU Lesser General Public License along# with CubicWeb. If not, see <http://www.gnu.org/licenses/>."""Some utilities for the CubicWeb server."""__docformat__="restructuredtext en"importsysimportstringimportloggingfromthreadingimportTimer,Threadfromgetpassimportgetpassfromrandomimportchoicefromcubicweb.serverimportSOURCE_TYPEStry:fromcryptimportcryptexceptImportError:# crypt is not available (eg windows)fromcubicweb.md5cryptimportcryptdefgetsalt(chars=string.letters+string.digits):"""generate a random 2-character 'salt'"""returnchoice(chars)+choice(chars)defcrypt_password(passwd,salt=None):"""return the encrypted password using the given salt or a generated one """ifpasswdisNone:returnNoneifsaltisNone:salt=getsalt()returncrypt(passwd,salt)defcartesian_product(seqin):"""returns a generator which returns the cartesian product of `seqin` for more details, see : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 """defrloop(seqin,comb):"""recursive looping function"""ifseqin:# any more sequences to process?foriteminseqin[0]:newcomb=comb+[item]# add next item to current combination# call rloop w/ remaining seqs, newcombforiteminrloop(seqin[1:],newcomb):yielditem# seqs and newcombelse:# processing last sequenceyieldcomb# comb finished, add to listreturnrloop(seqin,[])defcleanup_solutions(rqlst,solutions):forsolinsolutions:forvnameinsol.keys():ifnot(vnameinrqlst.defined_varsorvnameinrqlst.aliases):delsol[vname]defeschema_eid(session,eschema):"""get eid of the CWEType entity for the given yams type. You should use this because when schema has been loaded from the file-system, not from the database, (e.g. during tests), eschema.eid is not set. """ifeschema.eidisNone:eschema.eid=session.execute('Any X WHERE X is CWEType, X name %(name)s',{'name':str(eschema)})[0][0]returneschema.eidDEFAULT_MSG='we need a manager connection on the repository \(the server doesn\'t have to run, even should better not)'defmanager_userpasswd(user=None,msg=DEFAULT_MSG,confirm=False,passwdmsg='password'):ifnotuser:ifmsg:printmsgwhilenotuser:user=raw_input('login: ')user=unicode(user,sys.stdin.encoding)passwd=getpass('%s: '%passwdmsg)ifconfirm:whileTrue:passwd2=getpass('confirm password: ')ifpasswd==passwd2:breakprint'password doesn\'t match'passwd=getpass('password: ')# XXX decode password using stdin encoding then encode it using appl'encodingreturnuser,passwd_MARKER=object()deffunc_name(func):name=getattr(func,'__name__',_MARKER)ifnameis_MARKER:name=getattr(func,'func_name',_MARKER)ifnameis_MARKER:name=repr(func)returnnameclassLoopTask(object):"""threaded task restarting itself once executed"""def__init__(self,interval,func,args):ifinterval<=0:raiseValueError('Loop task interval must be > 0 ''(current value: %f for %s)'% \(interval,func_name(func)))self.interval=intervaldefauto_restart_func(self=self,func=func,args=args):try:func(*args)except:logger=logging.getLogger('cubicweb.repository')logger.exception('Unhandled exception in LoopTask %s',self.name)raisefinally:self.start()self.func=auto_restart_funcself.name=func_name(func)def__str__(self):return'%s (%s seconds)'%(self.name,self.interval)defstart(self):self._t=Timer(self.interval,self.func)self._t.setName('%s-%s[%d]'%(self._t.getName(),self.name,self.interval))self._t.start()defcancel(self):self._t.cancel()defjoin(self):ifself._t.isAlive():self._t.join()classRepoThread(Thread):"""subclass of thread so it auto remove itself from a given list once executed """def__init__(self,target,running_threads):defauto_remove_func(self=self,func=target):try:func()except:logger=logging.getLogger('cubicweb.repository')logger.exception('Unhandled exception in RepoThread %s',self._name)raisefinally:self.running_threads.remove(self)Thread.__init__(self,target=auto_remove_func)self.running_threads=running_threadsself._name=func_name(target)defstart(self):self.running_threads.append(self)self.daemon=TrueThread.start(self)defgetName(self):return'%s(%s)'%(self._name,Thread.getName(self))