Esempio n. 1
0
def start():
    #********command line arguments**************************
    editype =''
    messagetype = ''
    configdir = 'config'
    for arg in sys.argv[1:]:
        if not arg:
            continue
        if arg.startswith('-c'):
            configdir = arg[2:]
            if not configdir:
                print '    !!Indicated Bots should use specific .ini file but no file name was given.'
                showusage()
        elif arg in ["?", "/?"] or arg.startswith('-'):
            showusage()
        else:
            if not editype:
                editype = arg
            else:
                messagetype = arg
    if not (editype and messagetype):
        print '    !!Both editype and messagetype are required.'
        showusage()
    #********end handling command line arguments**************************

    try:
        botsinit.generalinit(configdir)
        botsinit.initenginelogging()
        grammar.grammarread(editype,messagetype)
    except:
        print 'Found error in grammar:'
        print botslib.txtexc()
    else:
        print 'OK - no error found in grammar'
Esempio n. 2
0
def startmulti(grammardir,editype):
    ''' specialized tool for bulk checking of grammars while developing botsgrammars 
        grammardir: directory with gramars (eg bots/usersys/grammars/edifact)
        editype: eg edifact
    '''
    configdir = 'config'
    botsinit.generalinit(configdir)     #find locating of bots, configfiles, init paths etc.
    process_name = 'grammarcheck'
    botsglobal.logger = botsinit.initenginelogging(process_name)
    atexit.register(logging.shutdown)
    
    for filename in glob.iglob(grammardir):
        filename_basename = os.path.basename(filename)
        if filename_basename in ['__init__.py','envelope.py']:
            continue
        if filename_basename.startswith('edifact') or filename_basename.startswith('records') or filename_basename.endswith('records.py'):
            continue
        if filename_basename.endswith('pyc'):
            continue
        filename_noextension = os.path.splitext(filename_basename)[0]
        try:
            grammar.grammarread(editype,filename_noextension)
        except:
            print botslib.txtexc()
            print '\n'
        else:
            print 'OK - no error found in grammar',filename,'\n'
def startmulti(grammardir, editype):
    ''' specialized tool for bulk checking of grammars while developing botsgrammars 
        grammardir: directory with gramars (eg bots/usersys/grammars/edifact)
        editype: eg edifact
    '''
    configdir = 'config'
    botsinit.generalinit(
        configdir)  #find locating of bots, configfiles, init paths etc.
    process_name = 'grammarcheck'
    botsglobal.logger = botsinit.initenginelogging(process_name)
    atexit.register(logging.shutdown)

    for filename in glob.iglob(grammardir):
        filename_basename = os.path.basename(filename)
        if filename_basename in ['__init__.py', 'envelope.py']:
            continue
        if filename_basename.startswith(
                'edifact') or filename_basename.startswith(
                    'records') or filename_basename.endswith('records.py'):
            continue
        if filename_basename.endswith('pyc'):
            continue
        filename_noextension = os.path.splitext(filename_basename)[0]
        try:
            grammar.grammarread(editype, filename_noextension)
        except:
            print botslib.txtexc()
            print '\n'
        else:
            print 'OK - no error found in grammar', filename, '\n'
Esempio n. 4
0
def start():
    #********command line arguments**************************
    editype = ''
    messagetype = ''
    configdir = 'config'
    for arg in sys.argv[1:]:
        if not arg:
            continue
        if arg.startswith('-c'):
            configdir = arg[2:]
            if not configdir:
                print '    !!Indicated Bots should use specific .ini file but no file name was given.'
                showusage()
        elif arg in ["?", "/?"] or arg.startswith('-'):
            showusage()
        else:
            if not editype:
                editype = arg
            else:
                messagetype = arg
    if not (editype and messagetype):
        print '    !!Both editype and messagetype are required.'
        showusage()
    #********end handling command line arguments**************************

    try:
        botsinit.generalinit(configdir)
        botsinit.initenginelogging()
        grammar.grammarread(editype, messagetype)
    except:
        print 'Found error in grammar:'
        print botslib.txtexc()
    else:
        print 'OK - no error found in grammar'
Esempio n. 5
0
def start():
    # ********command line arguments**************************
    editype = ""
    messagetype = ""
    botsinifile = "config"
    for arg in sys.argv[1:]:
        if not arg:
            continue
        if arg.startswith("-c"):
            botsinifile = arg[2:]
            if not botsinifile:
                print "    !!Indicated Bots should use specific .ini file but no file name was given."
                showusage()
        elif arg in ["?", "/?"] or arg.startswith("-"):
            showusage()
        else:
            if not editype:
                editype = arg
            else:
                messagetype = arg
    if not (editype and messagetype):
        print "    !!Both editype and messagetype are required."
        showusage()
    # ********end handling command line arguments**************************

    try:
        botslib.initconfigurationfile(botsinifile)
        botslib.initlogging()
        grammar.grammarread(editype, messagetype)
    except:
        print "Found error in grammar:"
        print botslib.txtexc()
    else:
        print "OK - no error found in grammar"
Esempio n. 6
0
def start():
    #NOTE: bots directory should always be on PYTHONPATH - otherwise it will not start.
    #********command line arguments**************************
    usage = '''
    This is "%(name)s" version %(version)s, part of Bots open source edi translator (http://bots.sourceforge.net).
    Checks a Bots grammar. Same checks are used as in translations with bots-engine. Searches for grammar in 
    regular place: bots/usersys/grammars/<editype>/<messagetype>.py  (even if a path is passed).
    
    Usage:  %(name)s  -c<directory> <editype> <messagetype>
       or   %(name)s  -c<directory> <path to grammar>
    Options:
        -c<directory>   directory for configuration files (default: config).
    Examples:
        %(name)s -cconfig  edifact  ORDERSD96AUNEAN008
        %(name)s -cconfig  C:/python27/lib/site-packages/bots/usersys/grammars/edifact/ORDERSD96AUNEAN008.py
        
    '''%{'name':os.path.basename(sys.argv[0]),'version':botsglobal.version}
    configdir = 'config'
    editype =''
    messagetype = ''
    for arg in sys.argv[1:]:
        if arg.startswith('-c'):
            configdir = arg[2:]
            if not configdir:
                print 'Error: configuration directory indicated, but no directory name.'
                sys.exit(1)
        elif arg in ["?", "/?",'-h', '--help'] or arg.startswith('-'):
            print usage
            sys.exit(0)
        else:
            if os.path.isfile(arg):
                p1,p2 = os.path.split(arg)
                editype = os.path.basename(p1)
                messagetype,ext = os.path.splitext(p2)
                messagetype = str(messagetype)
                print 'grammarcheck',editype,messagetype
            elif not editype:
                editype = arg
            else:
                messagetype = arg
    if not (editype and messagetype):
        print 'Error: both editype and messagetype, or a file path, are required.'
        sys.exit(1)
    #***end handling command line arguments**************************
    botsinit.generalinit(configdir)     #find locating of bots, configfiles, init paths etc.
    process_name = 'grammarcheck'
    botsglobal.logger = botsinit.initenginelogging(process_name)
    atexit.register(logging.shutdown)

    try:
        grammar.grammarread(editype,messagetype)
    except:
        print 'Found error in grammar: ',botslib.txtexc()
        sys.exit(1)
    else:
        print 'OK - no error found in grammar'
        sys.exit(0)
Esempio n. 7
0
 def run(self):
     ''' class for (test) orderprint; delevers a valid html-file.
         Uses a kid-template for the enveloping/merging.
         use kid to write; no envelope grammar is used
     '''
     import kid
     defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])   #needed beause we do not know envelope; read syntax for editype/messagetype
     self.ta_info.update(defmessage.syntax)
     botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
     if not self.ta_info['envelope-template']:
         raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype": syntax option "envelope-template" not filled; is required.'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'])
     templatefile = botslib.abspath('templates',self.ta_info['envelope-template'])
     ta_list = self.filelist2absolutepaths()
     try:
         botsglobal.logger.debug(u'Start writing envelope to file "%s".',self.ta_info['filename'])
         ediprint = kid.Template(file=templatefile, data=ta_list) #init template; pass list with filenames
     except:
         txt=botslib.txtexc()
         raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype": $txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
     try:
         f = botslib.opendata(self.ta_info['filename'],'wb')
         ediprint.write(f,
                         encoding=self.ta_info['charset'],
                         output=self.ta_info['output'])
     except:
         txt=botslib.txtexc()
         raise botslib.OutMessageError(_(u'While enveloping error in "$editype.$messagetype"; probably in html file(s) to be merged: $txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
Esempio n. 8
0
 def run(self):
     ''' class for (test) orderprint; delevers a valid html-file.
         Uses a kid-template for the enveloping/merging.
         use kid to write; no envelope grammar is used
     '''
     try:
         from genshi.template import TemplateLoader
     except:
         txt=botslib.txtexc()
         raise ImportError(_(u'Dependency failure: editype "template" requires python library "genshi". Error:\n%s'%txt))
     defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])   #needed because we do not know envelope; read syntax for editype/messagetype
     self.ta_info.update(defmessage.syntax)
     botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
     if not self.ta_info['envelope-template']:
         raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype": syntax option "envelope-template" not filled; is required.'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'])
     templatefile = botslib.abspath('templateshtml',self.ta_info['envelope-template'])
     ta_list = self.filelist2absolutepaths()
     try:
         botsglobal.logger.debug(u'Start writing envelope to file "%s".',self.ta_info['filename'])
         loader = TemplateLoader(auto_reload=False)
         tmpl = loader.load(templatefile)
     except:
         txt=botslib.txtexc()
         raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
     try:
         f = botslib.opendata(self.ta_info['filename'],'wb')
         stream = tmpl.generate(data=ta_list)
         stream.render(method='xhtml',encoding=self.ta_info['charset'],out=f)
     except:
         txt=botslib.txtexc()
         raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
Esempio n. 9
0
 def messagegrammarread(self,typeofgrammarfile='grammars'):
     ''' read grammar for a message/envelope.
         (try to) read the topartner dependent grammar syntax.
     '''
     super(Outmessage,self).messagegrammarread(typeofgrammarfile)
     #read partner-syntax. Use this to always overrule values in self.ta_info
     if self.ta_info.get('frompartner'):   
         try:
             partnersyntax = grammar.grammarread(self.ta_info['editype'],self.ta_info['frompartner'],typeofgrammarfile='partners')
             self.ta_info.update(partnersyntax.syntax) #partner syntax overrules!
         except ImportError:
             pass        #No partner specific syntax found (is not an error).
     if self.ta_info.get('topartner'):   
         try:
             partnersyntax = grammar.grammarread(self.ta_info['editype'],self.ta_info['topartner'],typeofgrammarfile='partners')
             self.ta_info.update(partnersyntax.syntax) #partner syntax overrules!
         except ImportError:
             pass        #No partner specific syntax found (is not an error).
Esempio n. 10
0
 def run(self):
     ''' class for (test) orderprint; delevers a valid html-file.
         Uses a kid-template for the enveloping/merging.
         use kid to write; no envelope grammar is used
     '''
     try:
         from genshi.template import TemplateLoader
     except:
         txt = botslib.txtexc()
         raise ImportError(
             _(u'Dependency failure: editype "template" requires python library "genshi". Error:\n%s'
               % txt))
     defmessage = grammar.grammarread(
         self.ta_info['editype'], self.ta_info['messagetype']
     )  #needed because we do not know envelope; read syntax for editype/messagetype
     self.ta_info.update(defmessage.syntax)
     botslib.tryrunscript(self.userscript,
                          self.scriptname,
                          'ta_infocontent',
                          ta_info=self.ta_info)
     if not self.ta_info['envelope-template']:
         raise botslib.OutMessageError(_(
             u'While enveloping in "$editype.$messagetype": syntax option "envelope-template" not filled; is required.'
         ),
                                       editype=self.ta_info['editype'],
                                       messagetype=self.
                                       ta_info['messagetype'])
     templatefile = botslib.abspath('templateshtml',
                                    self.ta_info['envelope-template'])
     ta_list = self.filelist2absolutepaths()
     try:
         botsglobal.logger.debug(u'Start writing envelope to file "%s".',
                                 self.ta_info['filename'])
         loader = TemplateLoader(auto_reload=False)
         tmpl = loader.load(templatefile)
     except:
         txt = botslib.txtexc()
         raise botslib.OutMessageError(
             _(u'While enveloping in "$editype.$messagetype", error:\n$txt'
               ),
             editype=self.ta_info['editype'],
             messagetype=self.ta_info['messagetype'],
             txt=txt)
     try:
         filehandler = botslib.opendata(self.ta_info['filename'], 'wb')
         stream = tmpl.generate(data=ta_list)
         stream.render(method='xhtml',
                       encoding=self.ta_info['charset'],
                       out=filehandler)
     except:
         txt = botslib.txtexc()
         raise botslib.OutMessageError(
             _(u'While enveloping in "$editype.$messagetype", error:\n$txt'
               ),
             editype=self.ta_info['editype'],
             messagetype=self.ta_info['messagetype'],
             txt=txt)
Esempio n. 11
0
 def run(self):
     ''' class for (test) orderprint; delevers a valid html-file.
         Uses a kid-template for the enveloping/merging.
         use kid to write; no envelope grammar is used
     '''
     try:
         import kid
     except:
         txt = botslib.txtexc()
         raise ImportError(
             _(u'Dependency failure: editype "template" requires python library "kid". Error:\n%s'
               % txt))
     defmessage = grammar.grammarread(
         self.ta_info['editype'], self.ta_info['messagetype']
     )  #needed because we do not know envelope; read syntax for editype/messagetype
     self.ta_info.update(defmessage.syntax)
     botslib.tryrunscript(self.userscript,
                          self.scriptname,
                          'ta_infocontent',
                          ta_info=self.ta_info)
     if not self.ta_info['envelope-template']:
         raise botslib.OutMessageError(_(
             u'While enveloping in "$editype.$messagetype": syntax option "envelope-template" not filled; is required.'
         ),
                                       editype=self.ta_info['editype'],
                                       messagetype=self.
                                       ta_info['messagetype'])
     templatefile = botslib.abspath('templates',
                                    self.ta_info['envelope-template'])
     ta_list = self.filelist2absolutepaths()
     try:
         botsglobal.logger.debug(u'Start writing envelope to file "%s".',
                                 self.ta_info['filename'])
         ediprint = kid.Template(
             file=templatefile,
             data=ta_list)  #init template; pass list with filenames
     except:
         txt = botslib.txtexc()
         raise botslib.OutMessageError(
             _(u'While enveloping in "$editype.$messagetype", error:\n$txt'
               ),
             editype=self.ta_info['editype'],
             messagetype=self.ta_info['messagetype'],
             txt=txt)
     try:
         filehandler = botslib.opendata(self.ta_info['filename'], 'wb')
         ediprint.write(filehandler,
                        encoding=self.ta_info['charset'],
                        output=self.ta_info['output'])
     except:
         txt = botslib.txtexc()
         raise botslib.OutMessageError(
             _(u'While enveloping in "$editype.$messagetype", error:\n$txt'
               ),
             editype=self.ta_info['editype'],
             messagetype=self.ta_info['messagetype'],
             txt=txt)
Esempio n. 12
0
 def messagegrammarread(self,typeofgrammarfile='grammars'):
     ''' read grammar for a message/envelope.
     '''
     #read grammar for message.
     #starts with default values from grammar.py; values are overruled by envelope settings; values are overrules by messagetype setting.
     self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'],typeofgrammarfile)
     #write values from grammar to self.ta_info - unless these values are already set (eg by mappingscript)
     botslib.updateunlessset(self.ta_info,self.defmessage.syntax)
     if not self.ta_info['charset']:
         self.ta_info['charset'] = self.defmessage.syntax['charset']      #always use charset of edi file.
Esempio n. 13
0
def startmulti(grammardir,editype):
    import glob
    botslib.initconfigurationfile('config')
    botslib.initlogging()
    for g in glob.glob(grammardir):
        g1 = os.path.basename(g)
        g2 = os.path.splitext(g1)[0]
        if g1 in ['__init__.py']:
            continue
        if g1.startswith('edifact'):
            continue
        if g1.startswith('records') or g1.endswith('records.py'):
            continue
        try:
            grammar.grammarread(editype,g2)
        except:
            #~ print 'Found error in grammar:',g
            print botslib.txtexc()
            print '\n'
        else:
            print 'OK - no error found in grammar',g,'\n'
Esempio n. 14
0
def startmulti(grammardir, editype):
    ''' used in seperate tool for bulk checking of gramamrs while developing edifact->botsgramamrs '''
    import glob
    botslib.generalinit('config')
    botslib.initenginelogging()
    for g in glob.glob(grammardir):
        g1 = os.path.basename(g)
        g2 = os.path.splitext(g1)[0]
        if g1 in ['__init__.py']:
            continue
        if g1.startswith('edifact'):
            continue
        if g1.startswith('records') or g1.endswith('records.py'):
            continue
        try:
            grammar.grammarread(editype, g2)
        except:
            #~ print 'Found error in grammar:',g
            print botslib.txtexc()
            print '\n'
        else:
            print 'OK - no error found in grammar', g, '\n'
Esempio n. 15
0
def startmulti(grammardir,editype):
    ''' used in seperate tool for bulk checking of gramamrs while developing edifact->botsgramamrs '''
    import glob
    botslib.generalinit('config')
    botslib.initenginelogging()
    for g in glob.glob(grammardir):
        g1 = os.path.basename(g)
        g2 = os.path.splitext(g1)[0]
        if g1 in ['__init__.py']:
            continue
        if g1.startswith('edifact'):
            continue
        if g1.startswith('records') or g1.endswith('records.py'):
            continue
        try:
            grammar.grammarread(editype,g2)
        except:
            #~ print 'Found error in grammar:',g
            print botslib.txtexc()
            print '\n'
        else:
            print 'OK - no error found in grammar',g,'\n'
Esempio n. 16
0
 def messagegrammarread(self, typeofgrammarfile='grammars'):
     ''' read grammar for a message/envelope.
     '''
     #read grammar for message.
     #starts with default values from grammar.py; values are overruled by envelope settings; values are overrules by messagetype setting.
     self.defmessage = grammar.grammarread(self.ta_info['editype'],
                                           self.ta_info['messagetype'],
                                           typeofgrammarfile)
     #write values from grammar to self.ta_info - unless these values are already set (eg by mappingscript)
     botslib.updateunlessset(self.ta_info, self.defmessage.syntax)
     if not self.ta_info['charset']:
         self.ta_info['charset'] = self.defmessage.syntax[
             'charset']  #always use charset of edi file.
Esempio n. 17
0
def startmulti(grammardir, editype):
    import glob

    botslib.initconfigurationfile("config")
    botslib.initlogging()
    for g in glob.glob(grammardir):
        g1 = os.path.basename(g)
        g2 = os.path.splitext(g1)[0]
        if g1 in ["__init__.py"]:
            continue
        if g1.startswith("edifact"):
            continue
        if g1.startswith("records") or g1.endswith("records.py"):
            continue
        try:
            grammar.grammarread(editype, g2)
        except:
            # ~ print 'Found error in grammar:',g
            print botslib.txtexc()
            print "\n"
        else:
            print "OK - no error found in grammar", g, "\n"
Esempio n. 18
0
 def outmessagegrammarread(self,editype,messagetype):
     ''' read the grammar for a out-message.
         try to read the topartner dependent grammar syntax.
     ''' 
     self.defmessage = grammar.grammarread(editype,messagetype)
     #~ print 'self.ta_info',self.ta_info
     #~ print 'self.defmessage.syntax',self.defmessage.syntax
     botslib.updateunlessset(self.ta_info,self.defmessage.syntax)    #write values from grammar to self.ta_info - unless these values are already set eg by mapping script
     if self.ta_info['topartner']:   #read syntax-file for partner dependent syntax
         try:
             partnersyntax = grammar.syntaxread('partners',editype,self.ta_info['topartner'])
             self.ta_info.update(partnersyntax.syntax) #partner syntax overrules!
         except ImportError:
             pass        #No partner specific syntax found (is not an error).
Esempio n. 19
0
 def run(self):
     """ class for (test) orderprint; delevers a valid html-file.
         Uses a kid-template for the enveloping/merging.
         use kid to write; no envelope grammar is used
     """
     try:
         import kid
     except:
         txt = botslib.txtexc()
         raise ImportError(
             _(u'Dependency failure: editype "template" requires python library "kid". Error:\n%s' % txt)
         )
     defmessage = grammar.grammarread(
         self.ta_info["editype"], self.ta_info["messagetype"]
     )  # needed because we do not know envelope; read syntax for editype/messagetype
     self.ta_info.update(defmessage.syntax)
     botslib.tryrunscript(self.userscript, self.scriptname, "ta_infocontent", ta_info=self.ta_info)
     if not self.ta_info["envelope-template"]:
         raise botslib.OutMessageError(
             _(
                 u'While enveloping in "$editype.$messagetype": syntax option "envelope-template" not filled; is required.'
             ),
             editype=self.ta_info["editype"],
             messagetype=self.ta_info["messagetype"],
         )
     templatefile = botslib.abspath("templates", self.ta_info["envelope-template"])
     ta_list = self.filelist2absolutepaths()
     try:
         botsglobal.logger.debug(u'Start writing envelope to file "%s".', self.ta_info["filename"])
         ediprint = kid.Template(file=templatefile, data=ta_list)  # init template; pass list with filenames
     except:
         txt = botslib.txtexc()
         raise botslib.OutMessageError(
             _(u'While enveloping in "$editype.$messagetype", error:\n$txt'),
             editype=self.ta_info["editype"],
             messagetype=self.ta_info["messagetype"],
             txt=txt,
         )
     try:
         filehandler = botslib.opendata(self.ta_info["filename"], "wb")
         ediprint.write(filehandler, encoding=self.ta_info["charset"], output=self.ta_info["output"])
     except:
         txt = botslib.txtexc()
         raise botslib.OutMessageError(
             _(u'While enveloping in "$editype.$messagetype", error:\n$txt'),
             editype=self.ta_info["editype"],
             messagetype=self.ta_info["messagetype"],
             txt=txt,
         )
Esempio n. 20
0
 def run(self):
     if not self.ta_info["topartner"] or not self.ta_info["frompartner"]:
         raise botslib.OutMessageError(
             _(u'In enveloping "frompartner" or "topartner" unknown: "$ta_info".'), ta_info=self.ta_info
         )
     self._openoutenvelope(self.ta_info["editype"], self.ta_info["envelope"])
     self.ta_info.update(self.out.ta_info)
     # need to know the functionalgroup code:
     defmessage = grammar.grammarread(self.ta_info["editype"], self.ta_info["messagetype"])
     self.ta_info["functionalgroup"] = defmessage.syntax["functionalgroup"]
     botslib.tryrunscript(self.userscript, self.scriptname, "ta_infocontent", ta_info=self.ta_info)
     # prepare data for envelope
     isa09date = time.strftime("%y%m%d")
     # test indicator can either be from configuration (self.ta_info['ISA15']) or by mapping (self.ta_info['testindicator'])
     # mapping overrules.
     if self.ta_info["testindicator"] and self.ta_info["testindicator"] != "0":  #'0' is default value (in db)
         testindicator = self.ta_info["testindicator"]
     else:
         testindicator = self.ta_info["ISA15"]
     # ~ print self.ta_info['messagetype'], 'grammar:',self.ta_info['ISA15'],'ta:',self.ta_info['testindicator'],'out:',testindicator
     if botsglobal.ini.getboolean("settings", "interchangecontrolperpartner", False):
         self.ta_info["reference"] = str(botslib.unique("isacounter_" + self.ta_info["topartner"]))
     else:
         self.ta_info["reference"] = str(botslib.unique("isacounter_" + self.ta_info["frompartner"]))
     # ISA06 and GS02 can be different; eg ISA06 is a service provider.
     # ISA06 and GS02 can be in the syntax....
     isa06sender = self.ta_info.get("ISA06", self.ta_info["frompartner"])
     isa06sender = isa06sender.ljust(15)  # add spaces; is fixed length
     gs02sender = self.ta_info.get("GS02", self.ta_info["frompartner"])
     # also for ISA08 and GS03
     isa08receiver = self.ta_info.get("ISA08", self.ta_info["topartner"])
     isa08receiver = isa08receiver.ljust(15)  # add spaces; is fixed length
     gs03receiver = self.ta_info.get("GS03", self.ta_info["topartner"])
     # build the envelope segments (that is, the tree from which the segments will be generated)
     self.out.put(
         {
             "BOTSID": "ISA",
             "ISA01": self.ta_info["ISA01"],
             "ISA02": self.ta_info["ISA02"],
             "ISA03": self.ta_info["ISA03"],
             "ISA04": self.ta_info["ISA04"],
             "ISA05": self.ta_info["ISA05"],
             "ISA06": isa06sender,
             "ISA07": self.ta_info["ISA07"],
             "ISA08": isa08receiver,
             "ISA09": isa09date,
             "ISA10": time.strftime("%H%M"),
             "ISA11": self.ta_info["ISA11"],  # if ISA version > 00403, replaced by reprtion separator
             "ISA12": self.ta_info["version"],
             "ISA13": self.ta_info["reference"],
             "ISA14": self.ta_info["ISA14"],
             "ISA15": testindicator,
         },
         strip=False,
     )  # MIND: strip=False: ISA fields shoudl not be stripped as it is soemwhat like fixed-length
     self.out.put({"BOTSID": "ISA"}, {"BOTSID": "IEA", "IEA01": "1", "IEA02": self.ta_info["reference"]})
     gs08messagetype = self.ta_info["messagetype"][3:]
     if gs08messagetype[:6] < "004010":
         gs04date = time.strftime("%y%m%d")
     else:
         gs04date = time.strftime("%Y%m%d")
     self.out.put(
         {"BOTSID": "ISA"},
         {
             "BOTSID": "GS",
             "GS01": self.ta_info["functionalgroup"],
             "GS02": gs02sender,
             "GS03": gs03receiver,
             "GS04": gs04date,
             "GS05": time.strftime("%H%M"),
             "GS06": self.ta_info["reference"],
             "GS07": self.ta_info["GS07"],
             "GS08": gs08messagetype,
         },
     )
     self.out.put(
         {"BOTSID": "ISA"},
         {"BOTSID": "GS"},
         {"BOTSID": "GE", "GE01": self.ta_info["nrmessages"], "GE02": self.ta_info["reference"]},
     )  # dummy segment; is not used
     # user exit
     botslib.tryrunscript(self.userscript, self.scriptname, "envelopecontent", ta_info=self.ta_info, out=self.out)
     # convert the tree into segments; here only the UNB is written (first segment)
     self.out.checkmessage(self.out.root, self.out.defmessage)
     self.out.tree2records(self.out.root)
     # start doing the actual writing:
     tofile = botslib.opendata(self.ta_info["filename"], "wb", self.ta_info["charset"])
     isa_string = self.out.record2string(self.out.records[0])
     if self.ta_info["version"] < "00403":
         isa_string = (
             isa_string[:103] + self.ta_info["field_sep"] + self.ta_info["sfield_sep"] + isa_string[103:]
         )  # hack for strange characters at end of ISA; hardcoded
     else:
         isa_string = (
             isa_string[:82]
             + self.ta_info["reserve"]
             + isa_string[83:103]
             + self.ta_info["field_sep"]
             + self.ta_info["sfield_sep"]
             + isa_string[103:]
         )  # hack for strange characters at end of ISA; hardcoded
     tofile.write(isa_string)  # write ISA
     tofile.write(self.out.record2string(self.out.records[1]))  # write GS
     self.writefilelist(tofile)
     tofile.write(self.out.record2string(self.out.records[-2]))  # write GE
     tofile.write(self.out.record2string(self.out.records[-1]))  # write IEA
     tofile.close()
     if self.ta_info["functionalgroup"] != "FA" and botslib.checkconfirmrules(
         "ask-x12-997",
         idroute=self.ta_info["idroute"],
         idchannel=self.ta_info["tochannel"],
         topartner=self.ta_info["topartner"],
         frompartner=self.ta_info["frompartner"],
         editype=self.ta_info["editype"],
         messagetype=self.ta_info["messagetype"],
     ):
         self.ta_info["confirmtype"] = u"ask-x12-997"
         self.ta_info["confirmasked"] = True
Esempio n. 21
0
def start():
    #NOTE: bots directory should always be on PYTHONPATH - otherwise it will not start.
    #********command line arguments**************************
    usage = '''
    This is "%(name)s" version %(version)s, part of Bots open source edi translator (http://bots.sourceforge.net).
    Checks a Bots grammar. Same checks are used as in translations with bots-engine. Searches for grammar in 
    regular place: bots/usersys/grammars/<editype>/<messagetype>.py  (even if a path is passed).
    
    Usage:  %(name)s  -c<directory> <editype> <messagetype>
       or   %(name)s  -c<directory> <path to grammar>
    Options:
        -c<directory>   directory for configuration files (default: config).
    Examples:
        %(name)s -cconfig  edifact  ORDERSD96AUNEAN008
        %(name)s -cconfig  C:/python27/lib/site-packages/bots/usersys/grammars/edifact/ORDERSD96AUNEAN008.py
        
    ''' % {
        'name': os.path.basename(sys.argv[0]),
        'version': botsglobal.version
    }
    configdir = 'config'
    editype = ''
    messagetype = ''
    for arg in sys.argv[1:]:
        if arg.startswith('-c'):
            configdir = arg[2:]
            if not configdir:
                print 'Error: configuration directory indicated, but no directory name.'
                sys.exit(1)
        elif arg in ["?", "/?", '-h', '--help'] or arg.startswith('-'):
            print usage
            sys.exit(0)
        else:
            if os.path.isfile(arg):
                p1, p2 = os.path.split(arg)
                editype = os.path.basename(p1)
                messagetype, ext = os.path.splitext(p2)
                messagetype = unicode(messagetype)
                print 'grammarcheck', editype, messagetype
            elif not editype:
                editype = arg
            else:
                messagetype = arg
    if not (editype and messagetype):
        print 'Error: both editype and messagetype, or a file path, are required.'
        sys.exit(1)
    #***end handling command line arguments**************************
    botsinit.generalinit(
        configdir)  #find locating of bots, configfiles, init paths etc.
    process_name = 'grammarcheck'
    botsglobal.logger = botsinit.initenginelogging(process_name)
    atexit.register(logging.shutdown)

    try:
        grammar.grammarread(editype, messagetype)
    except:
        print 'Found error in grammar: ', botslib.txtexc()
        sys.exit(1)
    else:
        print 'OK - no error found in grammar'
        sys.exit(0)
Esempio n. 22
0
 def messagegrammarread(self,typeofgrammarfile='grammars'):
     ''' read grammar for a message/envelope.
     '''
     self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'],typeofgrammarfile)
     #write values from grammar to self.ta_info - unless these values are already set (eg by mappingscript)
     botslib.updateunlessset(self.ta_info,self.defmessage.syntax)
Esempio n. 23
0
 def run(self):
     if not self.ta_info['topartner'] or not self.ta_info['frompartner']:
         raise botslib.OutMessageError(_(
             u'In enveloping "frompartner" or "topartner" unknown: "$ta_info".'
         ),
                                       ta_info=self.ta_info)
     self._openoutenvelope(self.ta_info['editype'],
                           self.ta_info['envelope'])
     self.ta_info.update(self.out.ta_info)
     #need to know the functionalgroup code:
     defmessage = grammar.grammarread(self.ta_info['editype'],
                                      self.ta_info['messagetype'])
     self.ta_info['functionalgroup'] = defmessage.syntax['functionalgroup']
     botslib.tryrunscript(self.userscript,
                          self.scriptname,
                          'ta_infocontent',
                          ta_info=self.ta_info)
     #prepare data for envelope
     isa09date = time.strftime('%y%m%d')
     #test indicator can either be from configuration (self.ta_info['ISA15']) or by mapping (self.ta_info['testindicator'])
     #mapping overrules.
     if self.ta_info['testindicator'] and self.ta_info[
             'testindicator'] != '0':  #'0' is default value (in db)
         testindicator = self.ta_info['testindicator']
     else:
         testindicator = self.ta_info['ISA15']
     #~ print self.ta_info['messagetype'], 'grammar:',self.ta_info['ISA15'],'ta:',self.ta_info['testindicator'],'out:',testindicator
     if botsglobal.ini.getboolean('settings',
                                  'interchangecontrolperpartner', False):
         self.ta_info['reference'] = str(
             botslib.unique('isacounter_' + self.ta_info['topartner']))
     else:
         self.ta_info['reference'] = str(
             botslib.unique('isacounter_' + self.ta_info['frompartner']))
     #ISA06 and GS02 can be different; eg ISA06 is a service provider.
     #ISA06 and GS02 can be in the syntax....
     isa06sender = self.ta_info.get('ISA06', self.ta_info['frompartner'])
     isa06sender = isa06sender.ljust(15)  #add spaces; is fixed length
     gs02sender = self.ta_info.get('GS02', self.ta_info['frompartner'])
     #also for ISA08 and GS03
     isa08receiver = self.ta_info.get('ISA08', self.ta_info['topartner'])
     isa08receiver = isa08receiver.ljust(15)  #add spaces; is fixed length
     gs03receiver = self.ta_info.get('GS03', self.ta_info['topartner'])
     #build the envelope segments (that is, the tree from which the segments will be generated)
     self.out.put(
         {
             'BOTSID': 'ISA',
             'ISA01': self.ta_info['ISA01'],
             'ISA02': self.ta_info['ISA02'],
             'ISA03': self.ta_info['ISA03'],
             'ISA04': self.ta_info['ISA04'],
             'ISA05': self.ta_info['ISA05'],
             'ISA06': isa06sender,
             'ISA07': self.ta_info['ISA07'],
             'ISA08': isa08receiver,
             'ISA09': isa09date,
             'ISA10': time.strftime('%H%M'),
             'ISA11': self.ta_info[
                 'ISA11'],  #if ISA version > 00403, replaced by reprtion separator
             'ISA12': self.ta_info['version'],
             'ISA13': self.ta_info['reference'],
             'ISA14': self.ta_info['ISA14'],
             'ISA15': testindicator
         },
         strip=False
     )  #MIND: strip=False: ISA fields shoudl not be stripped as it is soemwhat like fixed-length
     self.out.put({'BOTSID': 'ISA'}, {
         'BOTSID': 'IEA',
         'IEA01': '1',
         'IEA02': self.ta_info['reference']
     })
     gs08messagetype = self.ta_info['messagetype'][3:]
     if gs08messagetype[:6] < '004010':
         gs04date = time.strftime('%y%m%d')
     else:
         gs04date = time.strftime('%Y%m%d')
     self.out.put({'BOTSID': 'ISA'}, {
         'BOTSID': 'GS',
         'GS01': self.ta_info['functionalgroup'],
         'GS02': gs02sender,
         'GS03': gs03receiver,
         'GS04': gs04date,
         'GS05': time.strftime('%H%M'),
         'GS06': self.ta_info['reference'],
         'GS07': self.ta_info['GS07'],
         'GS08': gs08messagetype
     })
     self.out.put({'BOTSID': 'ISA'}, {'BOTSID': 'GS'}, {
         'BOTSID': 'GE',
         'GE01': self.ta_info['nrmessages'],
         'GE02': self.ta_info['reference']
     })  #dummy segment; is not used
     #user exit
     botslib.tryrunscript(self.userscript,
                          self.scriptname,
                          'envelopecontent',
                          ta_info=self.ta_info,
                          out=self.out)
     #convert the tree into segments; here only the UNB is written (first segment)
     self.out.checkmessage(self.out.root, self.out.defmessage)
     self.out.tree2records(self.out.root)
     #start doing the actual writing:
     tofile = botslib.opendata(self.ta_info['filename'], 'wb',
                               self.ta_info['charset'])
     isa_string = self.out.record2string(self.out.records[0])
     if self.ta_info['version'] < '00403':
         isa_string = isa_string[:103] + self.ta_info[
             'field_sep'] + self.ta_info['sfield_sep'] + isa_string[
                 103:]  #hack for strange characters at end of ISA; hardcoded
     else:
         isa_string = isa_string[:82] + self.ta_info[
             'reserve'] + isa_string[83:103] + self.ta_info[
                 'field_sep'] + self.ta_info['sfield_sep'] + isa_string[
                     103:]  #hack for strange characters at end of ISA; hardcoded
     tofile.write(isa_string)  #write ISA
     tofile.write(self.out.record2string(self.out.records[1]))  #write GS
     self.writefilelist(tofile)
     tofile.write(self.out.record2string(self.out.records[-2]))  #write GE
     tofile.write(self.out.record2string(self.out.records[-1]))  #write IEA
     tofile.close()
     if self.ta_info[
             'functionalgroup'] != 'FA' and botslib.checkconfirmrules(
                 'ask-x12-997',
                 idroute=self.ta_info['idroute'],
                 idchannel=self.ta_info['tochannel'],
                 topartner=self.ta_info['topartner'],
                 frompartner=self.ta_info['frompartner'],
                 editype=self.ta_info['editype'],
                 messagetype=self.ta_info['messagetype']):
         self.ta_info['confirmtype'] = u'ask-x12-997'
         self.ta_info['confirmasked'] = True
Esempio n. 24
0
 def run(self):
     self._openoutenvelope(self.ta_info['editype'],self.ta_info['envelope'])
     self.ta_info.update(self.out.ta_info)
     #need to know the functionalgroup code:
     defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])
     self.ta_info['functionalgroup'] = defmessage.syntax['functionalgroup']
     botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
     #prepare data for envelope
     ISA09date = time.strftime('%y%m%d')
     #test indicator can either be from configuration (self.ta_info['ISA15']) or by mapping (self.ta_info['testindicator'])
     #mapping overrules. 
     if self.ta_info['testindicator'] and self.ta_info['testindicator']!='0':    #'0' is default value (in db)
         testindicator = self.ta_info['testindicator']
     else:
         testindicator = self.ta_info['ISA15']
     #~ print self.ta_info['messagetype'], 'grammar:',self.ta_info['ISA15'],'ta:',self.ta_info['testindicator'],'out:',testindicator
     if botsglobal.ini.getboolean('settings','interchangecontrolperpartner',False):
         self.ta_info['reference'] = str(botslib.unique('isacounter_' + self.ta_info['topartner']))
     else:
         self.ta_info['reference'] = str(botslib.unique('isacounter_' + self.ta_info['frompartner']))
     #ISA06 and GS02 can be different; eg ISA06 is a service provider.
     #ISA06 and GS02 can be in the syntax....
     ISA06 = self.ta_info.get('ISA06',self.ta_info['frompartner'])
     GS02 = self.ta_info.get('GS02',self.ta_info['frompartner'])
     #also for ISA08 and GS03
     ISA08 = self.ta_info.get('ISA08',self.ta_info['topartner'])
     GS03 = self.ta_info.get('GS03',self.ta_info['topartner'])
     #build the envelope segments (that is, the tree from which the segments will be generated)
     self.out.put({'BOTSID':'ISA',
                     'ISA01':self.ta_info['ISA01'],
                     'ISA02':self.ta_info['ISA02'],
                     'ISA03':self.ta_info['ISA03'],
                     'ISA04':self.ta_info['ISA04'],
                     'ISA05':self.ta_info['ISA05'],
                     'ISA06':ISA06,
                     'ISA07':self.ta_info['ISA07'],
                     'ISA08':ISA08,
                     'ISA09':ISA09date,
                     'ISA10':time.strftime('%H%M'),
                     'ISA11':self.ta_info['ISA11'],      #if ISA version > 00403, replaced by reprtion separator
                     'ISA12':self.ta_info['version'],
                     'ISA13':self.ta_info['reference'],
                     'ISA14':self.ta_info['ISA14'],
                     'ISA15':testindicator})
     self.out.put({'BOTSID':'ISA'},{'BOTSID':'IEA','IEA01':'1','IEA02':self.ta_info['reference']})
     GS08 = self.ta_info['messagetype'][3:]
     if GS08[:6]<'004010':
         GS04date = time.strftime('%y%m%d')
     else:
         GS04date = time.strftime('%Y%m%d')
     self.out.put({'BOTSID':'ISA'},{'BOTSID':'GS',
                                     'GS01':self.ta_info['functionalgroup'],
                                     'GS02':GS02,
                                     'GS03':GS03,
                                     'GS04':GS04date,
                                     'GS05':time.strftime('%H%M'),
                                     'GS06':self.ta_info['reference'],
                                     'GS07':self.ta_info['GS07'],
                                     'GS08':GS08})
     self.out.put({'BOTSID':'ISA'},{'BOTSID':'GS'},{'BOTSID':'GE','GE01':self.ta_info['nrmessages'],'GE02':self.ta_info['reference']})  #dummy segment; is not used
     #user exit
     botslib.tryrunscript(self.userscript,self.scriptname,'envelopecontent',ta_info=self.ta_info,out=self.out)
     #convert the tree into segments; here only the UNB is written (first segment)
     self.out.normalisetree(self.out.root)
     self.out.tree2records(self.out.root)
     #start doing the actual writing:
     tofile = botslib.opendata(self.ta_info['filename'],'wb',self.ta_info['charset'])
     ISAstring = self.out._record2string(self.out.records[0])
     if self.ta_info['version']<'00403':
         ISAstring = ISAstring[:103] + self.ta_info['field_sep']+ self.ta_info['sfield_sep'] + ISAstring[103:] #hack for strange characters at end of ISA; hardcoded
     else:
         ISAstring = ISAstring[:82] +self.ta_info['reserve'] + ISAstring[83:103] + self.ta_info['field_sep']+ self.ta_info['sfield_sep'] + ISAstring[103:] #hack for strange characters at end of ISA; hardcoded
     tofile.write(ISAstring)                                     #write ISA
     tofile.write(self.out._record2string(self.out.records[1]))  #write GS
     self.writefilelist(tofile)
     tofile.write(self.out._record2string(self.out.records[-2])) #write GE
     tofile.write(self.out._record2string(self.out.records[-1])) #write IEA
     tofile.close()
     if self.ta_info['functionalgroup']!='FA' and botslib.checkconfirmrules('ask-x12-997',idroute=self.ta_info['idroute'],idchannel=self.ta_info['tochannel'],
                                                                             topartner=self.ta_info['topartner'],frompartner=self.ta_info['frompartner'],
                                                                             editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype']):
         self.ta_info['confirmtype'] = u'ask-x12-997'
         self.ta_info['confirmasked'] = True