Exemplo n.º 1
0
TYPED_TEST(DocumentMove, MoveAssignmentParseError) {
    typedef TypeParam Allocator;
    typedef GenericDocument<UTF8<>, Allocator> Document;

    ParseResult noError;
    Document a;
    a.Parse("{ 4 = 4]");
    ParseResult error(a.GetParseError(), a.GetErrorOffset());
    EXPECT_TRUE(a.HasParseError());
    EXPECT_NE(error.Code(), noError.Code());
    EXPECT_NE(error.Offset(), noError.Offset());

    Document b;
    b = std::move(a);
    EXPECT_FALSE(a.HasParseError());
    EXPECT_TRUE(b.HasParseError());
    EXPECT_EQ(a.GetParseError(), noError.Code());
    EXPECT_EQ(b.GetParseError(), error.Code());
    EXPECT_EQ(a.GetErrorOffset(), noError.Offset());
    EXPECT_EQ(b.GetErrorOffset(), error.Offset());

    Document c;
    c = std::move(b);
    EXPECT_FALSE(b.HasParseError());
    EXPECT_TRUE(c.HasParseError());
    EXPECT_EQ(b.GetParseError(), noError.Code());
    EXPECT_EQ(c.GetParseError(), error.Code());
    EXPECT_EQ(b.GetErrorOffset(), noError.Offset());
    EXPECT_EQ(c.GetErrorOffset(), error.Offset());
}
Exemplo n.º 2
0
bool ZatData::InitSession()
{
  string jsonString = HttpGet(zattooServer + "/zapi/v2/session", true);
  Document doc;
  doc.Parse(jsonString.c_str());
  if (doc.GetParseError() || !doc["success"].GetBool())
  {
    XBMC->Log(LOG_ERROR, "Initialize session failed.");
    return false;
  }

  if (!doc["session"]["loggedin"].GetBool())
  {
    XBMC->Log(LOG_DEBUG, "Need to login.");

    string uuid = GetUUID();
    if (uuid.empty())
    {
      return false;
    }

    SendHello(uuid);
    //Ignore if hello fails

    if (!Login())
    {
      return false;
    }
    jsonString = HttpGet(zattooServer + "/zapi/v2/session", true);
    doc.Parse(jsonString.c_str());
    if (doc.GetParseError() || !doc["success"].GetBool()
        || !doc["session"]["loggedin"].GetBool())
    {
      XBMC->Log(LOG_ERROR, "Initialize session failed.");
      return false;
    }
  }

  const Value& session = doc["session"];

  countryCode = session["aliased_country_code"].GetString();
  recallEnabled = streamType == "dash" && session["recall_eligible"].GetBool();
  recordingEnabled = session["recording_eligible"].GetBool();
  if (recallEnabled)
  {
    maxRecallSeconds = session["recall_seconds"].GetInt();
  }
  if (updateThread == NULL)
  {
    updateThread = new UpdateThread(this);
  }
  powerHash = session["power_guide_hash"].GetString();
  return true;
}
Exemplo n.º 3
0
 EReturn Initialiser::initialiseProblemJSON(PlanningProblem_ptr problem,
     const std::string& constraints)
 {
   {
     Document document;
     if (!document.Parse<0>(constraints.c_str()).HasParseError())
     {
       if (ok(problem->reinitialise(document, problem)))
       {
         // Everythinh is fine
       }
       else
       {
         INDICATE_FAILURE
         ;
         return FAILURE;
       }
     }
     else
     {
       ERROR(
           "Can't parse constraints from JSON string!\n"<<document.GetParseError() <<"\n"<<constraints.substr(document.GetErrorOffset(),50));
       return FAILURE;
     }
   }
   return SUCCESS;
 }
Exemplo n.º 4
0
string ZatData::GetChannelStreamUrl(int uniqueId)
{

  ZatChannel *channel = FindChannel(uniqueId);
  //XBMC->QueueNotification(QUEUE_INFO, "Getting URL for channel %s", XBMC->UnknownToUTF8(channel->name.c_str()));

  ostringstream dataStream;
  dataStream << "cid=" << channel->cid << "&stream_type=" << streamType
      << "&format=json";

  if (recallEnabled)
  {
    dataStream << "&timeshift=" << maxRecallSeconds;
  }

  string jsonString = HttpPost(zattooServer + "/zapi/watch", dataStream.str());

  Document doc;
  doc.Parse(jsonString.c_str());
  if (doc.GetParseError() || !doc["success"].GetBool())
  {
    return "";
  }
  string url = doc["stream"]["url"].GetString();
  return url;

}
Exemplo n.º 5
0
int ZatData::GetRecordingsAmount(bool future)
{
  string jsonString = HttpGetCached(zattooServer + "/zapi/playlist", 60);

  time_t current_time;
  time(&current_time);

  Document doc;
  doc.Parse(jsonString.c_str());
  if (doc.GetParseError() || !doc["success"].GetBool())
  {
    return 0;
  }

  const Value& recordings = doc["recordings"];

  int count = 0;
  for (Value::ConstValueIterator itr = recordings.Begin();
      itr != recordings.End(); ++itr)
  {
    const Value& recording = (*itr);
    time_t startTime = StringToTime(recording["start"].GetString());
    if (future == (startTime > current_time))
    {
      count++;
    }
  }
  return count;
}
Exemplo n.º 6
0
void RankScene::onGetRankResponse(HttpClient * sender, HttpResponse *response) {
	if (!response) return;

	if (!response->isSucceed()) {
		log("response failed");
		log("error buffer: %s", response->getErrorBuffer());
		return;
	}

	string res = Global::toString(response->getResponseData());
	Document d;
	d.Parse<0>(res.c_str());

	if (d.HasParseError()) {
		CCLOG("GetParseError %s\n", d.GetParseError());
	}

	if (d.IsObject() && d.HasMember("result") && d.HasMember("info")) {
		bool result = d["result"].GetBool();
		if (!result) {
			CCLOG("Failed to login: %s\n", d["info"].GetString());
		}
		else {
			setRankBoard(d["info"].GetString());
		}
	}
}
Exemplo n.º 7
0
	bool FileUtil::LoadFromFile(const Serializable::Ptr &source, const std::string &filePath)
	{
		using namespace rapidjson;

		std::ifstream stream(filePath);
		if (stream)
		{
			std::stringstream buffer;
			buffer << stream.rdbuf();

			Document dom;
			dom.Parse(buffer.str().c_str());

			if (dom.HasParseError())
			{
				LOGE << "Error parsing json file " << filePath << ": " << dom.GetParseError();
				return false;
			}

			if (!source->Load(&dom))
			{
				LOGE << "Serialization failed!";
				return false;
			}

			LOGD << filePath << " successfully deserialized!";
			return true;
		}
		return false;
	}
Exemplo n.º 8
0
void LoginScene::onLoginResponse(HttpClient * sender, HttpResponse *response)
{
	if (!response) return;

	if (!response->isSucceed()) {
		log("response failed");
		log("error buffer: %s", response->getErrorBuffer());
		return;
	}

	string res = Global::toString(response->getResponseData());
	Document d;
	d.Parse<0>(res.c_str());

	if (d.HasParseError()) {
		CCLOG("GetParseError %s\n", d.GetParseError());
	}

	if (d.IsObject() && d.HasMember("result") && d.HasMember("info")) {
		bool result = d["result"].GetBool();
		if (result) {
			Global::saveStatus(response->getResponseHeader(), textField->getString());
			Director::getInstance()->replaceScene(TransitionFade::create(1, GameScene::createScene()));
		}
		else {
			CCLOG("Failed to login: %s\n", d["info"].GetString());
		}
	}
}
Exemplo n.º 9
0
TEST(Document, UnchangedOnParseError) {
    Document doc;
    doc.SetArray().PushBack(0, doc.GetAllocator());

    ParseResult err = doc.Parse("{]");
    EXPECT_TRUE(doc.HasParseError());
    EXPECT_EQ(err.Code(), doc.GetParseError());
    EXPECT_EQ(err.Offset(), doc.GetErrorOffset());
    EXPECT_TRUE(doc.IsArray());
    EXPECT_EQ(doc.Size(), 1u);

    err = doc.Parse("{}");
    EXPECT_FALSE(doc.HasParseError());
    EXPECT_FALSE(err.IsError());
    EXPECT_EQ(err.Code(), doc.GetParseError());
    EXPECT_EQ(err.Offset(), doc.GetErrorOffset());
    EXPECT_TRUE(doc.IsObject());
    EXPECT_EQ(doc.MemberCount(), 0u);
}
Exemplo n.º 10
0
bool ZatData::Record(int programId)
{
  ostringstream dataStream;
  dataStream << "program_id=" << programId;

  string jsonString = HttpPost(zattooServer + "/zapi/playlist/program",
      dataStream.str());
  Document doc;
  doc.Parse(jsonString.c_str());
  return !doc.GetParseError() && doc["success"].GetBool();
}
Exemplo n.º 11
0
bool ZatData::DeleteRecording(string recordingId)
{
  ostringstream dataStream;
  dataStream << "recording_id=" << recordingId << "";

  string jsonString = HttpPost(zattooServer + "/zapi/playlist/remove",
      dataStream.str());

  Document doc;
  doc.Parse(jsonString.c_str());
  return !doc.GetParseError() && doc["success"].GetBool();
}
Exemplo n.º 12
0
int Dynamo::PostReq(const std::string &op, const string &req) {

//	logdebug("req: \n%s", req.c_str());
//
//	char *ueReq = curl_easy_escape(curl, req.data(), (int) req.length());
//
//	if (NULL == ueReq) {
//		snprintf(lastErr, sizeof(lastErr), "curl_easy_escape failed");
//		return -1;
//	}
//
//	std::string data = ueReq;
//	curl_free (ueReq);

	if (0 != UpdateHead(op, req)) {
		return -1;
	}

//	logdebug("\ncommand=%s\nrequest=\n%s", op.c_str(), req.c_str());

	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req.c_str());
//	curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.length());

	strRsp.clear();

	CURLcode code = curl_easy_perform(curl);
	if (CURLE_OK != code) {
		snprintf(lastErr, sizeof(lastErr), "%s", curl_easy_strerror(code));
		return -1;
	}
//	logdebug("\ncommand=%s\nresponse=\n%s", op.c_str(), strRsp.c_str());

    Document d;
    d.Parse<0>(strRsp.c_str());
    if (d.HasParseError()) {
    	snprintf(lastErr, sizeof(lastErr), "json doc parse failed, %u", d.GetParseError());
    	return -1;
    }

    rsp.SetNull();
    allocator.Clear();
    rsp.CopyFrom(d, allocator);

    if (rsp.HasMember("__type")) {
		snprintf(lastErr, sizeof(lastErr), "dynamo return error: %s", rsp.FindMember("__type")->value.GetString());
		return -1;
    }

	return 0;
}
Exemplo n.º 13
0
bgfx_effect* effect_manager::load_effect(std::string name)
{
	std::string full_name = name;
	if (full_name.length() < 5 || (full_name.compare(full_name.length() - 5, 5, ".json") != 0)) {
		full_name = full_name + ".json";
	}
	std::string path;
	osd_subst_env(path, util::string_format("%s" PATH_SEPARATOR "effects" PATH_SEPARATOR, m_options.bgfx_path()));
	path += full_name;

	bx::CrtFileReader reader;
	if (!bx::open(&reader, path.c_str()))
	{
		printf("Unable to open effect file %s\n", path.c_str());
		return nullptr;
	}

	int32_t size (bx::getSize(&reader));

	char* data = new char[size + 1];
	bx::read(&reader, reinterpret_cast<void*>(data), size);
	bx::close(&reader);
	data[size] = 0;

	Document document;
	document.Parse<kParseCommentsFlag>(data);

	delete [] data;

	if (document.HasParseError()) {
		std::string error(GetParseError_En(document.GetParseError()));
		printf("Unable to parse effect %s. Errors returned:\n", path.c_str());
		printf("%s\n", error.c_str());
		return nullptr;
	}

	bgfx_effect* effect = effect_reader::read_from_value(document, "Effect '" + name + "': ", m_shaders);

	if (effect == nullptr) {
		printf("Unable to load effect %s\n", path.c_str());
		return nullptr;
	}

	m_effects[name] = effect;

	return effect;
}
Exemplo n.º 14
0
bool Export(const char* data, const char* outFile)
{
	Document document;
	document.Parse(data);

	if (document.HasParseError()) {
		ParseErrorCode err = document.GetParseError();
		printf("pares error! %d %d", err, document.GetErrorOffset());
		return false;
	}

	if (!document.IsObject())
	{
		printf("error, not a object");
		return false;
	}

	InitializeSdkObjects();

	const Value& skel = document["Skeleton"];
	if (!skel.IsNull())
	{
		ExportBones(skel);
	}

	const Value& mesh = document["Mesh"];
	if (!mesh.IsNull())
	{
		for (uint32_t i = 0; i < mesh.Size(); i++)
		{
			ExportFbxMesh(mesh[i]);
		}
	}

	const Value& anim = document["Animation"];
	if (!anim.IsNull())
	{
		for (uint32_t i = 0; i < anim.Size(); i++)
		{
			ExportAnimation(anim[i]);
		}
	}
	
	SaveFbxFile(outFile);

	return true;
}
Exemplo n.º 15
0
bool EpicCompiler::Init(char* JsonPath, EpicCompilerConfig Conf[])
{
	// 读入Compiler.json文件
	char json[MAX_SIZE] = { 0 };
	FILE* fp = NULL;
	fopen_s(&fp, JsonPath, "r");
	if (fp == NULL)
		return false;
	fseek(fp, 0, SEEK_END);
	int size = ftell(fp);
	if (size == -1)
		return false;
	rewind(fp);
	fread(json, size, 1, fp); fclose(fp); fclose(fp);
	
	// 把JSON解析至DOM
	Document document;  // Default template parameter uses UTF8 and MemoryPoolAllocator.
	if (document.Parse(json).HasParseError())
	{
		//MessageBoxA(NULL, GetParseError_En(document.GetParseError()), (LPCSTR)(unsigned)document.GetErrorOffset(), MB_ICONWARNING + MB_OK);
		cout << GetParseError_En(document.GetParseError()) << endl;
		return false;
	}

	//读入Json数组
	{
		const Value& a = document["Compilers"]; // 使用引用来让连续访问非常方便和非常快
		assert(a.IsArray());
		for (SizeType i = 0; i < a.Size(); i++) // rapidjson 使用 SizeType 而不是 size_t.
		{
			assert(a[i].IsObject());
			assert(a[i].HasMember("Name"));
			assert(a[i].HasMember("Path"));
			assert(a[i].HasMember("Description"));
			assert(a[i].HasMember("Arguments"));
			assert(a[i]["Name"].IsString());
			assert(a[i]["Path"].IsString());
			assert(a[i]["Description"].IsString());
			assert(a[i]["Arguments"].IsString());
			strcpy_s(Conf[i].name, a[i]["Name"].GetString());
			strcpy_s(Conf[i].path, a[i]["Path"].GetString());
			strcpy_s(Conf[i].desc, a[i]["Description"].GetString());
			strcpy_s(Conf[i].argu, a[i]["Arguments"].GetString());
		}
	}
	return true;
}
Exemplo n.º 16
0
Sprites parseSprite(const std::string& image, const std::string& json) {
    using namespace rapidjson;

    Sprites sprites;

    // Parse the sprite image.
    const util::Image raster(image);
    if (!raster) {
        Log::Warning(Event::Sprite, "Could not parse sprite image");
        return sprites;
    }

    Document doc;
    doc.Parse<0>(json.c_str());

    if (doc.HasParseError()) {
        Log::Warning(Event::Sprite, std::string{ "Failed to parse JSON: " } + doc.GetParseError() +
                                        " at offset " + std::to_string(doc.GetErrorOffset()));
        return sprites;
    } else if (!doc.IsObject()) {
        Log::Warning(Event::Sprite, "Sprite JSON root must be an object");
        return sprites;
    } else {
        for (Value::ConstMemberIterator itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr) {
            const std::string name = { itr->name.GetString(), itr->name.GetStringLength() };
            const Value& value = itr->value;

            if (value.IsObject()) {
                const uint16_t x = getUInt16(value, "x", 0);
                const uint16_t y = getUInt16(value, "y", 0);
                const uint16_t width = getUInt16(value, "width", 0);
                const uint16_t height = getUInt16(value, "height", 0);
                const double pixelRatio = getDouble(value, "pixelRatio", 1);
                const bool sdf = getBoolean(value, "sdf", false);

                auto sprite = createSpriteImage(raster, x, y, width, height, pixelRatio, sdf);
                if (sprite) {
                    sprites.emplace(name, sprite);
                }
            }
        }
    }

    return sprites;
}
Exemplo n.º 17
0
string ZatData::GetRecordingStreamUrl(string recordingId)
{
  ostringstream dataStream;
  dataStream << "recording_id=" << recordingId << "&stream_type=" << streamType;

  string jsonString = HttpPost(zattooServer + "/zapi/watch", dataStream.str());

  Document doc;
  doc.Parse(jsonString.c_str());
  if (doc.GetParseError() || !doc["success"].GetBool())
  {
    return "";
  }

  string url = doc["stream"]["url"].GetString();
  return url;

}
Exemplo n.º 18
0
bool ConnInfoUI::LoadConfig( const std::string& path )
{
    m_pListUI->RemoveAll();
    /// 设置利用回调填充数据
    m_pListUI->SetTextCallback(this);//[1]
    m_dicServerInfo.clear();
    
    FILE* fp = fopen(kConfigFilePath, "r");
    if (!fp) return false;

    FileStream is(fp);
    Document document;    /// Default template parameter uses UTF8 and MemoryPoolAllocator.
    if (document.ParseStream<0>(is).HasParseError())
    {
        UserMessageBox(GetHWND(), 10014, Base::CharacterSet::ANSIToUnicode(document.GetParseError()).c_str(), MB_ICONERROR);
        fclose(fp);
        return false;
    }

    const Value& serverConfig = document["Server"];
    int idx = 0;
    for (Value::ConstValueIterator itr = serverConfig.Begin(); itr != serverConfig.End(); ++itr)
    {
        const Value& subConfig = *itr;
        CDuiString name = Base::CharacterSet::UTF8ToUnicode(subConfig["name"].GetString()).c_str();
        m_dicServerInfo[kServerNameIndex].push_back(Base::CharacterSet::UnicodeToANSI(name.GetData()));
        m_dicServerInfo[kServerIpIndex].push_back(subConfig["ip"].GetString());
        std::ostringstream os;
        os<<subConfig["port"].GetInt();
        m_dicServerInfo[kServerPortIndex].push_back(os.str());
        m_dicServerInfo[kServerAuthIndex].push_back(subConfig["auth"].GetString());

        CListTextElementUI* pListElement = new CListTextElementUI;
        pListElement->SetTag(idx++);
        /// 设置工具提示
        pListElement->SetToolTip(m_pListUI->GetToolTip());
        m_pListUI->Add(pListElement);
    }
    fclose(fp);

    return true;
}
Exemplo n.º 19
0
string server_http::init(char *http_url)
{
    if( !CCLayer::init() )
    {
        return 0;
    }
    
    CURL *curl;
    CURLcode res;
    std::string buffer;
    res = curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, http_url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, server_http::writer);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L );
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        if (res == 0)
        {
            if(buffer.c_str() != NULL && !document.Parse<0>(buffer.c_str()).HasParseError())
            {
//                CCLog(document["result"].GetString());
                if(document["errno"].GetInt() == 0)
                {
//                    CCLOG("%s", buffer.c_str());
                    return buffer;
                }
            }
            else
            {
                CCLog(document.GetParseError());
            }
        }
    }
    
    return 0;
}
Exemplo n.º 20
0
bool ZatData::Login()
{
  XBMC->Log(LOG_DEBUG, "Try to login.");

  ostringstream dataStream;
  dataStream << "login="******"&password="******"&format=json";
  string jsonString = HttpPost(zattooServer + "/zapi/account/login",
      dataStream.str(), true);

  Document doc;
  doc.Parse(jsonString.c_str());
  if (doc.GetParseError() || !doc["success"].GetBool())
  {
    XBMC->Log(LOG_ERROR, "Login failed.");
    return false;
  }

  XBMC->Log(LOG_DEBUG, "Login was successful.");
  return true;
}
Exemplo n.º 21
0
bool ZatData::SendHello(string uuid)
{
  XBMC->Log(LOG_DEBUG, "Send hello.");
  ostringstream dataStream;
  dataStream << "uuid=" << uuid << "&lang=en&format=json&client_app_token="
      << appToken;

  string jsonString = HttpPost(zattooServer + "/zapi/session/hello",
      dataStream.str(), true);

  Document doc;
  doc.Parse(jsonString.c_str());
  if (!doc.GetParseError() && doc["success"].GetBool())
  {
    XBMC->Log(LOG_DEBUG, "Hello was successful.");
    return true;
  }
  else
  {
    XBMC->Log(LOG_ERROR, "Hello failed.");
    return false;
  }
}
Exemplo n.º 22
0
bool ZatData::ReadDataJson()
{
  if (!XBMC->FileExists(data_file.c_str(), true))
  {
    return true;
  }
  string jsonString = Utils::ReadFile(data_file.c_str());
  if (jsonString == "")
  {
    XBMC->Log(LOG_ERROR, "Loading data.json failed.");
    return false;
  }

  Document doc;
  doc.Parse(jsonString.c_str());
  if (doc.GetParseError())
  {
    XBMC->Log(LOG_ERROR, "Parsing data.json failed.");
    return false;
  }

  const Value& recordings = doc["recordings"];
  for (Value::ConstValueIterator itr = recordings.Begin();
      itr != recordings.End(); ++itr)
  {
    const Value& recording = (*itr);
    ZatRecordingData *recData = new ZatRecordingData();
    recData->recordingId = recording["recordingId"].GetString();
    recData->playCount = recording["playCount"].GetInt();
    recData->lastPlayedPosition = recording["lastPlayedPosition"].GetInt();
    recData->stillValid = false;
    recordingsData[recData->recordingId] = recData;
  }

  XBMC->Log(LOG_DEBUG, "Loaded data.json.");
  return true;
}
Exemplo n.º 23
0
int server_http::read_json_int(string json, int key_num, char *key_1, char *key_2, char *key_3, char *key_4)
{
    if(json.c_str() != NULL && !document.Parse<0>(json.c_str()).HasParseError())
    {
        if(key_num == 1)
        {
            return document["result"][key_1].GetInt();
        }else if(key_num == 2)
        {
            return document["result"][key_1][key_2].GetInt();
        }else if(key_num == 3)
        {
            return document["result"][key_1][key_2][key_3].GetInt();
        }else if(key_num == 4)
        {
            return document["result"][key_1][key_2][key_3][key_4].GetInt();
        }
    }
    else
    {
        CCLog(document.GetParseError());
    }
    return 0;
}
Exemplo n.º 24
0
IPResponeData TigerIPLocation::parseJson(const std::string json)
{
    IPResponeData data = IPResponeData();
    
    Document document;
    
    document.Parse<0>(json.c_str());
    
    if (document.HasParseError())
    {
        cocos2d::log("### json document parse error [%u]###", document.GetParseError());
        return data;
    }
    
    if (document.IsObject())
    {
        if (document.HasMember("countryCode"))
        {
            data._countryCode = document["countryCode"].GetString();
        }
    }
    
    return data;
}
Exemplo n.º 25
0
int main() {
    Document d;

    {
        AsyncDocumentParser<> parser(d);

        const char json1[] = " { \"hello\" : \"world\", \"t\" : tr";
        //const char json1[] = " { \"hello\" : \"world\", \"t\" : trX"; // For test parsing error
        const char json2[] = "ue, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.14";
        const char json3[] = "16, \"a\":[1, 2, 3, 4] } ";

        parser.ParsePart(json1, sizeof(json1) - 1);
        parser.ParsePart(json2, sizeof(json2) - 1);
        parser.ParsePart(json3, sizeof(json3) - 1);
    }

    if (d.HasParseError()) {
        std::cout << "Error at offset " << d.GetErrorOffset() << ": " << GetParseError_En(d.GetParseError()) << std::endl;
        return EXIT_FAILURE;
    }
    
    // Stringify the JSON to cout
    OStreamWrapper os(std::cout);
    Writer<OStreamWrapper> writer(os);
    d.Accept(writer);
    std::cout << std::endl;

    return EXIT_SUCCESS;
}
GameState* JsonEncodeDecode::decode(const char *buffer)
{
	Document doc;

	// Parse and catch errors
	if (doc.Parse(buffer).HasParseError())
	{
		printf("\n----------\nError (offset %u): %s\n----------\n",
				(unsigned)doc.GetErrorOffset(),
				GetParseError_En(doc.GetParseError()));
		return NULL;
	}

	// Create new GameState
	GameState* state = new GameState();

	// Iterate through JSON document
	for (Value::ConstMemberIterator itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr)
	{
		/*
		 * GAME OVER STATE
		 */
		if (strcmp(itr->name.GetString(), "GameOver") == 0)
		{
			int gameOver = itr->value.GetInt();
			state->setGameOver(gameOver);
		}

		/*
		 * TIME TO RESTART
		 */
		if (strcmp(itr->name.GetString(), "SecToRestart") == 0)
		{
			int secToRestart = itr->value.GetInt();
			state->setSecToRestart(secToRestart);
		}

		/*
		 * VEHICLES
		 */
		if (strcmp(itr->name.GetString(), "Vehicles") == 0)
		{
			// If Vehicles is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Vehicles array is not array\n----------\n");
				return NULL;
			}

			const Value& vehicleArray = itr->value;
			for (SizeType i = 0; i < vehicleArray.Size(); i++)
			{
				if (decodeVehicle(state, vehicleArray[i]) == -1)
				{
					printf("\n----------\nError decoding vehicles\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * BULLETS
		 */
		if (strcmp(itr->name.GetString(), "Bullets") == 0)
		{
			// If Bullets is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Bullets array is not array\n----------\n");
				return NULL;
			}

			const Value& bulletArray = itr->value;
			for (SizeType i = 0; i < bulletArray.Size(); i++)
			{
				if (decodeBullet(state, bulletArray[i]) == -1)
				{
					printf("\n----------\nError decoding bullets\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * BASES
		 */
		if (strcmp(itr->name.GetString(), "Bases") == 0)
		{
			// If Bases is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Bases array is not array\n----------\n");
				return NULL;
			}

			const Value& basesArray = itr->value;
			for (SizeType i = 0; i < basesArray.Size(); i++)
			{
				if (decodeBase(state, basesArray[i]) == -1)
				{
					printf("\n----------\nError decoding bases\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * SHIELDS
		 */
		if (strcmp(itr->name.GetString(), "Shields") == 0)
		{
			// If Shields is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Shields array is not array\n----------\n");
				return NULL;
			}

			const Value& shieldsArray = itr->value;
			for (SizeType i = 0; i < shieldsArray.Size(); i++)
			{
				if (decodeShield(state, shieldsArray[i]) == -1)
				{
					printf("\n----------\nError decoding shields\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * SHIELD GENERATORS
		 */
		if (strcmp(itr->name.GetString(), "ShieldGenerators") == 0)
		{
			// If ShieldGenerators is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Shield gens array is not array\n----------\n");
				return NULL;
			}

			const Value& shieldGenArray = itr->value;
			for (SizeType i = 0; i < shieldGenArray.Size(); i++)
			{
				if (decodeShieldGen(state, shieldGenArray[i]) == -1)
				{
					printf("\n----------\nError decoding shield gens\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * POWERUPS
		 */
		if (strcmp(itr->name.GetString(), "PowerUps") == 0)
		{
			// If Powerups is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Powerups array is not array\n----------\n");
				return NULL;
			}

			const Value& powerupArray = itr->value;
			for (SizeType i = 0; i < powerupArray.Size(); i++)
			{
				if (decodePowerup(state, powerupArray[i]) == -1)
				{
					printf("\n----------\nError decoding powerups\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * ROCKETS
		 */
		if (strcmp(itr->name.GetString(), "Rockets") == 0)
		{
			// If Rockets is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Rockets array is not array\n----------\n");
				return NULL;
			}

			const Value& rocketArray = itr->value;
			for (SizeType i = 0; i < rocketArray.Size(); i++)
			{
				if (decodeRocket(state, rocketArray[i]) == -1)
				{
					printf("\n----------\nError decoding rockets\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * GRAVITY WELLS
		 */
		if (strcmp(itr->name.GetString(), "GravityWells") == 0)
		{
			// If GravityWells is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: GravityWells array is not array\n----------\n");
				return NULL;
			}

			const Value& gravWellArray = itr->value;
			for (SizeType i = 0; i < gravWellArray.Size(); i++)
			{
				if (decodeGravWell(state, gravWellArray[i]) == -1)
				{
					printf("\n----------\nError decoding gravity wells\n----------\n");
					return NULL;
				}
			}
		}
	}

	return state;
}
Exemplo n.º 27
0
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    auto visibleSize = Director::getInstance()->getVisibleSize();
    auto origin = Director::getInstance()->getVisibleOrigin();

	//////////////////////////////////////////////////////////////////////////
	/// 数据读取
	SSIZE_T size;
/*	FILE* file1 = fopen("test.json", "wr");*/
	unsigned char* ch = FileUtils::getInstance()->getFileData("test.json","r", &size);
	std::string data = std::string((const char* )ch, size);
	//////////////////////////////////////////////////////////////////////////
	
	//////////////////////////////////////////////////////////////////////////
	/// 数据解析成json格式数据
	Document doc;		///< 创建一个Document对象 rapidJson的相关操作都在Document类中
	doc.Parse<0>(data.c_str());	///< 通过Parse方法将Json数据解析出来
	if (doc.HasParseError()) 
	{ 
		CCLOG("GetParseError %s\n",doc.GetParseError());
	} 
	//////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////
	/// Json数据读取和更改-----对值操作
	rapidjson::Value& valString = doc["hello1"];		///< 读取键“hello”的值,根据我们的json文档,是一个字符串
	if (valString.IsString())	///< 判断是否是字符串
	{
		const char* ch = valString.GetString();
		log(ch);
		log(valString.GetString());
		valString.SetString("newString");
		log(valString.GetString());
	}
	rapidjson::Value& valArray = doc["a"];			///< 读取键“a”值,根据我们的json文档,是一个数组
	if (valArray.IsArray())							///< 判断val的类型 是否为数组 我们的Tollgate键对应的value实际为数组
	{
		for (int i = 0; i < valArray.Capacity(); ++i)
		{
			rapidjson::Value& first	= valArray[i];	///< 获取到val中的第i个元素 根据我们这里的json文件 val中共有4个元素
			CCLOG("%f", first.GetDouble());			///< 将value转换成Double类型打印出来 结果为0.5
			first.SetDouble(10.f);
			CCLOG("%f", first.GetDouble());			///< 将value转换成Double类型打印出来 结果为0.5S
		}
	}
	//////////////////////////////////////////////////////////////////////////

	/////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////
	/// json数据操作---对键操作之添加成员对象
	/// 添加一个String对象;	
	rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();	///< 获取最初数据的分配器
	rapidjson::Value strObject(rapidjson::kStringType);					///< 添加字符串方法1
	strObject.SetString("love");
	doc.AddMember("hello1", strObject, allocator);
/*	doc.AddMember("hello1", "love you", allocator);						///< 添加字符串方法2:往分配器中添加一个对象*/

	/// 添加一个null对象
	rapidjson::Value nullObject(rapidjson::kNullType);
	doc.AddMember("null", nullObject, allocator);						///< 往分配器中添加一个对象

	/// 添加一个数组对象
	rapidjson::Value array(rapidjson::kArrayType);		///< 创建一个数组对象
	rapidjson::Value object(rapidjson::kObjectType);	///< 创建数组里面对象。
	object.AddMember("id", 1, allocator);
	object.AddMember("name", "lai", allocator);
	object.AddMember("age", "12", allocator);
	object.AddMember("low", true, allocator);
	array.PushBack(object, allocator);
	doc.AddMember("player", array, allocator);			///< 将上述的数组内容添加到一个名为“player”的数组中

	/// 在已有的数组中添加一个成员对象
	rapidjson::Value& aArray1 = doc["a"];
	aArray1.PushBack(2.0, allocator);
	//////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////
	/// json数据操作---对键操作之删除成员对象
	/// 删除数组成员对象里面元素
	rapidjson::Value& aArray2 = doc["a"];	///< 读取键“a”值,根据我们的json文档,是一个数组
	aArray2.PopBack();		///< 删除数组最后一个成员对象

	if (doc.RemoveMember("i"))				///< 删除键为“i”的成员变量
	{
		log("delet i member ok!");
	}
	//////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////
	/// 将json数据重新写入文件中---先将文件删除,再写入内容
	rapidjson::StringBuffer  buffer;
	rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
	doc.Accept(writer);		

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
	system("del E:\cocos2d-x-3.2rc0\tests\cpp-empty-test\Resources\test.josn");		///< 先将文件删除掉---之前重这个文件读取数据,因此确保这个文件存在了
	FILE* file = fopen("test.json", "wb");

	if (file)
	{
		fputs(buffer.GetString(), file);
		fclose(file);
	}
#else if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	/// 原理差不多,就是先将文件清空,在写入。这里就不写了。
#endif
	//////////////////////////////////////////////////////////////////////////    
    return true;
}
Exemplo n.º 28
0
bool GateConfig::load(const char* jsonConfig)
{
	char *json = filetool::get_whole_file_buf(jsonConfig);
	if (NULL == json) {
		return false;
	}

	Document doc;

	if (doc.ParseInsitu(json).HasParseError()) {
		LOG_ERROR << "parse config<" << jsonConfig << "> failed, error code = " << doc.GetParseError() << ", error offset = " << doc.GetErrorOffset()
		          << ", err text = " << json[doc.GetErrorOffset()];

		delete[] json;
		return false;
	}

	if (!doc.IsObject()) {
		LOG_ERROR;
		return false;
	}

	{
		// ¶ÁÈ¡ÄÚÍøÍøÂçÅäÖÃ
		const Value& wan = doc["wan"];
		const Value& wanListen = wan["listen"];

		m_wanListen.ip = wanListen["ip"].GetString();
		m_wanListen.port = wanListen["port"].GetInt();

		m_wanThreadNum = wan["threads"].GetInt();
	}

	{
		// ¶ÁÈ¡ÍâÍøÍøÂçÅäÖÃ
		const Value& lan = doc["lan"];
		const Value& lanListens = lan["listen"];
		const Value& lanConnects = lan["listen"];

		IpPort ipport;
		for (SizeType i = 0; i < lanListens.Size(); i++) {
			const Value &listen = lanListens[i];

			ipport.ip = listen["ip"].GetString();
			ipport.port = listen["port"].GetInt();

			m_lanListens.push_back(ipport);
		}

		for (SizeType i = 0; i < lanConnects.Size(); i++) {
			const Value &connect = lanConnects[i];

			ipport.ip = connect["ip"].GetString();
			ipport.port = connect["port"].GetInt();

			m_lanConnects.push_back(ipport);
		}

		m_lanThreadNum = lan["threads"].GetInt();
	}

	delete[] json;
	return true;
}
Exemplo n.º 29
0
bool PlayFabRequestHandler::DecodeRequest(int httpStatus, HttpRequest* request, void* userData, PlayFabBaseModel& outResult, PlayFabError& outError)
{
	std::string response = request->GetReponse();
	Document rawResult;
	rawResult.Parse<0>(response.c_str());

	// Check for bad responses
	if (response.length() == 0 // Null response
		|| rawResult.GetParseError() != NULL) // Non-Json response
	{
		// If we get here, we failed to connect meaningfully to the server - Assume a timeout
		outError.HttpCode = 408;
		outError.ErrorCode = PlayFabErrorConnectionTimeout;
		// For text returns, use the non-json response if possible, else default to no response
		outError.ErrorName = outError.ErrorMessage = outError.HttpStatus = response.length() == 0 ? "Request Timeout or null response" : response;
		return false;
	}

	// Check if the returned json indicates an error
	const Value::Member* errorCodeJson = rawResult.FindMember("errorCode");
	if (errorCodeJson != NULL)
	{
		// There was an error, BUMMER
		if (!errorCodeJson->value.IsNumber())
		{
			// unexpected json formatting - If we get here, we failed to connect meaningfully to the server - Assume a timeout
			outError.HttpCode = 408;
			outError.ErrorCode = PlayFabErrorConnectionTimeout;
			// For text returns, use the non-json response if possible, else default to no response
			outError.ErrorName = outError.ErrorMessage = outError.HttpStatus = response.length() == 0 ? "Request Timeout or null response" : response;
			return false;
		}
		// TODO: what happens when the error is not in the enum?
		outError.ErrorCode = static_cast<PlayFabErrorCode>(errorCodeJson->value.GetInt());

		const Value::Member* codeJson = rawResult.FindMember("code");
		if (codeJson != NULL && codeJson->value.IsNumber())
			outError.HttpCode = codeJson->value.GetInt();

		const Value::Member* statusJson = rawResult.FindMember("status");
		if (statusJson != NULL && statusJson->value.IsString())
			outError.HttpStatus = statusJson->value.GetString();

		const Value::Member* errorNameJson = rawResult.FindMember("error");
		if (errorNameJson != NULL && errorNameJson->value.IsString())
			outError.ErrorName = errorNameJson->value.GetString();

		const Value::Member* errorMessageJson = rawResult.FindMember("errorMessage");
		if (errorMessageJson != NULL && errorMessageJson->value.IsString())
			outError.ErrorMessage = errorMessageJson->value.GetString();

		const Value::Member* errorDetailsJson = rawResult.FindMember("errorDetails");
		if (errorDetailsJson != NULL && errorDetailsJson->value.IsObject())
		{
			const Value& errorDetailsObj = errorDetailsJson->value;

			for (Value::ConstMemberIterator itr = errorDetailsObj.MemberBegin(); itr != errorDetailsObj.MemberEnd(); ++itr)
			{
				if (itr->name.IsString() && itr->value.IsArray())
				{
					const Value& errorList = itr->value;
					for (Value::ConstValueIterator erroListIter = errorList.Begin(); erroListIter != errorList.End(); ++erroListIter)
						outError.ErrorDetails.insert(std::pair<std::string, std::string>(itr->name.GetString(), erroListIter->GetString()));
				}
			}
		}
		// We encountered no errors parsing the error
		return false;
	}

	const Value::Member* data = rawResult.FindMember("data");
	if (data == NULL || !data->value.IsObject())
		return false;

	return outResult.readFromValue(data->value);
}
INT_PTR CALLBACK Dlg_AchievementsReporter::AchievementsReporterProc( HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	switch( uMsg )
	{
		case WM_INITDIALOG:
		{
			HWND hList = GetDlgItem( hDlg, IDC_RA_REPORTBROKENACHIEVEMENTSLIST );
			SetupColumns( hList );

			for( size_t i = 0; i < g_pActiveAchievements->NumAchievements(); ++i )
				AddAchievementToListBox( hList, &g_pActiveAchievements->GetAchievement( i ) );

			ListView_SetExtendedListViewStyle( hList, LVS_EX_CHECKBOXES | LVS_EX_HEADERDRAGDROP );
			SetDlgItemText( hDlg, IDC_RA_BROKENACH_BUGREPORTER, Widen( RAUsers::LocalUser().Username() ).c_str() );
		}
		return FALSE;

	case WM_COMMAND:
		switch( LOWORD( wParam ) )
		{
		case IDOK:
		{
			HWND hList = GetDlgItem( hDlg, IDC_RA_REPORTBROKENACHIEVEMENTSLIST );

			const bool bProblem1Sel = ( IsDlgButtonChecked( hDlg, IDC_RA_PROBLEMTYPE1 ) == BST_CHECKED );
			const bool bProblem2Sel = ( IsDlgButtonChecked( hDlg, IDC_RA_PROBLEMTYPE2 ) == BST_CHECKED );

			if( ( bProblem1Sel == false ) && ( bProblem2Sel == false ) )
			{
				MessageBox( nullptr, L"Please select a problem type.", L"Warning", MB_ICONWARNING );
				return FALSE;
			}

			int nProblemType = bProblem1Sel ? 1 : bProblem2Sel ? 2 : 0;	// 0==?
			const char* sProblemTypeNice = PROBLEM_STR[ nProblemType ];

			char sBuggedIDs[ 1024 ];
			sprintf_s( sBuggedIDs, 1024, "" );

			int nReportCount = 0;

			const size_t nListSize = ListView_GetItemCount( hList );
			for( size_t i = 0; i < nListSize; ++i )
			{
				if( ListView_GetCheckState( hList, i ) != 0 )
				{
					//	NASTY big assumption here...
					char buffer[ 1024 ];
					sprintf_s( buffer, 1024, "%d,", g_pActiveAchievements->GetAchievement( i ).ID() );
					strcat_s( sBuggedIDs, 1024, buffer );

					//ListView_GetItem( hList );	
					nReportCount++;
				}
			}

			if( nReportCount > 5 )
			{
				if( MessageBox( nullptr, L"You have over 5 achievements selected. Is this OK?", L"Warning", MB_YESNO ) == IDNO )
					return FALSE;
			}

			wchar_t sBugReportCommentWide[ 4096 ];
			GetDlgItemText( hDlg, IDC_RA_BROKENACHIEVEMENTREPORTCOMMENT, sBugReportCommentWide, 4096 );
			std::string sBugReportComment = Narrow( sBugReportCommentWide );

			char sBugReportInFull[ 8192 ];
			sprintf_s( sBugReportInFull, 8192,
					"--New Bug Report--\n"
					"\n"
					"Game: %s\n"
					"Achievement IDs: %s\n"
					"Problem: %s\n"
					"Reporter: %s\n"
					"ROM Checksum: %s\n"
					"\n"
					"Comment: %s\n"
					"\n"
					"Is this OK?",
					CoreAchievements->GameTitle().c_str(),
					sBuggedIDs,
					sProblemTypeNice,
					RAUsers::LocalUser().Username().c_str(),
					g_sCurrentROMMD5.c_str(),
					sBugReportComment.c_str() );

			if( MessageBox( nullptr, Widen( sBugReportInFull ).c_str(), L"Summary", MB_YESNO ) == IDNO )
				return FALSE;

			PostArgs args;
			args[ 'u' ] = RAUsers::LocalUser().Username();
			args[ 't' ] = RAUsers::LocalUser().Token();
			args[ 'i' ] = sBuggedIDs;
			args[ 'p' ] = std::to_string( nProblemType );
			args[ 'n' ] = sBugReportComment.c_str();
			args[ 'm' ] = g_sCurrentROMMD5;

			Document doc;
			if( RAWeb::DoBlockingRequest( RequestSubmitTicket, args, doc ) )
			{
				if( doc[ "Success" ].GetBool() )
				{
					char buffer[ 2048 ];
					sprintf_s( buffer, 2048, "Submitted OK!\n"
							"\n"
							"Thankyou for reporting that bug(s), and sorry it hasn't worked correctly.\n"
							"\n"
							"The development team will investigate this bug as soon as possible\n"
							"and we will send you a message on RetroAchievements.org\n"
							"as soon as we have a solution.\n"
							"\n"
							"Thanks again!" );

					MessageBox( hDlg, Widen( buffer ).c_str(), L"Success!", MB_OK );
					EndDialog( hDlg, TRUE );
					return TRUE;
				}
				else
				{
					char buffer[ 2048 ];
					sprintf_s( buffer, 2048,
							"Failed!\n"
							"\n"
							"Response From Server:\n"
							"\n"
							"Error code: %d", doc.GetParseError() );
					MessageBox( hDlg, Widen( buffer ).c_str(), L"Error from server!", MB_OK );
					return FALSE;
				}
			}
			else
			{
				MessageBox( hDlg,
							L"Failed!\n"
							L"\n"
							L"Cannot reach server... are you online?\n"
							L"\n",
							L"Error!", MB_OK );
				return FALSE;
			}
		}
		break;

		case IDCANCEL:
			EndDialog( hDlg, TRUE );
			return TRUE;
		}
		return FALSE;

	case WM_CLOSE:
		EndDialog( hDlg, FALSE );
		return TRUE;

	default:
		return FALSE;
	}
}