SUMO - Simulation of Urban MObility
OutputDevice.cpp
Go to the documentation of this file.
1 /****************************************************************************/
9 // Static storage of an output device and its base (abstract) implementation
10 /****************************************************************************/
11 // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
12 // Copyright (C) 2004-2017 DLR (http://www.dlr.de/) and contributors
13 /****************************************************************************/
14 //
15 // This file is part of SUMO.
16 // SUMO is free software: you can redistribute it and/or modify
17 // it under the terms of the GNU General Public License as published by
18 // the Free Software Foundation, either version 3 of the License, or
19 // (at your option) any later version.
20 //
21 /****************************************************************************/
22 
23 
24 // ===========================================================================
25 // included modules
26 // ===========================================================================
27 #ifdef _MSC_VER
28 #include <windows_config.h>
29 #else
30 #include <config.h>
31 #endif
32 
33 #include <map>
34 #include <fstream>
35 #include <sstream>
36 #include <string>
37 #include <iomanip>
38 #include "OutputDevice.h"
39 #include "OutputDevice_File.h"
40 #include "OutputDevice_COUT.h"
41 #include "OutputDevice_CERR.h"
42 #include "OutputDevice_Network.h"
43 #include "PlainXMLFormatter.h"
47 #include <utils/common/ToString.h>
50 
51 
52 // ===========================================================================
53 // static member definitions
54 // ===========================================================================
55 std::map<std::string, OutputDevice*> OutputDevice::myOutputDevices;
56 
57 
58 // ===========================================================================
59 // static method definitions
60 // ===========================================================================
62 OutputDevice::getDevice(const std::string& name) {
63  // check whether the device has already been aqcuired
64  if (myOutputDevices.find(name) != myOutputDevices.end()) {
65  return *myOutputDevices[name];
66  }
67  // build the device
68  OutputDevice* dev = 0;
69  // check whether the device shall print to stdout
70  if (name == "stdout") {
72  } else if (name == "stderr") {
74  } else if (FileHelpers::isSocket(name)) {
75  try {
76  int port = TplConvert::_2int(name.substr(name.find(":") + 1).c_str());
77  dev = new OutputDevice_Network(name.substr(0, name.find(":")), port);
78  } catch (NumberFormatException&) {
79  throw IOError("Given port number '" + name.substr(name.find(":") + 1) + "' is not numeric.");
80  } catch (EmptyData&) {
81  throw IOError("No port number given.");
82  }
83  } else {
84  const int len = (int)name.length();
85  std::string name2 = name;
86  if (OptionsCont::getOptions().isSet("output-prefix") && name != "/dev/null") {
87  std::string prefix = OptionsCont::getOptions().getString("output-prefix");
88  const std::string::size_type metaTimeIndex = prefix.find("TIME");
89  if (metaTimeIndex != std::string::npos) {
90  time_t rawtime;
91  char buffer [80];
92  time(&rawtime);
93  struct tm* timeinfo = localtime(&rawtime);
94  strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
95  prefix.replace(metaTimeIndex, 4, std::string(buffer));
96  }
97  name2 = FileHelpers::prependToLastPathComponent(prefix, name);
98  }
99  dev = new OutputDevice_File(name2, len > 4 && name.substr(len - 4) == ".sbx");
100  }
101  dev->setPrecision();
102  dev->getOStream() << std::setiosflags(std::ios::fixed);
103  myOutputDevices[name] = dev;
104  return *dev;
105 }
106 
107 
108 bool
109 OutputDevice::createDeviceByOption(const std::string& optionName,
110  const std::string& rootElement,
111  const std::string& schemaFile) {
112  if (!OptionsCont::getOptions().isSet(optionName)) {
113  return false;
114  }
115  OutputDevice& dev = OutputDevice::getDevice(OptionsCont::getOptions().getString(optionName));
116  if (rootElement != "") {
117  dev.writeXMLHeader(rootElement, schemaFile);
118  }
119  return true;
120 }
121 
122 
124 OutputDevice::getDeviceByOption(const std::string& optionName) {
125  std::string devName = OptionsCont::getOptions().getString(optionName);
126  if (myOutputDevices.find(devName) == myOutputDevices.end()) {
127  throw InvalidArgument("Device '" + devName + "' has not been created.");
128  }
129  return OutputDevice::getDevice(devName);
130 }
131 
132 
133 void
135  std::vector<OutputDevice*> errorDevices;
136  std::vector<OutputDevice*> nonErrorDevices;
137  for (std::map<std::string, OutputDevice*>::iterator i = myOutputDevices.begin(); i != myOutputDevices.end(); ++i) {
138  if (MsgHandler::getErrorInstance()->isRetriever(i->second)) {
139  errorDevices.push_back(i->second);
140  } else {
141  nonErrorDevices.push_back(i->second);
142  }
143  }
144  for (std::vector<OutputDevice*>::iterator i = nonErrorDevices.begin(); i != nonErrorDevices.end(); ++i) {
145  try {
146  (*i)->close();
147  } catch (const IOError& e) {
148  WRITE_ERROR("Error on closing output devices.");
149  WRITE_ERROR(e.what());
150  }
151  }
152  for (std::vector<OutputDevice*>::iterator i = errorDevices.begin(); i != errorDevices.end(); ++i) {
153  try {
154  (*i)->close();
155  } catch (const IOError& e) {
156  std::cerr << "Error on closing error output devices." << std::endl;
157  std::cerr << e.what() << std::endl;
158  }
159  }
160 }
161 
162 
163 std::string
164 OutputDevice::realString(const double v, const int precision) {
165  std::ostringstream oss;
166  if (v == 0) {
167  return "0";
168  }
169  if (v < pow(10., -precision)) {
170  oss.setf(std::ios::scientific, std::ios::floatfield);
171  } else {
172  oss.setf(std::ios::fixed , std::ios::floatfield); // use decimal format
173  oss.setf(std::ios::showpoint); // print decimal point
174  oss << std::setprecision(precision);
175  }
176  oss << v;
177  return oss.str();
178 }
179 
180 
181 // ===========================================================================
182 // member method definitions
183 // ===========================================================================
184 OutputDevice::OutputDevice(const bool binary, const int defaultIndentation)
185  : myAmBinary(binary) {
186  if (binary) {
188  } else {
189  myFormatter = new PlainXMLFormatter(defaultIndentation);
190  }
191 }
192 
193 
195  delete myFormatter;
196 }
197 
198 
199 bool
201  return getOStream().good();
202 }
203 
204 
205 void
207  while (closeTag()) {}
208  for (std::map<std::string, OutputDevice*>::iterator i = myOutputDevices.begin(); i != myOutputDevices.end(); ++i) {
209  if (i->second == this) {
210  myOutputDevices.erase(i);
211  break;
212  }
213  }
214  delete this;
215 }
216 
217 
218 void
220  getOStream() << std::setprecision(precision);
221 }
222 
223 
224 bool
225 OutputDevice::writeXMLHeader(const std::string& rootElement,
226  const std::string& schemaFile,
227  std::map<SumoXMLAttr, std::string> attrs) {
228  if (schemaFile != "") {
229  attrs[SUMO_ATTR_XMLNS] = "http://www.w3.org/2001/XMLSchema-instance";
230  attrs[SUMO_ATTR_SCHEMA_LOCATION] = "http://sumo.dlr.de/xsd/" + schemaFile;
231  }
232  return myFormatter->writeXMLHeader(getOStream(), rootElement, attrs);
233 }
234 
235 
237 OutputDevice::openTag(const std::string& xmlElement) {
238  myFormatter->openTag(getOStream(), xmlElement);
239  return *this;
240 }
241 
242 
244 OutputDevice::openTag(const SumoXMLTag& xmlElement) {
245  myFormatter->openTag(getOStream(), xmlElement);
246  return *this;
247 }
248 
249 
250 bool
252  if (myFormatter->closeTag(getOStream())) {
253  postWriteHook();
254  return true;
255  }
256  return false;
257 }
258 
259 
260 void
262 
263 
264 void
265 OutputDevice::inform(const std::string& msg, const char progress) {
266  if (progress != 0) {
267  getOStream() << msg << progress;
268  } else {
269  getOStream() << msg << '\n';
270  }
271  postWriteHook();
272 }
273 
274 
275 /****************************************************************************/
276 
void close()
Closes the device and removes it from the dictionary.
SumoXMLTag
Numbers representing SUMO-XML - element names.
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
Definition: MsgHandler.cpp:76
bool isRetriever(OutputDevice *retriever) const
Returns whether the given output device retrieves messages from the handler.
Definition: MsgHandler.cpp:187
virtual bool closeTag(std::ostream &into)=0
Closes the most recently opened tag.
static std::map< std::string, OutputDevice * > myOutputDevices
map from names to output devices
Definition: OutputDevice.h:341
static std::string prependToLastPathComponent(const std::string &prefix, const std::string &path)
prepend the given prefix to the last path component of the given file path
virtual bool writeXMLHeader(std::ostream &into, const std::string &rootElement, const std::map< SumoXMLAttr, std::string > &attrs)=0
Writes an XML header with optional configuration.
static bool isSocket(const std::string &name)
Returns the information whether the given name represents a socket.
Definition: FileHelpers.cpp:90
void setPrecision(int precision=gPrecision)
Sets the precison or resets it to default.
static std::string realString(const double v, const int precision=gPrecision)
Helper method for string formatting.
An output device for TCP/IP network connections.
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:65
void inform(const std::string &msg, const char progress=0)
Retrieves a message to this device.
Output formatter for plain XML output.
static void closeAll()
bool writeXMLHeader(const std::string &rootElement, const std::string &schemaFile, std::map< SumoXMLAttr, std::string > attrs=std::map< SumoXMLAttr, std::string >())
Writes an XML header with optional configuration.
static OutputDevice * getDevice()
Returns the single cout instance.
An output device that encapsulates an ofstream.
virtual void openTag(std::ostream &into, const std::string &xmlElement)=0
Opens an XML tag.
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
OutputDevice(const bool binary=false, const int defaultIndentation=0)
Constructor.
virtual bool ok()
returns the information whether one can write into the device
Output formatter for plain XML output.
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:206
static int _2int(const E *const data)
converts a char-type array into the integer value described by it
Definition: TplConvert.h:149
virtual ~OutputDevice()
Destructor.
static OutputDevice & getDevice(const std::string &name)
Returns the described OutputDevice.
static OutputDevice & getDeviceByOption(const std::string &name)
Returns the device described by the option.
const bool myAmBinary
Definition: OutputDevice.h:348
OutputFormatter * myFormatter
The formatter for XML.
Definition: OutputDevice.h:346
static bool createDeviceByOption(const std::string &optionName, const std::string &rootElement="", const std::string &schemaFile="")
Creates the device using the output definition stored in the named option.
Static storage of an output device and its base (abstract) implementation.
Definition: OutputDevice.h:71
bool closeTag()
Closes the most recently opened tag.
static OutputDevice * getDevice()
Returns the single cerr instance.
virtual std::ostream & getOStream()=0
Returns the associated ostream.
virtual void postWriteHook()
Called after every write access.
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.