Eclipse SUMO - Simulation of Urban MObility
OutputDevice.cpp
Go to the documentation of this file.
1 /****************************************************************************/
2 // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
3 // Copyright (C) 2004-2022 German Aerospace Center (DLR) and others.
4 // This program and the accompanying materials are made available under the
5 // terms of the Eclipse Public License 2.0 which is available at
6 // https://www.eclipse.org/legal/epl-2.0/
7 // This Source Code may also be made available under the following Secondary
8 // Licenses when the conditions for such availability set forth in the Eclipse
9 // Public License 2.0 are satisfied: GNU General Public License, version 2
10 // or later which is available at
11 // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12 // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13 /****************************************************************************/
20 // Static storage of an output device and its base (abstract) implementation
21 /****************************************************************************/
22 #include <config.h>
23 
24 #include <map>
25 #include <fstream>
26 #include <sstream>
27 #include <string>
28 #include <iomanip>
29 #ifdef WIN32
30 #define NOMINMAX
31 #include <windows.h>
32 #undef NOMINMAX
33 #endif
34 #include "OutputDevice.h"
35 #include "OutputDevice_File.h"
36 #include "OutputDevice_COUT.h"
37 #include "OutputDevice_CERR.h"
38 #include "OutputDevice_Network.h"
39 #include "PlainXMLFormatter.h"
43 #include <utils/common/ToString.h>
46 
47 
48 // ===========================================================================
49 // static member definitions
50 // ===========================================================================
51 std::map<std::string, OutputDevice*> OutputDevice::myOutputDevices;
53 
54 
55 // ===========================================================================
56 // static method definitions
57 // ===========================================================================
59 OutputDevice::getDevice(const std::string& name) {
60 #ifdef WIN32
61  // fix the windows console output on first call
62  if (myPrevConsoleCP == -1) {
63  myPrevConsoleCP = GetConsoleOutputCP();
64  SetConsoleOutputCP(CP_UTF8);
65  }
66 #endif
67  // check whether the device has already been aqcuired
68  if (myOutputDevices.find(name) != myOutputDevices.end()) {
69  return *myOutputDevices[name];
70  }
71  // build the device
72  OutputDevice* dev = nullptr;
73  // check whether the device shall print to stdout
74  if (name == "stdout") {
76  } else if (name == "stderr") {
78  } else if (FileHelpers::isSocket(name)) {
79  try {
80  int port = StringUtils::toInt(name.substr(name.find(":") + 1));
81  dev = new OutputDevice_Network(name.substr(0, name.find(":")), port);
82  } catch (NumberFormatException&) {
83  throw IOError("Given port number '" + name.substr(name.find(":") + 1) + "' is not numeric.");
84  } catch (EmptyData&) {
85  throw IOError("No port number given.");
86  }
87  } else {
88  std::string name2 = (name == "nul" || name == "NUL") ? "/dev/null" : name;
89  if (OptionsCont::getOptions().isSet("output-prefix") && name2 != "/dev/null") {
90  std::string prefix = OptionsCont::getOptions().getString("output-prefix");
91  const std::string::size_type metaTimeIndex = prefix.find("TIME");
92  if (metaTimeIndex != std::string::npos) {
93  time_t rawtime;
94  char buffer [80];
95  time(&rawtime);
96  struct tm* timeinfo = localtime(&rawtime);
97  strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
98  prefix.replace(metaTimeIndex, 4, std::string(buffer));
99  }
100  name2 = FileHelpers::prependToLastPathComponent(prefix, name);
101  }
102  const int len = (int)name.length();
103  dev = new OutputDevice_File(name2, len > 3 && name.substr(len - 3) == ".gz");
104  }
105  dev->setPrecision();
106  dev->getOStream() << std::setiosflags(std::ios::fixed);
107  myOutputDevices[name] = dev;
108  return *dev;
109 }
110 
111 
112 bool
113 OutputDevice::createDeviceByOption(const std::string& optionName,
114  const std::string& rootElement,
115  const std::string& schemaFile) {
116  if (!OptionsCont::getOptions().isSet(optionName)) {
117  return false;
118  }
119  OutputDevice& dev = OutputDevice::getDevice(OptionsCont::getOptions().getString(optionName));
120  if (rootElement != "") {
121  dev.writeXMLHeader(rootElement, schemaFile);
122  }
123  return true;
124 }
125 
126 
128 OutputDevice::getDeviceByOption(const std::string& optionName) {
129  std::string devName = OptionsCont::getOptions().getString(optionName);
130  if (myOutputDevices.find(devName) == myOutputDevices.end()) {
131  throw InvalidArgument("Device '" + devName + "' has not been created.");
132  }
133  return OutputDevice::getDevice(devName);
134 }
135 
136 
137 void
138 OutputDevice::closeAll(bool keepErrorRetrievers) {
139  std::vector<OutputDevice*> errorDevices;
140  std::vector<OutputDevice*> nonErrorDevices;
141  for (std::map<std::string, OutputDevice*>::iterator i = myOutputDevices.begin(); i != myOutputDevices.end(); ++i) {
142  if (MsgHandler::getErrorInstance()->isRetriever(i->second)) {
143  errorDevices.push_back(i->second);
144  } else {
145  nonErrorDevices.push_back(i->second);
146  }
147  }
148  for (OutputDevice* const dev : nonErrorDevices) {
149  try {
150  dev->close();
151  } catch (const IOError& e) {
152  WRITE_ERROR("Error on closing output devices.");
153  WRITE_ERROR(e.what());
154  }
155  }
156  if (!keepErrorRetrievers) {
157  for (OutputDevice* const dev : errorDevices) {
158  try {
159  dev->close();
160  } catch (const IOError& e) {
161  std::cerr << "Error on closing error output devices." << std::endl;
162  std::cerr << e.what() << std::endl;
163  }
164  }
165 #ifdef WIN32
166  if (myPrevConsoleCP != -1) {
167  SetConsoleOutputCP(myPrevConsoleCP);
168  }
169 #endif
170  }
171 }
172 
173 
174 std::string
175 OutputDevice::realString(const double v, const int precision) {
176  std::ostringstream oss;
177  if (v == 0) {
178  return "0";
179  }
180  if (v < pow(10., -precision)) {
181  oss.setf(std::ios::scientific, std::ios::floatfield);
182  } else {
183  oss.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
184  oss.setf(std::ios::showpoint); // print decimal point
185  oss << std::setprecision(precision);
186  }
187  oss << v;
188  return oss.str();
189 }
190 
191 
192 // ===========================================================================
193 // member method definitions
194 // ===========================================================================
195 OutputDevice::OutputDevice(const int defaultIndentation, const std::string& filename) :
196  myFilename(filename), myFormatter(new PlainXMLFormatter(defaultIndentation)) {
197 }
198 
199 
201  delete myFormatter;
202 }
203 
204 
205 bool
207  return getOStream().good();
208 }
209 
210 
211 const std::string&
213  return myFilename;
214 }
215 
216 void
218  while (closeTag()) {}
219  for (std::map<std::string, OutputDevice*>::iterator i = myOutputDevices.begin(); i != myOutputDevices.end(); ++i) {
220  if (i->second == this) {
221  myOutputDevices.erase(i);
222  break;
223  }
224  }
226  delete this;
227 }
228 
229 
230 void
232  getOStream() << std::setprecision(precision);
233 }
234 
235 
236 bool
237 OutputDevice::writeXMLHeader(const std::string& rootElement,
238  const std::string& schemaFile,
239  std::map<SumoXMLAttr, std::string> attrs,
240  bool includeConfig) {
241  if (schemaFile != "") {
242  attrs[SUMO_ATTR_XMLNS] = "http://www.w3.org/2001/XMLSchema-instance";
243  attrs[SUMO_ATTR_SCHEMA_LOCATION] = "http://sumo.dlr.de/xsd/" + schemaFile;
244  }
245  return myFormatter->writeXMLHeader(getOStream(), rootElement, attrs, includeConfig);
246 }
247 
248 
250 OutputDevice::openTag(const std::string& xmlElement) {
251  myFormatter->openTag(getOStream(), xmlElement);
252  return *this;
253 }
254 
255 
257 OutputDevice::openTag(const SumoXMLTag& xmlElement) {
258  myFormatter->openTag(getOStream(), xmlElement);
259  return *this;
260 }
261 
262 
263 bool
264 OutputDevice::closeTag(const std::string& comment) {
265  if (myFormatter->closeTag(getOStream(), comment)) {
266  postWriteHook();
267  return true;
268  }
269  return false;
270 }
271 
272 
273 void
275 
276 
277 void
278 OutputDevice::inform(const std::string& msg, const char progress) {
279  if (progress != 0) {
280  getOStream() << msg << progress;
281  } else {
282  getOStream() << msg << '\n';
283  }
284  postWriteHook();
285 }
286 
287 
288 /****************************************************************************/
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:288
SumoXMLTag
Numbers representing SUMO-XML - element names.
@ SUMO_ATTR_XMLNS
@ SUMO_ATTR_SCHEMA_LOCATION
static bool isSocket(const std::string &name)
Returns the information whether the given name represents a socket.
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
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
Definition: MsgHandler.cpp:80
static void removeRetrieverFromAllInstances(OutputDevice *out)
ensure that that given output device is no longer used as retriever by any instance
Definition: MsgHandler.cpp:209
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:58
static OutputDevice * getDevice()
Returns the single cerr instance.
static OutputDevice * getDevice()
Returns the single cout instance.
An output device that encapsulates an ofstream.
An output device for TCP/IP network connections.
Static storage of an output device and its base (abstract) implementation.
Definition: OutputDevice.h:61
virtual ~OutputDevice()
Destructor.
OutputDevice(const int defaultIndentation=0, const std::string &filename="")
Constructor.
static std::string realString(const double v, const int precision=gPrecision)
Helper method for string formatting.
void close()
Closes the device and removes it from the dictionary.
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.
virtual void postWriteHook()
Called after every write access.
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.
const std::string & getFilename()
get filename or suitable description of this device
virtual std::ostream & getOStream()=0
Returns the associated ostream.
static OutputDevice & getDeviceByOption(const std::string &name)
Returns the device described by the option.
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
void setPrecision(int precision=gPrecision)
Sets the precision or resets it to default.
const std::string myFilename
Definition: OutputDevice.h:359
static void closeAll(bool keepErrorRetrievers=false)
void inform(const std::string &msg, const char progress=0)
Retrieves a message to this device.
OutputFormatter *const myFormatter
The formatter for XML.
Definition: OutputDevice.h:363
static int myPrevConsoleCP
old console code page to restore after ending
Definition: OutputDevice.h:356
bool writeXMLHeader(const std::string &rootElement, const std::string &schemaFile, std::map< SumoXMLAttr, std::string > attrs=std::map< SumoXMLAttr, std::string >(), bool includeConfig=true)
Writes an XML header with optional configuration.
static std::map< std::string, OutputDevice * > myOutputDevices
map from names to output devices
Definition: OutputDevice.h:353
static OutputDevice & getDevice(const std::string &name)
Returns the described OutputDevice.
virtual bool ok()
returns the information whether one can write into the device
virtual bool writeXMLHeader(std::ostream &into, const std::string &rootElement, const std::map< SumoXMLAttr, std::string > &attrs, bool includeConfig=true)=0
Writes an XML header with optional configuration.
virtual bool closeTag(std::ostream &into, const std::string &comment="")=0
Closes the most recently opened tag and optinally add a comment.
virtual void openTag(std::ostream &into, const std::string &xmlElement)=0
Opens an XML tag.
Output formatter for plain XML output.
static int toInt(const std::string &sData)
converts a string into the integer value described by it by calling the char-type converter,...