static StructuredData::ObjectSP ParseJSONObject(JSONParser &json_parser) {
  // The "JSONParser::Token::ObjectStart" token should have already been
  // consumed by the time this function is called
  auto dict_up = llvm::make_unique<StructuredData::Dictionary>();

  std::string value;
  std::string key;
  while (1) {
    JSONParser::Token token = json_parser.GetToken(value);

    if (token == JSONParser::Token::String) {
      key.swap(value);
      token = json_parser.GetToken(value);
      if (token == JSONParser::Token::Colon) {
        StructuredData::ObjectSP value_sp = ParseJSONValue(json_parser);
        if (value_sp)
          dict_up->AddItem(key, value_sp);
        else
          break;
      }
    } else if (token == JSONParser::Token::ObjectEnd) {
      return StructuredData::ObjectSP(dict_up.release());
    } else if (token == JSONParser::Token::Comma) {
      continue;
    } else {
      break;
    }
  }
  return StructuredData::ObjectSP();
}
Example #2
0
void App::readConfig()
{
	string configFileName = config()->get(CPPAPP_CONFIG_FILE_CFG_KEY,
								   getDefaultConfigFile())->asString();
	
	Ref<FileInput> configInput = new FileInput(configFileName);
	if (!configInput->exists()) {
		LOG_WARNING("Configuration file " << configFileName << " does not exist.");
		return;
	}
	
	JSONParser parser;
	config_ = parser.parse(configInput);
	configInput->close();
	
	if (config_->isError()) {
		Ref<DynError> err = config_.as<DynError>();
		LOG_ERROR("Syntax error in config file at " << err->getErrorLoc() << ": " << err->getString());
		exit(1);
	}
	
	//Ref<PrettyPrinter> printer = new PrettyPrinter();
	//config_->print(printer);
	//printer->print("\n");
	
	// Override the configuration read from the file by the command line
	// options.
	options().setConfigKeys(config_);
}
Example #3
0
Object * JSONParser::objectFromString(String * str)
{
	Object * result;
	JSONParser * parser;
	
	parser = new JSONParser();
    parser->setContent(str);
	parser->parse();
	result = parser->result();
    result->retain()->autorelease();
    parser->release();
	
	return result;
}
Example #4
0
static StructuredData::ObjectSP
ParseJSONArray (JSONParser &json_parser)
{
    // The "JSONParser::Token::ObjectStart" token should have already been consumed
    // by the time this function is called
    std::unique_ptr<StructuredData::Array> array_up(new StructuredData::Array());

    std::string value;
    std::string key;
    while (1)
    {
        StructuredData::ObjectSP value_sp = ParseJSONValue(json_parser);
        if (value_sp)
            array_up->AddItem(value_sp);
        else
            break;

        JSONParser::Token token = json_parser.GetToken(value);
        if (token == JSONParser::Token::Comma)
        {
            continue;
        }
        else if (token == JSONParser::Token::ArrayEnd)
        {
            return StructuredData::ObjectSP(array_up.release());
        }
        else
        {
            break;
        }
    }
    return StructuredData::ObjectSP();
}
Example #5
0
bool JSONParser::parseArray()
{
    int position;
    Array * array;
    
    position = mPosition;
    
    if (!scanCharacter('[', position)) {
        return false;
    }
    position ++;
    position = skipBlank(position);
    
    array = Array::array();
    
    if (scanCharacter(']', position)) {
        position ++;
    }
    else {
        while (1) {
            JSONParser * valueParser;
            Object * value;
            
            if (position >= mContent->length())
                return false;
            
            value = NULL;
            valueParser = new JSONParser();
            valueParser->setContent(mContent);
            valueParser->setPosition(position);
            valueParser->autorelease();
            if (!valueParser->parse())
                return false;
            
            value = valueParser->result();
            
            position = valueParser->position();
            array->addObject(value);
            
            position = skipBlank(position);
            
            if (scanCharacter(',', position)) {
                position ++;
                position = skipBlank(position);
            }
            else if (scanCharacter(']', position)) {
                position ++;
                break;
            }
            else {
                return false;
            }
        }
    }
    
    mResult = array->retain();
    mPosition = position;
    
    return true;
}
Example #6
0
bool Round::RemoteNode::postMessage(uHTTP::HTTPRequest *httpReq, JSONObject **rootObj, Error *error) {
  // HTTP Request
  
  std::string requestAddr;
  int requestPort;
  if (!getRequestAddress(&requestAddr, error) || !getRequestPort(&requestPort, error))
    return false;
  
  httpReq->setHost(requestAddr, requestPort);
  
  uHTTP::HTTPResponse httpRes;
  httpReq->post(requestAddr, requestPort, &httpRes);
  
  // Set error code and message
  
  int statusCode = httpRes.getStatusCode();
  if (!uHTTP::HTTP::IsStatusCodeSuccess(statusCode)) {
    error->setCode(statusCode);
    error->setMessage(uHTTP::HTTP::StatusCodeToString(statusCode));
    return false;
  }
  
  std::string httpContent = httpRes.getContent();
  if (httpContent.length() <= 0) {
    statusCode = uHTTP::HTTP::NOT_FOUND;
    error->setCode(statusCode);
    error->setMessage(uHTTP::HTTP::StatusCodeToString(statusCode));
    return false;
  }
  
  JSONParser jsonParser;
  if (jsonParser.parse(httpContent, error) == false) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeParserError, error);
    return false;
  }
  
  *rootObj = jsonParser.popRootObject();
  if (!(*rootObj)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeParserError, error);
    return false;
  }

  return true;
}
Example #7
0
bool Round::set_alias::exec(LocalNode *node, const NodeRequest *nodeReq, NodeResponse *nodeRes) const {
  std::string params;
  if (!nodeReq->getParams(&params))
    return false;
  
  JSONParser jsonParser;
  Error error;
  if (!jsonParser.parse(params, &error))
    return false;
  
  JSONDictionary *paramDict = dynamic_cast<JSONDictionary *>(jsonParser.getRootObject());
  if (!paramDict)
    return false;
  
  // Essential Parameters
  
  std::string name, method;
  
  if (!paramDict->get(ALIAS_NAME, &name))
    return false;
  
  if (!paramDict->get(ALIAS_METHOD, &method))
    return false;
  
  if ((name.length() <= 0) || (method.length() <= 0))
    return false;

  // Optional Parameters
  
  std::string defaults;
  paramDict->get(ALIAS_DEFAULTS, &defaults);

  // Set alias
  
  Alias *alias = new Alias();
  
  alias->setName(name);
  alias->setObject(method);
  alias->setDefaults(defaults);
  
  return node->setAlias(alias);
}
Example #8
0
static StructuredData::ObjectSP
ParseJSONValue (JSONParser &json_parser)
{
    std::string value;
    const JSONParser::Token token = json_parser.GetToken(value);
    switch (token)
    {
        case JSONParser::Token::ObjectStart:
            return ParseJSONObject(json_parser);

        case JSONParser::Token::ArrayStart:
            return ParseJSONArray(json_parser);

        case JSONParser::Token::Integer:
            {
                bool success = false;
                uint64_t uval = StringConvert::ToUInt64(value.c_str(), 0, 0, &success);
                if (success)
                    return StructuredData::ObjectSP(new StructuredData::Integer(uval));
            }
            break;

        case JSONParser::Token::Float:
            {
                bool success = false;
                double val = StringConvert::ToDouble(value.c_str(), 0.0, &success);
                if (success)
                    return StructuredData::ObjectSP(new StructuredData::Float(val));
            }
            break;

        case JSONParser::Token::String:
            return StructuredData::ObjectSP(new StructuredData::String(value));

        case JSONParser::Token::True:
        case JSONParser::Token::False:
            return StructuredData::ObjectSP(new StructuredData::Boolean(token == JSONParser::Token::True));

        case JSONParser::Token::Null:
            return StructuredData::ObjectSP(new StructuredData::Null());

        default:
            break;
    }
    return StructuredData::ObjectSP();

}
Example #9
0
bool BFCPMsgFloorRelease::ParseAttributes(JSONParser &parser)
{
	do {
		// Get key name.
		if (! parser.ParseJSONString()) {
			::Error("BFCPMsgFloorRelease::ParseAttributes() | failed to parse JSON key\n");
			goto error;
		}

		enum BFCPAttribute::Name attribute = BFCPAttribute::mapJsonStr2Name[parser.GetValue()];
		//::Log("BFCPMsgFloorRelease::ParseAttributes() | BFCPAttribute::Name attribute: %d\n", attribute);

		if (! parser.ParseDoubleDot()) {
			::Error("BFCPMsgFloorRelease::ParseAttributes() | failed to parse ':'\n");
			goto error;
		}

		switch(attribute) {
			case BFCPAttribute::FloorRequestId:
				if (! parser.ParseJSONNumber()) {
					::Error("BFCPMsgFloorRequest::ParseAttributes() | failed to parse 'floorRequestId'\n");
					goto error;
				}

				::Debug("BFCPMsgFloorRequest::ParseAttributes() | attribute 'floorRequestId' found\n");
				SetFloorRequestId((int)parser.GetNumberValue());
				break;

			default:
				::Debug("BFCPMsgFloorRelease::ParseAttributes() | skiping unknown key\n");
				parser.SkipJSONValue();
				break;
		}
	} while (parser.ParseComma());

	::Debug("BFCPMsgFloorRelease::ParseAttributes() | exiting attributes object\n");
	return true;

error:
	return false;
}
static StructuredData::ObjectSP ParseJSONValue(JSONParser &json_parser) {
  std::string value;
  const JSONParser::Token token = json_parser.GetToken(value);
  switch (token) {
  case JSONParser::Token::ObjectStart:
    return ParseJSONObject(json_parser);

  case JSONParser::Token::ArrayStart:
    return ParseJSONArray(json_parser);

  case JSONParser::Token::Integer: {
    uint64_t uval;
    if (llvm::to_integer(value, uval, 0))
      return std::make_shared<StructuredData::Integer>(uval);
  } break;

  case JSONParser::Token::Float: {
    double val;
    if (llvm::to_float(value, val))
      return std::make_shared<StructuredData::Float>(val);
  } break;

  case JSONParser::Token::String:
    return std::make_shared<StructuredData::String>(value);

  case JSONParser::Token::True:
  case JSONParser::Token::False:
    return std::make_shared<StructuredData::Boolean>(token ==
                                                     JSONParser::Token::True);

  case JSONParser::Token::Null:
    return std::make_shared<StructuredData::Null>();

  default:
    break;
  }
  return StructuredData::ObjectSP();
}
Example #11
0
bool JSONParser::parseDictionary()
{
    int position;
    HashMap * dict;
    
    position = mPosition;
    
    if (!scanCharacter('{', position)) {
        return false;
    }
    position ++;
    position = skipBlank(position);
    
    dict = HashMap::hashMap();
    
    if (scanCharacter('}', position)) {
        position ++;
    }
    else {
        while (1) {
            JSONParser * keyParser;
            JSONParser * valueParser;
            String * key;
            Object * value;
            
            if (position >= mContent->length())
                return false;
            
            key = NULL;
            keyParser = new JSONParser();
            keyParser->autorelease();
            keyParser->setContent(mContent);
            keyParser->setPosition(position);
            if (!keyParser->parse())
                return false;
            
            if (!keyParser->result()->className()->isEqual(MCSTR("mailcore::String")))
                return false;
            
            key = (String *) keyParser->result();
            position = keyParser->position();
            
            position = skipBlank(position);
            
            if (!scanCharacter(':', position))
                return false;
            position ++;
            
            position = skipBlank(position);
            
            value = NULL;
            valueParser = new JSONParser();
            valueParser->autorelease();
            valueParser->setContent(mContent);
            valueParser->setPosition(position);
            if (!valueParser->parse())
                return false;
            
            value = valueParser->result();
            position = valueParser->position();
            
            dict->setObjectForKey(key, value);
            
            position = skipBlank(position);
            
            if (scanCharacter(',', position)) {
                position ++;
                position = skipBlank(position);
            }
            else if (scanCharacter('}', position)) {
                position ++;
                break;
            }
            else {
                return false;
            }
        }
    }
    
    mResult = dict->retain();
    mPosition = position;
    
    return true;
}
Example #12
0
bool BFCPMsgFloorQuery::ParseAttributes(JSONParser &parser)
{
	do {
		// Get key name.
		if (! parser.ParseJSONString()) {
			::Error("BFCPMsgFloorQuery::ParseAttributes() | failed to parse JSON key\n");
			goto error;
		}

		enum BFCPAttribute::Name attribute = BFCPAttribute::mapJsonStr2Name[parser.GetValue()];

		if (! parser.ParseDoubleDot()) {
			::Error("BFCPMsgFloorQuery::ParseAttributes() | failed to parse ':'\n");
			goto error;
		}

		switch(attribute) {
			case BFCPAttribute::FloorId:
				if (! parser.ParseJSONArrayStart()) {
					::Error("BFCPMsgFloorQuery::ParseAttributes() | failed to parse 'floorId' array start\n");
					goto error;
				}
				if (parser.ParseJSONArrayEnd())
					break;

				do {
					if (! parser.ParseJSONNumber()) {
						::Error("BFCPMsgFloorQuery::ParseAttributes() | failed to parse 'floorId' value in the array\n");
						goto error;
					}

					int floorId = (int)parser.GetNumberValue();
					::Debug("BFCPMsgFloorQuery::ParseAttributes() | attribute 'floorId' found\n");
					AddFloorId(floorId);
				} while (parser.ParseComma());

				if (! parser.ParseJSONArrayEnd()) {
					::Error("BFCPMsgFloorQuery::ParseAttributes() | failed to parse 'floorId' array end\n");
					goto error;
				}
				break;

			default:
				::Debug("BFCPMsgFloorQuery::ParseAttributes() | skiping unknown key\n");
				parser.SkipJSONValue();
				break;
		}
	} while (parser.ParseComma());

	::Debug("BFCPMsgFloorQuery::ParseAttributes() | exiting attributes object\n");
	return true;

error:
	return false;
}