Exemple #1
1
class User(StateNode):
	STATE_ACTIVE = 'Active'

	def __init__( self, name, parent ):
		StateNode.__init__( self, name, parent, initialState = self.STATE_ACTIVE )
		self.log = Logger().get_instance( self.__class__.__name__ )
		self.dialogs = {}

	def identifyEvent( self, event ):
		self.log.info( str(event) )
		if isinstance( event, MessageEvent ):
			return event.id
		elif isinstance( event, StateChangeNotification ):
			if event.node in self.dialogs.itervalues():
				return 'Dialog' + event.node.currentState

		raise SipException( '[' + str(self.name) + '] ' + 'Ignoring event ' + str(event) + '.' )

	def inActive_onRxRequest( self, event ):
		callid = event.message['Call-ID']
		if not callid in self.dialogs:
			dialog = Dialog( callid, self, event )
			dialog.addListener( self )
			self.dialogs[callid] = dialog

#FIXME: We don't really want to create a dialog for everything (e.g. REGISTER).
#       Even if we create a dummy dialog, then the subscribe and register dialogs would conflict.
		dialog = self.dialogs[callid]
		self.send( event, dialog, False )

	def inActive_onRxResponse( self, event ):
		callid = event.message['Call-ID']
		if not callid in self.dialogs:
			self.handled = True
			raise SipException( 'Dialog, ' + str(callid) + ' not found in user, ' + str(self.name) + '.' )
		else:
			dialog = self.dialogs[callid]
			self.send( event, dialog, False )

	def inActive_onTxRequest( self, event ):
		self.notify( event, False )

	def inActive_onTxResponse( self, event ):
		self.notify( event, False )

	def inActive_onDialogEarly( self, event ):
		#FIXME:
		self.inActive_onDialogProceeding( self, event )

	def inActive_onDialogProceeding( self, event ):
		dialog = [ d for d in self.dialogs.itervalues() ][0]
		transaction = dialog.transaction
		#FIXME:
		e = transaction.lastRequestEvent
		ne = createResponseEvent( e, 200 )
		self.notify( ne, True )
		event.handled = True
Exemple #2
0
	def __init__(self,mtdSrcDict,classDict,pkgDict,impDict,mtdInv):
		self.mtdSrcDict = mtdSrcDict
		self.classDict = classDict
		self.pkgDict = pkgDict
		self.impDict = impDict
		self.mtdInv = mtdInv
		self.log = Logger().get_instance(self)
    def __init__(self, pkgDict, impDict, inhDict, classDict, methDict,
                 mtdSrcDict, miList, mtdpfDict, sFile, nr, content, raw):
        self.log = Logger().get_instance(self)
        self.pkgDict = pkgDict
        self.impDict = impDict
        self.inhDict = inhDict
        self.classDict = classDict
        self.methDict = methDict
        self.mtdSrcDict = mtdSrcDict
        self.miList = miList
        self.sourceFile = sFile
        self.lineNr = nr
        self.content = content
        self.raw = raw  # full grep content
        self.mtdpfDict = mtdpfDict

        # to be filled in
        self.src_unqName = None  # fully qualified caller method
        self.src_name = None  # caller method
        self.src_param = None  # caller method parameters

        self.dst_base = None
        self.dst_name = None
        self.dst_param = None

        self.srcLoc = None  # caller method filename
        self.srcLineNr = None  # caller method line number

        self.dstLoc = None
        self.dstLineNr = None
Exemple #4
0
    def __init__(self, line):
        self.log = Logger().get_instance(self)
        self.cols = line.split(";")
        self.owner = self.cols[0]
        self.name = self.cols[1] + "(" + utils.cleanCol(self.cols[7]) + ")"

        sourceFile = self.cols[3]
        lineNr = self.cols[4].split(".")[0]
        self.sourceLocation = SourceLocation(sourceFile, lineNr, lineNr)

        self.isConstructor = False
        # TODO: parse visibility codes
        self.accessControlQualifier = "public"
        # TODO: static?
        self.hasClassScope = False
        # TODO: abstract? Interface?
        self.isAbstract = False
        params = self.cols[7]
        if "{}" == params:
            self.parameters = []
            self.parameterNames = []
        else:
            self.parameters = utils.cleanCol(params).split(",")
            self.parameterNames = utils.cleanCol(self.cols[8]).split(",")

        # to be resolved later
        self.package = None
        self.retType = None
        self.parentType = None
        # scope, visibility, abstract
        self.__resolveCharacteristics(self.cols[5])
Exemple #5
0
 def __init__(self, obj=None):
     """
     初始化方法:
     - 1.初始化配置信息
     - 2.初始化 className
     - 3.初始化数据库表的主键
     """
     if not obj:
         raise Exception(
             "BaseDao is missing a required parameter --> obj(class object).\nFor example [super().__init__(User)]."
         )
     else:
         self.__logger = Logger(self.__class__)  # 初始化日志对象
         self.__logger.start()  # 开启日志
         if not self.__parser:  # 解析 xml
             self.__parser = ConfigurationParser()
             self.__poolConfigDict = self.__parser.parseConfiguration()
             print(self.__poolConfigDict)
             self.__pool = PooledDB(**self.__poolConfigDict)
         # 初始化参数
         if (self.__obj == None) or (self.__obj != obj):
             global PRIMARY_KEY_DICT_LIST
             if (not PRIMARY_KEY_DICT_LIST) or (PRIMARY_KEY_DICT_LIST.count
                                                == 0):
                 self.__init_primary_key_dict_list()  # 初始化主键字典列表
             self.__init_params(obj)  # 初始化参数
             self.__init_columns()  # 初始化字段列表
             self.__logger.end()  # 结束日志
     pass
Exemple #6
0
 def __init__(self, line):
     self.log = Logger().get_instance(self)
     cols = line.split(":")
     self.sourceFile = cols[0].replace("./", "")
     self.lineNr = cols[1]
     self.content = cols[2].lstrip().split(
         " ")[0].strip()  # typically some code behind it
     self.owner = ""
class Parser(object):
    def __init__(self, fileName):
        self.log = Logger().get_instance(self.__class__.__name__)
        self.log.debug('Init parser for file ' + fileName)
        self.fileName = fileName

    def loadInClass(self, className):
        pass
Exemple #8
0
    def __init__(self, line):
        line = line.strip()

        self.metricLOC, self.metricCC, self.metricCOM, \
        self.pkgName, self.className, self.methodName = \
         self.__decomposeCols(line)

        self.invEntRef = None  # ref to invokable entity; to be resolved later
        self.log = Logger().get_instance(self)
class TransitiveInheritanceDictionary:
    ##
    # Initialize a transitive inheritance dictionary given an include dictionary.
    ##
    def __init__(self, inheritanceDictionary):
        # initialize an empty dictionary
        self.dict = {}
        self.inhDict = inheritanceDictionary

        self.calculateTransitiveSuperclasses()

        self.inhDict = None
        self.log = Logger().get_instance(self)

        ##
        # Add the transitive included files for each including file.
        ##

    def calculateTransitiveSuperclasses(self):
        for subclass in self.inhDict.dict:
            transitiveSuperclasses = self.inhDict.getTransitiveSuperclasses(subclass)
            self.dict[subclass] = transitiveSuperclasses

            ##
            # Is the dictionary aware of any superclasses of the given className
            ##

    def hasKey(self, className):
        return className in self.dict

        ##
        # Retrieve a list of names of transitive superclasses of the given class-name.
        ##

    def getTransitiveSuperclasses(self, className):
        superclasses = []

        if className in self.dict:
            superclasses = self.dict[className]

        return superclasses

        ##
        # Verify whether the given superclass-name is a known (transitive) superclass of the given subclass-name.
        ##

    def isSubclassOf(self, subclassName, superclassName):
        return superclassName in self.getTransitiveSuperclasses(subclassName)

        ##
        # Print the contents of the dictionary.
        ##

    def printContent(self):
        self.log.info("Dictionary has", len(self.dict), "elements:")
        for key in self.dict:
            self.log.info("[", key, ",", self.getTransitiveSuperclasses(key), "]")
Exemple #10
0
 def setUpClass(cls):
     open(cls.log_file, mode="w", encoding="utf-8").close()
     cls.file = open(cls.log_file, mode="r", encoding="utf-8")
     file_handler = {
         'class': 'logging.FileHandler',
         'filename': cls.log_file
     }
     Logger.configure(root={"handlers": ["file"]},
                      handlers={"file": file_handler})
Exemple #11
0
    def __init__(self, inheritanceDictionary):
        # initialize an empty dictionary
        self.dict = {}
        self.inhDict = inheritanceDictionary

        self.calculateTransitiveSuperclasses()

        self.inhDict = None
        self.log = Logger().get_instance(self)
Exemple #12
0
class Resources(Node):
	"""Dispatches incoming MessageEvents based on the Request-URI."""

	def __init__( self, name, parent ):
		super( Resources, self ).__init__( name, parent )
		self.log = Logger().get_instance( self.__class__.__name__ )

		self.resources = {}

	def identifyEvent( self, event ):
		self.log.info( str(event) )

		if isinstance( event, MessageEvent ):
			return event.id
		elif isinstance( event, ResourceEvent ):
			return event.id

		raise SipException( '[' + str(self.name) + '] ' + 'Ignoring event ' + str(event) + '.' )

	def onBind( self, event ):
		obj = importExtension( event.clsName )
		if obj:
			resource = obj( str(event.uri), self )
			if resource:
				resource.addListener( self )
				self.resources[event.uri] = resource

		if not obj or not resource:
			raise Exception( 'Failed to import resource, ' + str(event.uri) + ', of type, ' + str(event.clsName) + '.' )

		event.handled = True

	def onUnbind( self, event ):
		del self.resources[event.uri]

		event.handled = True


	def onRxRequest( self, event ):
		try:
			host = event.message.requestUri.host

			resource = self.resources[host]

			self.send( event, resource, queued=False )
		except KeyError:
			pass

	def onRxResponse( self, event ):
		raise 'FIXME:IMPLEMENT: Need to find the corresponding request, then the request-URI, then look up the resource in self.resources.'

	def onTxRequest( self, event ):
		self.notify( event, queued=False )

	def onTxResponse( self, event ):
		self.notify( event, queued=False )
class Parser(object):
	
	def __init__(self,fileName):
		self.log = Logger().get_instance(self.__class__.__name__)
		self.log.debug('Init parser for file '+fileName)
		self.fileName = fileName
		
		
	def loadInClass(self,className):
		pass
Exemple #14
0
class Event(Loadable):
    def __init__(self, eventName=None):
        self.log = Logger().get_instance(self.__class__.__name__)
        self.eventName = eventName
        self.eventParameters = []

    def setDict(self, dictData):
        self.log.debug(str(dictData))
        self.eventName = dictData["eventName"]
        self.eventParameters = dictData["eventParameters"]
 def __init__(self):
     self.log = Logger().get_instance(self.__class__.__name__)
     self.zone = None
     self.functions = []
     self.contiguous = {}
     self.contiguous['south'] = None
     self.contiguous['north'] = None
     self.contiguous['east'] = None
     self.contiguous['west'] = None
     self.character = None
Exemple #16
0
    def __init__(self, itemsLoader):
        '''
    Constructor
    '''
        '''
    Logger
    '''
        self.log = Logger().get_instance(self.__class__.__name__)
        '''
    Tile loader able to convert tile CODE
    '''
        self.itemsLoader = itemsLoader

        #    self._name = name
        #    self._type = type
        #
        #    self._move = move
        #    self._weapon_skill = weapon_skill
        #    self._ballistic_skill = ballistic_skill
        #    self._strength = strength
        #    self._toughness = toughness
        #    self._wounds = wounds
        #    self._current_wounds = wounds
        #    self._initiative = initiative
        #    self._attacks = attacks
        #    self._gold = gold
        #    self._armor = armor
        #    self._damage = damage

        self._type = ""
        self._name = ""
        """
    all Stats
    """

        self._move = 0
        self._weapon_skill = 0
        self._ballistic_skill = 0
        self._strength = 0
        self._toughness = 0
        self._wounds = 0
        self._initiative = 0
        self._attacks = 0
        self._gold = 0
        self._armor = 0
        self._damage = 0
        self._extra_damage = 0
        self._extra_damage_hit = 0
        self._pinning = 6
        self._current_wounds = 0

        # Default battle level is 1
        self._battle_level = 1

        self._effects = []
Exemple #17
0
class TransitiveInheritanceDictionary:
    ##
    # Initialize a transitive inheritance dictionary given an include dictionary.
    ##
    def __init__(self, inheritanceDictionary):
        # initialize an empty dictionary
        self.dict = {}
        self.inhDict = inheritanceDictionary

        self.calculateTransitiveSuperclasses()

        self.inhDict = None
        self.log = Logger().get_instance(self)

    ##
    # Add the transitive included files for each including file.
    ##
    def calculateTransitiveSuperclasses(self):
        for subclass in self.inhDict.dict:
            transitiveSuperclasses = self.inhDict.getTransitiveSuperclasses(
                subclass)
            self.dict[subclass] = transitiveSuperclasses

    ##
    # Is the dictionary aware of any superclasses of the given className
    ##
    def hasKey(self, className):
        return (className in self.dict)

    ##
    # Retrieve a list of names of transitive superclasses of the given class-name.
    ##
    def getTransitiveSuperclasses(self, className):
        superclasses = []

        if (className in self.dict):
            superclasses = self.dict[className]

        return superclasses

    ##
    # Verify whether the given superclass-name is a known (transitive) superclass of the given subclass-name.
    ##
    def isSubclassOf(self, subclassName, superclassName):
        return (superclassName in self.getTransitiveSuperclasses(subclassName))

    ##
    # Print the contents of the dictionary.
    ##
    def printContent(self):
        self.log.info("Dictionary has", len(self.dict), "elements:")
        for key in self.dict:
            self.log.info("[", key, ",", self.getTransitiveSuperclasses(key),
                          "]")
class Item(object):
  '''
  classdocs
  '''
  _name = ""
  _gold = 0
  _effects = []
  _type = 'Item'
  _magical = False
  _ranged = True
  _modfiers = []
  _profil = []
  _maxUsage = -1
  
    
  def __init__(self, name=None, gold=0, effects=None):
    '''
    Constructor
    '''
    
    '''
    Logger
    '''
    self.log = Logger().get_instance(self.__class__.__name__)
    
    self._name = name
    self._gold = gold
    self._effects = effects
    self._type = None
    self._basePurchasePrice = 0
    
  def equip(self, target):
    pass
  
  def unequip(self, target):
    pass
  
  def use(self, target):
    pass
  
  def setDict(self,dictData):
    self.log.debug(str(dictData))
    self._name = dictData['name']
    self._type = dictData['type']
    self._gold = dictData['gold']
    self._basePurchasePrice = dictData['basePurchasePrice']
    self._description = dictData['description']
    
    if dictData.has_key('stock'):
        self._ranged = dictData['stock']
    if dictData.has_key('maxUsage'):
        self._ranged = dictData['maxUsage']
    if dictData.has_key('ranged'):
        self._ranged = dictData['ranged']
Exemple #19
0
class Event(Loadable):
    
    def __init__(self,eventName=None):
        self.log = Logger().get_instance(self.__class__.__name__)
        self.eventName = eventName
        self.eventParameters = []
        
    def setDict(self,dictData):
        self.log.debug(str(dictData))
        self.eventName = dictData['eventName']
        self.eventParameters = dictData['eventParameters'] 
class AsciiRender(Render):
    pass

    def __init__(self):
        self.log = Logger().get_instance(self.__class__.__name__)
        
    
    def renderTabletop(self,tableTop):
        asciiMap = ''
        index=0
        self.log.debug('Tabletop size x:'+str(tableTop.sizeX)+'  y:'+str(tableTop.sizeY))
        
        for i in range(0,tableTop.sizeY):
            for j in range(0,tableTop.sizeX):
                tile = tableTop.tiles[index]
                asciiMap += self.getImageForTile(tile)
                index +=1
            asciiMap += '\n'
        print asciiMap

    
    def renderZone(self,zone):
        asciiMap = ''
        index=0
        self.log.debug('Zone size x:'+str(zone.sizeX)+'  y:'+str(zone.sizeY))
        
        asciiMap += '\n| |'
        
        for x in range(zone.getMinX(),zone.getMaxX() +1 ):
            asciiMap += '|'+str(x)+'|'
        asciiMap += '\n'
        for y in range(zone.getMinY(),zone.getMaxY() +1 ):
            asciiMap += '|'+str(y)+'|'
            for x in range(0,zone.sizeX):
                tile = zone.tiles[index]
                asciiMap += self.getImageForTile(tile)
                index +=1
            asciiMap += '\n'
        return asciiMap
    
    
    def getImageForTile(self,tile):
        if tile != None and tile.hasFunction('IO'):
            return '[D]'
        if tile != None and tile.hasFunction('Idol'):
            return '[@]'
        if tile != None and tile.hasFunction('Fire'):
            return '[w]'
        if tile != None and tile.hasFunction('Water'):
            return '[~]'
        if tile != None and tile.hasFunction('D'):
            return '[ ]'
        return '___';
class Item(object):
    '''
  classdocs
  '''
    _name = ""
    _gold = 0
    _effects = []
    _type = 'Item'
    _magical = False
    _ranged = True
    _modfiers = []
    _profil = []
    _maxUsage = -1

    def __init__(self, name=None, gold=0, effects=None):
        '''
    Constructor
    '''
        '''
    Logger
    '''
        self.log = Logger().get_instance(self.__class__.__name__)

        self._name = name
        self._gold = gold
        self._effects = effects
        self._type = None
        self._basePurchasePrice = 0

    def equip(self, target):
        pass

    def unequip(self, target):
        pass

    def use(self, target):
        pass

    def setDict(self, dictData):
        self.log.debug(str(dictData))
        self._name = dictData['name']
        self._type = dictData['type']
        self._gold = dictData['gold']
        self._basePurchasePrice = dictData['basePurchasePrice']
        self._description = dictData['description']

        if dictData.has_key('stock'):
            self._ranged = dictData['stock']
        if dictData.has_key('maxUsage'):
            self._ranged = dictData['maxUsage']
        if dictData.has_key('ranged'):
            self._ranged = dictData['ranged']
Exemple #22
0
class AsciiRender(Render):
    pass

    def __init__(self):
        self.log = Logger().get_instance(self.__class__.__name__)

    def renderTabletop(self, tableTop):
        asciiMap = ''
        index = 0
        self.log.debug('Tabletop size x:' + str(tableTop.sizeX) + '  y:' +
                       str(tableTop.sizeY))

        for i in range(0, tableTop.sizeY):
            for j in range(0, tableTop.sizeX):
                tile = tableTop.tiles[index]
                asciiMap += self.getImageForTile(tile)
                index += 1
            asciiMap += '\n'
        print asciiMap

    def renderZone(self, zone):
        asciiMap = ''
        index = 0
        self.log.debug('Zone size x:' + str(zone.sizeX) + '  y:' +
                       str(zone.sizeY))

        asciiMap += '\n| |'

        for x in range(zone.getMinX(), zone.getMaxX() + 1):
            asciiMap += '|' + str(x) + '|'
        asciiMap += '\n'
        for y in range(zone.getMinY(), zone.getMaxY() + 1):
            asciiMap += '|' + str(y) + '|'
            for x in range(0, zone.sizeX):
                tile = zone.tiles[index]
                asciiMap += self.getImageForTile(tile)
                index += 1
            asciiMap += '\n'
        return asciiMap

    def getImageForTile(self, tile):
        if tile != None and tile.hasFunction('IO'):
            return '[D]'
        if tile != None and tile.hasFunction('Idol'):
            return '[@]'
        if tile != None and tile.hasFunction('Fire'):
            return '[w]'
        if tile != None and tile.hasFunction('Water'):
            return '[~]'
        if tile != None and tile.hasFunction('D'):
            return '[ ]'
        return '___'
class TileFunction:
    def __init__(self):
        self.log = Logger().get_instance(self.__class__.__name__)
        self.name = ''
        self.objectType = ''
        self.code = ''

    def setDict(self, dictData):
        self.log.debug(str(dictData))
        self.name = dictData['name']
        self.objectType = dictData['objectType']

        self.code = dictData['code']
    def __init__(self, line):
        TypedEntity.__init__(self, line)
        self.log = Logger().get_instance(self)

        self.namespaceName = None

        self.cols = self.line.split(";")
        self.sourceIndicationIndex = -1  # to be initialized by subclass
        self.visibilityIndicationIndex = -1  # to be initialized by subclass
        self.nameIndex = -1  # to be initialized by subclass

        self.initialize()
        self.postInitialize()  # for subclasses to override
Exemple #25
0
class AccessDictionary:
	# initialize an empty dictionary
	dict = {}

	##
	# Initialize a dictionary.
	##
	def __init__(self):
		self.log = Logger().get_instance(self)
		pass

	##
	# Print the dictionary
	##
	def printContent(self):
		self.log.info("Dictionary has", len(self.dict), "elements:")
		for key in self.dict:
			self.log.info( "[",key,",",self.convertToList(self.dict[key]),"]")

	def createKey(self, fileName, lineNr):
		return fileName+":"+lineNr

	def hasKeyFor(self, fileName, lineNr):
		return self.hasKey(self.createKey(fileName,lineNr))

	def hasKey(self, key):
		return self.dict.has_key(key)

	def getValue(self, fileName, lineNr):
		assert self.hasKey(self.createKey(fileName, lineNr))
		return self.dict[self.createKey(fileName,  lineNr)]

	def getValueAsList(self, fileName, lineNr):
		return self.getValue(fileName, lineNr).split(",")

	def convertToList(self, value):
		return value.split(",")

	def add(self, fileName, lineNr, typeClass):
		if typeClass != "" and typeClass != None:
			key = self.createKey(fileName, lineNr)

			value = typeClass
			if self.dict.has_key(key) :
				value = self.dict[key]
				valueAsList=self.convertToList(value)

				if not typeClass in valueAsList:
					value=value+","+typeClass

			self.dict[key] = value
Exemple #26
0
    def __init__(self, line):
        """ Initialize a method entity given a line from the SourceNavigator \
			dbdump file (.methods). """
        self.log = Logger().get_instance(self)
        cols = line.split(";")
        self.owner = cols[0]
        self.name = cols[1]
        self.sourceFile = cols[3]
        self.lineNr = cols[4].split(".")[0]
        self.visibility = "public"
        # to be configured with additional information
        self.package = None
        self.attrType = None
        self.parentType = None
    def __init__(self, name=None, gold=0, effects=None):
        '''
    Constructor
    '''
        '''
    Logger
    '''
        self.log = Logger().get_instance(self.__class__.__name__)

        self._name = name
        self._gold = gold
        self._effects = effects
        self._type = None
        self._basePurchasePrice = 0
Exemple #28
0
 def __init__(self, line):
     self.log = Logger().get_instance(self)
     self.cols = line.split(";")
     self.dst_class = self.cols[0]
     self.dst_name = self.cols[1]
     self.src_class = self.cols[3]
     self.src_name = self.cols[4]
     self.acc_type = self.cols[5]
     self.sourceFile = self.cols[8]
     self.lineNr = utils.removeUpfrontZeroes(self.cols[7])
     self.src_param = utils.cleanCol(self.cols[10].strip()).split(",")
     self.package = ""
     self.srcSourceLocation = SourceLocation("", "0", "0")
     self.dstSourceLocation = SourceLocation("", "0", "0")
 def __init__(self):
     self.log = Logger().get_instance(self.__class__.__name__)
     super(TableTop, self).__init__()
     self.zones = []
     self.lastZones = []
     self.sizeY = 0
     self.sizeX = 2
     self.initialConnector = Connector(None)
     self.initialConnector.position1X = 0
     self.initialConnector.position1Y = -1
     self.initialConnector.position2X = 1
     self.initialConnector.position2Y = -1
     self.initialConnector.direction = 'south'
     self.initialConnector.zoneDealer = None
class TileFunction:

    def __init__(self):
        self.log = Logger().get_instance(self.__class__.__name__)
        self.name = ''
        self.objectType = ''
        self.code = ''
    
    def setDict(self,dictData):
        self.log.debug(str(dictData))
        self.name = dictData['name']
        self.objectType = dictData['objectType'] 
        
        self.code = dictData['code']  
Exemple #31
0
class PackageDictionary:
	##
	# Initialize a dictionary.
	##
	def __init__(self):
		self.dict={}
		self.log = Logger().get_instance(self)

	##
	# Verify whether the dictionary contains a given Package-name.
	##
	def hasKey(self, nsName):
		return (nsName in self.dict)

	##
	# Add a Package contained in the given sourceFile at the given line-nr
	# to the dictionary.
	#
	# @nsName - the name of the Package
	# @sourceFile - the name of the file in which the Package is declared
	#
	# @returns True/False indicating whether the Package was added
	##
	def add(self,sourceFile, nsName):
		isAdded = False

		if ( not(sourceFile in self.dict) ):
			self.dict[sourceFile] = nsName
			isAdded = True
		else:
			self.log.warn("Ignoring additional package declaration "+nsName+"for file ",\
							sourceFile+" already packaged in "+self.dict[sourceFile])

		return isAdded

	##
	# Retrieve a list of [sourceFile, lineNr] elements for which it holds
	# that in sourceFile at lineNr a class with name className is declared.
	#
	# @param className - the class name for which to find source locations.
	#
	# @returns a list of elements [sourceFile, lineNr]
	##
	def getPackageForFile(self, sourceFile):
		noNS = ""
		if ( sourceFile in self.dict ):
			return self.dict[sourceFile]
		else:
			return noNS
    def __init__(self,pkgDict,impDict,inhDict, classDict,methDict,mtdSrcDict,miList, mtdpfDict, sFile,nr,content, raw):
        self.log = Logger().get_instance(self)
        self.pkgDict = pkgDict
        self.impDict = impDict
        self.inhDict = inhDict
        self.classDict = classDict
        self.methDict = methDict
        self.mtdSrcDict = mtdSrcDict
        self.miList = miList
        self.sourceFile = sFile
        self.lineNr = nr
        self.content = content
        self.raw = raw # full grep content
        self.mtdpfDict = mtdpfDict

        # to be filled in
        self.src_unqName = None # fully qualified caller method
        self.src_name = None    # caller method
        self.src_param = None   # caller method parameters

        self.dst_base = None
        self.dst_name = None
        self.dst_param = None

        self.srcLoc = None      # caller method filename
        self.srcLineNr = None   # caller method line number

        self.dstLoc = None
        self.dstLineNr = None
Exemple #33
0
 def __init__(self, isImplementation, line):
     TypedEntity.__init__(self, line)
     MultipleLocationEntity.__init__(self)
     self.log = Logger().get_instance(self)
     self.isAbstract = False
     self.isImplementation = isImplementation
     self.namespaceName = None
Exemple #34
0
	def __init__(self, line):
		self.log = Logger().get_instance(self)
		cols = line.split(":")
		self.sourceFile = cols[0].replace("./", "")
		self.lineNr = cols[1]
		self.content = cols[2].lstrip().split(" ")[0].strip() # typically some code behind it
		self.owner = ""
Exemple #35
0
	def __init__(self, line):
		self.log = Logger().get_instance(self)
		self.cols = line.split(";")
		self.owner = self.cols[0]
		self.name = self.cols[1]+"("+utils.cleanCol(self.cols[7])+")"

		sourceFile = self.cols[3]
		lineNr = self.cols[4].split(".")[0]
		self.sourceLocation = SourceLocation(sourceFile, lineNr, lineNr)

		self.isConstructor = False
		# TODO: parse visibility codes
		self.accessControlQualifier = "public"
		# TODO: static?
		self.hasClassScope = False
		# TODO: abstract? Interface?
		self.isAbstract = False
		params = self.cols[7]
		if "{}" == params:
			self.parameters = []
			self.parameterNames = []
		else:
			self.parameters = utils.cleanCol(params).split(",")
			self.parameterNames = utils.cleanCol(self.cols[8]).split(",")

		# to be resolved later
		self.package = None
		self.retType = None
		self.parentType = None
		# scope, visibility, abstract
		self.__resolveCharacteristics(self.cols[5])
 def __init__(self, mtdSrcDict, classDict, pkgDict, impDict, mtdInv):
     self.mtdSrcDict = mtdSrcDict
     self.classDict = classDict
     self.pkgDict = pkgDict
     self.impDict = impDict
     self.mtdInv = mtdInv
     self.log = Logger().get_instance(self)
Exemple #37
0
    def __init__(self, activityDescription):
        if sys.platform == "win32":
            self.timer = time.clock
        else:
            self.timer = time.time

        self.begin = self.end = 0
        self.activityDescription = activityDescription
        self.logger = Logger().get_instance(self)
Exemple #38
0
    def __init__(self, line):
        self.log = Logger().get_instance(self)
        cols = line.split(";")

        # TODO: check number of cols
        self.subclass = cols[0]
        # fix SN messing up fully qualified inheritance [class A extends pkg.B {}]
        self.superclass = cols[1].replace(".", "::")
        sourceFile = cols[3]
        start = cols[4].split(".")[0]
        self.sourceLocation = SourceLocation(sourceFile, start, start)
        vis = cols[5].strip()
        self.accessControlQualifier = ""
        self.decomposeVisibility(vis)

        # to be filled in later
        self.package = ""
        self.superSourceLocation = None
Exemple #39
0
	def __init__(self, activityDescription):
		if sys.platform == "win32":
			self.timer = time.clock
		else:
			self.timer = time.time

		self.begin = self.end = 0
		self.activityDescription = activityDescription
		self.logger = Logger().get_instance(self)
Exemple #40
0
    def __init__(self, includeDictionary):
        # initialize an empty dictionary
        self.dict = {}
        self.includeDict = includeDictionary

        self.calculateTransitiveIncludes()

        self.includeDict = None
        self.log = Logger().get_instance(self)
	def __init__(self, line):
		line = line.strip()

		self.metricLOC, self.metricCC, self.metricCOM, \
		self.pkgName, self.className, self.methodName = \
			self.__decomposeCols(line)

		self.invEntRef = None # ref to invokable entity; to be resolved later
		self.log = Logger().get_instance(self)
Exemple #42
0
 def __init__(self):
     self.log = Logger().get_instance(self.__class__.__name__)
     self.loaders = []
     self.data = {}
     self.donjonSubTypeCount = {}
     self.generateDongeonArray = []
     self.renderObject = None
     self.tableTop = TableTop()
     self.firstZoneDealer = None
    def __init__(self, inheritanceDictionary):
        # initialize an empty dictionary
        self.dict = {}
        self.inhDict = inheritanceDictionary

        self.calculateTransitiveSuperclasses()

        self.inhDict = None
        self.log = Logger().get_instance(self)
 def __init__(self):
     self.extractor = None
     self.repositoryUri = None
     self.repositoryType = None
     self.folderName = None
     self.checkOutByDate = True
     self.cleanProjectFolder = False
     self.log = Logger().get_instance(self)
     self.saveCdifCounter = 0
     self.reprocess = False
     self.firstTransaction = False
     self.fullMacroDict = {}
     self.fullClassDict = EvoClassDictionary(None)
     self.fullClassDict.restricting = False
     self.fullAttrDict = EvoAccessibleEntityDictionary(None)
     self.fullAttrDict.restricting = False
     self.fullInvokableEntityDict = EvoInvokableEntityDictionary(None)
     self.fullInvokableEntityDict.restricting = False
     addLogTarget(self.log)
Exemple #45
0
class Host(StateNode):

	STATE_ACTIVE = 'Active'

	def __init__( self, name, parent ):
		StateNode.__init__( self, name, parent, initialState = self.STATE_ACTIVE )
		self.log = Logger().get_instance( self.__class__.__name__ )

		self.users = {}

	def identifyEvent( self, event ):
		self.log.info( str(event) )
		if isinstance( event, MessageEvent ):
			return event.id
		elif isinstance( event, StateChangeNotification ):
			if event.node in self.users.itervalues():
				return 'User' + event.node.currentState

		raise SipException( '[' + str(self.name) + '] ' + 'Ignoring event ' + str(event) + '.' )

	def inActive_onRxRequest( self, event ):
		userName = event.message['To'].uri.user
		if not userName in self.users:
			user = User( userName, self )
			user.addListener( self )
			self.users[userName] = user

		event.localUser = self.users[userName]
		self.send( event, event.localUser, False )

	def inActive_onRxResponse( self, event ):
		userName = event.message['From'].uri.user
		if not userName in self.users:
			self.users[userName] = User( userName, self )

		event.localUser = self.users[userName]
		self.send( event, event.localUser, False )

	def inActive_onTxRequest( self, event ):
		self.notify( event, False )

	def inActive_onTxResponse( self, event ):
		self.notify( event, False )
 def __init__(self):
     self.log = Logger().get_instance(self.__class__.__name__)
     self.zone = None
     self.functions = []
     self.contiguous = {}
     self.contiguous['south'] = None 
     self.contiguous['north'] = None 
     self.contiguous['east'] = None 
     self.contiguous['west'] = None 
     self.character = None
Exemple #47
0
	def __init__( self, name, parent ):
		StateNode.__init__( self, name, parent, initialState = self.STATE_ACTIVE )
		self.log = Logger().get_instance( self.__class__.__name__ )

		self.authentication = AuthenticationAdapter( 'auth_adapter', self )
		self.authentication.addListener( self )
		self.authentication = None #FIXME:

		self.transactions = {}
		self.dialogs = {}
Exemple #48
0
class Timer:
	def __init__(self, activityDescription):
		if sys.platform == "win32":
			self.timer = time.clock
		else:
			self.timer = time.time

		self.begin = self.end = 0
		self.activityDescription = activityDescription
		self.logger = Logger().get_instance(self)

	##
	# Starts the timer.
	##
	def start(self):
		self.begin = self.timer()
	##
	# Stop the timer.
	##
	def stop(self):
		self.end = self.timer()

	def log(self, nrOfWorkItems):
		self.logger.info(self.activityDescription + " took "\
		 + `self.milli()` + " ms for " + `nrOfWorkItems` + " work items, or " \
		 + `self.getMillisPerItem(nrOfWorkItems)` + " ms per item.")

	def seconds(self):
		return self.milli() / 1000

	def getMillisPerItem(self, nrOfItems):
		millisPerItem = 0

		if nrOfItems != 0:
			millisPerItem = float(self.milli()) / float(nrOfItems)

		return millisPerItem

	def milli(self):
		return self.micro() / 1000

	def micro(self):
		return int((self.end - self.begin) * 1000000)
class ZoneDealer:
    
    def __init__(self,zones = []):
        self.log = Logger().get_instance(self.__class__.__name__)
        self.zones = zones
    
    def addZone(self,zone):
        self.log.debug('Add zone '+zone.name)
        self.zones.append(zone)
    
    def getAndRemoveZone(self):
        if len(self.zones) > 0:
            zone = self.zones.pop()
            zone.zoneDealer = self
            return zone
    
    def split(self,count):
        split = {}
        if count == 0:
            return None
        elif count == 1:
            split[0] = self

        else:
            for i in range(0,count):
                split[i] = []
            
            index = 0
            for zone in self.zones:
                split[index].append(zone)
                index = index + 1
                if index == count:
                    index=0
            
            for i in range(0,count):
                split[i] = ZoneDealer(split[i])
            
        return split
        
    def __str__(self, *args, **kwargs):
        data = 'There are '+str(len(self.zones))+' zone in zoneDealer'
        return data
Exemple #50
0
class ZoneDealer:
    def __init__(self, zones=[]):
        self.log = Logger().get_instance(self.__class__.__name__)
        self.zones = zones

    def addZone(self, zone):
        self.log.debug('Add zone ' + zone.name)
        self.zones.append(zone)

    def getAndRemoveZone(self):
        if len(self.zones) > 0:
            zone = self.zones.pop()
            zone.zoneDealer = self
            return zone

    def split(self, count):
        split = {}
        if count == 0:
            return None
        elif count == 1:
            split[0] = self

        else:
            for i in range(0, count):
                split[i] = []

            index = 0
            for zone in self.zones:
                split[index].append(zone)
                index = index + 1
                if index == count:
                    index = 0

            for i in range(0, count):
                split[i] = ZoneDealer(split[i])

        return split

    def __str__(self, *args, **kwargs):
        data = 'There are ' + str(len(self.zones)) + ' zone in zoneDealer'
        return data
 def __init__(self,
              scope,
              transInhDict,
              typedefDict,
              invEntityDict,
              accessDict=AccessDictionary()):
     self.transInhDict = transInhDict
     self.typedefDict = typedefDict
     self.scope = scope
     self.invEntityDict = invEntityDict
     self.accessDict = accessDict
     self.log = Logger().get_instance(self)
Exemple #52
0
class ResolutionReport:
    ##
    # Initialize the generic data.
    ##
    def __init__(self, line):
        self.line = line.strip()
        self.entityType = "Undefined"
        self.logger = Logger().get_instance(self)
        self.logger.set_loglevel(LOGLEVEL_DEBUG)

        ##
        # Return a string representation of the report.
        ##

    def __repr__(self):
        assert False, "Should be implemented by subclass."

        ##
        # Verify whether the resolution succeeded.
        ##

    def resolutionSucceeded(self):
        assert False, "Should be implemented by subclass."

    def log(self):
        self.logger.debug("Failed to resolve " + self.entityType + ": " + self.line)
        self.logger.debug(self.__repr__())

    def logIfFlawed(self):
        if self.resolutionFeasible() and (not self.resolutionSucceeded()):
            self.log()
	def __init__(self, line):
		TypedEntity.__init__(self, line)
		self.log = Logger().get_instance(self)

		self.namespaceName = None

		self.cols = self.line.split(";")
		self.sourceIndicationIndex = -1 # to be initialized by subclass
		self.visibilityIndicationIndex = -1 # to be initialized by subclass
		self.nameIndex = -1 # to be initialized by subclass

		self.initialize()
		self.postInitialize() # for subclasses to override
Exemple #54
0
	def __init__(self, line):
		""" Initialize a method entity given a line from the SourceNavigator \
			dbdump file (.methods). """
		self.log = Logger().get_instance(self)
		cols = line.split(";")
		self.owner = cols[0]
		self.name = cols[1]
		self.sourceFile = cols[3]
		self.lineNr = cols[4].split(".")[0]
		self.visibility = "public"
		# to be configured with additional information
		self.package = None
		self.attrType = None
		self.parentType = None
Exemple #55
0
	def __init__(self, line):
		self.log = Logger().get_instance(self)
		self.cols = line.split(";")
		self.dst_class = self.cols[0]
		self.dst_name = self.cols[1]
		self.src_class = self.cols[3]
		self.src_name = self.cols[4]
		self.acc_type = self.cols[5]
		self.sourceFile = self.cols[8]
		self.lineNr = utils.removeUpfrontZeroes(self.cols[7])
		self.src_param = utils.cleanCol(self.cols[10].strip()).split(",")
		self.package = ""
		self.srcSourceLocation = SourceLocation("","0","0")
		self.dstSourceLocation = SourceLocation("","0","0")
Exemple #56
0
	def __init__( self, name, parent ):
		StateNode.__init__( self, name, parent, initialState = System.STATE_STOPPED )
		self.log = Logger().get_instance( self.__class__.__name__ )

		self.config = Configuration( 'config', self )
		self.config.addListener( self )

		self.network = MessageAdapter( 'msg_net', self )
		self.network.addListener( self )

		self.resources = Resources( 'resources', self )
		self.resources.addListener( self )

		self.addListener( parent )
	def setup(self):
		# Create a namespace object for the Friend of a friend namespace.
		# figure out trailing pound thing...
		#self.FOAF = Namespace(self.server.config.foaf_url + "#")
		#self.TRUST = Namespace(self.server.config.trust_url + "#")
		#self.WOT = Namespace(self.server.config.wot_url + "#")
		#self.RDF = Namespace(self.server.config.rdf_url + "#")
		
		self.FOAF = Namespace("http://xmlns.com/foaf/0.1/")
		self.TRUST = Namespace("http://www.konfidi.org/ns/trust/1.2#")
		self.WOT = Namespace("http://xmlns.com/wot/0.1/")
		self.RDF = Namespace("http://www.w3.org/2000/01/rdf-schema#")
		
		self.log = Logger().get_instance(self)
 def __init__(self):
     self.log = Logger().get_instance(self.__class__.__name__)
     super(TableTop,self).__init__()
     self.zones = []
     self.lastZones = []
     self.sizeY = 0
     self.sizeX = 2
     self.initialConnector = Connector(None)
     self.initialConnector.position1X = 0 
     self.initialConnector.position1Y = -1
     self.initialConnector.position2X = 1
     self.initialConnector.position2Y = -1
     self.initialConnector.direction = 'south'
     self.initialConnector.zoneDealer = None