root / pykota / trunk / pykota / dumper.py @ 2264

Revision 2264, 8.0 kB (checked in by jerome, 19 years ago)

Improved data dumper : speed and correctness

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota Print Quota Data Dumper
2#
3# PyKota - Print Quotas for CUPS and LPRng
4#
5# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22#
23
24import sys
25import os
26import pwd
27from xml.sax import saxutils
28
29from mx import DateTime
30
31try :
32    import jaxml
33except ImportError :   
34    sys.stderr.write("The jaxml Python module is not installed. XML output is disabled.\n")
35    sys.stderr.write("Download jaxml from http://www.librelogiciel.com/software/ or from your Debian archive of choice\n")
36    hasJAXML = 0
37else :   
38    hasJAXML = 1
39
40from pykota import version
41from pykota.tool import PyKotaTool, PyKotaToolError, N_
42
43class DumPyKota(PyKotaTool) :       
44    """A class for dumpykota."""
45    validdatatypes = { "history" : N_("History"),
46                       "users" : N_("Users"),
47                       "groups" : N_("Groups"),
48                       "printers" : N_("Printers"),
49                       "upquotas" : N_("Users Print Quotas"),
50                       "gpquotas" : N_("Users Groups Print Quotas"),
51                       "payments" : N_("History of Payments"),
52                       "pmembers" : N_("Printers Groups Membership"), 
53                       "umembers" : N_("Users Groups Membership"),
54                     }
55    validformats = { "csv" : N_("Comma Separated Values"),
56                     "ssv" : N_("Semicolon Separated Values"),
57                     "tsv" : N_("Tabulation Separated Values"),
58                     "xml" : N_("eXtensible Markup Language"),
59                     "cups" : N_("CUPS' page_log"),
60                   } 
61    validfilterkeys = [ "username",
62                        "groupname",
63                        "printername",
64                        "pgroupname",
65                        "hostname",
66                        "billingcode",
67                      ]
68    def main(self, arguments, options, restricted=1) :
69        """Print Quota Data Dumper."""
70        if restricted and not self.config.isAdmin :
71            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
72           
73        extractonly = {}
74        for filterexp in arguments :
75            if filterexp.strip() :
76                try :
77                    (filterkey, filtervalue) = [part.strip() for part in filterexp.split("=")]
78                    if filterkey not in self.validfilterkeys :
79                        raise ValueError               
80                except ValueError :   
81                    raise PyKotaToolError, _("Invalid filter value [%s], see help.") % filterexp
82                else :   
83                    extractonly.update({ filterkey : filtervalue })
84           
85        datatype = options["data"]
86        if datatype not in self.validdatatypes.keys() :
87            raise PyKotaToolError, _("Invalid modifier [%s] for --data command line option, see help.") % datatype
88                   
89        format = options["format"]
90        if (format not in self.validformats.keys()) \
91              or ((format == "cups") and (datatype != "history")) :
92            raise PyKotaToolError, _("Invalid modifier [%s] for --format command line option, see help.") % format
93           
94        if (format == "xml") and not hasJAXML :
95            raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.")
96           
97        entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly)
98        if entries :
99            mustclose = 0   
100            if options["output"].strip() == "-" :   
101                self.outfile = sys.stdout
102            else :   
103                self.outfile = open(options["output"], "w")
104                mustclose = 1
105               
106            retcode = getattr(self, "dump%s" % format.title())(entries, datatype)
107           
108            if mustclose :
109                self.outfile.close()
110               
111            return retcode   
112        return 0
113       
114    def dumpWithSeparator(self, separator, entries) :   
115        """Dumps datas with a separator."""
116        for entry in entries :
117            line = []
118            for value in entry :
119                if type(value).__name__ in ("str", "NoneType") :
120                    line.append('"%s"' % str(value).replace(separator, "\\%s" % separator).replace('"', '\\"'))
121                else :   
122                    line.append(str(value))
123            try :
124                self.outfile.write("%s\n" % separator.join(line))
125            except IOError, msg :   
126                sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg))
127                return -1
128        return 0       
129       
130    def dumpCsv(self, entries, dummy) :   
131        """Dumps datas with a comma as the separator."""
132        return self.dumpWithSeparator(",", entries)
133                           
134    def dumpSsv(self, entries, dummy) :   
135        """Dumps datas with a comma as the separator."""
136        return self.dumpWithSeparator(";", entries)
137                           
138    def dumpTsv(self, entries, dummy) :   
139        """Dumps datas with a comma as the separator."""
140        return self.dumpWithSeparator("\t", entries)
141       
142    def dumpCups(self, entries, dummy) :   
143        """Dumps history datas as CUPS' page_log format."""
144        fieldnames = entries[0]
145        fields = {}
146        for i in range(len(fieldnames)) :
147            fields[fieldnames[i]] = i
148        sortindex = fields["jobdate"]   
149        entries = entries[1:]
150        entries.sort(lambda m,n,si=sortindex : cmp(m[si], n[si]))
151        for entry in entries :   
152            printername = entry[fields["printername"]]
153            username = entry[fields["username"]]
154            jobid = entry[fields["jobid"]]
155            jobdate = DateTime.ISO.ParseDateTime(entry[fields["jobdate"]])
156            gmtoffset = jobdate.gmtoffset()
157            jobdate = "%s %+03i00" % (jobdate.strftime("%d/%b/%Y:%H:%M:%S"), gmtoffset.hour)
158            jobsize = entry[fields["jobsize"]] or 0
159            copies = entry[fields["copies"]] or 1
160            hostname = entry[fields["hostname"]] or ""
161            billingcode = entry[fields["billingcode"]] or "-"
162            for pagenum in range(1, jobsize+1) :
163                self.outfile.write("%s %s %s [%s] %s %s %s %s\n" % (printername, username, jobid, jobdate, pagenum, copies, billingcode, hostname))
164       
165    def dumpXml(self, entries, datatype) :   
166        """Dumps datas as XML."""
167        x = jaxml.XML_document(encoding="UTF-8")
168        x.pykota(version=version.__version__, author=version.__author__)
169        x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype)
170        headers = entries[0]
171        for entry in entries[1:] :
172            x._push()
173            x.entry()
174            for (header, value) in zip(headers, entry) :
175                strvalue = str(value)
176                typval = type(value).__name__
177                if header in ("filename", "title", "options", "billingcode") \
178                          and (typval == "str") :
179                    try :
180                        strvalue = unicode(strvalue, self.getCharset()).encode("UTF-8")
181                    except UnicodeError :   
182                        pass
183                    strvalue = saxutils.escape(strvalue, { "'" : "&apos;", \
184                                                           '"' : "&quot;" })
185                x.attribute(strvalue, type=typval, name=header)
186            x._pop()   
187        x._output(self.outfile)
Note: See TracBrowser for help on using the browser.