Show
Ignore:
Timestamp:
09/27/08 22:02:37 (16 years ago)
Author:
jerome
Message:

Removed unnecessary spaces at EOL.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/pykota/dumper.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    3232try : 
    3333    import jaxml 
    34 except ImportError :     
     34except ImportError : 
    3535    sys.stderr.write("The jaxml Python module is not installed. XML output is disabled.\n") 
    3636    sys.stderr.write("Download jaxml from http://www.librelogiciel.com/software/ or from your Debian archive of choice\n") 
    3737    hasJAXML = False 
    38 else :     
     38else : 
    3939    hasJAXML = True 
    4040 
     
    4545from pykota.errors import PyKotaToolError, PyKotaCommandLineError 
    4646 
    47 class DumPyKota(PyKotaTool) :         
     47class DumPyKota(PyKotaTool) : 
    4848    """A class for dumpykota.""" 
    4949    validdatatypes = { u"history" : N_("History"), 
     
    5454                       u"gpquotas" : N_("Users Groups Print Quotas"), 
    5555                       u"payments" : N_("History of Payments"), 
    56                        u"pmembers" : N_("Printers Groups Membership"),  
     56                       u"pmembers" : N_("Printers Groups Membership"), 
    5757                       u"umembers" : N_("Users Groups Membership"), 
    5858                       u"billingcodes" : N_("Billing Codes"), 
     
    6464                     u"xml" : N_("eXtensible Markup Language"), 
    6565                     u"cups" : N_("CUPS' page_log"), 
    66                    }   
     66                   } 
    6767    validfilterkeys = [ "username", 
    6868                        "groupname", 
     
    7171                        "hostname", 
    7272                        "billingcode", 
    73                         "jobid",  
     73                        "jobid", 
    7474                        "start", 
    7575                        "end", 
     
    7878        """Print Quota Data Dumper.""" 
    7979        self.adminOnly(restricted) 
    80              
     80 
    8181        datatype = options.data 
    8282        if datatype not in self.validdatatypes.keys() : 
    8383            raise PyKotaCommandLineError, _("Invalid data type '%(datatype)s', see help.") % locals() 
    84                      
     84 
    8585        orderby = options.orderby or [] 
    8686        if orderby : 
     
    9191                   or ((field[0] in ("+", "-")) and field[1:].isalpha()) : 
    9292                    orderby.append(field) 
    93                 else :     
     93                else : 
    9494                    logerr(_("Skipping invalid ordering statement '%(field)s'") % locals()) 
    95              
     95 
    9696        extractonly = {} 
    97         if datatype == u"all" :             
     97        if datatype == u"all" : 
    9898            if (options.format != u"xml") or options.sum or arguments : 
    9999                self.printInfo(_("Dumping all PyKota's datas forces format to XML, and disables --sum and filters."), "warn") 
    100100            options.format = u"xml" 
    101101            options.sum = None 
    102         else :     
     102        else : 
    103103            for filterexp in arguments : 
    104104                if filterexp.strip() : 
     
    107107                        filterkey = filterkey.encode("ASCII", "replace").lower() 
    108108                        if filterkey not in self.validfilterkeys : 
    109                             raise ValueError                 
    110                     except ValueError :     
     109                            raise ValueError 
     110                    except ValueError : 
    111111                        raise PyKotaCommandLineError, _("Invalid filter value '%(filterexp)s', see help.") % locals() 
    112                     else :     
     112                    else : 
    113113                        extractonly.update({ filterkey : filtervalue }) 
    114              
     114 
    115115        format = options.format 
    116116        if (format not in self.validformats.keys()) \ 
     
    118118              and ((datatype != u"history") or options.sum)) : 
    119119            raise PyKotaCommandLineError, _("Invalid format '%(format)s', see help.") % locals() 
    120              
     120 
    121121        if (format == u"xml") and not hasJAXML : 
    122122            raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.") 
    123              
    124         if datatype not in (u"payments", u"history") :  
    125             if options.sum :  
     123 
     124        if datatype not in (u"payments", u"history") : 
     125            if options.sum : 
    126126                raise PyKotaCommandLineError, _("Invalid data type '%(datatype)s' for --sum command line option, see help.") % locals() 
    127             if extractonly.has_key(u"start") or extractonly.has_key(u"end") :     
     127            if extractonly.has_key(u"start") or extractonly.has_key(u"end") : 
    128128                self.printInfo(_("Invalid filter for the '%(datatype)s' data type.") % locals(), "warn") 
    129129                try : 
    130130                    del extractonly[u"start"] 
    131                 except KeyError :     
     131                except KeyError : 
    132132                    pass 
    133133                try : 
    134134                    del extractonly[u"end"] 
    135                 except KeyError :     
     135                except KeyError : 
    136136                    pass 
    137              
     137 
    138138        retcode = 0 
    139         nbentries = 0     
     139        nbentries = 0 
    140140        mustclose = False 
    141141        outfname = options.output.strip().encode(sys.getfilesystemencoding()) 
    142         if outfname == "-" :     
     142        if outfname == "-" : 
    143143            self.outfile = sys.stdout 
    144         else :     
     144        else : 
    145145            self.outfile = open(outfname, "w") 
    146146            mustclose = True 
    147              
    148         if datatype == u"all" :     
     147 
     148        if datatype == u"all" : 
    149149            # NB : order does matter to allow easier or faster restore 
    150150            allentries = [] 
     
    152152                          "billingcodes", "umembers", "upquotas", \ 
    153153                          "gpquotas", "payments", "history" ] 
    154             neededdatatypes = datatypes[:]               
     154            neededdatatypes = datatypes[:] 
    155155            for datatype in datatypes : 
    156156                entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly) # We don't care about ordering here 
     
    158158                    nbentries += len(entries) 
    159159                    allentries.append(entries) 
    160                 else :     
     160                else : 
    161161                    neededdatatypes.remove(datatype) 
    162162            retcode = self.dumpXml(allentries, neededdatatypes) 
    163         else :     
     163        else : 
    164164            datatype = datatype.encode("ASCII") 
    165165            format = format.encode("ASCII") 
     
    168168                nbentries = len(entries) 
    169169                retcode = getattr(self, "dump%s" % format.title())([self.summarizeDatas(entries, datatype, extractonly, options.sum)], [datatype]) 
    170                  
     170 
    171171        if mustclose : 
    172172            self.outfile.close() 
    173             if not nbentries :  
     173            if not nbentries : 
    174174                os.remove(options.output) 
    175              
     175 
    176176        return retcode 
    177          
    178     def summarizeDatas(self, entries, datatype, extractonly, sum=0) :     
     177 
     178    def summarizeDatas(self, entries, datatype, extractonly, sum=0) : 
    179179        """Transforms the datas into a summarized view (with totals). 
    180          
     180 
    181181           If sum is false, returns the entries unchanged. 
    182         """    
     182        """ 
    183183        if not sum : 
    184184            return entries 
    185         else :     
     185        else : 
    186186            headers = entries[0] 
    187187            nbheaders = len(headers) 
     
    190190            for i in range(nbheaders) : 
    191191                fieldnumber[headers[i]] = i 
    192              
     192 
    193193            if datatype == "payments" : 
    194194                totalize = [ ("amount", float) ] 
    195195                keys = [ "username" ] 
    196196            else : # elif datatype == "history" 
    197                 totalize = [ ("jobsize", int),  
     197                totalize = [ ("jobsize", int), 
    198198                             ("jobprice", float), 
    199199                             ("jobsizebytes", int), 
     
    202202                           ] 
    203203                keys = [ k for k in ("username", "printername", "hostname", "billingcode") if k in extractonly.keys() ] 
    204                  
     204 
    205205            newentries = [ headers ] 
    206206            sortedentries = entries[1:] 
     
    222222                    for k in keys : 
    223223                        summary[fieldnumber[k]] = prevkeys[k] 
    224                     for k in totals.keys() :     
     224                    for k in totals.keys() : 
    225225                        summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"]) 
    226226                    newentries.append(summary) 
    227                     for k in totals.keys() :     
     227                    for k in totals.keys() : 
    228228                        totals[k]["value"] = totals[k]["convert"](entry[fieldnumber[k]]) 
    229                 else :     
    230                     for k in totals.keys() :     
     229                else : 
     230                    for k in totals.keys() : 
    231231                        totals[k]["value"] += totals[k]["convert"](entry[fieldnumber[k]] or 0.0) 
    232232                for k in keys : 
     
    235235            for k in keys : 
    236236                summary[fieldnumber[k]] = prevkeys[k] 
    237             for k in totals.keys() :     
     237            for k in totals.keys() : 
    238238                summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"]) 
    239239            newentries.append(summary) 
    240240            return newentries 
    241              
    242     def dumpWithSeparator(self, separator, allentries) :     
     241 
     242    def dumpWithSeparator(self, separator, allentries) : 
    243243        """Dumps datas with a separator.""" 
    244244        for entries in allentries : 
     
    252252                        if value is None : 
    253253                            strvalue = '"None"' # Double quotes around None to prevent spreadsheet from failing 
    254                         else :     
     254                        else : 
    255255                            strvalue = str(value) 
    256256                    line.append(strvalue) 
    257257                try : 
    258258                    self.outfile.write("%s\n" % separator.join(line)) 
    259                 except IOError, msg :     
     259                except IOError, msg : 
    260260                    self.printInfo("%s : %s" % (_("PyKota data dumper failed : I/O error"), msg), "error") 
    261261                    return -1 
    262         return 0         
    263          
    264     def dumpCsv(self, allentries, dummy) :     
     262        return 0 
     263 
     264    def dumpCsv(self, allentries, dummy) : 
    265265        """Dumps datas with a comma as the separator.""" 
    266266        return self.dumpWithSeparator(",", allentries) 
    267                             
    268     def dumpSsv(self, allentries, dummy) :     
     267 
     268    def dumpSsv(self, allentries, dummy) : 
    269269        """Dumps datas with a comma as the separator.""" 
    270270        return self.dumpWithSeparator(";", allentries) 
    271                             
    272     def dumpTsv(self, allentries, dummy) :     
     271 
     272    def dumpTsv(self, allentries, dummy) : 
    273273        """Dumps datas with a comma as the separator.""" 
    274274        return self.dumpWithSeparator("\t", allentries) 
    275          
    276     def dumpCups(self, allentries, dummy) :     
     275 
     276    def dumpCups(self, allentries, dummy) : 
    277277        """Dumps history datas as CUPS' page_log format.""" 
    278278        months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] 
     
    282282        for i in range(len(fieldnames)) : 
    283283            fields[fieldnames[i]] = i 
    284         sortindex = fields["jobdate"]     
     284        sortindex = fields["jobdate"] 
    285285        entries = entries[1:] 
    286286        entries.sort(lambda m, n, si=sortindex : cmp(m[si], n[si])) 
    287         for entry in entries :     
     287        for entry in entries : 
    288288            printername = entry[fields["printername"]] 
    289289            username = entry[fields["username"]] 
     
    305305            for pagenum in range(1, jobsize+1) : 
    306306                line = "%s %s %s [%s] %s %s %s %s" % (printername, username, jobid, jobdate, pagenum, copies, billingcode, hostname) 
    307                 self.outfile.write("%s\n" % line.encode(self.charset,  
     307                self.outfile.write("%s\n" % line.encode(self.charset, 
    308308                                                        "replace")) 
    309         return 0         
    310          
     309        return 0 
     310 
    311311    def dumpXml(self, allentries, datatypes) : 
    312312        """Dumps datas as XML.""" 
     
    326326                                                   { "'" : "&apos;", \ 
    327327                                                     '"' : "&quot;" }) 
    328                     except AttributeError :     
     328                    except AttributeError : 
    329329                        strvalue = str(value) 
    330330                    # We use 'str' instead of 'unicode' below to be compatible 
    331331                    # with older releases of PyKota. 
    332                     # The XML dump will contain UTF-8 encoded strings,  
     332                    # The XML dump will contain UTF-8 encoded strings, 
    333333                    #�not unicode strings anyway. 
    334334                    x.attribute(strvalue, \ 
    335335                                type=type(value).__name__.replace("unicode", "str"), \ 
    336336                                name=header) 
    337                 x._pop()     
    338             x._pop()     
     337                x._pop() 
     338            x._pop() 
    339339        x._output(self.outfile) 
    340         return 0         
     340        return 0