Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
OutputDevice.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2004-2026 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#include <windows.h>
31#endif
32#include "OutputDevice.h"
33#include "OutputDevice_File.h"
34#include "OutputDevice_COUT.h"
35#include "OutputDevice_CERR.h"
37#include "PlainXMLFormatter.h"
44
45
46// ===========================================================================
47// static member definitions
48// ===========================================================================
50std::map<std::string, OutputDevice*> OutputDevice::myOutputDevices;
52
53
54// ===========================================================================
55// static method definitions
56// ===========================================================================
58OutputDevice::getDevice(const std::string& name, bool usePrefix) {
59#ifdef WIN32
60 // fix the windows console output on first call
61 if (myPrevConsoleCP == -1) {
62 myPrevConsoleCP = GetConsoleOutputCP();
63 SetConsoleOutputCP(CP_UTF8);
64 }
65#endif
66 // check whether the device has already been aqcuired
67 if (myOutputDevices.find(name) != myOutputDevices.end()) {
68 return *myOutputDevices[name];
69 }
70 // build the device
71 const int len = (int)name.length();
72 bool isCSV = mySettings.format == "csv" || (len > 4 && name.substr(len - 4) == ".csv") || (len > 7 && name.substr(len - 7) == ".csv.gz");
73 bool isParquet = mySettings.format == "parquet" || (len > 8 && name.substr(len - 8) == ".parquet");
74#ifndef HAVE_PARQUET
75 if (isParquet) {
76 WRITE_WARNING("Compiled without Parquet support, falling back to XML.")
77 isParquet = false;
78 }
79#endif
80 OutputDevice* dev = nullptr;
81 // check whether the device shall print to stdout
82 if (name == "stdout") {
84 isCSV = isParquet = false;
85 } else if (name == "stderr") {
87 isCSV = isParquet = false;
88 } else if (FileHelpers::isSocket(name)) {
89 try {
90 const bool ipv6 = name[0] == '['; // IPv6 addresses may be written like '[::1]:8000'
91 const size_t sepIndex = name.find(":", ipv6 ? name.find("]") : 0);
92 const int port = StringUtils::toInt(name.substr(sepIndex + 1));
93 dev = new OutputDevice_Network(ipv6 ? name.substr(1, sepIndex - 2) : name.substr(0, sepIndex), port);
94 } catch (NumberFormatException&) {
95 throw IOError("Given port number '" + name.substr(name.find(":") + 1) + "' is not numeric.");
96 } catch (EmptyData&) {
97 throw IOError(TL("No port number given."));
98 }
99 } else {
100 std::string name2 = (name == "nul" || name == "NUL") ? "/dev/null" : name;
101 if (usePrefix && !mySettings.prefix.empty() && name2 != "/dev/null") {
102 std::string prefix = mySettings.prefix;
103 const std::string::size_type metaTimeIndex = prefix.find("TIME");
104 if (metaTimeIndex != std::string::npos) {
105 const time_t rawtime = std::chrono::system_clock::to_time_t(mySettings.loadTime);
106 char buffer [80];
107 struct tm* timeinfo = localtime(&rawtime);
108 strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
109 prefix.replace(metaTimeIndex, 4, buffer);
110 }
111 name2 = FileHelpers::prependToLastPathComponent(prefix, name);
112 }
113 if (usePrefix && !mySettings.suffix.empty() && name2 != "/dev/null") {
114 std::string suffix = mySettings.suffix;
115 const std::string::size_type metaTimeIndex = suffix.find("TIME");
116 if (metaTimeIndex != std::string::npos) {
117 const time_t rawtime = std::chrono::system_clock::to_time_t(mySettings.loadTime);
118 char buffer [80];
119 struct tm* timeinfo = localtime(&rawtime);
120 strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
121 suffix.replace(metaTimeIndex, 4, buffer);
122 }
123 name2 = FileHelpers::appendBeforeExtension(name2, suffix);
124 }
126 dev = new OutputDevice_File(name2, isParquet);
127 }
128 if (isCSV) {
130 }
131#ifdef HAVE_PARQUET
132 if (isParquet) {
134 }
135#endif
136 dev->setPrecision();
137 dev->getOStream() << std::setiosflags(std::ios::fixed);
138 myOutputDevices[name] = dev;
139 return *dev;
140}
141
142
143void
145 for (auto item : myOutputDevices) {
146 item.second->flush();
147 }
148}
149
150
151void
152OutputDevice::closeAll(bool keepErrorRetrievers) {
153 std::vector<OutputDevice*> errorDevices;
154 std::vector<OutputDevice*> nonErrorDevices;
155 for (std::map<std::string, OutputDevice*>::iterator i = myOutputDevices.begin(); i != myOutputDevices.end(); ++i) {
156 if (MsgHandler::getErrorInstance()->isRetriever(i->second)) {
157 errorDevices.push_back(i->second);
158 } else {
159 nonErrorDevices.push_back(i->second);
160 }
161 }
162 for (OutputDevice* const dev : nonErrorDevices) {
163 try {
164 dev->close();
165 } catch (const IOError& e) {
166 WRITE_ERROR(TL("Error on closing output devices."));
167 WRITE_ERROR(e.what());
168 }
169 }
170 if (!keepErrorRetrievers) {
171 for (OutputDevice* const dev : errorDevices) {
172 try {
173 dev->close();
174 } catch (const IOError& e) {
175 std::cerr << "Error on closing error output devices." << std::endl;
176 std::cerr << e.what() << std::endl;
177 }
178 }
179#ifdef WIN32
180 if (myPrevConsoleCP != -1) {
181 SetConsoleOutputCP(myPrevConsoleCP);
182 }
183#endif
184 }
185}
186
187
188// ===========================================================================
189// member method definitions
190// ===========================================================================
191OutputDevice::OutputDevice(const int defaultIndentation, const std::string& filename) :
192 myFilename(filename), myFormatter(new PlainXMLFormatter(defaultIndentation)) {
193}
194
195
199
200
201bool
203 return getOStream().good();
204}
205
206
207const std::string&
211
212void
214 while (closeTag()) {}
215 for (std::map<std::string, OutputDevice*>::iterator i = myOutputDevices.begin(); i != myOutputDevices.end(); ++i) {
216 if (i->second == this) {
217 myOutputDevices.erase(i);
218 break;
219 }
220 }
222 delete this;
223}
224
225
226void
228 getOStream() << std::setprecision(precision);
229}
230
231
232bool
233OutputDevice::writeXMLHeader(const std::string& rootElement,
234 const std::string& schemaFile,
235 std::map<SumoXMLAttr, std::string> attrs,
236 bool includeConfig) {
237 if (schemaFile != "") {
238 attrs[SUMO_ATTR_XMLNS] = "http://www.w3.org/2001/XMLSchema-instance";
239 attrs[SUMO_ATTR_SCHEMA_LOCATION] = "http://sumo.dlr.de/xsd/" + schemaFile;
240 }
241 return myFormatter->writeXMLHeader(getOStream(), rootElement, attrs, includeConfig);
242}
243
244
246OutputDevice::openTag(const std::string& xmlElement) {
247 myFormatter->openTag(getOStream(), xmlElement);
248 return *this;
249}
250
251
254 myFormatter->openTag(getOStream(), xmlElement);
255 return *this;
256}
257
258
259bool
260OutputDevice::closeTag(const std::string& comment) {
261 if (myFormatter->closeTag(getOStream(), comment)) {
263 return true;
264 }
265 return false;
266}
267
268
269void
271
272
273void
274OutputDevice::inform(const std::string& msg, const bool progress) {
275 if (progress) {
276 getOStream() << msg;
277 } else {
278 getOStream() << msg << '\n';
279 }
281}
282
283
284/****************************************************************************/
#define WRITE_ERROR(msg)
Definition MsgHandler.h:307
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
#define TL(string)
Definition MsgHandler.h:316
SumoXMLTag
Numbers representing SUMO-XML - element names.
@ SUMO_ATTR_XMLNS
@ SUMO_ATTR_SCHEMA_LOCATION
Output formatter for CSV output.
static std::string appendBeforeExtension(const std::string &path, const std::string &suffix, bool checkSep=true)
append the given suffix after the file name but before the extension
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.
bool isRetriever(OutputDevice *retriever) const
Returns whether the given output device retrieves messages from the handler.
static void removeRetrieverFromAllInstances(OutputDevice *out)
ensure that that given output device is no longer used as retriever by any instance
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.
virtual std::ostream & getOStream()=0
Returns the associated ostream.
virtual ~OutputDevice()
Destructor.
static Settings mySettings
the output related option values, set by SystemFrame so that this class does not depend on the option...
OutputDevice(const int defaultIndentation=0, const std::string &filename="")
Constructor.
void inform(const std::string &msg, const bool progress=false)
Retrieves a message to this device.
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 void flushAll()
const std::string & getFilename()
get filename or suitable description of this device
OutputFormatter * myFormatter
The formatter for XML, CSV or Parquet.
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
static void closeAll(bool keepErrorRetrievers=false)
void setFormatter(OutputFormatter *formatter)
static OutputDevice & getDevice(const std::string &name, bool usePrefix=true)
Returns the described OutputDevice.
static int myPrevConsoleCP
old console code page to restore after ending
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
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)
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 Parquet output.
Output formatter for plain XML output.
static std::string substituteEnvironment(const std::string &str, const std::chrono::time_point< std::chrono::system_clock > *const timeRef=nullptr)
Replaces an environment variable with its value (similar to bash); syntax for a variable is ${NAME}.
static int toInt(const std::string &sData)
converts a string into the integer value described by it by calling the char-type converter,...
values of the output related options, handed over by SystemFrame so that this class does not depend o...
std::string suffix
the suffix to append to all output file names
std::string prefix
the prefix to prepend to all output file names
std::string columnHeader
how to derive column headers (CSV and Parquet)
std::string columnSeparator
the separator for CSV output
std::string compression
the compression algorithm for Parquet output
std::chrono::time_point< std::chrono::system_clock > loadTime
the time the configuration was loaded, used to replace TIME in prefix, suffix and file names
std::string format
the default output format ("xml", "csv" or "parquet")