Cross-Platform Programming with wxWidgets
Just Make It Cross-Platform
Subscribe to Feed
  • Home
  • Projects
  • Links

wxJSON Tutorial – Part II – Сonfiguration File

wxWidgets Add comments |

Preface

Here is a second part of wxJSON tutorial provided by Luciano Cattani, author and maintainer of wxJSON library.

  • Visit wxJSON homepage
  • Read Part I of this tutorial
  • Read Part II of this tutorial
  • Read Part III of this tutorial
  • Read Part IV of this tutorial

Creating a Configuration File with wxJSON

We start by using JSON for an application’s configuration file. There are many formats for storing application’s configuration data. I remember when there was MS-DOS: each application used its own, unreadable and proprietary format (it was a nightmare). Next came Windows 3: it had a better way for storing application’s configuration data; they were kept in an .INI file which contains simple ASCII text. This was a good thing because it was easier for humans to fine-tuning application’s behaviour.

In this example we use JSON to store the configuration data of a simple web server application. If you take a look at the Apache config file you will notice that our example looks very similar (but much more human readable).

Our server is a neverending application and it is not interactive: it reads its configuration at startup and when a signal is sent to it. Using JSON for the configuration data is a good choice because it is easy for humans to write the JSON text document. Below we find our webserver’s configuration file:

{
   // global configuration
   "Global" :  {
     "DocumentRoot"  : "/var/www/html",
     "MaxClients"    : 250,
     "ServerPort"    : 80,
     "ServerAddress" : 0.0.0.00
     "MaxRequestsPerClient"  : 1000
   }

   // an array of objects that describes the modules that has to
   // be loaded at startup
   "Modules" : [
      {
        "Name"    : "auth_basic",
        "File"    : "modules/mod_auth_basic.so",
        "OnStart" : true
      },
      {
        "Name"    : "auth_digest",
        "File"    : "modules/mod_auth_digest.so",
        "OnStart" : true
      },
      {
        "Name"    : "auth_file",
        "File"    : "modules/mod_auth_file.so",
        "OnStart" : false
      },
   ]

   // Main server configuration
   "Server" :       {
      "Admin" : "root@localhost.localdomain"
      "Name"  : "www.example.com"
   },

   // The description of directories and their access permissions
   "Diretory"  : [
      {
         "Path"       : "/var/www/html",
         "AllowFrom"  : "ALL",
         "DenyFrom"   : null,
         "Options" :     {
            "Multiviews"    : false,
            "Indexes"       : true,
            "FollowSymLink" : false
         }
      }
   ]
 }

I think that the file is self-explanatory. I do not want to write the code of the whole web-server application: I only want to show you how to read the configuration data.

When the application starts, it calls a function that reads the configuration file and returns ZERO if there was no error or an exit status code if the file is not correct. The function may be similar to the following one:

 int ReadConfig( wxInputStream& jsonStream )
  {
    // comment lines are recognized by the wxJSON library and
    // can also be stored in the JSON value objects they refer to
    // but this is not needed by our application because the
    // config file is written by hand by the website admin
    // so we use the default ctor of the parser which recognizes
    // comment lines but do not store them
    wxJSONReader reader;
    wxJSONvalue  root;
    int numErrors = reader.Parse( jsonStream, root );
    if ( numErrors > 0 )  {
      // if there are errors in the JSON document, print the
      // errors and return a non-ZERO value
      const wxArrayString& errors = reader.GetErrors();
      for ( int i = 0; i < numErrors; i++ )  {
        cout << errors[i] << endl;
      }
      return 1;
    }

    // if the config file is syntactically correct, we retrieve
    // the values and store them in application's variables
    gs_docRoot = root["Global"]["DocumentRoot"].AsString();

    // we use the Get() memberfunction to get the port on which
    // the server listens. If the parameter does not exist in the
    // JSON value, the default port 80 is returned
    wxJSONvalue defaultPort = 80;
    gs_serverPort = root["Global"].Get( "ServerPort", defaultPort ).AsInt();

    // the array of modules is processed in a different way: for
    // every module we print its name and the 'OnStart' flag.
    // if the flag is TRUE, we load it.
    wxJSONValue modules = root["Modules"];

    // check that the 'Modules' value is of type ARRAY
    if ( !modules.IsArray() ) {
      cout << "ERROR: \'modules\' must be a JSON array" << endl;
      return 1;
    }

    for ( int i = 0; i < modules.Size(); i++ )  {
      cout << "Processing module: " << modules[i]["Name"].AsString() << endl;
      bool load =  modules[i]["OnStart"].AsBool();
      cout << "Load module? " << ( load ? "YES" : "NO" ) << endl;
      if ( load )  {
        LoadModule( modules[i]["File"].Asstring());
      }
    }
    // return a ZERO value: it means success.
    return 0;
  }

January 19th, 2008 |

Tags: Articles, wxJSON, wxWidgets, Статьи

Related Posts

  • wxJSON Tutorial – Part I – Introduction
  • wxJSON Tutorial – Part III – Describing a Table
  • wxJSON Tutorial – Part IV – Using Comment Lines in wxJSON
  • wxJSON 1.1.0 Released
  • wxJSON 1.0 Released
Балка двутавровая 20 б1. Продажа и доставка балки, балка двутавровая 20 .;Vip-сувениры и подарки. Vip сувениры современные .

Leave a Reply

Please leave these two fields as-is:

  • This blog is about…

    Articles Code::Blocks Components Controls Database DatabaseLayer Document/View Eclipse Localization NetBeans Networking News Printing Reports SQLite Tutorilas Video Visual Studio wxAUI wxButton wxDev-CPP wxGrid wxHelpController wxJavaScript wxJSON wxLocale wxLog wxPaintDC wxPropertyGrid wxRuby wxSQLite3 wxThread wxValidator wxWidgets wxWinCE wxZipInputStream wxZipOutputStream XML Библиотека Книги Статьи
  • Showcase

    Visit wxToolBox Homepage

    Buy wxToolBox (with source code)

  • Archives

    • November 2009
    • September 2009
    • August 2009
    • May 2009
    • April 2009
    • March 2009
    • February 2009
    • January 2009
    • December 2008
    • September 2008
    • August 2008
    • July 2008
    • June 2008
    • May 2008
    • April 2008
    • March 2008
    • February 2008
    • January 2008
    • December 2007
    • June 2007
    • May 2007
    • January 2007
  • Recent Comments

    • T-Rex on Getting Acquainted with Document/View Framework – Simple Image Viewer
    • T-Rex on Сделайте мне красиво – Часть II – wxAUI в Multi-View приложений
    • Mardiko on Getting Acquainted with Document/View Framework – Simple Image Viewer
    • marty on Сделайте мне красиво – Часть II – wxAUI в Multi-View приложений
    • T-Rex on Перевод книги Julian’а Smart’а – Глава VI – Обработка данных с устройств ввода
  • Buttons

    Locations of visitors to this page

    Rambler's Top100
    Рейтинг@Mail.ru

Copyright © 2010 Cross-Platform Programming with wxWidgets All Rights Reserved
RSS Log in