systematic use of context managers for dealing with files instead of open()/close...
[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             with open(filepath, "r") as f:
32                 xml = f.read()
33
34             ec = parser.from_xml(xml)
35
36         return ec
37
38     def serialize(self, ec, format = SFormats.XML):
39         if format == SFormats.XML:
40             from nepi.util.parsers.xml_parser import ECXMLParser
41             
42             parser = ECXMLParser()
43             sec = parser.to_xml(ec)
44
45         return sec
46
47     def save(self, ec, dirpath, format = SFormats.XML):
48         date = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
49         filename = "%s_%s" % (ec.exp_id, date)
50
51         if format == SFormats.XML:
52             filepath = os.path.join(dirpath, "%s.xml" % filename)
53             sec = self.serialize(ec, format = format)
54             with open(filepath, "w") as f:
55                 f.write(sec)
56
57         return filepath
58