#!/usr/bin/env python
###### 1 #################
import sys,os,logging
from xml.sax import handler,make_parser
import xml.dom.minidom
import datetime
import getopt
#0:means just ignore the tag
ignoreTagsMap={'OAM':0,'Application':0,'Domain':0,'SubDomain':0,'Description':0,'DNSyntaxReference':0,'Summary':0,'Context':0,'Actor':0,'LockReference':0,"DNSyntaxVirtual":0}
indentationMap={0:'\n ',1:'\n ',2:'\n ',3:'\n ',4:'\n ',5:'\n ',
6:'\n ',7:'\n ',8:'\n ',
9:'\n ',10:'\n ',11:'\n ',
12:'\n ', 13:'\n ',
14:'\n ',
15:'\n '}
dataTypeDir='/local/mypython/xml2lua/datatype1/'
needModules={}
DataTypeList={'__JUST_AFTER_COMMIT':'String','__DN_SYNTAX_NAME':'String','__INTERNAL_REQUEST_NAME':'String','__DISTINGUISH_NAME':'String','__ATTRIBUTE_NAME_LIST':'String','__BOOL':'Boolean'}
dataTypeDocs=[]
currentModuleName=''
currentRequestName=''
def findType(attName,attvalue):
if attName == '':
return attvalue
attvalue=attvalue[4:]
attType=''
if DataTypeList.has_key(attName):
attType=DataTypeList[attName]
else:
attrType=fixTypeInDataFile(attName)
if attType == '' or attType.startswith('String'):
attvalue="'"+attvalue+"'"
logging.debug('findType, att='+attName+',type='+attType+',value:'+attvalue)
return attvalue
def fixTypeInDataFile(attName):
attType=''
for oneDoc in dataTypeDocs:
datas = oneDoc.getElementsByTagName('Data')
for data in datas: #data
#logging.debug('find ('+attName+') Data, NodeType:'+str(data.nodeType)+',name='+str(data.nodeName)+',attName='+str(data.getAttribute('name')))
if data.nodeType==data.ELEMENT_NODE:
#logging.debug('find '+attName+',node:'+data.nodeName)
dataName=data.getAttribute('name')
if dataName == attName:
for oneType in data.childNodes: #String or Integer
if oneType.nodeType == oneType.ELEMENT_NODE:
attType=oneType.nodeName
for maxType in oneType.childNodes: #whether is a list or just a value
if maxType.nodeType == oneType.ELEMENT_NODE:
if maxType.nodeName =='MaxOccurs':
attType +='List'
break
#logging.debug('in the data file, find '+attName+',type='+attType)
DataTypeList[attName]=attType
break
if attType =='':
logging.error('Cannot find the type of '+attName+',using the default type - String')
#print 'Cannot find the type of '+attName+',using the default type - String'
DataTypeList[attName]='String'
return DataTypeList[attName]
def isListType(attName):
if attName == '':
return False
attType=''
if DataTypeList.has_key(attName):
attType=DataTypeList[attName]
else:
attType=fixTypeInDataFile(attName)
logging.debug('isListType find '+attName+',type='+attType)
if attType !='' and attType.endswith('List'):
return True
else:
return False
class Element:
def __init__(self,name,attrs):
self.name=name
self.childList=[]
self.parent=None
self.content=''
self.attrs=attrs
self.indentInt=0
self.contractable=False
def addChild(self,child):
self.childList.append(child)
def isContractable(self):
if len(self.childList)==0 :
return False
else:
for one in self.childList:
if one.isContractable() :
return True
return False
def getName(self):
return self.name
def setIndentInt(self,level):
self.indentInt=level
def getIndentInt(self):
return self.indentInt
def getIndentation(self):
if indentationMap.has_key(self.indentInt):
return indentationMap[self.indentInt]
else:
return '\n '
def setParent(self,parent):
self.parent=parent
def getParent(self):
return self.parent
def appendContent(self,content):
self.content +=content
def tolua(self):
return self.content
class BUSINESSENTITY_Elt(Element):#BusinessEntity
def tolua(self):
return ''
class REQUEST_Elt(Element):#Request
def tolua(self):
requestName=self.attrs['name']
lua ='\n\n\nfunction '+requestName+'(be1,...) \n'
lua +=' be=be1\n'
lua +=' clearCache()\n'
global currentModuleName
global currentRequestName
currentRequestName=requestName
#print 'RequestElt:'+currentModuleName+"#"+currentRequestName
lua +=" Util.info('---"+currentModuleName+"#"+currentRequestName+" begin ---')\n"
lua +=" if ... ~= nil and type(...) == 'table' then\n"
lua +=' UpdateV(...)\n'
lua +=' end\n'
lua +=" contractBELoaded=false"
return lua
class ALLPARAMETERS_Elt(Element):#AllParameters
def tolua(self):
return 'all'
class EXCEPTPARAMETER_Elt(Element):#ExceptParameter
def tolua(self):
print "WARNING: ExceptParameter tag is ignored!!"
return self.getIndentation() +'WARNING: ExceptParameter'
class LOCKREFERENCE_Elt(Element):# LockReference
def tolua(self):
print "WARNING: LockReference tag is ignored!!"
return self.getIndentation() +'WARNING: LockReference'
class CATCHEXCEPTION_Elt(Element): #CatchException
def tolua(self):
print "WARNING: CatchException tag is ignored!!"
return self.getIndentation() +'WARNING: CatchException'
class LOCKPOLICY_Elt(Element):#LockPolicy, just extract the childlist
def tolua(self):
if len(self.childList)==0:
return ''
lua=''
for one in self.childList:
lua += self.getIndentation()+one
return lua
class PROC_Elt(Element): #Proc, just extract the childlist
def tolua(self):
if len(self.childList) == 0:
return ''
print "WARNING: Proc tag is >>Partially<< ignored!!"
lua=''
for one in self.childList:#Proc,has the in and out
if one.startswith('IN:'):
lua += self.getIndentation() + 'UpdateV({'+one[3:]+'})'
elif one.startswith('OUT:'):
lua += self.getIndentation() + 'UpdateV({'+one[4:]+'})'
else:
lua += self.getIndentation()+one
return lua
class TESTATTRIBUTE_Elt(Element):# TestAttribute
def tolua(self):
print "WARNING: TestAttribute tag is ignored!!"
return self.getIndentation() +'WARNING: TestAttribute'
class REQPARAMETERS_Elt(Element):#ReqParameters
def tolua(self):
if len(self.childList)==0:
return ''
log =self.getIndentation()+"if Util.isDebug() then"
log +=self.getIndentation()+" Util.debug('--"+currentModuleName+"#"+currentRequestName+":"
for one in self.childList:
isList=isListType(one)
if isList :
log += one+"='..tostring(GetV('"+one+"',true))..',"
else:
log += one+"='..tostring(GetV('"+one+"'))..',"
log=log[:len(log)-4]+")"
log +=self.getIndentation()+"end\n"
return log
class MANDATORY_Elt(Element):#Mandatory
def tolua(self):
attName=self.attrs['name']
return attName
class OPTIONAL_Elt(Element):#Optional
def tolua(self):
attName=self.attrs['name']
return attName
class CONDITIONAL_Elt(Element):#Conditional
def tolua(self):
attName=self.attrs['name']
return attName
class SET_Elt(Element):#Set
def tolua(self):
attName=self.attrs['name']
lua=''
one=self.childList[0]
if one.startswith('MULTI:'): #multi values
one='*'+one[6:]
#logging.debug('MULTIs:'+one)
oness =one.split('*')
for eve in oness:
if eve.startswith('Val:'):
eveN=findType(attName,eve)
one=one.replace(eve,eveN)
#logging.debug('MULTIs After:'+one)
lua=self.getIndentation()+'be:addValue({'
one=one.replace('*',","+attName+"=")
lua +=one[1:]+'},DA)'
else: #single value
value=self.childList[0]
if value.startswith('Val:'):
value=findType(attName,value)
lua=self.getIndentation()+'SetV({'+attName+'='+value+'},DA)'
return lua
class REF_Elt(Element):#Ref
def tolua(self):
attName=self.attrs['name']
lua=''
isList=isListType(attName)
if self.attrs.has_key('entityName'):
entityName=self.attrs['entityName']
if entityName=='PostCommitBeContext':
if isList :
lua="be:getValue('"+attName+"',PC)"
else:
lua="be:getValue('"+attName+"',PC)[1]"
else:
if entityName.find('.ContractData.') == -1:
if isList:
lua="be:getValue('"+attName+"','"+entityName+"')"
else:
lua="be:getValue('"+attName+"','"+entityName+"')[1]"
else: #is contract data
lua=self.toluaForContractData(attName,entityName,isList) #this is temply for the contract data
else:
if self.attrs.has_key('defaultValue'):
if isList:
lua="be:getValue('"+attName+"','default')"
else:
lua="be:getValue('"+attName+"','default')[1]"
else:
if isList:
lua="GetV('"+attName+"',true)"
else:
lua="GetV('"+attName+"')"
return lua
def toluaForContractData(self, attName, entityName,isList):
if entityName == 'HSS.ContractData.ContractData.Cont_OAM_EirContractOverloadAlarm':
return '800000' #MaxEIRListEntry=800000
elif entityName == 'HSS.ContractData.ContractData.Cont_OAM_ContractEirFunction':
self.contractable = True
if isList:
return "GetContractV('"+attName+"',true)"
else:
return "GetContractV('"+attName+"')"
else:
if isList:
return "GetContractV('"+attName+"',true)"
else:
return "GetContractV('"+attName+"')"
class CALLBE_Elt(Element):# CallBE
def tolua(self):
methodName=self.attrs['name']
entityName=self.attrs['entityName']
lua=''
call_In=''
call_Out=''
if len(self.childList) ==2:
call_In=self.childList[0][3:len(self.childList[0])] #IN:
for val in call_In.split(","):
temp = val
call_Out=self.childList[1][4:len(self.childList[1])] #OUT:
elif len(self.childList) ==1:
if self.childList[0].startswith('IN:'):
call_In=self.childList[0][3:len(self.childList[0])]
else:
call_Out=self.childList[0][4:len(self.childList[0])]
if entityName.find('*') == -1: #normal BE
moduleName=''
if entityName.find('.') != -1:
moduleName=entityName[entityName.rindex('.')+1:]
lua =''
if moduleName == currentModuleName:
lua=self.getIndentation()+"tmpTb="+methodName+"(be,{"+call_In+"})"
else:
if not needModules.has_key(moduleName):
needModules[moduleName]=1
lua=self.getIndentation()+"tmpTb="+moduleName+"."+methodName+"(be,{"+call_In+"})"
if call_Out !='' and call_Out !='all':
for one in call_Out.split(','):
if one.find('=') !=-1:
beforeName=one[:one.find('=')]
afterName=one[one.find('=')+1:]
lua +=self.getIndentation()+"tmpTb['"+beforeName+"']=tmpTb["+afterName+"]"
lua +=self.getIndentation()+'tmpTb['+afterName+']=nil'
lua +=self.getIndentation()+"UpdateV(tmpTb,true)"
else:
moduleName=entityName
if entityName =='PostCommitBeContext' and methodName =='modify':
lua=self.getIndentation()+"SetV({"+call_In+"},PC)"
else: #special BE
#print 'CallBE Special BE,Call_OUT:'+call_Out
lua=self.getIndentation()
if entityName =='HSS.EIR.*.DnHandler' and call_In.find('__DISTINGUISH_NAME') ==-1:
lua += "be:callBE{BE='"+entityName+"',IN={__DISTINGUISH_NAME=GetV('__DISTINGUISH_NAME',false),__CALLED_METHOD_NAME='"+methodName+"'"
else:
lua += "be:callBE{BE='"+entityName+"',IN={__CALLED_METHOD_NAME='"+methodName+"'"
if call_In !='':
lua +=","+call_In+"}"
else:
lua +="}"
if call_Out.find('all') !=-1: #OUT='all', it has to clear all the cache, because it dont know who out
lua +=",OUT='all'}"
lua +=self.getIndentation()+"clearCache()"
else:
lua +=",OUT={"+call_Out+"}}"
if call_Out !='':
lua +=self.getIndentation()+"DeleteVFromCache{"+call_Out+"}"
return lua
class IF_Elt(Element):#If,generally two childrean, one is condition, the other is then
def tolua(self):
lua=self.getIndentation()+'if '+self.childList[0]+' then'
lua +=self.childList[1]
if len(self.childList) >2 : #sometimes, has the third children: else
lua +=self.childList[2]
lua +=self.getIndentation()+'end'
return lua
class ELSE_Elt(Element):#Else
def tolua(self):
lua=self.getIndentation()+'else'
for one in self.childList:
if one != '' :
lua +=one
return lua
class ELSEIF_Elt(Element):#ElseIf, has two children, one is elseif, the other is then
def tolua(self):
lua=self.getIndentation()+'elseif '+self.childList[0]+' then'
lua +=self.childList[1] #thenElt has contains the indentation
return lua
class MULTIIF_Elt(Element):#MultiIf, contains the first child:If, multiple elseif
def tolua(self):
if len(self.childList)==0:
return ''
lua=''
ifLua = self.childList[0]
self.childList[0]=ifLua.rstrip(self.getIndentation()+'end') #remove the end
for one in self.childList:
lua +=one
lua +=self.getIndentation()+'end'
return lua
class BREAK_Elt(Element):#Break
def tolua(self):
return self.getIndentation()+'break'
class CONTINUE_Elt(Element):#Continue
def tolua(self):
return self.getIndentation()+'continue'
class FOREACH_Elt(Element):#Foreach MULTI
def tolua(self):
if len(self.childList)==0:
return ''
everyPara = self.attrs['name']
arrays = self.childList[0] #must be the multivalue
if arrays.startswith('MULTI:'):
arrays=arrays[6:]
#print 'Foreach Elt:'+arrays
lua =self.getIndentation()+'for i=1,#'+arrays+' do'
lua +=self.getIndentation()+" cacheTb['"+everyPara+"']="+arrays+"[i]"
i = 0
for one in self.childList:
if i ==0 :
i =1
continue
lua += self.getIndentation()+' '+one
lua += self.getIndentation()+'end'
return lua
class CONDITION_Elt(Element):#Condition
def tolua(self):
lua=''
oprName=self.attrs['operator']
one=self.childList[0]
two=self.childList[1]
if two.startswith('Val:'):
attNa=one
if one.find('Get') !=-1 or one.startswith('be:getValue('):
attNa=one.split("'")[1]
two=findType(attNa,two)
if oprName =='setGreater':
if two == 'nil':
lua=one +'~= nil'
else:
lua=one+' > '+two
elif oprName == 'greaterOrEqual':
lua=one+' >= '+two
elif oprName == 'greater':
lua = one +'>'+ two
elif oprName =='lessOrEqual':
lua=one+' <= '+two
elif oprName =='setLessOrEqual':
if two == 'nil':
lua=one+' == nil'
else:
lua=one+' <= '+two
elif oprName=='eq':
if two=='true':
lua=one
elif two=='false':
lua=' not '+one
else:
lua=one+' == '+two
elif oprName =='neq':
if two =='true':
lua=' not '+one
elif two =='false':
lua=one
else:
lua=one+' ~= '+two
elif oprName == 'nullIntersection':
lua = "Util.nullInsterSection("+one+","+two+")"
elif oprName == 'notNullIntersection':
lua = "Util.notNullInsterSection("+one+","+two+")"
return lua
class THEN_Elt(Element):#Then
def tolua(self):
lua=''
for one in self.childList:
if one !='':
lua +=one
return lua
class OR_Elt(Element):#OR
def tolua(self):
lua='('
for one in self.childList:
lua += one + ' or '
lua = lua[:len(lua)-4]+')'
return lua
class AND_Elt(Element):#AND
def tolua(self):
lua='('
for one in self.childList:
lua += one + ' and '
lua = lua[:len(lua)-5]+')'
return lua
class THROWEXCEPTION_Elt(Element):#ThrowException
def tolua(self):
lua=self.getIndentation()+'Util.throwException('+self.childList[0]+')'
return lua
class ERROR_Elt(Element):#Error
def tolua(self):
ErrorId=self.attrs['ErrorId'] #21
return ErrorId+','+self.childList[0]
class FRAME_Elt(Element):#Frame
def tolua(self):
FrameId=self.attrs['FrameId']
lua = FrameId
for one in self.childList:
lua +=','+one
return lua
class STRINGATTRIBUTETYPE_Elt(Element):#StringAttributeType
def tolua(self):
lua=self.childList[0]
if lua.startswith('Val:'):
lua=lua[4:]
if not lua.startswith('GetV'):
return "'"+lua+"'"
else:
return "tostring("+lua+")"
class INTEGERATTRIBUTETYPE_Elt(Element):#IntegerAttributeType
def tolua(self):
lua=self.childList[0]
if lua.startswith('Val:'):
lua=lua[4:]
if not lua.startswith('GetV'):
return "tonumber("+lua+")"
else:
return "tonumber("+lua+")"
class IN_Elt(Element):#In
def tolua(self):
lua = 'IN:'
for one in self.childList:
#print "one:"+one
if one.find(",")!=-1 and one.find('=') ==-1: #such as one:'associatedMainMsisdn','multiSimMember','roleInMultiSim','deactivatedSubscription','msimPublicMsisdn',
#print "IN_Elt one:"+one
oness =one.split(",")
one =''
for eve in oness:
isList=isListType(eve)
if isList :
one += eve[1:len(eve)-1] +"=GetV("+eve+",true),"
else:
one += eve[1:len(eve)-1] +"=GetV("+eve+"),"
one=one[:len(one)-1]
if one.find('=') == -1:
isList=isListType(one)
if isList :
one = one +"=GetV('"+one+"',true)"
else:
one = one +"=GetV('"+one+"')"
lua +=one+','
return lua[:len(lua)-1]
class PARAMETER_Elt(Element):#Parameter
def tolua(self):
attrName=self.attrs['name']
if len(self.childList)==0:
return attrName
else:
value=self.childList[0]
if value.startswith('Val:'):
if value.find('_@@_')!=-1:
value=value[4:]
value=value.replace('_@@_',"','")
#print "Value:"+value
return "'"+value+"'"
else:
value=findType(attrName,value)
return attrName+'='+value
else:
return attrName+'='+value
class OUT_Elt(Element): #Out
def tolua(self):
lua = 'OUT:'
for one in self.childList:
if one.find('=')!=-1:
if one.find('(') !=-1: #such as: initialDN=GetV('__DISTINGUISH_NAME')
#print "OUT_Elt contains C and = :"+one
one=one[:one.index('=')+1]+one[one.index('(')+1:one.index(')')]
else: #basicServiceGroupId='SPEECH'
#print "OUT_Elt contains '=' :"+one
one=one
lua+=one+','
else:
lua +="'"+one+"',"
return lua[:len(lua)-1]
class VAL_Elt(Element): #Val
def tolua(self):
return "Val:"+self.content
class MULTIVALUE_Elt(Element): #MultiValue
def tolua(self):
lua = 'MULTI:'
for one in self.childList:
lua +=one+'*'
return lua[:len(lua)-1]
class NULL_Elt(Element): #Null
def tolua(self):
return 'nil'
class NOTEXIST_Elt(Element):#NotExist
def tolua(self):
return 'nil'
class REMOVE_Elt(Element): #Remove
def tolua(self):
attName=self.attrs['name']
lua = self.getIndentation()+ "be:delValue({'"+attName+"'},DA)"
return lua
class RESULT_Elt(Element):#Result
def tolua(self):
if len(self.childList) ==0:
lua ="\n Util.info('--- "+currentModuleName+"#"+currentRequestName+" End----')\nend"
return lua
lua ="\n Util.info('--- "+currentModuleName+"#"+currentRequestName+" End----')\n"
lua +=self.getIndentation()+'return {'
for one in self.childList:
lua +=one+"=GetV('"+one+"'),"
lua =lua[:len(lua)-1]+'}\nend\n'
return lua
class XMLHandler(handler.ContentHandler):
'''
handle one BE XML
'''
def __init__(self):
handler.ContentHandler.__init__(self)
self.fileName=""
self.luaFile=None
def setFileName(self,fileName,packName):
'''
start paring for one new file
'''
self.fileName=fileName
self.root=None
self.currentElement=None
self.tmpElementList=[]
self.luafilename=None
self.packName=packName
if not os.path.exists(packName):
os.mkdir(packName)
def getRoot(self):
return self.root
def startDocument(self):
logging.info("Document:=========%s========= Start..."%self.fileName)
def beginLuaFile(self, modName):
global currentModuleName
currentModuleName = modName
#print "currentModuleName:"+currentModuleName
self.luafilename=self.packName+"/"+modName+'.lua'
logging.info('luafileName:'+ self.luafilename)
print ' the produced lua file: '+self.luafilename
self.luaFile=open(self.luafilename,'w')
self.luaFile.writelines("require 'LuaOam'\n")
self.luaFile.writelines("require ('oamUtil')\n")
self.luaFile.writelines("\n\nmodule('"+modName+"', package.seeall)\n")
self.luaFile.writelines("\nlocal DA=0 --NO_MODEL_DIRECT_ACCESS\n")
self.luaFile.writelines("local PC=1 --POST_COMMIT_MODEL\n")
self.luaFile.writelines("local GH=2 --GDMI_HISTORY_MODEL\n")
self.luaFile.writelines("local CA=3 --PERMANENT_CACHE_MODEL\n")
self.luaFile.writelines("local be=nil\n")
self.luaFile.writelines("local cacheTb={}\n")
self.luaFile.writelines("local contractBELoaded=false")
def endDocument(self):
self.luaFile.writelines("\n\nfunction UpdateV(tb1,...)\n")
self.luaFile.writelines(" if not tb1 then\n")
self.luaFile.writelines(" return\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" for k,v in pairs(tb1) do\n")
self.luaFile.writelines(" if Util.isDebug() then\n")
self.luaFile.writelines(" Util.debug('---- UpdateV#k='..tostring(k)..',v='..tostring(v)..',type='..tostring(type(v)))\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" if type(k) ~= 'number' and v ~= 'Null' then \n")
self.luaFile.writelines(" cacheTb[k]=v\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" if ... then\n")
self.luaFile.writelines(" be:setValue(tb1,DA)\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines("end\n")
self.luaFile.writelines("\nfunction clearCache()\n")
self.luaFile.writelines(" for k,v in pairs(cacheTb) do\n")
self.luaFile.writelines(" cacheTb[k]=nil\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines("end\n")
self.luaFile.writelines("\nfunction GetV(attName, ...) -- ...: ture or false means whether is ListType or not\n")
self.luaFile.writelines(" if cacheTb[attName] == false or cacheTb[attName] ~= nil then\n")
self.luaFile.writelines(" return cacheTb[attName]\n")
self.luaFile.writelines(" else\n")
self.luaFile.writelines(" if attName == '__DISTINGUISH_NAME' and cacheTb['__DISTINGUISH_NAME'] == nil then \n")
self.luaFile.writelines(" cacheTb['__DISTINGUISH_NAME']=be:getDn()\n")
self.luaFile.writelines(" return cacheTb['__DISTINGUISH_NAME']\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" local vall=nil")
self.luaFile.writelines(" if ... then\n")
self.luaFile.writelines(" vall=be:getValue(attName,DA)\n")
self.luaFile.writelines(" else \n")
self.luaFile.writelines(" vall=be:getValue(attName,DA)[1]\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" cacheTb[attName]=vall\n")
self.luaFile.writelines(" return vall\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines("end\n")
self.luaFile.writelines("function SetV(tb, mode) --setValue, and update cache\n")
self.luaFile.writelines(" for k,v in pairs(tb) do\n")
self.luaFile.writelines(" if type(k) ~= 'number' then \n")
self.luaFile.writelines(" cacheTb[k]=v\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" be:setValue(tb,mode)\n")
self.luaFile.writelines("end\n")
self.luaFile.writelines("function DeleteVFromCache(tb) -- delete value from the cache\n")
self.luaFile.writelines(" for k,v in pairs(tb) do\n")
self.luaFile.writelines(" if type(k) == 'number' then \n")
self.luaFile.writelines(" cacheTb[v]=nil\n")
self.luaFile.writelines(" else\n")
self.luaFile.writelines(" cacheTb[k]=nil\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines("end \n")
self.luaFile.writelines("function GetContractV(attrName, ...) -- GetContractV, (...) ture or false means whether is ListType or not\n")
self.luaFile.writelines(" if contractBELoaded == false then\n")
self.luaFile.writelines(" contractBELoaded = true\n")
self.luaFile.writelines(" be:callBE{BE='HSS.ContractData.ContractData.Cont_OAM_ContractEirFunction', \n")
self.luaFile.writelines(" IN={__CALLED_METHOD_NAME='query',__DISTINGUISH_NAME='contractEirFunctionId=1,eirContractDataId=1,customizationFunctionId=1,managedElementId=HSS1'},\n")
self.luaFile.writelines(" OUT='all'} --this is temply for get the Contract Data\n")
self.luaFile.writelines(" end\n")
self.luaFile.writelines(" local kk=nil\n")
self.luaFile.writelines(" if ... then\n")
self.luaFile.writelines(" kk=be:getValue(attrName,DA)\n")
self.luaFile.writelines(" else \n")
self.luaFile.writelines(" kk=be:getValue(attrName,DA)[1]\n")
self.luaFile.writelines(" return kk\n")
self.luaFile.writelines("end\n")
self.luaFile.close()
if len(needModules) !=0:
origFile=open(self.luafilename)
origLines=origFile.readlines()
origFile.close()
modiFile=open(self.luafilename,'w')
appendLine=''
for moduleName in needModules.keys():
appendLine+="\nrequire ('"+self.packName+"."+moduleName+"')"
linN = 0
for line in origLines:
if linN == 2:
modiFile.writelines(appendLine)
modiFile.writelines(line)
linN = linN + 1
modiFile.close()
logging.info("Document:=========%s========= End"%self.fileName)
def startElement(self,name,attrs):
if ignoreTagsMap.has_key(name):
return
try:
newElement=globals()[name.upper()+'_Elt'](name,attrs)
except KeyError:
print 'ERROR: No Class Element was Found:'+name
return
if name == 'BusinessEntity':
modName=attrs['name']
self.beginLuaFile(modName)
self.root=newElement #the root would be the BusinessEntityElt
self.currentElement = None
logging.debug('Create a new Root Element: BussinessEntity')
newElement.setParent(self.currentElement)
if self.currentElement !=None:
if name =='Else' or name =='ElseIf' or self.currentElement.getName() == 'Proc' or self.currentElement.getName() == 'LockPolicy' or self.currentElement.getName() == 'MultiIf':
newElement.setIndentInt(self.currentElement.getIndentInt())
else:
newElement.setIndentInt(self.currentElement.getIndentInt()+1)
logging.debug('Start Element name:'+name+',atLine:'+str(self._locator.getLineNumber())+',parentname:'+self.currentElement.getName()+',indentInt:'+str(newElement.getIndentInt()))
self.currentElement=newElement
self.tmpElementList.append(newElement)
if name == 'Request':
self.luaFile.writelines(newElement.tolua())
def endElement(self,name):
logging.debug('End Element:'+name)
if ignoreTagsMap.has_key(name) or name == 'BusinessEntity':
return
##Begin[merge the children to the current]
sub=0
if self.currentElement == None:
print 'No Parent Element name:'+name+',atLine:'+str(self._locator.getLineNumber())
parentElt = self.currentElement.getParent()
for i in range(len(self.tmpElementList)):
if self.tmpElementList[i]==self.currentElement:
sub=i+1
break
for i in range(sub,len(self.tmpElementList)):
self.currentElement.addChild(self.tmpElementList[i].tolua())
##End[merge the children to the current]
self.tmpElementList=self.tmpElementList[:sub]
if parentElt != None and parentElt.getName() == 'Request':
if self.currentElement.tolua() !='':
self.luaFile.writelines(self.currentElement.tolua())
logging.debug('lua Code:'+self.currentElement.tolua())
self.currentElement=parentElt
def characters(self,ch):
if self.currentElement != None:
if ch !=None and ch != '':
self.currentElement.appendContent(ch.strip())
class XmlFileParser:
def __init__(self,xmlFileName,packName):
self.xmlFileName=xmlFileName
self.packName=packName
def parse(self):
parser=make_parser()
xmlHandler=XMLHandler()
parser.setContentHandler(xmlHandler)
xmlHandler.setFileName(os.path.basename(self.xmlFileName),packName)
xmlFile=file(self.xmlFileName)
try:
parser.parse(xmlFile)
except Exception,e:
print 'Error'
logging.exception("ChangeListFileParser Exception:%s"%e)
def initLog(level=logging.WARNING):
FORMAT = '[%(asctime)s ][%(thread)d] %(levelname)s{%(pathname)s:%(lineno)d }: %(message)s'
workDir="/tmp/"+os.getenv("USER", "xmlcoverage")
mkdirCmd="mkdir -p "+workDir
os.system(mkdirCmd)
generatetime = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
logFile='xml2lua'+str(generatetime)+".log"
print "Log file Path:"+workDir+"/"+logFile
logging.basicConfig(filename=workDir+"/"+logFile,format=FORMAT)
logging.getLogger().setLevel(level)
def Usage():
print "Usage: "+sys.argv[0]+" need parameter:"
print " -x : one xml file or one directory path: contains xml files"
print " -p : the expected produced-package name"
print "Example: python oamxml2lua.py -x xmlFil -p Eir"
sys.exit(1)
if __name__=='__main__':
try:
opts,args = getopt.getopt(sys.argv[1:],"x:p:")
except getopt.GetoptError:
Usage()
paraValue=''
packName=''
for o,a in opts:
if o in ('-x','--xml'):
paraValue=a
if o in ('-p','--packname'):
packName=a
if paraValue == '':
Usage()
if packName == '':
Usage()
print "-x:"+paraValue+",d"+packName
dataTypeFiles=os.listdir(dataTypeDir)
for one in dataTypeFiles:
filePath=os.path.join(dataTypeDir,one)
print 'DataType File:'+filePath
if filePath !='' and not os.path.isdir(filePath):
dataTypeDocs.append(xml.dom.minidom.parse(filePath))
xmlFiles=[]
if paraValue.find(".xml") !=-1:
paraValue=os.getcwd()+'/'+paraValue
print "the Input xmlfile:"+paraValue
xmlFiles.append(paraValue)
else:
absDir=paraValue
if not paraValue.startswith('/'):
absDir=os.getcwd()+'/'+paraValue
fileNames=os.listdir(paraValue)
for one in fileNames:
if one.endswith('.xml'):
filePath=os.path.join(absDir,one)
print "Dir on file:"+filePath
xmlFiles.append(filePath)
initLog(logging.DEBUG)
for absxmlFile in xmlFiles:
needModules={}
parser=XmlFileParser(absxmlFile,packName)
parser.parse()