Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
XMLSubSys.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2002-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// Utility methods for initialising, closing and using the XML-subsystem
21/****************************************************************************/
22#include <config.h>
23
24#include <cstdint>
25#include <xercesc/util/PlatformUtils.hpp>
26#include <xercesc/util/TransService.hpp>
27#include <xercesc/util/TranscodingException.hpp>
28#include <xercesc/util/XMLString.hpp>
29#include <xercesc/sax2/XMLReaderFactory.hpp>
30#include <xercesc/framework/XMLGrammarPoolImpl.hpp>
35#include "SUMOSAXHandler.h"
36#include "SUMOSAXReader.h"
37#include "XMLSubSys.h"
38
39using XERCES_CPP_NAMESPACE::SAX2XMLReader;
40using XERCES_CPP_NAMESPACE::XMLPlatformUtils;
41using XERCES_CPP_NAMESPACE::XMLReaderFactory;
42
43
44// ===========================================================================
45// static member variables
46// ===========================================================================
47std::vector<SUMOSAXReader*> XMLSubSys::myReaders;
49std::string XMLSubSys::myValidationScheme = "local";
50std::string XMLSubSys::myNetValidationScheme = "local";
51std::string XMLSubSys::myRouteValidationScheme = "local";
52XERCES_CPP_NAMESPACE::XMLGrammarPool* XMLSubSys::myGrammarPool = nullptr;
54
55
56// ===========================================================================
57// method definitions
58// ===========================================================================
59void
61 try {
62 XMLPlatformUtils::Initialize();
64 } catch (const XERCES_CPP_NAMESPACE::XMLException& e) {
65 throw ProcessError("Error during XML-initialization:\n " + XMLSubSys::transcode(e.getMessage()));
66 }
67}
68
69
70std::string
71XMLSubSys::warnLocalScheme(const std::string& newScheme, const bool haveSUMO_HOME) {
72 if (newScheme != "never" && newScheme != "auto" && newScheme != "always" && newScheme != "local") {
73 throw ProcessError("Unknown xml validation scheme + '" + newScheme + "'.");
74 }
75 if (!haveSUMO_HOME && newScheme == "local") {
77 WRITE_WARNING(TL("Environment variable SUMO_HOME is not set properly, disabling XML validation. Set 'auto' or 'always' for web lookups."));
79 }
80 return "never";
81 }
82 return newScheme;
83}
84
85
86void
87XMLSubSys::setValidation(const std::string& validationScheme, const std::string& netValidationScheme, const std::string& routeValidationScheme) {
88 const char* sumoPath = std::getenv("SUMO_HOME");
89 const bool haveSUMO_HOME = sumoPath != nullptr && FileHelpers::isReadable(sumoPath + std::string("/data/xsd/net_file.xsd"));
90 myValidationScheme = warnLocalScheme(validationScheme, haveSUMO_HOME);
91 myNetValidationScheme = warnLocalScheme(netValidationScheme, haveSUMO_HOME);
92 myRouteValidationScheme = warnLocalScheme(routeValidationScheme, haveSUMO_HOME);
93 if (myGrammarPool == nullptr &&
94 (myValidationScheme != "never" ||
95 myNetValidationScheme != "never" ||
96 myRouteValidationScheme != "never")) {
97 if (!haveSUMO_HOME) {
99 WRITE_WARNING(TL("Environment variable SUMO_HOME is not set properly, XML validation will fail or use slow website lookups."));
101 }
102 return;
103 }
104 myGrammarPool = new XERCES_CPP_NAMESPACE::XMLGrammarPoolImpl(XMLPlatformUtils::fgMemoryManager);
105 SAX2XMLReader* parser(XMLReaderFactory::createXMLReader(XMLPlatformUtils::fgMemoryManager, myGrammarPool));
106#if _XERCES_VERSION >= 30100
107 parser->setFeature(XERCES_CPP_NAMESPACE::XMLUni::fgXercesHandleMultipleImports, true);
108#endif
109 for (const char* const& filetype : {
110 "additional", "routes", "net"
111 }) {
112 const std::string file = sumoPath + std::string("/data/xsd/") + filetype + "_file.xsd";
113 if (!parser->loadGrammar(file.c_str(), XERCES_CPP_NAMESPACE::Grammar::SchemaGrammarType, true)) {
114 WRITE_WARNINGF(TL("Cannot read local schema '%'."), file);
115 }
116 }
117 delete parser;
118 }
119}
120
121
122void
124 for (std::vector<SUMOSAXReader*>::iterator i = myReaders.begin(); i != myReaders.end(); ++i) {
125 delete *i;
126 }
127 myReaders.clear();
128 delete myGrammarPool;
129 myGrammarPool = nullptr;
130 XMLPlatformUtils::Terminate();
131}
132
133
135XMLSubSys::getSAXReader(SUMOSAXHandler& handler, const bool isNet, const bool isRoute) {
136 std::string validationScheme = isNet ? myNetValidationScheme : myValidationScheme;
137 if (isRoute) {
138 validationScheme = myRouteValidationScheme;
139 }
140 return new SUMOSAXReader(handler, validationScheme, myGrammarPool);
141}
142
143
144void
146 myReaders[myNextFreeReader - 1]->setHandler(handler);
147}
148
149
150bool
151XMLSubSys::runParser(GenericSAXHandler& handler, const std::string& file,
152 const bool isNet, const bool isRoute, const bool isExternal, const bool catchExceptions) {
154 std::string errorMsg = "";
155 try {
156 std::string validationScheme = isNet ? myNetValidationScheme : myValidationScheme;
157 if (isRoute) {
158 validationScheme = myRouteValidationScheme;
159 }
160 if (isExternal && validationScheme == "local") {
161 WRITE_MESSAGEF(TL("Disabling XML validation for external file '%'. Use 'auto' or 'always' to enable."), file);
162 validationScheme = "never";
163 }
164 if (myNextFreeReader == (int)myReaders.size()) {
165 myReaders.push_back(new SUMOSAXReader(handler, validationScheme, myGrammarPool));
166 } else {
167 myReaders[myNextFreeReader]->setValidation(validationScheme);
168 myReaders[myNextFreeReader]->setHandler(handler);
169 }
171 std::string prevFile = handler.getFileName();
172 handler.setFileName(file);
173 myReaders[myNextFreeReader - 1]->parse(file);
174 handler.setFileName(prevFile);
176 } catch (const ProcessError& e) {
177 if (catchExceptions) {
178 errorMsg = std::string(e.what()) != std::string("") ? e.what() : TL("Process Error");
179 } else {
180 throw;
181 }
182 } catch (const std::runtime_error& re) {
183 errorMsg = TLF("Runtime error: % while parsing '%'", re.what(), file);
184 } catch (const std::exception& ex) {
185 errorMsg = TLF("Error occurred: % while parsing '%'", ex.what(), file);
186 } catch (const XERCES_CPP_NAMESPACE::SAXException& e) {
187 errorMsg = TLF("SAX error occurred while parsing '%':\n %", file, XMLSubSys::transcode(e.getMessage()));
188 } catch (...) {
189 errorMsg = TLF("Unspecified error occurred while parsing '%'", file);
190 }
191 if (errorMsg != "") {
192 if (catchExceptions) {
193 WRITE_ERROR(errorMsg);
194 } else {
195 throw ProcessError(errorMsg);
196 }
197 }
199}
200
201
202std::string
203XMLSubSys::transcode(const XMLCh* const data, int length) {
204 if (data == 0) {
205 throw EmptyData();
206 }
207 if (length < 0) {
208 length = (int)XERCES_CPP_NAMESPACE::XMLString::stringLen(data);
209 }
210 if (length == 0) {
211 return "";
212 }
213 // fast path: ASCII is identical in UTF-8
214 std::string ascii;
215 ascii.reserve(length);
216 int i = 0;
217 for (; i < length && data[i] != 0 && data[i] < 0x80; i++) {
218 ascii += (char)data[i];
219 }
220 if (i == length || data[i] == 0) {
221 return ascii;
222 }
223#if _XERCES_VERSION < 30100
224 char* t = XERCES_CPP_NAMESPACE::XMLString::transcode(data);
225 std::string result(t);
226 XERCES_CPP_NAMESPACE::XMLString::release(&t);
227 return result;
228#else
229 try {
230 XERCES_CPP_NAMESPACE::TranscodeToStr utf8(data, "UTF-8");
231 return reinterpret_cast<const char*>(utf8.str());
232 } catch (XERCES_CPP_NAMESPACE::TranscodingException&) {
233 return "?";
234 }
235#endif
236}
237
238
239/****************************************************************************/
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:301
#define WRITE_ERROR(msg)
Definition MsgHandler.h:307
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
#define TL(string)
Definition MsgHandler.h:316
#define TLF(string,...)
Definition MsgHandler.h:318
static bool isReadable(std::string path)
Checks whether the given file is readable.
A handler which converts occurring elements and attributes into enums.
void setFileName(const std::string &name)
Sets the current file name.
const std::string & getFileName() const
returns the current file name
bool wasInformed() const
Returns the information whether any messages were added.
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
virtual void clear(bool resetInformed=true)
Clears information whether an error occurred previously and print aggregated message summary.
SAX-handler base for SUMO-files.
SAX-reader encapsulation containing binary reader.
static int myNextFreeReader
Information whether the reader is parsing.
Definition XMLSubSys.h:162
static std::vector< SUMOSAXReader * > myReaders
The XML Readers used for repeated parsing.
Definition XMLSubSys.h:159
static void setHandler(GenericSAXHandler &handler)
Sets the given handler for the default reader.
static std::string myValidationScheme
Information whether built reader/parser shall validate XML-documents against schemata.
Definition XMLSubSys.h:165
static void setValidation(const std::string &validationScheme, const std::string &netValidationScheme, const std::string &routeValidationScheme)
Enables or disables validation.
Definition XMLSubSys.cpp:87
static XERCES_CPP_NAMESPACE::XMLGrammarPool * myGrammarPool
Schema cache to be used for grammars which are not declared.
Definition XMLSubSys.h:174
static SUMOSAXReader * getSAXReader(SUMOSAXHandler &handler, const bool isNet=false, const bool isRoute=false)
Builds a reader and assigns the handler to it.
static void close()
Closes the xml-subsystem.
static std::string transcode(const XMLCh *const data, int length=-1)
converts a 0-terminated XMLCh* array (usually UTF-16, stemming from Xerces) into std::string in UTF-8
static void init()
Initialises the xml-subsystem.
Definition XMLSubSys.cpp:60
static std::string warnLocalScheme(const std::string &newScheme, const bool haveSUMO_HOME)
Definition XMLSubSys.cpp:71
static bool runParser(GenericSAXHandler &handler, const std::string &file, const bool isNet=false, const bool isRoute=false, const bool isExternal=false, const bool catchExceptions=true)
Runs the given handler on the given file; returns if everything's ok.
static std::string myRouteValidationScheme
Information whether built reader/parser shall validate SUMO routes against schemata.
Definition XMLSubSys.h:171
static bool myNeedsValidationWarning
Whether a warning about missing SUMO_HOME should be emitted.
Definition XMLSubSys.h:177
static std::string myNetValidationScheme
Information whether built reader/parser shall validate SUMO networks against schemata.
Definition XMLSubSys.h:168