VirtualBox

source: vbox/trunk/include/VBox/settings.h@ 16254

Last change on this file since 16254 was 16188, checked in by vboxsync, 16 years ago

Merge OVF branch.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 40.6 KB
Line 
1/** @file
2 * Settings File Manipulation API.
3 */
4
5/*
6 * Copyright (C) 2007 Sun Microsystems, Inc.
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.virtualbox.org. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 *
16 * The contents of this file may alternatively be used under the terms
17 * of the Common Development and Distribution License Version 1.0
18 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
19 * VirtualBox OSE distribution, in which case the provisions of the
20 * CDDL are applicable instead of those of the GPL.
21 *
22 * You may elect to license modified versions of this file under the
23 * terms and conditions of either the GPL or the CDDL or both.
24 *
25 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
26 * Clara, CA 95054 USA or visit http://www.sun.com if you need
27 * additional information or have any questions.
28 */
29
30#ifndef ___VBox_settings_h
31#define ___VBox_settings_h
32
33#include <iprt/cdefs.h>
34#include <iprt/cpputils.h>
35#include <iprt/string.h>
36
37#include <list>
38#include <memory>
39#include <limits>
40
41/* these conflict with numeric_digits<>::min and max */
42#undef min
43#undef max
44
45#include <iprt/time.h>
46
47#include <VBox/xml.h>
48
49#include <stdarg.h>
50
51
52/** @defgroup grp_settings Settings File Manipulation API
53 * @{
54 *
55 * The Settings File Manipulation API allows to maintain a configuration file
56 * that contains "name-value" pairs grouped under named keys which are in turn
57 * organized in a hierarchical tree-like structure:
58 *
59 * @code
60 * <RootKey>
61 * <Key1 attr1="value" attr2=""/>
62 * <Key2 attr1="value">
63 * <SubKey1>SubKey1_Value</SubKey1>
64 * <SubKey2 attr1="value">SubKey2_Value</SubKey2>
65 * Key2_Value
66 * </Key2>
67 * </RootKey>
68 * @endcode
69 *
70 * All strings this API manipulates with are zero-terminated arrays of @c char
71 * in UTF-8 encoding. Strings returned by the API are owned by the API unless
72 * explicitly stated otherwise. Strings passed to the API are accessed by the
73 * API only during the given API call unless explicitly stated otherwise. If
74 * necessary, the API will make a copy of the supplied string.
75 *
76 * Error reporting is perfomed using C++ exceptions. All exceptions thrown by
77 * this API are derived from settings::Error. This doesn't cover exceptions
78 * that may be thrown by third-party library calls made by this API.
79 *
80 * All public classes represented by this API that support copy operations
81 * (i.e. may be created or assigned from other instsances of the same class),
82 * such as Key and Value classes, implement shallow copies and use this mode by
83 * default. It means two things:
84 *
85 * 1. Instances of these classes can be freely copied around and used as return
86 * values. All copies will share the same internal data block (using the
87 * reference counting technique) so that the copy operation is cheap, both
88 * in terms of memory and speed.
89 *
90 * 2. Since copied instances share the same data, an attempt to change data in
91 * the original will be reflected in all existing copies.
92 *
93 * Making deep copies or detaching the existing shallow copy from its original
94 * is not yet supported.
95 *
96 * Note that the Settings File API is not thread-safe. It means that if you
97 * want to use the same instance of a class from the settings namespace on more
98 * than one thread at a time, you will have to provide necessary access
99 * serialization yourself.
100 *
101 * Due to some (not propely studied) libxml2 limitations, the Settings File
102 * API is not thread-safe. Therefore, the API caller must provide
103 * serialization for threads using this API simultaneously. Note though that
104 * if the libxml2 library is (even imlicitly) used on some other thread which
105 * doesn't use this API (e.g. third-party code), it may lead to resource
106 * conflicts (followed by crashes, memory corruption etc.). A proper solution
107 * for these conflicts is to be found.
108 *
109 * In order to load a settings file the program creates a TreeBackend instance
110 * using one of the specific backends (e.g. XmlTreeBackend) and then passes an
111 * Input stream object (e.g. File or MemoryBuf) to the TreeBackend::read()
112 * method to parse the stream and build the settings tree. On success, the
113 * program uses the TreeBackend::rootKey() method to access the root key of
114 * the settings tree. The root key provides access to the whole tree of
115 * settings through the methods of the Key class which allow to read, change
116 * and create new key values. Below is an example that uses the XML backend to
117 * load the settings tree, then modifies it and then saves the modifications.
118 *
119 * @code
120 using namespace settings;
121
122 try
123 {
124 File file (File::ReadWrite, "myfile.xml");
125 XmlTreeBackend tree;
126
127 // load the tree, parse it and validate using the XML schema
128 tree.read (aFile, "myfile.xsd", XmlTreeBackend::Read_AddDefaults);
129
130 // get the root key
131 Key root = tree.key();
132 printf ("root=%s\n", root.name());
133
134 // enumerate all child keys of the root key named Foo
135 Key::list children = root.keys ("Foo");
136 for (Key::list::const_iterator it = children.begin();
137 it != children.end();
138 ++ it)
139 {
140 // get the "level" attribute
141 int level = (*it).value <int> ("level");
142 if (level > 5)
143 {
144 // if so, create a "Bar" key if it doesn't exist yet
145 Key bar = (*it).createKey ("Bar");
146 // set the "date" attribute
147 RTTIMESPEC now;
148 RTTimeNow (&now);
149 bar.setValue <RTTIMESPEC> ("date", now);
150 }
151 else if (level < 2)
152 {
153 // if its below 2, delete the whole "Foo" key
154 (*it).zap();
155 }
156 }
157
158 // save the tree on success (the second try is to distinguish between
159 // stream load and save errors)
160 try
161 {
162 aTree.write (aFile);
163 }
164 catch (const EIPRTFailure &err)
165 {
166 // this is an expected exception that may happen in case of stream
167 // read or write errors
168 printf ("Could not save the settings file '%s' (%Rrc)");
169 file.uri(), err.rc());
170
171 return FAILURE;
172 }
173
174 return SUCCESS;
175 }
176 catch (const EIPRTFailure &err)
177 {
178 // this is an expected exception that may happen in case of stream
179 // read or write errors
180 printf ("Could not load the settings file '%s' (%Rrc)");
181 file.uri(), err.rc());
182 }
183 catch (const XmlTreeBackend::Error &err)
184 {
185 // this is an XmlTreeBackend specific exception that may
186 // happen in case of XML parse or validation errors
187 printf ("Could not load the settings file '%s'.\n%s"),
188 file.uri(), err.what() ? err.what() : "Unknown error");
189 }
190 catch (const std::exception &err)
191 {
192 // the rest is unexpected (e.g. should not happen unless you
193 // specifically wish so for some reason and therefore allow for a
194 // situation that may throw one of these from within the try block
195 // above)
196 AssertMsgFailed ("Unexpected exception '%s' (%s)\n",
197 typeid (err).name(), err.what());
198 }
199 catch (...)
200 {
201 // this is even more unexpected, and no any useful info here
202 AssertMsgFailed ("Unexpected exception\n");
203 }
204
205 return FAILURE;
206 * @endcode
207 *
208 * Note that you can get a raw (string) value of the attribute using the
209 * Key::stringValue() method but often it's simpler and better to use the
210 * templated Key::value<>() method that can convert the string to a value of
211 * the given type for you (and throw exceptions when the converison is not
212 * possible). Similarly, the Key::setStringValue() method is used to set a raw
213 * string value and there is a templated Key::setValue<>() method to set a
214 * typed value which will implicitly convert it to a string.
215 *
216 * Currently, types supported by Key::value<>() and Key::setValue<>() include
217 * all C and IPRT integer types, bool and RTTIMESPEC (represented as isoDate
218 * in XML). You can always add support for your own types by creating
219 * additional specializations of the FromString<>() and ToString<>() templates
220 * in the settings namespace (see the real examples in this header).
221 *
222 * See individual funciton, class and method descriptions to get more details
223 * on the Settings File Manipulation API.
224 */
225
226/*
227 * Shut up MSVC complaining that auto_ptr[_ref] template instantiations (as a
228 * result of private data member declarations of some classes below) need to
229 * be exported too to in order to be accessible by clients.
230 *
231 * The alternative is to instantiate a template before the data member
232 * declaration with the VBOXXML_CLASS prefix, but the standard disables
233 * explicit instantiations in a foreign namespace. In other words, a declaration
234 * like:
235 *
236 * template class VBOXXML_CLASS std::auto_ptr <Data>;
237 *
238 * right before the member declaration makes MSVC happy too, but this is not a
239 * valid C++ construct (and G++ spits it out). So, for now we just disable the
240 * warning and will come back to this problem one day later.
241 *
242 * We also disable another warning (4275) saying that a DLL-exported class
243 * inherits form a non-DLL-exported one (e.g. settings::ENoMemory ->
244 * std::bad_alloc). I can't get how it can harm yet.
245 */
246#if defined(_MSC_VER)
247#pragma warning (disable:4251)
248#pragma warning (disable:4275)
249#endif
250
251/* Forwards */
252typedef struct _xmlParserInput xmlParserInput;
253typedef xmlParserInput *xmlParserInputPtr;
254typedef struct _xmlParserCtxt xmlParserCtxt;
255typedef xmlParserCtxt *xmlParserCtxtPtr;
256typedef struct _xmlError xmlError;
257typedef xmlError *xmlErrorPtr;
258
259
260/**
261 * Settings File Manipulation API namespace.
262 */
263namespace settings
264{
265
266// Exceptions (on top of vboxxml exceptions)
267//////////////////////////////////////////////////////////////////////////////
268
269class VBOXXML_CLASS ENoKey : public xml::LogicError
270{
271public:
272
273 ENoKey (const char *aMsg = NULL) : xml::LogicError (aMsg) {}
274};
275
276class VBOXXML_CLASS ENoValue : public xml::LogicError
277{
278public:
279
280 ENoValue (const char *aMsg = NULL) : xml::LogicError (aMsg) {}
281};
282
283class VBOXXML_CLASS ENoConversion : public xml::RuntimeError
284{
285public:
286
287 ENoConversion (const char *aMsg = NULL) : RuntimeError (aMsg) {}
288};
289
290
291// Helpers
292//////////////////////////////////////////////////////////////////////////////
293
294// string -> type conversions
295//////////////////////////////////////////////////////////////////////////////
296
297/** @internal
298 * Helper for the FromString() template, doesn't need to be called directly.
299 */
300DECLEXPORT (uint64_t) FromStringInteger (const char *aValue, bool aSigned,
301 int aBits, uint64_t aMin, uint64_t aMax);
302
303/**
304 * Generic template function to perform a conversion of an UTF-8 string to an
305 * arbitrary value of type @a T.
306 *
307 * This generic template is implenented only for 8-, 16-, 32- and 64- bit
308 * signed and unsigned integers where it uses RTStrTo[U]Int64() to perform the
309 * conversion. For all other types it throws an ENotImplemented
310 * exception. Individual template specializations for known types should do
311 * the conversion job.
312 *
313 * If the conversion is not possible (for example the string format is wrong
314 * or meaningless for the given type), this template will throw an
315 * ENoConversion exception. All specializations must do the same.
316 *
317 * If the @a aValue argument is NULL, this method will throw an ENoValue
318 * exception. All specializations must do the same.
319 *
320 * @param aValue Value to convert.
321 *
322 * @return Result of conversion.
323 */
324template <typename T>
325T FromString (const char *aValue)
326{
327 if (std::numeric_limits <T>::is_integer)
328 {
329 bool sign = std::numeric_limits <T>::is_signed;
330 int bits = std::numeric_limits <T>::digits + (sign ? 1 : 0);
331
332 return (T) FromStringInteger (aValue, sign, bits,
333 (uint64_t) std::numeric_limits <T>::min(),
334 (uint64_t) std::numeric_limits <T>::max());
335 }
336
337 throw xml::ENotImplemented (RT_SRC_POS);
338}
339
340/**
341 * Specialization of FromString for bool.
342 *
343 * Converts "true", "yes", "on" to true and "false", "no", "off" to false.
344 */
345template<> DECLEXPORT (bool) FromString <bool> (const char *aValue);
346
347/**
348 * Specialization of FromString for RTTIMESPEC.
349 *
350 * Converts the date in ISO format (<YYYY>-<MM>-<DD>T<hh>:<mm>:<ss>[timezone])
351 * to a RTTIMESPEC value. Currently, the timezone must always be Z (UTC).
352 */
353template<> DECLEXPORT (RTTIMESPEC) FromString <RTTIMESPEC> (const char *aValue);
354
355/**
356 * Converts a string of hex digits to memory bytes.
357 *
358 * @param aValue String to convert.
359 * @param aLen Where to store the length of the returned memory
360 * block (may be NULL).
361 *
362 * @return Result of conversion (a block of @a aLen bytes).
363 */
364DECLEXPORT (stdx::char_auto_ptr) FromString (const char *aValue, size_t *aLen);
365
366// type -> string conversions
367//////////////////////////////////////////////////////////////////////////////
368
369/** @internal
370 * Helper for the ToString() template, doesn't need to be called directly.
371 */
372DECLEXPORT (stdx::char_auto_ptr)
373ToStringInteger (uint64_t aValue, unsigned int aBase,
374 bool aSigned, int aBits);
375
376/**
377 * Generic template function to perform a conversion of an arbitrary value to
378 * an UTF-8 string.
379 *
380 * This generic template is implemented only for 8-, 16-, 32- and 64- bit
381 * signed and unsigned integers where it uses RTStrFormatNumber() to perform
382 * the conversion. For all other types it throws an ENotImplemented
383 * exception. Individual template specializations for known types should do
384 * the conversion job. If the conversion is not possible (for example the
385 * given value doesn't have a string representation), the relevant
386 * specialization should throw an ENoConversion exception.
387 *
388 * If the @a aValue argument's value would convert to a NULL string, this
389 * method will throw an ENoValue exception. All specializations must do the
390 * same.
391 *
392 * @param aValue Value to convert.
393 * @param aExtra Extra flags to define additional formatting. In case of
394 * integer types, it's the base used for string representation.
395 *
396 * @return Result of conversion.
397 */
398template <typename T>
399stdx::char_auto_ptr ToString (const T &aValue, unsigned int aExtra = 0)
400{
401 if (std::numeric_limits <T>::is_integer)
402 {
403 bool sign = std::numeric_limits <T>::is_signed;
404 int bits = std::numeric_limits <T>::digits + (sign ? 1 : 0);
405
406 return ToStringInteger (aValue, aExtra, sign, bits);
407 }
408
409 throw xml::ENotImplemented (RT_SRC_POS);
410}
411
412/**
413 * Specialization of ToString for bool.
414 *
415 * Converts true to "true" and false to "false". @a aExtra is not used.
416 */
417template<> DECLEXPORT (stdx::char_auto_ptr)
418ToString <bool> (const bool &aValue, unsigned int aExtra);
419
420/**
421 * Specialization of ToString for RTTIMESPEC.
422 *
423 * Converts the RTTIMESPEC value to the date string in ISO format
424 * (<YYYY>-<MM>-<DD>T<hh>:<mm>:<ss>[timezone]). Currently, the timezone will
425 * always be Z (UTC).
426 *
427 * @a aExtra is not used.
428 */
429template<> DECLEXPORT (stdx::char_auto_ptr)
430ToString <RTTIMESPEC> (const RTTIMESPEC &aValue, unsigned int aExtra);
431
432/**
433 * Converts memory bytes to a null-terminated string of hex values.
434 *
435 * @param aData Pointer to the memory block.
436 * @param aLen Length of the memory block.
437 *
438 * @return Result of conversion.
439 */
440DECLEXPORT (stdx::char_auto_ptr) ToString (const void *aData, size_t aLen);
441
442// the rest
443//////////////////////////////////////////////////////////////////////////////
444
445/**
446 * The Key class represents a settings key.
447 *
448 * Every settings key has a name and zero or more uniquely named values
449 * (attributes). There is a special attribute with a NULL name that is called
450 * a key value.
451 *
452 * Besides values, settings keys may contain other settings keys. This way,
453 * settings keys form a tree-like (or a directory-like) hierarchy of keys. Key
454 * names do not need to be unique even if they belong to the same parent key
455 * which allows to have an array of keys of the same name.
456 *
457 * @note Key and Value objects returned by methods of the Key and TreeBackend
458 * classes are owned by the given TreeBackend instance and may refer to data
459 * that becomes invalid when this TreeBackend instance is destroyed.
460 */
461class VBOXXML_CLASS Key
462{
463public:
464
465 typedef std::list <Key> List;
466
467 /**
468 * Key backend interface used to perform actual key operations.
469 *
470 * This interface is implemented by backends that provide specific ways of
471 * storing settings keys.
472 */
473 class VBOXXML_CLASS Backend : public stdx::auto_ref
474 {
475 public:
476
477 /** Performs the Key::name() function. */
478 virtual const char *name() const = 0;
479
480 /** Performs the Key::setName() function. */
481 virtual void setName (const char *aName) = 0;
482
483 /** Performs the Key::stringValue() function. */
484 virtual const char *value (const char *aName) const = 0;
485
486 /** Performs the Key::setStringValue() function. */
487 virtual void setValue (const char *aName, const char *aValue) = 0;
488
489 /** Performs the Key::keys() function. */
490 virtual List keys (const char *aName = NULL) const = 0;
491
492 /** Performs the Key::findKey() function. */
493 virtual Key findKey (const char *aName) const = 0;
494
495 /** Performs the Key::appendKey() function. */
496 virtual Key appendKey (const char *aName) = 0;
497
498 /** Performs the Key::zap() function. */
499 virtual void zap() = 0;
500
501 /**
502 * Returns an opaque value that uniquely represents the position of
503 * this key on the tree which is used to compare two keys. Two or more
504 * keys may return the same value only if they actually represent the
505 * same key (i.e. they have the same list of parents and children).
506 */
507 virtual void *position() const = 0;
508 };
509
510 /**
511 * Creates a new key object. If @a aBackend is @c NULL then a null key is
512 * created.
513 *
514 * Regular API users should never need to call this method with something
515 * other than NULL argument (which is the default).
516 *
517 * @param aBackend Key backend to use.
518 */
519 Key (Backend *aBackend = NULL) : m (aBackend) {}
520
521 /**
522 * Returns @c true if this key is null.
523 */
524 bool isNull() const { return m.is_null(); }
525
526 /**
527 * Makes this object a null key.
528 *
529 * Note that as opposed to #zap(), this methid does not delete the key from
530 * the list of children of its parent key.
531 */
532 void setNull() { m = NULL; }
533
534 /**
535 * Returns the name of this key.
536 * Returns NULL if this object a null (uninitialized) key.
537 */
538 const char *name() const { return m.is_null() ? NULL : m->name(); }
539
540 /**
541 * Sets the name of this key.
542 *
543 * @param aName New key name.
544 */
545 void setName (const char *aName) { if (!m.is_null()) m->setName (aName); }
546
547 /**
548 * Returns the value of the attribute with the given name as an UTF-8
549 * string. Returns @c NULL if there is no attribute with the given name.
550 *
551 * @param aName Name of the attribute. NULL may be used to
552 * get the key value.
553 */
554 const char *stringValue (const char *aName) const
555 {
556 return m.is_null() ? NULL : m->value (aName);
557 }
558
559 /**
560 * Sets the value of the attribute with the given name from an UTF-8
561 * string. This method will do a copy of the supplied @a aValue string.
562 *
563 * @param aName Name of the attribute. NULL may be used to
564 * set the key value.
565 * @param aValue New value of the attribute. NULL may be used to
566 * delete the value instead of setting it.
567 */
568 void setStringValue (const char *aName, const char *aValue)
569 {
570 if (!m.is_null()) m->setValue (aName, aValue);
571 }
572
573 /**
574 * Returns the value of the attribute with the given name as an object of
575 * type @a T. Throws ENoValue if there is no attribute with the given
576 * name.
577 *
578 * This function calls #stringValue() to get the string representation of
579 * the attribute and then calls the FromString() template to convert this
580 * string to a value of the given type.
581 *
582 * @param aName Name of the attribute. NULL may be used to
583 * get the key value.
584 */
585 template <typename T>
586 T value (const char *aName) const
587 {
588 try
589 {
590 return FromString <T> (stringValue (aName));
591 }
592 catch (const ENoValue &)
593 {
594 throw ENoValue(xml::FmtStr("No such attribute '%s'", aName));
595 }
596 }
597
598 /**
599 * Returns the value of the attribute with the given name as an object of
600 * type @a T. Returns the given default value if there is no attribute
601 * with the given name.
602 *
603 * This function calls #stringValue() to get the string representation of
604 * the attribute and then calls the FromString() template to convert this
605 * string to a value of the given type.
606 *
607 * @param aName Name of the attribute. NULL may be used to
608 * get the key value.
609 * @param aDefault Default value to return for the missing attribute.
610 */
611 template <typename T>
612 T valueOr (const char *aName, const T &aDefault) const
613 {
614 try
615 {
616 return FromString <T> (stringValue (aName));
617 }
618 catch (const ENoValue &)
619 {
620 return aDefault;
621 }
622 }
623
624 /**
625 * Sets the value of the attribute with the given name from an object of
626 * type @a T. This method will do a copy of data represented by @a aValue
627 * when necessary.
628 *
629 * This function converts the given value to a string using the ToString()
630 * template and then calls #setStringValue().
631 *
632 * @param aName Name of the attribute. NULL may be used to
633 * set the key value.
634 * @param aValue New value of the attribute.
635 * @param aExtra Extra field used by some types to specify additional
636 * details for storing the value as a string (such as the
637 * base for decimal numbers).
638 */
639 template <typename T>
640 void setValue (const char *aName, const T &aValue, unsigned int aExtra = 0)
641 {
642 try
643 {
644 stdx::char_auto_ptr value = ToString (aValue, aExtra);
645 setStringValue (aName, value.get());
646 }
647 catch (const ENoValue &)
648 {
649 throw ENoValue(xml::FmtStr("No value for attribute '%s'", aName));
650 }
651 }
652
653 /**
654 * Sets the value of the attribute with the given name from an object of
655 * type @a T. If the value of the @a aValue object equals to the value of
656 * the given @a aDefault object, then the attribute with the given name
657 * will be deleted instead of setting its value to @a aValue.
658 *
659 * This function converts the given value to a string using the ToString()
660 * template and then calls #setStringValue().
661 *
662 * @param aName Name of the attribute. NULL may be used to
663 * set the key value.
664 * @param aValue New value of the attribute.
665 * @param aDefault Default value to compare @a aValue to.
666 * @param aExtra Extra field used by some types to specify additional
667 * details for storing the value as a string (such as the
668 * base for decimal numbers).
669 */
670 template <typename T>
671 void setValueOr (const char *aName, const T &aValue, const T &aDefault,
672 unsigned int aExtra = 0)
673 {
674 if (aValue == aDefault)
675 zapValue (aName);
676 else
677 setValue <T> (aName, aValue, aExtra);
678 }
679
680 /**
681 * Deletes the value of the attribute with the given name.
682 * Shortcut to <tt>setStringValue(aName, NULL)</tt>.
683 */
684 void zapValue (const char *aName) { setStringValue (aName, NULL); }
685
686 /**
687 * Returns the key value.
688 * Shortcut to <tt>stringValue (NULL)</tt>.
689 */
690 const char *keyStringValue() const { return stringValue (NULL); }
691
692 /**
693 * Sets the key value.
694 * Shortcut to <tt>setStringValue (NULL, aValue)</tt>.
695 */
696 void setKeyStringValue (const char *aValue) { setStringValue (NULL, aValue); }
697
698 /**
699 * Returns the key value.
700 * Shortcut to <tt>value (NULL)</tt>.
701 */
702 template <typename T>
703 T keyValue() const { return value <T> (NULL); }
704
705 /**
706 * Returns the key value or the given default if the key value is NULL.
707 * Shortcut to <tt>value (NULL)</tt>.
708 */
709 template <typename T>
710 T keyValueOr (const T &aDefault) const { return valueOr <T> (NULL, aDefault); }
711
712 /**
713 * Sets the key value.
714 * Shortcut to <tt>setValue (NULL, aValue, aExtra)</tt>.
715 */
716 template <typename T>
717 void setKeyValue (const T &aValue, unsigned int aExtra = 0)
718 {
719 setValue <T> (NULL, aValue, aExtra);
720 }
721
722 /**
723 * Sets the key value.
724 * Shortcut to <tt>setValueOr (NULL, aValue, aDefault)</tt>.
725 */
726 template <typename T>
727 void setKeyValueOr (const T &aValue, const T &aDefault,
728 unsigned int aExtra = 0)
729 {
730 setValueOr <T> (NULL, aValue, aDefault, aExtra);
731 }
732
733 /**
734 * Deletes the key value.
735 * Shortcut to <tt>zapValue (NULL)</tt>.
736 */
737 void zapKeyValue () { zapValue (NULL); }
738
739 /**
740 * Returns a list of all child keys named @a aName.
741 *
742 * If @a aname is @c NULL, returns a list of all child keys.
743 *
744 * @param aName Child key name to list.
745 */
746 List keys (const char *aName = NULL) const
747 {
748 return m.is_null() ? List() : m->keys (aName);
749 };
750
751 /**
752 * Returns the first child key with the given name.
753 *
754 * Throws ENoKey if no child key with the given name exists.
755 *
756 * @param aName Child key name.
757 */
758 Key key (const char *aName) const
759 {
760 Key key = findKey (aName);
761 if (key.isNull())
762 {
763 throw ENoKey(xml::FmtStr("No such key '%s'", aName));
764 }
765 return key;
766 }
767
768 /**
769 * Returns the first child key with the given name.
770 *
771 * As opposed to #key(), this method will not throw an exception if no
772 * child key with the given name exists, but return a null key instead.
773 *
774 * @param aName Child key name.
775 */
776 Key findKey (const char *aName) const
777 {
778 return m.is_null() ? Key() : m->findKey (aName);
779 }
780
781 /**
782 * Creates a key with the given name as a child of this key and returns it
783 * to the caller.
784 *
785 * If one or more child keys with the given name already exist, no new key
786 * is created but the first matching child key is returned.
787 *
788 * @param aName Name of the child key to create.
789 */
790 Key createKey (const char *aName)
791 {
792 Key key = findKey (aName);
793 if (key.isNull())
794 key = appendKey (aName);
795 return key;
796 }
797
798 /**
799 * Appends a key with the given name to the list of child keys of this key
800 * and returns the appended key to the caller.
801 *
802 * @param aName Name of the child key to create.
803 */
804 Key appendKey (const char *aName)
805 {
806 return m.is_null() ? Key() : m->appendKey (aName);
807 }
808
809 /**
810 * Deletes this key.
811 *
812 * The deleted key is removed from the list of child keys of its parent
813 * key and becomes a null object.
814 */
815 void zap()
816 {
817 if (!m.is_null())
818 {
819 m->zap();
820 setNull();
821 }
822 }
823
824 /**
825 * Compares this object with the given object and returns @c true if both
826 * represent the same key on the settings tree or if both are null
827 * objects.
828 *
829 * @param that Object to compare this object with.
830 */
831 bool operator== (const Key &that) const
832 {
833 return m == that.m ||
834 (!m.is_null() && !that.m.is_null() &&
835 m->position() == that.m->position());
836 }
837
838 /**
839 * Counterpart to operator==().
840 */
841 bool operator!= (const Key &that) const { return !operator== (that); }
842
843private:
844
845 stdx::auto_ref_ptr <Backend> m;
846
847 friend class TreeBackend;
848};
849
850/**
851 * The TreeBackend class represents a storage backend used to read a settings
852 * tree from and write it to a stream.
853 *
854 * @note All Key objects returned by any of the TreeBackend methods (and by
855 * methods of returned Key objects) are owned by the given TreeBackend
856 * instance. When this instance is destroyed, all Key objects become invalid
857 * and an attempt to access Key data will cause the program crash.
858 */
859class VBOXXML_CLASS TreeBackend
860{
861public:
862
863 /**
864 * Reads and parses the given input stream.
865 *
866 * On success, the previous settings tree owned by this backend (if any)
867 * is deleted.
868 *
869 * The optional schema URI argument determines the name of the schema to
870 * use for input validation. If the schema URI is NULL then the validation
871 * is not performed. Note that you may set a custom input resolver if you
872 * want to provide the input stream for the schema file (and for other
873 * external entities) instead of letting the backend to read the specified
874 * URI directly.
875 *
876 * This method will set the read/write position to the beginning of the
877 * given stream before reading. After the stream has been successfully
878 * parsed, the position will be set back to the beginning.
879 *
880 * @param aInput Input stream.
881 * @param aSchema Schema URI to use for input stream validation.
882 * @param aFlags Optional bit flags.
883 */
884 void read (xml::Input &aInput, const char *aSchema = NULL, int aFlags = 0)
885 {
886 aInput.setPos (0);
887 rawRead (aInput, aSchema, aFlags);
888 aInput.setPos (0);
889 }
890
891 /**
892 * Reads and parses the given input stream in a raw fashion.
893 *
894 * This method doesn't set the stream position to the beginnign before and
895 * after reading but instead leaves it as is in both cases. It's the
896 * caller's responsibility to maintain the correct position.
897 *
898 * @see read()
899 */
900 virtual void rawRead (xml::Input &aInput, const char *aSchema = NULL,
901 int aFlags = 0) = 0;
902
903 /**
904 * Writes the current settings tree to the given output stream.
905 *
906 * This method will set the read/write position to the beginning of the
907 * given stream before writing. After the settings have been successfully
908 * written to the stream, the stream will be truncated at the position
909 * following the last byte written by this method anc ghd position will be
910 * set back to the beginning.
911 *
912 * @param aOutput Output stream.
913 */
914 void write (xml::Output &aOutput)
915 {
916 aOutput.setPos (0);
917 rawWrite (aOutput);
918 aOutput.truncate();
919 aOutput.setPos (0);
920 }
921
922 /**
923 * Writes the current settings tree to the given output stream in a raw
924 * fashion.
925 *
926 * This method doesn't set the stream position to the beginnign before and
927 * after reading and doesn't truncate the stream, but instead leaves it as
928 * is in both cases. It's the caller's responsibility to maintain the
929 * correct position and perform truncation.
930 *
931 * @see write()
932 */
933 virtual void rawWrite (xml::Output &aOutput) = 0;
934
935 /**
936 * Deletes the current settings tree.
937 */
938 virtual void reset() = 0;
939
940 /**
941 * Returns the root settings key.
942 */
943 virtual Key &rootKey() const = 0;
944
945protected:
946
947 static Key::Backend *GetKeyBackend (const Key &aKey) { return aKey.m.raw(); }
948};
949
950class XmlKeyBackend;
951
952/**
953 * The XmlTreeBackend class uses XML markup to store settings trees.
954 *
955 * @note libxml2 and libxslt libraries used by the XmlTreeBackend are not
956 * fully reentrant. To "fix" this, the XmlTreeBackend backend serializes access
957 * to such non-reentrant parts using a global mutex so that only one thread can
958 * use non-reentrant code at a time. Currently, this relates to the #rawRead()
959 * method (and to #read() as a consequence). This means that only one thread can
960 * parse an XML stream at a time; other threads trying to parse same or
961 * different streams using different XmlTreeBackend and Input instances
962 * will have to wait.
963 *
964 * Keep in mind that the above reentrancy fix does not imply thread-safety: it
965 * is still the caller's responsibility to provide serialization if the same
966 * XmlTreeBackend instnace (as well as instances of other classes from the
967 * settings namespace) needs to be used by more than one thread.
968 */
969class VBOXXML_CLASS XmlTreeBackend : public TreeBackend
970{
971public:
972
973 /** Flags for TreeBackend::read(). */
974 enum
975 {
976 /**
977 * Sbstitute default values for missing attributes that have defaults
978 * in the XML schema. Otherwise, stringValue() will return NULL for
979 * such attributes.
980 */
981 Read_AddDefaults = RT_BIT (0),
982 };
983
984 /**
985 * The EConversionCycle class represents a conversion cycle detected by the
986 * AutoConverter::needsConversion() implementation.
987 */
988 class VBOXXML_CLASS EConversionCycle : public xml::RuntimeError
989 {
990 public:
991
992 EConversionCycle (const char *aMsg = NULL) : RuntimeError (aMsg) {}
993 };
994
995 /**
996 * The InputResolver class represents an interface to provide input streams
997 * for external entities given an URL and entity ID.
998 */
999 class VBOXXML_CLASS InputResolver
1000 {
1001 public:
1002
1003 /**
1004 * Returns a newly allocated input stream for the given arguments. The
1005 * caller will delete the returned object when no more necessary.
1006 *
1007 * @param aURI URI of the external entity.
1008 * @param aID ID of the external entity (may be NULL).
1009 *
1010 * @return Input stream created using @c new or NULL to indicate
1011 * a wrong URI/ID pair.
1012 *
1013 * @todo Return by value after implementing the copy semantics for
1014 * Input subclasses.
1015 */
1016 virtual xml::Input *resolveEntity (const char *aURI, const char *aID) = 0;
1017 };
1018
1019 /**
1020 * The AutoConverter class represents an interface to automatically convert
1021 * old settings trees to a new version when the tree is read from the
1022 * stream.
1023 */
1024 class VBOXXML_CLASS AutoConverter
1025 {
1026 public:
1027
1028 /**
1029 * Returns @true if the given tree needs to be converted using the XSLT
1030 * template identified by #templateUri(), or @false if no conversion is
1031 * required.
1032 *
1033 * The implementation normally checks for the "version" value of the
1034 * root key to determine if the conversion is necessary. When the
1035 * @a aOldVersion argument is not NULL, the implementation must return a
1036 * non-NULL non-empty string representing the old version (before
1037 * conversion) in it this string is used by XmlTreeBackend::oldVersion()
1038 * and must be non-NULL to indicate that the conversion has been
1039 * performed on the tree. The returned string must be allocated using
1040 * RTStrDup() or such.
1041 *
1042 * This method is called again after the successful transformation to
1043 * let the implementation retry the version check and request another
1044 * transformation if necessary. This may be used to perform multi-step
1045 * conversion like this: 1.1 => 1.2, 1.2 => 1.3 (instead of 1.1 => 1.3)
1046 * which saves from the need to update all previous conversion
1047 * templates to make each of them convert directly to the recent
1048 * version.
1049 *
1050 * @note Multi-step transformations are performed in a loop that exits
1051 * only when this method returns @false. It's up to the
1052 * implementation to detect cycling (repeated requests to convert
1053 * from the same version) wrong version order, etc. and throw an
1054 * EConversionCycle exception to break the loop without returning
1055 * @false (which means the transformation succeeded).
1056 *
1057 * @param aRoot Root settings key.
1058 * @param aOldVersionString Where to store old version string
1059 * pointer. May be NULL. Allocated memory is
1060 * freed by the caller using RTStrFree().
1061 */
1062 virtual bool needsConversion (const Key &aRoot,
1063 char **aOldVersion) const = 0;
1064
1065 /**
1066 * Returns the URI of the XSLT template to perform the conversion.
1067 * This template will be applied to the tree if #needsConversion()
1068 * returns @c true for this tree.
1069 */
1070 virtual const char *templateUri() const = 0;
1071 };
1072
1073 XmlTreeBackend();
1074 ~XmlTreeBackend();
1075
1076 /**
1077 * Sets an external entity resolver used to provide input streams for
1078 * entities referred to by the XML document being parsed.
1079 *
1080 * The given resolver object must exist as long as this instance exists or
1081 * until a different resolver is set using setInputResolver() or reset
1082 * using resetInputResolver().
1083 *
1084 * @param aResolver Resolver to use.
1085 */
1086 void setInputResolver (InputResolver &aResolver);
1087
1088 /**
1089 * Resets the entity resolver to the default resolver. The default
1090 * resolver provides support for 'file:' and 'http:' protocols.
1091 */
1092 void resetInputResolver();
1093
1094 /**
1095 * Sets a settings tree converter and enables the automatic conversion.
1096 *
1097 * The Automatic settings tree conversion is useful for upgrading old
1098 * settings files to the new version transparently during execution of the
1099 * #read() method.
1100 *
1101 * The automatic conversion takes place after reading the document from the
1102 * stream but before validating it. The given converter is asked if the
1103 * conversion is necessary using the AutoConverter::needsConversion() call,
1104 * and if so, the XSLT template specified by AutoConverter::templateUri() is
1105 * applied to the settings tree.
1106 *
1107 * Note that in order to make the result of the conversion permanent, the
1108 * settings tree needs to be exlicitly written back to the stream.
1109 *
1110 * The given converter object must exist as long as this instance exists or
1111 * until a different converter is set using setAutoConverter() or reset
1112 * using resetAutoConverter().
1113 *
1114 * @param aConverter Settings converter to use.
1115 */
1116 void setAutoConverter (AutoConverter &aConverter);
1117
1118 /**
1119 * Disables the automatic settings conversion previously enabled by
1120 * setAutoConverter(). By default automatic conversion it is disabled.
1121 */
1122 void resetAutoConverter();
1123
1124 /**
1125 * Returns a non-NULL string if the automatic settings conversion has been
1126 * performed during the last successful #read() call. Returns @c NULL if
1127 * there was no settings conversion.
1128 *
1129 * If #read() fails, this method will return the version string set by the
1130 * previous successful #read() call or @c NULL if there were no #read()
1131 * calls.
1132 */
1133 const char *oldVersion() const;
1134
1135 void rawRead (xml::Input &aInput, const char *aSchema = NULL, int aFlags = 0);
1136 void rawWrite (xml::Output &aOutput);
1137 void reset();
1138 Key &rootKey() const;
1139
1140private:
1141
1142 /* Obscure class data */
1143 struct Data;
1144 std::auto_ptr <Data> m;
1145
1146 /* auto_ptr data doesn't have proper copy semantics */
1147 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (XmlTreeBackend)
1148
1149 static int ReadCallback (void *aCtxt, char *aBuf, int aLen);
1150 static int WriteCallback (void *aCtxt, const char *aBuf, int aLen);
1151 static int CloseCallback (void *aCtxt);
1152
1153 static void ValidityErrorCallback (void *aCtxt, const char *aMsg, ...);
1154 static void ValidityWarningCallback (void *aCtxt, const char *aMsg, ...);
1155 static void StructuredErrorCallback (void *aCtxt, xmlErrorPtr aErr);
1156
1157 static xmlParserInput *ExternalEntityLoader (const char *aURI,
1158 const char *aID,
1159 xmlParserCtxt *aCtxt);
1160
1161 static XmlTreeBackend *sThat;
1162
1163 static XmlKeyBackend *GetKeyBackend (const Key &aKey)
1164 { return (XmlKeyBackend *) TreeBackend::GetKeyBackend (aKey); }
1165};
1166
1167} /* namespace settings */
1168
1169
1170/*
1171 * VBoxXml
1172 *
1173 *
1174 */
1175
1176
1177class VBoxXmlBase
1178{
1179protected:
1180 VBoxXmlBase();
1181
1182 ~VBoxXmlBase();
1183
1184 xmlParserCtxtPtr m_ctxt;
1185};
1186
1187class VBoxXmlFile : public VBoxXmlBase
1188{
1189public:
1190 VBoxXmlFile();
1191 ~VBoxXmlFile();
1192};
1193
1194
1195
1196#if defined(_MSC_VER)
1197#pragma warning (default:4251)
1198#endif
1199
1200/** @} */
1201
1202#endif /* ___VBox_settings_h */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette