[Zrouter-src] ZRouter.org: push to zconf++ zconf++/http_json_handler.cc zconf+...
zrouter-src at zrouter.org
zrouter-src at zrouter.org
Wed Jan 11 06:35:08 UTC 2012
details: /rev/bc7e5c46eec7
changeset: 38:bc7e5c46eec7
user: "Nicolai Petri <nicolai at petri.dk>"
date: Wed Jan 11 07:34:43 2012 +0100
description:
style commit (first run of bcpp formatter)
diffstat:
zconf++/http_json_handler.cc | 130 ++--
zconf++/http_json_handler.h | 29 +-
zconf++/interfaces.h | 33 +-
zconf++/json_reader.cc | 1301 +++++++++++++++++++----------------------
zconf++/json_reader.h | 310 +++++-----
zconf++/model.cc | 165 ++--
zconf++/model.h | 323 +++++----
zconf++/tests/Makefile | 2 +-
zconf++/utils.cc | 37 +-
zconf++/utils.h | 12 +-
zconf++/zconfig.cc | 16 +-
zconf++/zextension.h | 15 +-
zconf++/zrouterhttp.cc | 37 +-
13 files changed, 1190 insertions(+), 1220 deletions(-)
diffs (2936 lines):
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/http_json_handler.cc
--- a/zconf++/http_json_handler.cc Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/http_json_handler.cc Wed Jan 11 07:34:43 2012 +0100
@@ -32,79 +32,81 @@
#include "libzhttp/request.hpp"
#include "libzhttp/reply.hpp"
-namespace ZRouter {
+namespace ZRouter
+{
-using namespace http;
-using namespace http::server;
-using namespace std;
+ using namespace http;
+ using namespace http::server;
+ using namespace std;
-http_json_handler::http_json_handler(Model::Model &p_model)
+ http_json_handler::http_json_handler(Model::Model &p_model)
:model(p_model) {
-}
+ }
-const std::string http_json_handler::ns_prefix() {
- return "/model/";
-}
+ const std::string http_json_handler::ns_prefix() {
+ return "/model/";
+ }
-const handlers::e_request_handler_type http_json_handler::type() {
- return handlers::NORMAL;
-}
-const bool http_json_handler::can_handle(const std::string &url, const server::request& req) {
- //cout << "can_handle: " << req.uri << " : " << req.uri.find("/model/") << endl;
- if (url.find(ns_prefix()) != 0) {
- // cout << "Not our thing" << endl;
- return false;
+ const handlers::e_request_handler_type http_json_handler::type() {
+ return handlers::NORMAL;
}
- return true;
-}
-void http_json_handler::handle(const std::string &url, const server::request& req, server::reply& rep) {
- // Fill out the reply to be sent to the client.
- std::vector<std::string> uri_parts;
- boost::split(uri_parts, url, boost::is_any_of("/"));
- std::vector<std::string>::iterator it = uri_parts.begin();
- it+=2; // Skip first junk (/model)
- Leaf *leaf = &model;
- for (; it != uri_parts.end(); it++) {
- if (*it == "")
- continue;
- leaf = &((*leaf)[*it]);
- cout << "REQ PART: " << *it << endl;
+ const bool http_json_handler::can_handle(const std::string &url, const server::request& req) {
+ //cout << "can_handle: " << req.uri << " : " << req.uri.find("/model/") << endl;
+ if (url.find(ns_prefix()) != 0) {
+ // cout << "Not our thing" << endl;
+ return false;
+ }
+ return true;
}
-// cout << "Handling request for << " << uri_parts[1] << ":" << uri_parts[2] << endl;
- rep.status = reply::ok;
-#ifdef JSON_WRITE_USING_STRING
- std::string resp = ModelWriter::write(leaf, "");
- rep.content.append(ss.str().c_str(), ss.str().length());
-#else
- std::stringstream ss;
- ss.str().reserve(16384); // Reserve 16K to avoid realloc hell on small request.
- // TEST: Do above actually make a change ?
- if (leaf->type() == action_leaf) {
- Json::Reader r;
- Leaf params;
- std::cout << "GOT BODY : " << req.body << std::endl;
- r.parse(req.body, params);
- std::stringstream stest;
- ModelWriter::write(stest, params, "PARSED REQ: ");
- std::cout << stest.str() << std::endl;
+ void http_json_handler::handle(const std::string &url, const server::request& req, server::reply& rep) {
+ // Fill out the reply to be sent to the client.
+ std::vector<std::string> uri_parts;
+ boost::split(uri_parts, url, boost::is_any_of("/"));
+ std::vector<std::string>::iterator it = uri_parts.begin();
+ it+=2; // Skip first junk (/model)
+ Leaf *leaf = &model;
+ for (; it != uri_parts.end(); it++) {
+ if (*it == "")
+ continue;
+ leaf = &((*leaf)[*it]);
+ cout << "REQ PART: " << *it << endl;
+ }
+ // cout << "Handling request for << " << uri_parts[1] << ":" << uri_parts[2] << endl;
+ rep.status = reply::ok;
+ #ifdef JSON_WRITE_USING_STRING
+ std::string resp = ModelWriter::write(leaf, "");
+ rep.content.append(ss.str().c_str(), ss.str().length());
+ #else
+ std::stringstream ss;
+ ss.str().reserve(16384); // Reserve 16K to avoid realloc hell on small request.
+ // TEST: Do above actually make a change ?
+ if (leaf->type() == action_leaf) {
+ Json::Reader r;
+ Leaf params;
+ std::cout << "GOT BODY : " << req.body << std::endl;
+ r.parse(req.body, params);
+ std::stringstream stest;
+ ModelWriter::write(stest, params, "PARSED REQ: ");
+ std::cout << stest.str() << std::endl;
- Leaf resp = leaf->call(params);
- ModelWriter::write(ss, resp, "");
- } else {
- ModelWriter::write(ss, *leaf, "");
+ Leaf resp = leaf->call(params);
+ ModelWriter::write(ss, resp, "");
+ }
+ else {
+ ModelWriter::write(ss, *leaf, "");
+ }
+ rep.content = ss.str();
+ //rep.content = "1";
+ #endif
+
+ rep.headers.resize(2);
+ rep.headers[0].name = "Content-Length";
+ rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
+ //rep.headers[0].value = "20";
+ rep.headers[1].name = "Content-Type";
+ //rep.headers[1].value = mime_types::extension_to_type(extension);
+ rep.headers[1].value = "application/json; charset=utf-8";
}
- rep.content = ss.str();
- //rep.content = "1";
-#endif
-
- rep.headers.resize(2);
- rep.headers[0].name = "Content-Length";
- rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
- //rep.headers[0].value = "20";
- rep.headers[1].name = "Content-Type";
- //rep.headers[1].value = mime_types::extension_to_type(extension);
- rep.headers[1].value = "application/json; charset=utf-8";
-}
}
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/http_json_handler.h
--- a/zconf++/http_json_handler.h Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/http_json_handler.h Wed Jan 11 07:34:43 2012 +0100
@@ -30,20 +30,21 @@
// #include "json_spirit/json_spirit.h"
#include "model.h"
-namespace ZRouter {
+namespace ZRouter
+{
-class http_json_handler : public http::handlers::i_request_handler {
- public:
- http_json_handler(Model::Model &p_model);
- virtual const std::string ns_prefix() ;
- virtual const http::handlers::e_request_handler_type type() ;
- virtual const bool can_handle(const std::string &url, const http::server::request& req) ;
- virtual void handle(const std::string &url, const http::server::request& req, http::server::reply& rep) ;
- // virtual void
- protected:
- Model::Model& model;
-};
+ class http_json_handler : public http::handlers::i_request_handler
+ {
+ public:
+ http_json_handler(Model::Model &p_model);
+ virtual const std::string ns_prefix() ;
+ virtual const http::handlers::e_request_handler_type type() ;
+ virtual const bool can_handle(const std::string &url, const http::server::request& req) ;
+ virtual void handle(const std::string &url, const http::server::request& req, http::server::reply& rep) ;
+ // virtual void
+ protected:
+ Model::Model& model;
+ };
}
-#endif // __HTTP_JSON_HANDLER__H
-
+#endif // __HTTP_JSON_HANDLER__H
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/interfaces.h
--- a/zconf++/interfaces.h Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/interfaces.h Wed Jan 11 07:34:43 2012 +0100
@@ -28,32 +28,37 @@
#include "model.h"
-namespace ZRouter {
+namespace ZRouter
+{
class ZFrame;
- // abstract base class
- class ePacketReceivedFunctor
- {
- public:
+ // abstract base class
+ class ePacketReceivedFunctor
+ {
+ public:
- // two possible functions to call member function. virtual cause derived
- // classes will use a pointer to an object and a pointer to a member function
- // to make the function call
- virtual bool operator()(const ZFrame &pFrame )=0; // call using operator
- virtual bool Call(const ZFrame &pFrame)=0; // call using function
- };
+ // two possible functions to call member function. virtual cause derived
+ // classes will use a pointer to an object and a pointer to a member function
+ // to make the function call
+ // call using operator
+ virtual bool operator()(const ZFrame &pFrame )=0;
+ // call using function
+ virtual bool Call(const ZFrame &pFrame)=0;
+ };
- class iFrameLayer {
+ class iFrameLayer
+ {
public:
virtual void queue_cmd(const ZFrame &p) = 0;
virtual void addListener(ePacketReceivedFunctor* pListener) = 0;
virtual void setIdle(bool pIdle) = 0;
};
- class iEngine {
+ class iEngine
+ {
public:
virtual iFrameLayer* framelayer() = 0;
virtual Model& model() = 0;
};
};
-#endif // __INTERFACES__H
+#endif // __INTERFACES__H
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/json_reader.cc
--- a/zconf++/json_reader.cc Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/json_reader.cc Wed Jan 11 07:34:43 2012 +0100
@@ -33,743 +33,662 @@
#include <iostream>
#include <stdexcept>
-namespace Json {
+namespace Json
+{
-static inline bool
-in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 )
-{
- return c == c1 || c == c2 || c == c3 || c == c4;
-}
+ static inline bool
+ in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 ) {
+ return c == c1 || c == c2 || c == c3 || c == c4;
+ }
-static inline bool
-in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 )
-{
- return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
-}
+ static inline bool
+ in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 ) {
+ return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
+ }
+ static bool
+ containsNewLine( Reader::Location begin,
+ Reader::Location end ) {
+ for ( ;begin < end; ++begin )
+ if ( *begin == '\n' || *begin == '\r' )
+ return true;
+ return false;
+ }
-static bool
-containsNewLine( Reader::Location begin,
- Reader::Location end )
-{
- for ( ;begin < end; ++begin )
- if ( *begin == '\n' || *begin == '\r' )
- return true;
- return false;
-}
+ // Class Reader
+ // //////////////////////////////////////////////////////////////////
+ Reader::Reader() {
+ }
-// Class Reader
-// //////////////////////////////////////////////////////////////////
+ bool
+ Reader::parse( const std::string &document,
+ Value &root,
+ bool collectComments ) {
+ document_ = document;
+ const char *begin = document_.c_str();
+ const char *end = begin + document_.length();
+ return parse( begin, end, root, collectComments );
+ }
-Reader::Reader()
-{
-}
+ bool
+ Reader::parse( std::istream& sin,
+ Value &root,
+ bool collectComments ) {
+ //std::istream_iterator<char> begin(sin);
+ //std::istream_iterator<char> end;
+ // Those would allow streamed input from a file, if parse() were a
+ // template function.
-bool
-Reader::parse( const std::string &document,
- Value &root,
- bool collectComments )
-{
- document_ = document;
- const char *begin = document_.c_str();
- const char *end = begin + document_.length();
- return parse( begin, end, root, collectComments );
-}
+ // Since std::string is reference-counted, this at least does not
+ // create an extra copy.
+ std::string doc;
+ std::getline(sin, doc, (char)EOF);
+ return parse( doc, root, collectComments );
+ }
-bool
-Reader::parse( std::istream& sin,
- Value &root,
- bool collectComments )
-{
- //std::istream_iterator<char> begin(sin);
- //std::istream_iterator<char> end;
- // Those would allow streamed input from a file, if parse() were a
- // template function.
+ bool
+ Reader::parse( const char *beginDoc, const char *endDoc,
+ Value &root,
+ bool collectComments ) {
+ begin_ = beginDoc;
+ end_ = endDoc;
+ collectComments_ = collectComments;
+ current_ = begin_;
+ lastValueEnd_ = 0;
+ lastValue_ = 0;
+ commentsBefore_ = "";
+ errors_.clear();
+ while ( !nodes_.empty() )
+ nodes_.pop();
+ nodes_.push( &root );
- // Since std::string is reference-counted, this at least does not
- // create an extra copy.
- std::string doc;
- std::getline(sin, doc, (char)EOF);
- return parse( doc, root, collectComments );
-}
+ bool successful = readValue();
+ Token token;
+ skipCommentTokens( token );
+ // if ( collectComments_ && !commentsBefore_.empty() )
+ // root.setComment( commentsBefore_, commentAfter );
+ return successful;
+ }
-bool
-Reader::parse( const char *beginDoc, const char *endDoc,
- Value &root,
- bool collectComments )
-{
- begin_ = beginDoc;
- end_ = endDoc;
- collectComments_ = collectComments;
- current_ = begin_;
- lastValueEnd_ = 0;
- lastValue_ = 0;
- commentsBefore_ = "";
- errors_.clear();
- while ( !nodes_.empty() )
- nodes_.pop();
- nodes_.push( &root );
-
- bool successful = readValue();
- Token token;
- skipCommentTokens( token );
-// if ( collectComments_ && !commentsBefore_.empty() )
-// root.setComment( commentsBefore_, commentAfter );
- return successful;
-}
+ bool
+ Reader::readValue() {
+ Token token;
+ skipCommentTokens( token );
+ bool successful = true;
+ /* if ( collectComments_ && !commentsBefore_.empty() )
+ {
+ currentValue().setComment( commentsBefore_, commentBefore );
+ commentsBefore_ = "";
+ }
+ */
-bool
-Reader::readValue()
-{
- Token token;
- skipCommentTokens( token );
- bool successful = true;
+ switch ( token.type_ ) {
+ case tokenObjectBegin:
+ successful = readObject( token );
+ break;
+ case tokenArrayBegin:
+ successful = readArray( token );
+ break;
+ case tokenNumber:
+ successful = decodeNumber( token );
+ break;
+ case tokenString:
+ successful = decodeString( token );
+ break;
+ case tokenTrue:
+ currentValue() = true;
+ break;
+ case tokenFalse:
+ currentValue() = false;
+ break;
+ case tokenNull:
+ currentValue() = Value();
+ break;
+ default:
+ return addError( "Syntax error: value, object or array expected.", token );
+ }
-/* if ( collectComments_ && !commentsBefore_.empty() )
- {
- currentValue().setComment( commentsBefore_, commentBefore );
- commentsBefore_ = "";
- }
-*/
+ /* if ( collectComments_ )
+ {
+ lastValueEnd_ = current_;
+ lastValue_ = ¤tValue();
+ }
+ */
+ return successful;
+ }
- switch ( token.type_ )
- {
- case tokenObjectBegin:
- successful = readObject( token );
- break;
- case tokenArrayBegin:
- successful = readArray( token );
- break;
- case tokenNumber:
- successful = decodeNumber( token );
- break;
- case tokenString:
- successful = decodeString( token );
- break;
- case tokenTrue:
- currentValue() = true;
- break;
- case tokenFalse:
- currentValue() = false;
- break;
- case tokenNull:
- currentValue() = Value();
- break;
- default:
- return addError( "Syntax error: value, object or array expected.", token );
- }
+ void
+ Reader::skipCommentTokens( Token &token ) {
+ do {
+ readToken( token );
+ }
+ while ( token.type_ == tokenComment );
+ }
-/* if ( collectComments_ )
- {
- lastValueEnd_ = current_;
- lastValue_ = ¤tValue();
- }
-*/
- return successful;
-}
+ bool
+ Reader::expectToken( TokenType type, Token &token, const char *message ) {
+ readToken( token );
+ if ( token.type_ != type )
+ return addError( message, token );
+ return true;
+ }
+ bool
+ Reader::readToken( Token &token ) {
+ skipSpaces();
+ token.start_ = current_;
+ Char c = getNextChar();
+ bool ok = true;
+ switch ( c ) {
+ case '{':
+ token.type_ = tokenObjectBegin;
+ break;
+ case '}':
+ token.type_ = tokenObjectEnd;
+ break;
+ case '[':
+ token.type_ = tokenArrayBegin;
+ break;
+ case ']':
+ token.type_ = tokenArrayEnd;
+ break;
+ case '"':
+ token.type_ = tokenString;
+ ok = readString();
+ break;
+ case '/':
+ token.type_ = tokenComment;
+ ok = readComment();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '-':
+ token.type_ = tokenNumber;
+ readNumber();
+ break;
+ case 't':
+ token.type_ = tokenTrue;
+ ok = match( "rue", 3 );
+ break;
+ case 'f':
+ token.type_ = tokenFalse;
+ ok = match( "alse", 4 );
+ break;
+ case 'n':
+ token.type_ = tokenNull;
+ ok = match( "ull", 3 );
+ break;
+ case ',':
+ token.type_ = tokenArraySeparator;
+ break;
+ case ':':
+ token.type_ = tokenMemberSeparator;
+ break;
+ case 0:
+ token.type_ = tokenEndOfStream;
+ break;
+ default:
+ ok = false;
+ break;
+ }
+ if ( !ok )
+ token.type_ = tokenError;
+ token.end_ = current_;
+ return true;
+ }
-void
-Reader::skipCommentTokens( Token &token )
-{
- do
- {
- readToken( token );
- }
- while ( token.type_ == tokenComment );
-}
+ void
+ Reader::skipSpaces() {
+ while ( current_ != end_ ) {
+ Char c = *current_;
+ if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' )
+ ++current_;
+ else
+ break;
+ }
+ }
+ bool
+ Reader::match( Location pattern,
+ int patternLength ) {
+ if ( end_ - current_ < patternLength )
+ return false;
+ int index = patternLength;
+ while ( index-- )
+ if ( current_[index] != pattern[index] )
+ return false;
+ current_ += patternLength;
+ return true;
+ }
-bool
-Reader::expectToken( TokenType type, Token &token, const char *message )
-{
- readToken( token );
- if ( token.type_ != type )
- return addError( message, token );
- return true;
-}
+ bool
+ Reader::readComment() {
+ Location commentBegin = current_ - 1;
+ Char c = getNextChar();
+ bool successful = false;
+ if ( c == '*' )
+ successful = readCStyleComment();
+ else if ( c == '/' )
+ successful = readCppStyleComment();
+ if ( !successful )
+ return false;
+ /* if ( collectComments_ )
+ {
+ CommentPlacement placement = commentBefore;
+ if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) )
+ {
+ if ( c != '*' || !containsNewLine( commentBegin, current_ ) )
+ placement = commentAfterOnSameLine;
+ }
-bool
-Reader::readToken( Token &token )
-{
- skipSpaces();
- token.start_ = current_;
- Char c = getNextChar();
- bool ok = true;
- switch ( c )
- {
- case '{':
- token.type_ = tokenObjectBegin;
- break;
- case '}':
- token.type_ = tokenObjectEnd;
- break;
- case '[':
- token.type_ = tokenArrayBegin;
- break;
- case ']':
- token.type_ = tokenArrayEnd;
- break;
- case '"':
- token.type_ = tokenString;
- ok = readString();
- break;
- case '/':
- token.type_ = tokenComment;
- ok = readComment();
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '-':
- token.type_ = tokenNumber;
- readNumber();
- break;
- case 't':
- token.type_ = tokenTrue;
- ok = match( "rue", 3 );
- break;
- case 'f':
- token.type_ = tokenFalse;
- ok = match( "alse", 4 );
- break;
- case 'n':
- token.type_ = tokenNull;
- ok = match( "ull", 3 );
- break;
- case ',':
- token.type_ = tokenArraySeparator;
- break;
- case ':':
- token.type_ = tokenMemberSeparator;
- break;
- case 0:
- token.type_ = tokenEndOfStream;
- break;
- default:
- ok = false;
- break;
- }
- if ( !ok )
- token.type_ = tokenError;
- token.end_ = current_;
- return true;
-}
+ addComment( commentBegin, current_, placement );
+ } */
+ return true;
+ }
+ /*
+ void
+ Reader::addComment( Location begin,
+ Location end,
+ CommentPlacement placement )
+ {
+ assert( collectComments_ );
+ if ( placement == commentAfterOnSameLine )
+ {
+ assert( lastValue_ != 0 );
+ lastValue_->setComment( std::string( begin, end ), placement );
+ }
+ else
+ {
+ if ( !commentsBefore_.empty() )
+ commentsBefore_ += "\n";
+ commentsBefore_ += std::string( begin, end );
+ }
+ }
-void
-Reader::skipSpaces()
-{
- while ( current_ != end_ )
- {
- Char c = *current_;
- if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' )
- ++current_;
- else
- break;
- }
-}
+ */
+ bool
+ Reader::readCStyleComment() {
+ while ( current_ != end_ ) {
+ Char c = getNextChar();
+ if ( c == '*' && *current_ == '/' )
+ break;
+ }
+ return getNextChar() == '/';
+ }
+ bool
+ Reader::readCppStyleComment() {
+ while ( current_ != end_ ) {
+ Char c = getNextChar();
+ if ( c == '\r' || c == '\n' )
+ break;
+ }
+ return true;
+ }
-bool
-Reader::match( Location pattern,
- int patternLength )
-{
- if ( end_ - current_ < patternLength )
- return false;
- int index = patternLength;
- while ( index-- )
- if ( current_[index] != pattern[index] )
- return false;
- current_ += patternLength;
- return true;
-}
+ void
+ Reader::readNumber() {
+ while ( current_ != end_ ) {
+ if ( !(*current_ >= '0' && *current_ <= '9') &&
+ !in( *current_, '.', 'e', 'E', '+', '-' ) )
+ break;
+ ++current_;
+ }
+ }
+ bool
+ Reader::readString() {
+ Char c = 0;
+ while ( current_ != end_ ) {
+ c = getNextChar();
+ if ( c == '\\' )
+ getNextChar();
+ else if ( c == '"' )
+ break;
+ }
+ return c == '"';
+ }
-bool
-Reader::readComment()
-{
- Location commentBegin = current_ - 1;
- Char c = getNextChar();
- bool successful = false;
- if ( c == '*' )
- successful = readCStyleComment();
- else if ( c == '/' )
- successful = readCppStyleComment();
- if ( !successful )
- return false;
+ bool
+ Reader::readObject( Token &tokenStart ) {
+ Token tokenName;
+ std::string name;
+ //currentValue() = Value( objectValue );
+ currentValue() = Value( );
+ while ( readToken( tokenName ) ) {
+ bool initialTokenOk = true;
+ while ( tokenName.type_ == tokenComment && initialTokenOk )
+ initialTokenOk = readToken( tokenName );
+ if ( !initialTokenOk )
+ break;
+ // empty object
+ if ( tokenName.type_ == tokenObjectEnd && name.empty() )
+ return true;
+ if ( tokenName.type_ != tokenString )
+ break;
-/* if ( collectComments_ )
- {
- CommentPlacement placement = commentBefore;
- if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) )
- {
- if ( c != '*' || !containsNewLine( commentBegin, current_ ) )
- placement = commentAfterOnSameLine;
- }
+ name = "";
+ if ( !decodeString( tokenName, name ) )
+ return recoverFromError( tokenObjectEnd );
- addComment( commentBegin, current_, placement );
- } */
- return true;
-}
+ Token colon;
+ if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator ) {
+ return addErrorAndRecover( "Missing ':' after object member name",
+ colon,
+ tokenObjectEnd );
+ }
+ // Value &value = currentValue()[ name ];
+ Value &value = currentValue()[ name ];
+ nodes_.push( &value );
+ bool ok = readValue();
+ nodes_.pop();
+ if ( !ok ) // error already set
+ return recoverFromError( tokenObjectEnd );
-/*
-void
-Reader::addComment( Location begin,
- Location end,
- CommentPlacement placement )
-{
- assert( collectComments_ );
- if ( placement == commentAfterOnSameLine )
- {
- assert( lastValue_ != 0 );
- lastValue_->setComment( std::string( begin, end ), placement );
- }
- else
- {
- if ( !commentsBefore_.empty() )
- commentsBefore_ += "\n";
- commentsBefore_ += std::string( begin, end );
- }
-}
+ Token comma;
+ if ( !readToken( comma )
+ || ( comma.type_ != tokenObjectEnd &&
+ comma.type_ != tokenArraySeparator &&
+ comma.type_ != tokenComment ) ) {
+ return addErrorAndRecover( "Missing ',' or '}' in object declaration",
+ comma,
+ tokenObjectEnd );
+ }
+ bool finalizeTokenOk = true;
+ while ( comma.type_ == tokenComment &&
+ finalizeTokenOk )
+ finalizeTokenOk = readToken( comma );
+ if ( comma.type_ == tokenObjectEnd )
+ return true;
+ }
+ return addErrorAndRecover( "Missing '}' or object member name",
+ tokenName,
+ tokenObjectEnd );
+ }
-*/
-bool
-Reader::readCStyleComment()
-{
- while ( current_ != end_ )
- {
- Char c = getNextChar();
- if ( c == '*' && *current_ == '/' )
- break;
- }
- return getNextChar() == '/';
-}
+ bool
+ Reader::readArray( Token &tokenStart ) {
+ currentValue() = Value( );
+ skipSpaces();
+ // empty array
+ if ( *current_ == ']' ) {
+ Token endArray;
+ readToken( endArray );
+ return true;
+ }
+ int index = 0;
+ while ( true ) {
+ Value &value = currentValue()[ index++ ];
+ nodes_.push( &value );
+ bool ok = readValue();
+ nodes_.pop();
+ if ( !ok ) // error already set
+ return recoverFromError( tokenArrayEnd );
+ Token token;
+ if ( !readToken( token )
+ || ( token.type_ != tokenArraySeparator &&
+ token.type_ != tokenArrayEnd ) ) {
+ return addErrorAndRecover( "Missing ',' or ']' in array declaration",
+ token,
+ tokenArrayEnd );
+ }
+ if ( token.type_ == tokenArrayEnd )
+ break;
+ }
+ return true;
+ }
-bool
-Reader::readCppStyleComment()
-{
- while ( current_ != end_ )
- {
- Char c = getNextChar();
- if ( c == '\r' || c == '\n' )
- break;
- }
- return true;
-}
+ bool
+ Reader::decodeNumber( Token &token ) {
+ bool isDouble = false;
+ for ( Location inspect = token.start_; inspect != token.end_; ++inspect ) {
+ isDouble = isDouble
+ || in( *inspect, '.', 'e', 'E', '+' )
+ || ( *inspect == '-' && inspect != token.start_ );
+ }
+ if ( isDouble )
+ return decodeDouble( token );
+ Location current = token.start_;
+ bool isNegative = *current == '-';
+ if ( isNegative )
+ ++current;
+ unsigned int threshold = std::numeric_limits<int>::max() / 10;
+ //: Value::maxUInt) / 10;
+ unsigned int value = 0;
+ while ( current < token.end_ ) {
+ Char c = *current++;
+ if ( c < '0' || c > '9' )
+ return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
+ if ( value >= threshold )
+ return decodeDouble( token );
+ value = value * 10 + (unsigned int)(c - '0');
+ }
+ if ( isNegative )
+ currentValue() = Value(- (int)value );
+ else if ( value <= std::numeric_limits<int>::max() )
+ currentValue() = Value( (int)value );
+ else
+ currentValue() = Value((int)value );
+ return true;
+ }
+ bool
+ Reader::decodeDouble( Token &token ) {
+ double value = 0;
+ const int bufferSize = 32;
+ int count;
+ int length = int(token.end_ - token.start_);
+ if ( length <= bufferSize ) {
+ Char buffer[bufferSize];
+ memcpy( buffer, token.start_, length );
+ buffer[length] = 0;
+ count = sscanf( buffer, "%lf", &value );
+ }
+ else {
+ std::string buffer( token.start_, token.end_ );
+ count = sscanf( buffer.c_str(), "%lf", &value );
+ }
-void
-Reader::readNumber()
-{
- while ( current_ != end_ )
- {
- if ( !(*current_ >= '0' && *current_ <= '9') &&
- !in( *current_, '.', 'e', 'E', '+', '-' ) )
- break;
- ++current_;
- }
-}
+ if ( count != 1 )
+ return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
+ currentValue() = value;
+ return true;
+ }
-bool
-Reader::readString()
-{
- Char c = 0;
- while ( current_ != end_ )
- {
- c = getNextChar();
- if ( c == '\\' )
- getNextChar();
- else if ( c == '"' )
- break;
- }
- return c == '"';
-}
+ bool
+ Reader::decodeString( Token &token ) {
+ std::string decoded;
+ if ( !decodeString( token, decoded ) )
+ return false;
+ currentValue() = decoded;
+ return true;
+ }
+ bool
+ Reader::decodeString( Token &token, std::string &decoded ) {
+ decoded.reserve( token.end_ - token.start_ - 2 );
+ // skip '"'
+ Location current = token.start_ + 1;
+ // do not include '"'
+ Location end = token.end_ - 1;
+ while ( current != end ) {
+ Char c = *current++;
+ if ( c == '"' )
+ break;
+ else if ( c == '\\' ) {
+ if ( current == end )
+ return addError( "Empty escape sequence in string", token, current );
+ Char escape = *current++;
+ switch ( escape ) {
+ case '"': decoded += '"'; break;
+ case '/': decoded += '/'; break;
+ case '\\': decoded += '\\'; break;
+ case 'b': decoded += '\b'; break;
+ case 'f': decoded += '\f'; break;
+ case 'n': decoded += '\n'; break;
+ case 'r': decoded += '\r'; break;
+ case 't': decoded += '\t'; break;
+ case 'u':
+ {
+ unsigned int unicode;
+ if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) )
+ return false;
+ // @todo encode unicode as utf8.
+ // @todo remember to alter the writer too.
+ }
+ break;
+ default:
+ return addError( "Bad escape sequence in string", token, current );
+ }
+ }
+ else {
+ decoded += c;
+ }
+ }
+ return true;
+ }
-bool
-Reader::readObject( Token &tokenStart )
-{
- Token tokenName;
- std::string name;
- //currentValue() = Value( objectValue );
- currentValue() = Value( );
- while ( readToken( tokenName ) )
- {
- bool initialTokenOk = true;
- while ( tokenName.type_ == tokenComment && initialTokenOk )
- initialTokenOk = readToken( tokenName );
- if ( !initialTokenOk )
- break;
- if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object
- return true;
- if ( tokenName.type_ != tokenString )
- break;
-
- name = "";
- if ( !decodeString( tokenName, name ) )
- return recoverFromError( tokenObjectEnd );
+ bool
+ Reader::decodeUnicodeEscapeSequence( Token &token,
+ Location ¤t,
+ Location end,
+ unsigned int &unicode ) {
+ if ( end - current < 4 )
+ return addError( "Bad unicode escape sequence in string: four digits expected.", token, current );
+ unicode = 0;
+ for ( int index =0; index < 4; ++index ) {
+ Char c = *current++;
+ unicode *= 16;
+ if ( c >= '0' && c <= '9' )
+ unicode += c - '0';
+ else if ( c >= 'a' && c <= 'f' )
+ unicode += c - 'a' + 10;
+ else if ( c >= 'A' && c <= 'F' )
+ unicode += c - 'A' + 10;
+ else
+ return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current );
+ }
+ return true;
+ }
- Token colon;
- if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator )
- {
- return addErrorAndRecover( "Missing ':' after object member name",
- colon,
- tokenObjectEnd );
- }
-// Value &value = currentValue()[ name ];
- Value &value = currentValue()[ name ];
- nodes_.push( &value );
- bool ok = readValue();
- nodes_.pop();
- if ( !ok ) // error already set
- return recoverFromError( tokenObjectEnd );
+ bool
+ Reader::addError( const std::string &message,
+ Token &token,
+ Location extra ) {
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = extra;
+ errors_.push_back( info );
+ return false;
+ }
- Token comma;
- if ( !readToken( comma )
- || ( comma.type_ != tokenObjectEnd &&
- comma.type_ != tokenArraySeparator &&
- comma.type_ != tokenComment ) )
- {
- return addErrorAndRecover( "Missing ',' or '}' in object declaration",
- comma,
- tokenObjectEnd );
- }
- bool finalizeTokenOk = true;
- while ( comma.type_ == tokenComment &&
- finalizeTokenOk )
- finalizeTokenOk = readToken( comma );
- if ( comma.type_ == tokenObjectEnd )
- return true;
- }
- return addErrorAndRecover( "Missing '}' or object member name",
- tokenName,
- tokenObjectEnd );
-}
+ bool
+ Reader::recoverFromError( TokenType skipUntilToken ) {
+ int errorCount = int(errors_.size());
+ Token skip;
+ while ( true ) {
+ if ( !readToken(skip) )
+ // discard errors caused by recovery
+ errors_.resize( errorCount );
+ if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream )
+ break;
+ }
+ errors_.resize( errorCount );
+ return false;
+ }
+ bool
+ Reader::addErrorAndRecover( const std::string &message,
+ Token &token,
+ TokenType skipUntilToken ) {
+ addError( message, token );
+ return recoverFromError( skipUntilToken );
+ }
-bool
-Reader::readArray( Token &tokenStart )
-{
- currentValue() = Value( );
- skipSpaces();
- if ( *current_ == ']' ) // empty array
- {
- Token endArray;
- readToken( endArray );
- return true;
- }
- int index = 0;
- while ( true )
- {
- Value &value = currentValue()[ index++ ];
- nodes_.push( &value );
- bool ok = readValue();
- nodes_.pop();
- if ( !ok ) // error already set
- return recoverFromError( tokenArrayEnd );
+ Value &
+ Reader::currentValue() {
+ return *(nodes_.top());
+ }
- Token token;
- if ( !readToken( token )
- || ( token.type_ != tokenArraySeparator &&
- token.type_ != tokenArrayEnd ) )
- {
- return addErrorAndRecover( "Missing ',' or ']' in array declaration",
- token,
- tokenArrayEnd );
- }
- if ( token.type_ == tokenArrayEnd )
- break;
- }
- return true;
-}
+ Reader::Char
+ Reader::getNextChar() {
+ if ( current_ == end_ )
+ return 0;
+ return *current_++;
+ }
+ void
+ Reader::getLocationLineAndColumn( Location location,
+ int &line,
+ int &column ) const
+ {
+ Location current = begin_;
+ Location lastLineStart = current;
+ line = 0;
+ while ( current < location && current != end_ ) {
+ Char c = *current++;
+ if ( c == '\r' ) {
+ if ( *current == '\n' )
+ ++current;
+ lastLineStart = current;
+ ++line;
+ }
+ else if ( c == '\n' ) {
+ lastLineStart = current;
+ ++line;
+ }
+ }
+ // column & line start at 1
+ column = int(location - lastLineStart) + 1;
+ ++line;
+ }
-bool
-Reader::decodeNumber( Token &token )
-{
- bool isDouble = false;
- for ( Location inspect = token.start_; inspect != token.end_; ++inspect )
- {
- isDouble = isDouble
- || in( *inspect, '.', 'e', 'E', '+' )
- || ( *inspect == '-' && inspect != token.start_ );
- }
- if ( isDouble )
- return decodeDouble( token );
- Location current = token.start_;
- bool isNegative = *current == '-';
- if ( isNegative )
- ++current;
- unsigned int threshold = std::numeric_limits<int>::max() / 10;
- //: Value::maxUInt) / 10;
- unsigned int value = 0;
- while ( current < token.end_ )
- {
- Char c = *current++;
- if ( c < '0' || c > '9' )
- return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
- if ( value >= threshold )
- return decodeDouble( token );
- value = value * 10 + (unsigned int)(c - '0');
- }
- if ( isNegative )
- currentValue() = Value(- (int)value );
- else if ( value <= std::numeric_limits<int>::max() )
- currentValue() = Value( (int)value );
- else
- currentValue() = Value((int)value );
- return true;
-}
+ std::string
+ Reader::getLocationLineAndColumn( Location location ) const
+ {
+ int line, column;
+ getLocationLineAndColumn( location, line, column );
+ char buffer[18+16+16+1];
+ sprintf( buffer, "Line %d, Column %d", line, column );
+ return buffer;
+ }
+ std::string
+ Reader::getFormatedErrorMessages() const
+ {
+ std::string formattedMessage;
+ for ( Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError ) {
+ const ErrorInfo &error = *itError;
+ formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n";
+ formattedMessage += " " + error.message_ + "\n";
+ if ( error.extra_ )
+ formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n";
+ }
+ return formattedMessage;
+ }
-bool
-Reader::decodeDouble( Token &token )
-{
- double value = 0;
- const int bufferSize = 32;
- int count;
- int length = int(token.end_ - token.start_);
- if ( length <= bufferSize )
- {
- Char buffer[bufferSize];
- memcpy( buffer, token.start_, length );
- buffer[length] = 0;
- count = sscanf( buffer, "%lf", &value );
- }
- else
- {
- std::string buffer( token.start_, token.end_ );
- count = sscanf( buffer.c_str(), "%lf", &value );
- }
+ std::istream& operator>>( std::istream &sin, Value &root ) {
+ Json::Reader reader;
+ bool ok = reader.parse(sin, root, true);
+ //JSON_ASSERT( ok );
+ if (!ok) throw std::runtime_error(reader.getFormatedErrorMessages());
+ return sin;
+ }
- if ( count != 1 )
- return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
- currentValue() = value;
- return true;
-}
-
-
-bool
-Reader::decodeString( Token &token )
-{
- std::string decoded;
- if ( !decodeString( token, decoded ) )
- return false;
- currentValue() = decoded;
- return true;
-}
-
-
-bool
-Reader::decodeString( Token &token, std::string &decoded )
-{
- decoded.reserve( token.end_ - token.start_ - 2 );
- Location current = token.start_ + 1; // skip '"'
- Location end = token.end_ - 1; // do not include '"'
- while ( current != end )
- {
- Char c = *current++;
- if ( c == '"' )
- break;
- else if ( c == '\\' )
- {
- if ( current == end )
- return addError( "Empty escape sequence in string", token, current );
- Char escape = *current++;
- switch ( escape )
- {
- case '"': decoded += '"'; break;
- case '/': decoded += '/'; break;
- case '\\': decoded += '\\'; break;
- case 'b': decoded += '\b'; break;
- case 'f': decoded += '\f'; break;
- case 'n': decoded += '\n'; break;
- case 'r': decoded += '\r'; break;
- case 't': decoded += '\t'; break;
- case 'u':
- {
- unsigned int unicode;
- if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) )
- return false;
- // @todo encode unicode as utf8.
- // @todo remember to alter the writer too.
- }
- break;
- default:
- return addError( "Bad escape sequence in string", token, current );
- }
- }
- else
- {
- decoded += c;
- }
- }
- return true;
-}
-
-
-bool
-Reader::decodeUnicodeEscapeSequence( Token &token,
- Location ¤t,
- Location end,
- unsigned int &unicode )
-{
- if ( end - current < 4 )
- return addError( "Bad unicode escape sequence in string: four digits expected.", token, current );
- unicode = 0;
- for ( int index =0; index < 4; ++index )
- {
- Char c = *current++;
- unicode *= 16;
- if ( c >= '0' && c <= '9' )
- unicode += c - '0';
- else if ( c >= 'a' && c <= 'f' )
- unicode += c - 'a' + 10;
- else if ( c >= 'A' && c <= 'F' )
- unicode += c - 'A' + 10;
- else
- return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current );
- }
- return true;
-}
-
-
-bool
-Reader::addError( const std::string &message,
- Token &token,
- Location extra )
-{
- ErrorInfo info;
- info.token_ = token;
- info.message_ = message;
- info.extra_ = extra;
- errors_.push_back( info );
- return false;
-}
-
-
-bool
-Reader::recoverFromError( TokenType skipUntilToken )
-{
- int errorCount = int(errors_.size());
- Token skip;
- while ( true )
- {
- if ( !readToken(skip) )
- errors_.resize( errorCount ); // discard errors caused by recovery
- if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream )
- break;
- }
- errors_.resize( errorCount );
- return false;
-}
-
-
-bool
-Reader::addErrorAndRecover( const std::string &message,
- Token &token,
- TokenType skipUntilToken )
-{
- addError( message, token );
- return recoverFromError( skipUntilToken );
-}
-
-
-Value &
-Reader::currentValue()
-{
- return *(nodes_.top());
-}
-
-
-Reader::Char
-Reader::getNextChar()
-{
- if ( current_ == end_ )
- return 0;
- return *current_++;
-}
-
-
-void
-Reader::getLocationLineAndColumn( Location location,
- int &line,
- int &column ) const
-{
- Location current = begin_;
- Location lastLineStart = current;
- line = 0;
- while ( current < location && current != end_ )
- {
- Char c = *current++;
- if ( c == '\r' )
- {
- if ( *current == '\n' )
- ++current;
- lastLineStart = current;
- ++line;
- }
- else if ( c == '\n' )
- {
- lastLineStart = current;
- ++line;
- }
- }
- // column & line start at 1
- column = int(location - lastLineStart) + 1;
- ++line;
-}
-
-
-std::string
-Reader::getLocationLineAndColumn( Location location ) const
-{
- int line, column;
- getLocationLineAndColumn( location, line, column );
- char buffer[18+16+16+1];
- sprintf( buffer, "Line %d, Column %d", line, column );
- return buffer;
-}
-
-
-std::string
-Reader::getFormatedErrorMessages() const
-{
- std::string formattedMessage;
- for ( Errors::const_iterator itError = errors_.begin();
- itError != errors_.end();
- ++itError )
- {
- const ErrorInfo &error = *itError;
- formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n";
- formattedMessage += " " + error.message_ + "\n";
- if ( error.extra_ )
- formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n";
- }
- return formattedMessage;
-}
-
-
-std::istream& operator>>( std::istream &sin, Value &root )
-{
- Json::Reader reader;
- bool ok = reader.parse(sin, root, true);
- //JSON_ASSERT( ok );
- if (!ok) throw std::runtime_error(reader.getFormatedErrorMessages());
- return sin;
-}
-
-
-} // namespace Json
+} // namespace Json
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/json_reader.h
--- a/zconf++/json_reader.h Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/json_reader.h Wed Jan 11 07:34:43 2012 +0100
@@ -38,175 +38,175 @@
#define arrayValue ZRouter::array_leaf
#define Value ZRouter::Leaf
#define JSON_API
-namespace Json {
+namespace Json
+{
- class Value;
+ class Value;
- /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a Value.
- *
- *
- */
- class JSON_API Reader
- {
- public:
- typedef char Char;
- typedef const Char *Location;
+ /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a Value.
+ *
+ *
+ */
+ class JSON_API Reader
+ {
+ public:
+ typedef char Char;
+ typedef const Char *Location;
- Reader();
+ Reader();
- /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
- * \param document UTF-8 encoded string containing the document to read.
- * \param root [out] Contains the root value of the document if it was
- * successfully parsed.
- * \param collectComments \c true to collect comment and allow writing them back during
- * serialization, \c false to discard comments.
- * \return \c true if the document was successfully parsed, \c false if an error occurred.
- */
- bool parse( const std::string &document,
- Value &root,
- bool collectComments = true );
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
+ * \param document UTF-8 encoded string containing the document to read.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing them back during
+ * serialization, \c false to discard comments.
+ * \return \c true if the document was successfully parsed, \c false if an error occurred.
+ */
+ bool parse( const std::string &document,
+ Value &root,
+ bool collectComments = true );
- /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
- * \param document UTF-8 encoded string containing the document to read.
- * \param root [out] Contains the root value of the document if it was
- * successfully parsed.
- * \param collectComments \c true to collect comment and allow writing them back during
- * serialization, \c false to discard comments.
- * \return \c true if the document was successfully parsed, \c false if an error occurred.
- */
- bool parse( const char *beginDoc, const char *endDoc,
- Value &root,
- bool collectComments = true );
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> document.
+ * \param document UTF-8 encoded string containing the document to read.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing them back during
+ * serialization, \c false to discard comments.
+ * \return \c true if the document was successfully parsed, \c false if an error occurred.
+ */
+ bool parse( const char *beginDoc, const char *endDoc,
+ Value &root,
+ bool collectComments = true );
- /// \brief Parse from input stream.
- /// \see Json::operator>>(std::istream&, Json::Value&).
- bool parse( std::istream&,
- Value &root,
- bool collectComments = true );
+ /// \brief Parse from input stream.
+ /// \see Json::operator>>(std::istream&, Json::Value&).
+ bool parse( std::istream&,
+ Value &root,
+ bool collectComments = true );
- /** \brief Returns a user friendly string that list errors in the parsed document.
- * \return Formatted error message with the list of errors with their location in
- * the parsed document. An empty string is returned if no error occurred
- * during parsing.
- */
- std::string getFormatedErrorMessages() const;
+ /** \brief Returns a user friendly string that list errors in the parsed document.
+ * \return Formatted error message with the list of errors with their location in
+ * the parsed document. An empty string is returned if no error occurred
+ * during parsing.
+ */
+ std::string getFormatedErrorMessages() const;
- private:
- enum TokenType
- {
- tokenEndOfStream = 0,
- tokenObjectBegin,
- tokenObjectEnd,
- tokenArrayBegin,
- tokenArrayEnd,
- tokenString,
- tokenNumber,
- tokenTrue,
- tokenFalse,
- tokenNull,
- tokenArraySeparator,
- tokenMemberSeparator,
- tokenComment,
- tokenError
- };
+ private:
+ enum TokenType
+ {
+ tokenEndOfStream = 0,
+ tokenObjectBegin,
+ tokenObjectEnd,
+ tokenArrayBegin,
+ tokenArrayEnd,
+ tokenString,
+ tokenNumber,
+ tokenTrue,
+ tokenFalse,
+ tokenNull,
+ tokenArraySeparator,
+ tokenMemberSeparator,
+ tokenComment,
+ tokenError
+ };
- class Token
- {
- public:
- TokenType type_;
- Location start_;
- Location end_;
- };
+ class Token
+ {
+ public:
+ TokenType type_;
+ Location start_;
+ Location end_;
+ };
- class ErrorInfo
- {
- public:
- Token token_;
- std::string message_;
- Location extra_;
- };
+ class ErrorInfo
+ {
+ public:
+ Token token_;
+ std::string message_;
+ Location extra_;
+ };
- typedef std::deque<ErrorInfo> Errors;
+ typedef std::deque<ErrorInfo> Errors;
- bool expectToken( TokenType type, Token &token, const char *message );
- bool readToken( Token &token );
- void skipSpaces();
- bool match( Location pattern,
- int patternLength );
- bool readComment();
- bool readCStyleComment();
- bool readCppStyleComment();
- bool readString();
- void readNumber();
- bool readValue();
- bool readObject( Token &token );
- bool readArray( Token &token );
- bool decodeNumber( Token &token );
- bool decodeString( Token &token );
- bool decodeString( Token &token, std::string &decoded );
- bool decodeDouble( Token &token );
- bool decodeUnicodeEscapeSequence( Token &token,
- Location ¤t,
- Location end,
- unsigned int &unicode );
- bool addError( const std::string &message,
- Token &token,
- Location extra = 0 );
- bool recoverFromError( TokenType skipUntilToken );
- bool addErrorAndRecover( const std::string &message,
- Token &token,
- TokenType skipUntilToken );
- void skipUntilSpace();
- Value ¤tValue();
- Char getNextChar();
- void getLocationLineAndColumn( Location location,
- int &line,
- int &column ) const;
- std::string getLocationLineAndColumn( Location location ) const;
- /* void addComment( Location begin,
- Location end,
- CommentPlacement placement );*/
- void skipCommentTokens( Token &token );
-
- typedef std::stack<Value *> Nodes;
- Nodes nodes_;
- Errors errors_;
- std::string document_;
- Location begin_;
- Location end_;
- Location current_;
- Location lastValueEnd_;
- Value *lastValue_;
- std::string commentsBefore_;
- bool collectComments_;
- };
+ bool expectToken( TokenType type, Token &token, const char *message );
+ bool readToken( Token &token );
+ void skipSpaces();
+ bool match( Location pattern,
+ int patternLength );
+ bool readComment();
+ bool readCStyleComment();
+ bool readCppStyleComment();
+ bool readString();
+ void readNumber();
+ bool readValue();
+ bool readObject( Token &token );
+ bool readArray( Token &token );
+ bool decodeNumber( Token &token );
+ bool decodeString( Token &token );
+ bool decodeString( Token &token, std::string &decoded );
+ bool decodeDouble( Token &token );
+ bool decodeUnicodeEscapeSequence( Token &token,
+ Location ¤t,
+ Location end,
+ unsigned int &unicode );
+ bool addError( const std::string &message,
+ Token &token,
+ Location extra = 0 );
+ bool recoverFromError( TokenType skipUntilToken );
+ bool addErrorAndRecover( const std::string &message,
+ Token &token,
+ TokenType skipUntilToken );
+ void skipUntilSpace();
+ Value ¤tValue();
+ Char getNextChar();
+ void getLocationLineAndColumn( Location location,
+ int &line,
+ int &column ) const;
+ std::string getLocationLineAndColumn( Location location ) const;
+ /* void addComment( Location begin,
+ Location end,
+ CommentPlacement placement );*/
+ void skipCommentTokens( Token &token );
- /** \brief Read from 'sin' into 'root'.
+ typedef std::stack<Value *> Nodes;
+ Nodes nodes_;
+ Errors errors_;
+ std::string document_;
+ Location begin_;
+ Location end_;
+ Location current_;
+ Location lastValueEnd_;
+ Value *lastValue_;
+ std::string commentsBefore_;
+ bool collectComments_;
+ };
- Always keep comments from the input JSON.
+ /** \brief Read from 'sin' into 'root'.
- This can be used to read a file into a particular sub-object.
- For example:
- \code
- Json::Value root;
- cin >> root["dir"]["file"];
- cout << root;
- \endcode
- Result:
- \verbatim
- {
- "dir": {
- "file": {
- // The input stream JSON would be nested here.
- }
- }
- }
- \endverbatim
- \throw std::exception on parse error.
- \see Json::operator<<()
- */
- std::istream& operator>>( std::istream&, Value& );
+ Always keep comments from the input JSON.
-} // namespace Json
+ This can be used to read a file into a particular sub-object.
+ For example:
+ \code
+ Json::Value root;
+ cin >> root["dir"]["file"];
+ cout << root;
+ \endcode
+ Result:
+ \verbatim
+ {
+ "dir": {
+ "file": {
+ // The input stream JSON would be nested here.
+ }
+ }
+ }
+ \endverbatim
+ \throw std::exception on parse error.
+ \see Json::operator<<()
+ */
+ std::istream& operator>>( std::istream&, Value& );
-#endif // CPPTL_JSON_READER_H_INCLUDED
+} // namespace Json
+#endif // CPPTL_JSON_READER_H_INCLUDED
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/model.cc
--- a/zconf++/model.cc Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/model.cc Wed Jan 11 07:34:43 2012 +0100
@@ -29,62 +29,63 @@
using namespace std;
//using namespace boost;
-namespace ZRouter {
+namespace ZRouter
+{
-Model::Model() : Leaf() {
+ Model::Model() : Leaf() {
-}
+ }
-Leaf Model::populate_system() {
- Leaf s;
- s["hostname"] = false;
- s["extensions"] = Leaf();
- return s;
-}
+ Leaf Model::populate_system() {
+ Leaf s;
+ s["hostname"] = false;
+ s["extensions"] = Leaf();
+ return s;
+ }
-Leaf Model::load_state() {
- Leaf s;
- s["loaded"] = false;
- return s;
-}
+ Leaf Model::load_state() {
+ Leaf s;
+ s["loaded"] = false;
+ return s;
+ }
-Leaf Model::load_config() {
- Leaf s;
- s["loaded"] = false;
- s["somestring"] = "So broken";
- return s;
-}
+ Leaf Model::load_config() {
+ Leaf s;
+ s["loaded"] = false;
+ s["somestring"] = "So broken";
+ return s;
+ }
-void Model::populate() {
- /*root.push_back( Pair( "config", mObject()) );
- root.push_back( Pair( "state", mObject()) );*/
- (*this)["system"] = populate_system();
- (*this)["config"] = load_config();
- (*this)["state"] = load_state();
-}
+ void Model::populate() {
+ /*root.push_back( Pair( "config", mObject()) );
+ root.push_back( Pair( "state", mObject()) );*/
+ (*this)["system"] = populate_system();
+ (*this)["config"] = load_config();
+ (*this)["state"] = load_state();
+ }
+ std::string format_json_string(const std::string &p_str) {
+ return '"' + p_str + '"';
+ }
+ std::string format_json_int(const int p_int) {
+ return boost::lexical_cast<std::string>(p_int);
+ }
-std::string format_json_string(const std::string &p_str) {
- return '"' + p_str + '"';
-}
-std::string format_json_int(const int p_int) {
- return boost::lexical_cast<std::string>(p_int);
-}
+ std::string format_json_real(const double p_real) {
+ return boost::lexical_cast<std::string>(p_real);
+ }
-std::string format_json_real(const double p_real) {
- return boost::lexical_cast<std::string>(p_real);
-}
-
-std::string ModelWriter::write(Leaf& l, const std::string &indent) {
- string rv;
-// for (int c=0; c < l.numChildren(); c++) {
+ std::string ModelWriter::write(Leaf& l, const std::string &indent) {
+ string rv;
+ // for (int c=0; c < l.numChildren(); c++) {
if (l.type() == string_leaf) {
- // cout << " dumping " << " => " << l.get_string() << endl;
+ // cout << " dumping " << " => " << l.get_string() << endl;
//cout << indent << l.get_string() << endl;
rv += format_json_string(l);
- } else if (l.type() == object_leaf) {
+ }
+ else if (l.type() == object_leaf) {
//cout << " dumping " << " => object" << endl;
- rv.reserve(4096); // Reserve just some space to avoid lots of reallocs
+ rv.reserve(4096); // Reserve just some space to avoid lots of reallocs
rv += "{\n";
LeafMap &m = l.map();
LeafMap::iterator it = m.begin();
@@ -94,7 +95,8 @@
rv += indent;
if (first == false) {
rv += ",";
- } else {
+ }
+ else {
first = false;
}
rv += format_json_string(it->first) + ": " + write(it->second, indent+" ") + "\n";
@@ -107,42 +109,50 @@
rv += indent + (*it) + " => " + write(l[*it], indent + "@@@@") + " \n";
//cout << indent << " dumping " << (*it) << " => " << write(l[(*it)], indent + "@@@@") << endl;
}*/
- } else if (l.type() == array_leaf) {
+ }
+ else if (l.type() == array_leaf) {
//cout << " dumping " << " => array" << endl;
- rv.reserve(4096); // Reserve just some space to avoid lots of reallocs
+ rv.reserve(4096); // Reserve just some space to avoid lots of reallocs
rv += "[\n";
LeafArray &a = l.array();
for (int c=0; c < a.size(); c++) {
rv += indent /*+ Int2String(c) + " => "*/ + (c>0 ? "," : "") + write(a[c], indent+" ") + "\n";
}
rv += indent + "]";
- } else if (l.type() == real_leaf) {
+ }
+ else if (l.type() == real_leaf) {
rv += format_json_real(l.get_real());
- } else if (l.type() == numeric_leaf) {
+ }
+ else if (l.type() == numeric_leaf) {
rv += format_json_int(l.get_int());
-/* Actions should only be dumped on request */
- } else if (l.type() == action_leaf) {
- rv += "\"@ACTION@\"";
- } else if (l.type() == empty_leaf) {
+ /* Actions should only be dumped on request */
+ }
+ else if (l.type() == action_leaf) {
+ rv += "\"@ACTION@\"";
+ }
+ else if (l.type() == empty_leaf) {
rv += "null";
- } else if (l.type() == boolean_leaf) {
+ }
+ else if (l.type() == boolean_leaf) {
rv += l.get_bool() ? "true" : "false";
- } else {
+ }
+ else {
throw std::string("FIXME");
- //cout << "Foo biz baz" << endl;
+ //cout << "Foo biz baz" << endl;
}
-// }
- return rv;
-}
+ // }
+ return rv;
+ }
-void ModelWriter::write(std::stringstream &buf, Leaf& l, const std::string &indent) {
-// for (int c=0; c < l.numChildren(); c++) {
+ void ModelWriter::write(std::stringstream &buf, Leaf& l, const std::string &indent) {
+ // for (int c=0; c < l.numChildren(); c++) {
buf << indent;
if (l.type() == string_leaf) {
- // cout << " dumping " << " => " << l.get_string() << endl;
+ // cout << " dumping " << " => " << l.get_string() << endl;
//cout << indent << l.get_string() << endl;
buf << format_json_string(l);
- } else if (l.type() == object_leaf) {
+ }
+ else if (l.type() == object_leaf) {
//cout << " dumping " << " => object" << endl;
buf << "{\n";
LeafMap &m = l.map();
@@ -153,7 +163,8 @@
buf << indent;
if (first == false) {
buf << ",";
- } else {
+ }
+ else {
first = false;
}
buf << format_json_string(it->first) << ": " << write(it->second, indent+" ") << "\n";
@@ -166,7 +177,8 @@
rv += indent + (*it) + " => " + write(l[*it], indent + "@@@@") + " \n";
//cout << indent << " dumping " << (*it) << " => " << write(l[(*it)], indent + "@@@@") << endl;
}*/
- } else if (l.type() == array_leaf) {
+ }
+ else if (l.type() == array_leaf) {
//cout << " dumping " << " => array" << endl;
buf << "[\n";
LeafArray &a = l.array();
@@ -175,23 +187,30 @@
buf << indent /*+ Int2String(c) + " => "*/ << (c>0 ? "," : "") << write(a[c], indent+" ") << "\n";
}
buf << indent << "]";
- } else if (l.type() == real_leaf) {
+ }
+ else if (l.type() == real_leaf) {
buf << format_json_real(l.get_real());
- } else if (l.type() == numeric_leaf) {
+ }
+ else if (l.type() == numeric_leaf) {
buf << format_json_int(l.get_int());
- } else if (l.type() == action_leaf) {
+ }
+ else if (l.type() == action_leaf) {
buf << "\"@ACTION@\"";
- } else if (l.type() == empty_leaf) {
+ }
+ else if (l.type() == empty_leaf) {
buf << "null";
- } else {
+ }
+ else {
throw std::string("FIXME");
- //cout << "Foo biz baz" << endl;
+ //cout << "Foo biz baz" << endl;
}
-// }
+ // }
+ }
}
-}
+
+
/*
void dump_json(mObject &root) {
- std::cout << write_formatted(root) << std::endl;
+ std::cout << write_formatted(root) << std::endl;
}
*/
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/model.h
--- a/zconf++/model.h Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/model.h Wed Jan 11 07:34:43 2012 +0100
@@ -32,11 +32,12 @@
# include <list>
# include <iostream>
-namespace ZRouter {
+namespace ZRouter
+{
enum LeafType { empty_leaf, object_leaf, array_leaf, numeric_leaf, boolean_leaf, string_leaf, real_leaf, action_leaf, event_leaf };
class ModelWriter;
class Leaf;
- typedef Leaf& LeafRef;
+ typedef Leaf& LeafRef;
// abstract base class
class IModelActionHandler
@@ -45,13 +46,16 @@
// two possible functions to call member function. virtual cause derived
// classes will use a pointer to an object and a pointer to a member function
// to make the function call
- virtual Leaf handler(const std::string &uri, LeafRef pSelf, LeafRef pRequest )=0; // call using operator
- virtual LeafRef describe()=0; // call using function
+ // call using operator
+ virtual Leaf handler(const std::string &uri, LeafRef pSelf, LeafRef pRequest )=0;
+ // call using function
+ virtual LeafRef describe()=0;
};
typedef std::map<std::string, Leaf> LeafMap;
typedef std::vector<Leaf> LeafArray;
- class Leaf {
+ class Leaf
+ {
protected:
LeafType m_type;
std::string m_value_string;
@@ -61,19 +65,20 @@
IModelActionHandler *m_action_handler;
int m_value_int;
double m_value_real;
- void check_type_const(const LeafType t) const {
+ void check_type_const(const LeafType t) const
+ {
if (m_type == empty_leaf || m_type == t) {
// Unused leaf, let's just change type
//m_type = t;
- } else if (m_type != t)
- throw std::string("Type mismatch2");
+ } else if (m_type != t)
+ throw std::string("Type mismatch2");
};
void check_type(LeafType t) {
if (m_type == empty_leaf) {
// Unused leaf, let's just change type
m_type = t;
- } else if (m_type != t)
- throw std::string("Type mismatch");
+ } else if (m_type != t)
+ throw std::string("Type mismatch");
};
public:
LeafArray& array() {
@@ -86,14 +91,14 @@
}
Leaf call(LeafRef p_request) {
check_type_const(action_leaf);
- return m_action_handler->handler("dummy", *this, p_request);
+ return m_action_handler->handler("dummy", *this, p_request);
}
LeafRef describe() {
check_type_const(action_leaf);
return m_action_handler->describe();
}
/*Leaf& operator=( const bool p_bool) {
- *this = Leaf(p_bool);
+ *this = Leaf(p_bool);
return *this;
}*/
/*
@@ -109,72 +114,82 @@
}*/
const Leaf& operator=(const Leaf& source) {
//std::cout << "Copy2= const " << source.m_value_string << std::endl;
- /* if (source.is_null()) {
- //std::cout << "copy null" << std::endl;
- //impl = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
- }*/
+ /* if (source.is_null()) {
+ //std::cout << "copy null" << std::endl;
+ //impl = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
+ }*/
m_type = source.m_type;
if (m_type == empty_leaf) {
- } else if (m_type == string_leaf) {
+ }
+ else if (m_type == string_leaf) {
m_value_string = source.m_value_string;
- } else if (m_type == numeric_leaf || m_type == boolean_leaf) {
+ }
+ else if (m_type == numeric_leaf || m_type == boolean_leaf) {
m_value_int = source.m_value_int;
- } else if (m_type == real_leaf) {
- m_value_real = source.m_value_real;
- } else if (m_type == object_leaf) {
- m_map = source.m_map;
- } else if (m_type == array_leaf) {
- m_array = source.m_array;
- } else if (m_type == action_leaf) {
- m_action_handler = source.m_action_handler;
+ }
+ else if (m_type == real_leaf) {
+ m_value_real = source.m_value_real;
+ }
+ else if (m_type == object_leaf) {
+ m_map = source.m_map;
+ }
+ else if (m_type == array_leaf) {
+ m_array = source.m_array;
+ }
+ else if (m_type == action_leaf) {
+ m_action_handler = source.m_action_handler;
}
return *this;
- };
+ };
Leaf() : m_type(empty_leaf), m_parent(NULL) { };
Leaf(const Leaf& source)
: m_type(source.m_type)
- , m_parent(NULL)
- {
+ , m_parent(NULL) {
if (m_type == empty_leaf) {
return;
- } else if (m_type == string_leaf) {
+ }
+ else if (m_type == string_leaf) {
m_value_string = source.m_value_string;
- } else if (m_type == numeric_leaf || m_type == boolean_leaf) {
+ }
+ else if (m_type == numeric_leaf || m_type == boolean_leaf) {
m_value_int = source.m_value_int;
- } else if (m_type == real_leaf) {
- m_value_real = source.m_value_real;
- } else if (m_type == object_leaf) {
- m_map = source.m_map;
- } else if (m_type == array_leaf) {
- m_array = source.m_array;
- } else if (m_type == action_leaf) {
- m_action_handler = source.m_action_handler;
+ }
+ else if (m_type == real_leaf) {
+ m_value_real = source.m_value_real;
+ }
+ else if (m_type == object_leaf) {
+ m_map = source.m_map;
+ }
+ else if (m_type == array_leaf) {
+ m_array = source.m_array;
+ }
+ else if (m_type == action_leaf) {
+ m_action_handler = source.m_action_handler;
}
//std::cout << "Copy () const " << std::endl;
- //FIXME:
- };
-// Leaf_Impl(const LeafType);
+ //FIXME:
+ };
+ // Leaf_Impl(const LeafType);
Leaf(const std::string& p_str ) : m_value_string(p_str), m_type(string_leaf) {
- //std::cout << "Creating string leaf : " << p_str << std::endl;
+ //std::cout << "Creating string leaf : " << p_str << std::endl;
};
explicit Leaf( IModelActionHandler* p_action_hndl) : m_action_handler(p_action_hndl), m_type(action_leaf) { ; }
Leaf(const int p_int ) : m_value_int(p_int), m_type(numeric_leaf) { };
explicit Leaf(const bool p_bool ) : m_value_int(p_bool), m_type(boolean_leaf) { };
-
+
Leaf(const char* p_str) : m_value_string(p_str), m_type(string_leaf) { };
explicit Leaf(const double& p_val) :m_value_real(p_val), m_type(real_leaf) {
}
-/* std::list<std::string> keys() const {
- std::list<std::string> kmap;
-
- for(std::map<std::string, boost::shared_ptr<Leaf_Impl> >::const_iterator it = m_map.begin(); it != m_map.end(); it++)
- {
- kmap.push_back(it->first);
- }
+ /* std::list<std::string> keys() const {
+ std::list<std::string> kmap;
+ for(std::map<std::string, boost::shared_ptr<Leaf_Impl> >::const_iterator it = m_map.begin(); it != m_map.end(); it++)
+ {
+ kmap.push_back(it->first);
+ }
- return kmap;
- } */
+ return kmap;
+ } */
Leaf& operator[](const std::string& p_key) {
check_type(object_leaf);
if (m_map.find(p_key) == m_map.end()) {
@@ -190,38 +205,41 @@
// m_map[p_key] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
return (m_map.find(p_key)->second);
}*/
- const LeafType type() const {
+ const LeafType type() const
+ {
return m_type;
}
- LeafRef parent() const {
+ LeafRef parent() const
+ {
return *m_parent;
}
-/* const Leaf& operator[](const int p_idx) const {
- check_type_const(array_leaf);
- if (p_idx >= m_array.size())
- throw std::string("Error!");
- //m_array.resize(p_idx+1, boost::shared_ptr<Leaf_Impl>((Leaf_Impl*)NULL));
- //m_array[p_idx] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
- //if (m_array[p_idx].get() == NULL)
- // m_array[p_idx] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
- //std::cout << "FUCKED" << std::endl;
- return m_array[p_idx];
- }*/
+ /* const Leaf& operator[](const int p_idx) const {
+ check_type_const(array_leaf);
+ if (p_idx >= m_array.size())
+ throw std::string("Error!");
+ //m_array.resize(p_idx+1, boost::shared_ptr<Leaf_Impl>((Leaf_Impl*)NULL));
+ //m_array[p_idx] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
+ //if (m_array[p_idx].get() == NULL)
+ // m_array[p_idx] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
+ //std::cout << "FUCKED" << std::endl;
+ return m_array[p_idx];
+ }*/
Leaf& operator[](const int p_idx) {
check_type(array_leaf);
- // if (m_array.find(p_key) == m_map.end())
- // m_map[p_key] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
+ // if (m_array.find(p_key) == m_map.end())
+ // m_map[p_key] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
if (p_idx >= m_array.size()) {
m_array.resize(p_idx+1, Leaf());
m_array[p_idx].m_parent = this;
}
- //m_array[p_idx] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
+ //m_array[p_idx] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
//if (m_array[p_idx].get() == NULL)
// m_array[p_idx] = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
- //std::cout << "FUCKED" << std::endl;
+ //std::cout << "FUCKED" << std::endl;
return m_array[p_idx];
}
- const std::string get_string() const {
+ const std::string get_string() const
+ {
//std::cout << "get_string : " << m_type << " " << m_value_string << std::endl;
check_type_const(string_leaf);
return m_value_string;
@@ -235,12 +253,13 @@
check_type(array_leaf);
m_array.push_back(p_impl);
};
- const int numChildren() const {
+ const int numChildren() const
+ {
if (m_type == object_leaf)
return m_map.size();
else if (m_type == array_leaf)
return m_array.size();
- else
+ else
return 0;
}
operator const std::string () {
@@ -263,7 +282,8 @@
check_type_const(string_leaf);
return m_value_string.c_str();
}
- const bool is_null() const {
+ const bool is_null() const
+ {
return m_type == empty_leaf;
}
const bool operator==(const std::string source) {
@@ -274,70 +294,71 @@
check_type(string_leaf);
return m_value_string == std::string(p_cstr);
}
-/*
- const Leaf& operator=(const Leaf& source) {
- //std::cout << "Copy= const " << source.impl->get_string() << std::endl;
- if (source.is_null()) {
- std::cout << "copy null" << std::endl;
+ /*
+ const Leaf& operator=(const Leaf& source) {
+ //std::cout << "Copy= const " << source.impl->get_string() << std::endl;
+ if (source.is_null()) {
+ std::cout << "copy null" << std::endl;
+ }
+ m_type = source.m_type;
+ m_value_string = source.m_value_string;
+ m_value_int = source.m_value_int;
+ m_map = source.m_map;
+ m_array = source.m_array;
+ return *this;
+ }; */
+ };
+ /* public:
+ // Constructors
+ Leaf() : impl(new Leaf_Impl() ) { std::cout << "Default const : " << std::endl; };
+ Leaf(const Leaf& source) {
+ std::cout << "Copy (NOT IMPL) const " << source.impl->get_string() << std::endl;
+ //FIXME:
+ };
+ const Leaf& operator=(const Leaf& source) {
+ //std::cout << "Copy= const " << source.impl->get_string() << std::endl;
+ if (source.is_null()) {
+ std::cout << "copy null" << std::endl;
+ impl = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
+ }
+ else
+ *impl = *source.impl;
+ return *this;
+ };
+ Leaf(boost::shared_ptr<Leaf_Impl> p_impl) : impl(p_impl ) {
+ // std::cout << "Const const " << p_impl << std::endl;
+ };
+ // Leaf operator[](const std::string& p_value);
+ LEAF_IMPL_WRAP_WITH_ARG1(Leaf, operator[], const std::string&);
+ LEAF_IMPL_WRAP_CONST_WITH_ARG1(Leaf, operator[], const std::string&);
+ LEAF_IMPL_WRAP_WITH_ARG1(Leaf, operator[], const int);
+ LEAF_IMPL_WRAP_CONST_WITH_ARG1(Leaf, operator[], const int);
+ LEAF_IMPL_CNSTR(const std::string&);
+ LEAF_IMPL_CNSTR(const char*);
+ LEAF_IMPL_CNSTR(const int);
+ //Leaf(const std::string& p_value);
+ LEAF_IMPL_WRAP_CONST(const bool, is_null);
+ LEAF_IMPL_WRAP_CONST(const int, numChildren);
+ LEAF_IMPL_WRAP_CONST(const LeafType, type);
+ LEAF_IMPL_WRAP(const std::string, get_string);
+ LEAF_IMPL_WRAP_CONST(const std::string, get_string);
+ LEAF_IMPL_WRAP_CONST(std::list<std::string>, keys);
+ //std::list<std::string> keys() const {
+ LEAF_IMPL_WRAP(const std::string, to_json);
+ //LEAF_IMPL_WRAP_WITH_ARG1(void, push_back, Leaf);
+ void push_back(const Leaf& p_leaf) {
+ impl->push_back(p_leaf.impl);
}
- m_type = source.m_type;
- m_value_string = source.m_value_string;
- m_value_int = source.m_value_int;
- m_map = source.m_map;
- m_array = source.m_array;
- return *this;
- }; */
- };
-/* public:
- // Constructors
- Leaf() : impl(new Leaf_Impl() ) { std::cout << "Default const : " << std::endl; };
- Leaf(const Leaf& source) {
- std::cout << "Copy (NOT IMPL) const " << source.impl->get_string() << std::endl;
- //FIXME:
- };
- const Leaf& operator=(const Leaf& source) {
- //std::cout << "Copy= const " << source.impl->get_string() << std::endl;
- if (source.is_null()) {
- std::cout << "copy null" << std::endl;
- impl = boost::shared_ptr<Leaf_Impl>(new Leaf_Impl());
+ operator const char * () {
+ return impl->get_string().c_str();
}
- else
- *impl = *source.impl;
- return *this;
- };
- Leaf(boost::shared_ptr<Leaf_Impl> p_impl) : impl(p_impl ) {
- // std::cout << "Const const " << p_impl << std::endl;
- };
- // Leaf operator[](const std::string& p_value);
- LEAF_IMPL_WRAP_WITH_ARG1(Leaf, operator[], const std::string&);
- LEAF_IMPL_WRAP_CONST_WITH_ARG1(Leaf, operator[], const std::string&);
- LEAF_IMPL_WRAP_WITH_ARG1(Leaf, operator[], const int);
- LEAF_IMPL_WRAP_CONST_WITH_ARG1(Leaf, operator[], const int);
- LEAF_IMPL_CNSTR(const std::string&);
- LEAF_IMPL_CNSTR(const char*);
- LEAF_IMPL_CNSTR(const int);
- //Leaf(const std::string& p_value);
- LEAF_IMPL_WRAP_CONST(const bool, is_null);
- LEAF_IMPL_WRAP_CONST(const int, numChildren);
- LEAF_IMPL_WRAP_CONST(const LeafType, type);
- LEAF_IMPL_WRAP(const std::string, get_string);
- LEAF_IMPL_WRAP_CONST(const std::string, get_string);
- LEAF_IMPL_WRAP_CONST(std::list<std::string>, keys);
- //std::list<std::string> keys() const {
- LEAF_IMPL_WRAP(const std::string, to_json);
- //LEAF_IMPL_WRAP_WITH_ARG1(void, push_back, Leaf);
- void push_back(const Leaf& p_leaf) {
- impl->push_back(p_leaf.impl);
- }
- operator const char * () {
- return impl->get_string().c_str();
- }
- const bool operator== (const std::string &match) const {
- return match == impl->get_string();
- }
- };
-*/
- class Model : public Leaf {
+ const bool operator== (const std::string &match) const {
+ return match == impl->get_string();
+ }
+ };
+ */
+ class Model : public Leaf
+ {
public:
Model();
Leaf load_state();
@@ -345,35 +366,35 @@
Leaf populate_system();
void populate();
};
- class ModelWriter {
+ class ModelWriter
+ {
public:
static std::string write(Leaf& start_leaf, const std::string& indent);
static void write(std::stringstream &dest, Leaf& start_leaf, const std::string& indent);
};
- template <class TClass>
- class TModelActionHandler : public IModelActionHandler {
- protected:
- TClass *m_obj;
- Leaf (TClass::*m_handler)(const std::string& pUri, LeafRef pSelf, LeafRef pRequest);
- LeafRef (TClass::*m_describer)();
- public:
+ template <class TClass>
+ class TModelActionHandler : public IModelActionHandler
+ {
+ protected:
+ TClass *m_obj;
+ Leaf (TClass::*m_handler)(const std::string& pUri, LeafRef pSelf, LeafRef pRequest);
+ LeafRef (TClass::*m_describer)();
+ public:
TModelActionHandler(TClass *pObject, Leaf(TClass::*pHndlr)(const std::string& pUri, LeafRef pSelf, LeafRef pReq), LeafRef(TClass::*pDscrp)())
: m_obj(pObject)
, m_handler(pHndlr)
, m_describer(pDscrp)
- { ; }
+ { ; }
virtual Leaf handler(const std::string &uri, LeafRef pSelf, LeafRef pRequest ) {
return (*m_obj.*m_handler)(uri, pSelf, pRequest);
}
virtual LeafRef describe() {
return (*m_obj.*m_describer)();
}
- };
-// Make it easier to instantiate (less typing)
-#define ACTION_HANDLER(M_CLASS, M_OBJ, M_HANDLER, M_DESCRIBER) \
+ };
+ // Make it easier to instantiate (less typing)
+ #define ACTION_HANDLER(M_CLASS, M_OBJ, M_HANDLER, M_DESCRIBER) \
Leaf(new TModelActionHandler<M_CLASS>(M_OBJ, &M_CLASS::M_HANDLER, &M_CLASS::M_DESCRIBER))
}
-
-
-#endif // __MODEL__H
+#endif // __MODEL__H
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/tests/Makefile
--- a/zconf++/tests/Makefile Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/tests/Makefile Wed Jan 11 07:34:43 2012 +0100
@@ -1,4 +1,4 @@
-CXX=clang++
+#CXX=clang++
CXXFLAGS= -I /usr/local/include -g -I.. -fPIC -Wno-parentheses -DBOOST_USER_CONFIG=\"../boost_user_config.hpp\"
LDFLAGS+= -L /usr/local/lib -lboost_system -ltap
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/utils.cc
--- a/zconf++/utils.cc Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/utils.cc Wed Jan 11 07:34:43 2012 +0100
@@ -29,28 +29,29 @@
using namespace std;
-namespace ZRouter {
+namespace ZRouter
+{
-void dump_string_array(string s) {
- cout << " " << s << " ";
-}
+ void dump_string_array(string s) {
+ cout << " " << s << " ";
+ }
-string chars_to_string(deque<char>::const_iterator is, deque<char>::const_iterator ie) {
- string ret;
- while (is != ie) {
- ret += *is;
- is++;
+ string chars_to_string(deque<char>::const_iterator is, deque<char>::const_iterator ie) {
+ string ret;
+ while (is != ie) {
+ ret += *is;
+ is++;
+ }
+ return ret;
}
- return ret;
-}
-string chars_to_string(deque<unsigned char>::const_iterator is, deque<unsigned char>::const_iterator ie) {
- string ret;
- while (is != ie) {
- ret += *is;
- is++;
+ string chars_to_string(deque<unsigned char>::const_iterator is, deque<unsigned char>::const_iterator ie) {
+ string ret;
+ while (is != ie) {
+ ret += *is;
+ is++;
+ }
+ return ret;
}
- return ret;
-}
}
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/utils.h
--- a/zconf++/utils.h Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/utils.h Wed Jan 11 07:34:43 2012 +0100
@@ -29,13 +29,13 @@
#include <string>
#include <deque>
-namespace ZRouter {
+namespace ZRouter
+{
-std::string chars_to_string(std::deque<char>::const_iterator is, std::deque<char>::const_iterator ie);
-std::string chars_to_string(std::deque<unsigned char>::const_iterator is, std::deque<unsigned char>::const_iterator ie);
+ std::string chars_to_string(std::deque<char>::const_iterator is, std::deque<char>::const_iterator ie);
+ std::string chars_to_string(std::deque<unsigned char>::const_iterator is, std::deque<unsigned char>::const_iterator ie);
-void dump_string_array(std::string s);
+ void dump_string_array(std::string s);
}
-
-#endif // __UTILS__H
+#endif // __UTILS__H
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/zconfig.cc
--- a/zconf++/zconfig.cc Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/zconfig.cc Wed Jan 11 07:34:43 2012 +0100
@@ -32,12 +32,12 @@
#include "zextension.h"
#include "json_reader.h"
-
using namespace ZRouter;
using namespace boost::filesystem;
using namespace std;
-static class Z_Config_Module {
+static class Z_Config_Module
+{
protected:
Leaf *m_running;
Leaf *m_configured;
@@ -55,11 +55,11 @@
}
Leaf clear_interface(std::string &p_if_name) {
- return Leaf(true);
+ return Leaf(true);
}
Leaf clear_all_interfaces() {
- return Leaf(true);
+ return Leaf(true);
}
Leaf build_default_configuration() {
Leaf l;
@@ -67,7 +67,7 @@
// Should at least build based on state
l["config"]["serial"] = 1;
l["config"]["format"] = 1;
- l["system"]["hostname"] = "zouter";
+ l["system"]["hostname"] = "zouter";
l["users"]["admin"]["username"]="admin";
l["users"]["admin"]["description"]="Default ZRouter admin user";
l["users"]["admin"]["password"]="SOMEHASHEDVALUE";
@@ -130,12 +130,13 @@
Json::Reader r;
LeafRef targetLeaf = *m_running;
r.parse(cfgfile, targetLeaf);
- } else {
+ }
+ else {
cout << " - no saved configuration found, building default" << endl;
*m_running = build_default_configuration();
(*m_running)["config"]["modified"] = Leaf(true);
}
- return true;
+ return true;
}
public:
Z_Config_Module() : m_running(NULL), m_configured(NULL) {
@@ -149,4 +150,3 @@
//model["system"]["extensions"]["Platform_Posix_Module"]["vendor"]="ZRouter.org";
return _module.self_init(io, model);
}
-
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/zextension.h
--- a/zconf++/zextension.h Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/zextension.h Wed Jan 11 07:34:43 2012 +0100
@@ -34,22 +34,25 @@
#include "model.h"
-namespace ZRouter {
+namespace ZRouter
+{
typedef bool (*FP_ExtensionInitializer)(boost::asio::io_service&, Model&);
- struct TExtensionData {
+ struct TExtensionData
+ {
std::string name;
int init_priority;
FP_ExtensionInitializer initializer;
};
//boost::function<bool (boost::asio::io_service &, ZRouter::Model &model)> FP_ExtensionInitializer;
//typedef bool (int) FP_ExtensionInitializer;
- //typedef std::map<std::string, FP_ExtensionInitializer> T_ZExtensionMap;
- typedef std::multimap<int, TExtensionData> T_ZExtensionMap;
- class ZExtensionManager {
+ //typedef std::map<std::string, FP_ExtensionInitializer> T_ZExtensionMap;
+ typedef std::multimap<int, TExtensionData> T_ZExtensionMap;
+ class ZExtensionManager
+ {
public:
ZExtensionManager();
static void register_extension(std::string, int priority, FP_ExtensionInitializer);
};
//extern T_ZExtensionMap extension_init_map;
}
-#endif // __ZEXTENSION__H
+#endif // __ZEXTENSION__H
diff -r a34a88b89d44 -r bc7e5c46eec7 zconf++/zrouterhttp.cc
--- a/zconf++/zrouterhttp.cc Wed Jan 11 07:34:11 2012 +0100
+++ b/zconf++/zrouterhttp.cc Wed Jan 11 07:34:43 2012 +0100
@@ -27,7 +27,7 @@
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef WITH_BOOST_SIGNAL_SET
-# include <boost/asio/signal_set.hpp>
+# include <boost/asio/signal_set.hpp>
#endif
#include <iostream>
#include <iterator>
@@ -49,6 +49,7 @@
cout << "ZExtensionManager::" << endl;
}
+
void ZExtensionManager::register_extension(std::string mod_name, int mod_priority, FP_ExtensionInitializer ext_initiator) {
TExtensionData d;
d.name = mod_name;
@@ -60,33 +61,32 @@
}
-
-int main(int argc, char **argv)
-{
+int main(int argc, char **argv) {
// Make single IO handler
- boost::asio::io_service io;
+ boost::asio::io_service io;
// Register signal handlers so that the daemon may be shut down. You may
// also want to register for other signals, such as SIGHUP to trigger a
// re-read of a configuration file.
-#ifdef WITH_BOOST_SIGNAL_SET
+ #ifdef WITH_BOOST_SIGNAL_SET
// Not yet, waiting for new boost to be default in freebsd ports.
boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
signals.async_wait(
- boost::bind(&boost::asio::io_service::stop, &io_service));
-#endif
+ boost::bind(&boost::asio::io_service::stop, &io_service));
+ #endif
// Allocate object model
Model::Model model;
model["args"].map();
for (int ac=1; ac < argc; ac++) {
string arg = argv[ac];
- string::size_type pos = arg.find("=");
+ string::size_type pos = arg.find("=");
if (pos != string::npos) {
model["args"][argv[ac]] = string(arg, pos + 1);
- } else {
+ }
+ else {
model["args"][argv[ac]] = Leaf(true);
}
- }
+ }
// and fill with data
model.populate();
@@ -97,10 +97,10 @@
// Start server
http::server::server s(io, "0.0.0.0", "9080", "html");
- // Register model interface
- s.register_handler(&json_handler);
+ // Register model interface
+ s.register_handler(&json_handler);
- cout << "Loading extensions" << endl;
+ cout << "Loading extensions" << endl;
// Add all available extensions
ZRouter::T_ZExtensionMap::iterator ext_ptr = extension_map.begin();
while (ext_ptr != extension_map.end()) {
@@ -109,15 +109,14 @@
extObj["loaded"] = true;
extObj["version"] = "unknown";
extObj["vendor"] = "unknown";
-
+
model["system"]["extensions"][(*ext_ptr).second.name] = extObj;
(*ext_ptr).second.initializer(io, model);
ext_ptr++;
}
- cout << "Loading extensions completed" << endl;
-
+ cout << "Loading extensions completed" << endl;
+
io.run();
- return 0;
+ return 0;
}
-
More information about the Zrouter-src
mailing list