ad7a4c31cfecaacf927a1b35794ea625a2c6129a
[nepi.git] / src / nepi / util / serializer.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 INRIA
4 #
5 #    This program is free software: you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License version 2 as
7 #    published by the Free Software Foundation;
8 #
9 #    This program is distributed in the hope that it will be useful,
10 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #    GNU General Public License for more details.
13 #
14 #    You should have received a copy of the GNU General Public License
15 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
18
19 import datetime
20 import os
21
22 class SFormats:
23     XML = "xml"
24     
25 class ECSerializer(object):
26     def load(self, filepath, format = SFormats.XML):
27         if format == SFormats.XML:
28             from nepi.util.parsers.xml_parser import ECXMLParser
29             
30             parser = ECXMLParser()
31             f = open(filepath, "r")
32             xml = f.read()
33             f.close()
34
35             ec = parser.from_xml(xml)
36
37         return ec
38
39     def serialize(self, ec, format = SFormats.XML):
40         if format == SFormats.XML:
41             from nepi.util.parsers.xml_parser import ECXMLParser
42             
43             parser = ECXMLParser()
44             sec = parser.to_xml(ec)
45
46         return sec
47
48     def save(self, ec, dirpath, format = SFormats.XML):
49         date = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
50         filename = "%s_%s" % (ec.exp_id, date)
51
52         if format == SFormats.XML:
53             filepath = os.path.join(dirpath, "%s.xml" % filename)
54             sec = self.serialize(ec, format = format)
55             f = open(filepath, "w")
56             f.write(sec)
57             f.close()
58
59         return filepath
60