Ejemplo n.º 1
0
    int ToJsonObj(const Message& message, Json::Value& value)
    {
        const Reflection* pReflection = message.GetReflection();
        const FieldDescriptor* pFieldDescriptor = NULL;
        bool bRepeated = false;

        std::vector<const FieldDescriptor*> fields;
        pReflection->ListFields(message, &fields);
        int ret = 0;

        for (size_t i = 0; i < fields.size(); i++)
        {
            pFieldDescriptor = fields[i];
            bRepeated = pFieldDescriptor->is_repeated();
            string name_str = pFieldDescriptor->name();
            map<string, string> key_map;

            if (bRepeated)
            {
                ret += ToJsonArray(message, pFieldDescriptor, value, name_str, key_map);
                continue;
            }

            ret += ToJson(message, pFieldDescriptor, value, name_str, key_map);
        }

        return ret;
    }
Ejemplo n.º 2
0
		JSON* ManufacturerInfo::ToJson(unsigned short wLanguageCode)
		{
			JSON* pRet = ToJson();
			if (m_Display.find(wLanguageCode) != m_Display.end())
			{
				pRet->AddStringItem("Display", m_Display[wLanguageCode].ToCStr());
			}
			return pRet;
		}
Ejemplo n.º 3
0
std::string
JsonParse::ToJson()
{
    std::string str;

    if (m_ctx.Current()) {
        str = ToJson(static_cast<JsonValue *>(m_ctx.Current()));
    }
    return str;
}
void ResourceContainer::PushJson(MojObject& array) const
{
	MojErr errs = MojErrNone;

	MojObject rep(MojObject::TypeObject);

	MojErr err = ToJson(rep);
	MojErrAccumulate(errs, err);

	err = array.push(rep);
	MojErrAccumulate(errs, err);

	if (errs) {
		throw std::runtime_error("Unable to convert resource container to "
			"JSON object");
	}
}
Ejemplo n.º 5
0
bool UITheme::WriteToFile(const utf8 * path) const
{
    json_t * jsonTheme = ToJson();
    bool     result;
    try
    {
        Json::WriteToFile(path, jsonTheme, JSON_INDENT(4) | JSON_PRESERVE_ORDER);
        result = true;
    }
    catch (Exception ex)
    {
        log_error("Unable to save %s: %s", path, ex.GetMessage());
        result = false;
    }

    json_decref(jsonTheme);
    return result;
}
Ejemplo n.º 6
0
void sGameRecorded::save() {

    if (g_Fodder->mParams->mDemoRecord) {
        std::string Filename = g_Fodder->mParams->mDemoFile;
        if (Filename == "-") {
            Filename = std::to_string(g_Fodder->mGame_Data.mMission_Number);
            Filename += "-";
            Filename += std::to_string(g_Fodder->mGame_Data.mMission_Phase);
        }

        if (Filename.find(".") == Filename.npos)
            Filename += DEMO_EXTENSION;

        g_Debugger->Notice("Writing demo to " + Filename);
        std::ofstream outfile(Filename, std::ofstream::binary);
        outfile << ToJson();
        outfile.close();
    }
}
Ejemplo n.º 7
0
base::ByteBuffer *StatsPoster::MakeBody(const GameStats& stats) {
    std::string json = ToJson(stats);

    // Create HMAC like signature of hash(json + secret) so the receiver
    // can ensure it is valid.
    MD5_CTX md5;
    MD5Init(&md5);
    MD5Update(&md5, (const byte *)json.c_str(), json.size());
    MD5Update(&md5, (const byte *)kszStatSecret, strlen(kszStatSecret));
    byte hash[16];
    MD5Final(hash, &md5);
    char hash_str[33];
    strncpyz(hash_str, base::Format::ToHex(hash, sizeof(hash)),
            sizeof(hash_str));
    base::ByteBuffer *bb = new base::ByteBuffer(32 + json.size());
    bb->WriteBytes((const byte *)hash_str, 32);
    bb->WriteBytes((const byte *)json.c_str(), json.size());
    return bb;
}
Ejemplo n.º 8
0
std::string ClientJson::from_response(Client::Response response) {
  auto str = json_encode<string>(ToJson(static_cast<td_api::Object &>(*response.object)));
  CHECK(!str.empty() && str.back() == '}');
  std::string extra;
  if (response.id != 0) {
    std::lock_guard<std::mutex> guard(mutex_);
    auto it = extra_.find(response.id);
    if (it != extra_.end()) {
      extra = std::move(it->second);
      extra_.erase(it);
    }
  }
  if (!extra.empty()) {
    str.pop_back();
    str.reserve(str.size() + 10 + extra.size());
    str += ",\"@extra\":";
    str += extra;
    str += "}";
  }
  return str;
}
Ejemplo n.º 9
0
void UAssetImportData::Serialize(FArchive& Ar)
{
	if (Ar.UE4Ver() >= VER_UE4_ASSET_IMPORT_DATA_AS_JSON)
	{
		FString Json;
		if (Ar.IsLoading())
		{
			Ar << Json;
			TOptional<FAssetImportInfo> Copy = FromJson(MoveTemp(Json));
			if (Copy.IsSet())
			{
				CopyFrom(Copy.GetValue());
			}
		}
		else if (Ar.IsSaving())
		{
			Json = ToJson();
			Ar << Json;
		}
	}

	Super::Serialize(Ar);
}
Ejemplo n.º 10
0
    int ToJsonObjMap(const Message& message, Json::Value& value, map<string, string>& key_map)
    {
        const Reflection* pReflection = message.GetReflection();
        const FieldDescriptor* pFieldDescriptor = NULL;
        bool bRepeated = false;

        std::vector<const FieldDescriptor*> fields;
        pReflection->ListFields(message, &fields);
        int ret = 0;

        for (size_t i = 0; i < fields.size(); i++)
        {
            pFieldDescriptor = fields[i];
            bRepeated = pFieldDescriptor->is_repeated();
            string name_str = pFieldDescriptor->containing_type()->name() + "." + pFieldDescriptor->name();

            map<string, string>::iterator it = key_map.find(name_str);
            if (it != key_map.end())
            {
                name_str = it->second;
            }
            else
            {
                name_str = pFieldDescriptor->name();
            }

            if (bRepeated)
            {
                ret += ToJsonArray(message, pFieldDescriptor, value, name_str, key_map);
                continue;
            }

            ret += ToJson(message, pFieldDescriptor, value, name_str, key_map);
        }

        return ret;
    }
Ejemplo n.º 11
0
bool FPerfCounters::Tick(float DeltaTime)
{
	// if we didn't get a socket, don't tick
	if (Socket == nullptr)
	{
		return false;
	}

	// accept any connections
	static const FString PerfCounterRequest = TEXT("FPerfCounters Request");
	FSocket* IncomingConnection = Socket->Accept(PerfCounterRequest);
	if (IncomingConnection)
	{
		// make sure this is non-blocking
		bool bSuccess = false;
		IncomingConnection->SetNonBlocking(true);

		// read any data that's ready
		// NOTE: this is not a full HTTP implementation, just enough to be usable by curl
		uint8 Buffer[2*1024] = { 0 };
		int32 DataLen = 0;
		if (IncomingConnection->Recv(Buffer, sizeof(Buffer)-1, DataLen, ESocketReceiveFlags::None))
		{
			// scan the buffer for a line
			FUTF8ToTCHAR WideBuffer(reinterpret_cast<const ANSICHAR*>(Buffer));
			const TCHAR* BufferEnd = FCString::Strstr(WideBuffer.Get(), TEXT("\r\n"));
			if (BufferEnd != nullptr)
			{
				// crack into pieces
				FString MainLine(BufferEnd - WideBuffer.Get(), WideBuffer.Get());
				TArray<FString> Tokens;
				MainLine.ParseIntoArrayWS(Tokens);
				if (Tokens.Num() >= 2)
				{
					FString Body;
					int ResponseCode = 200;

					// handle the request
					if (Tokens[0] != TEXT("GET"))
					{
						Body = FString::Printf(TEXT("{ \"error\": \"Method %s not allowed\" }"), *Tokens[0]);
						ResponseCode = 405;
					}
					else if (Tokens[1] == TEXT("/stats"))
					{
						Body = ToJson();
					}
					else
					{
						Body = FString::Printf(TEXT("{ \"error\": \"%s not found\" }"), *Tokens[1]);
						ResponseCode = 404;
					}

					// send the response headers
					FString Header = FString::Printf(TEXT("HTTP/1.0 %d\r\nContent-Length: %d\r\nContent-Type: application/json\r\n\r\n"), ResponseCode, Body.Len());
					if (SendAsUtf8(IncomingConnection, Header) && SendAsUtf8(IncomingConnection, Body))
					{
						bSuccess = true;
					}
				}
			}
		}

		// log if we didn't succeed
		if (!bSuccess)
		{
			UE_LOG(LogPerfCounters, Warning, TEXT("FPerfCounters was unable to send a JSON response (or sent partial response)"));
		}

		// close the socket (whether we processed or not
		IncomingConnection->Close();
		ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(IncomingConnection);
	}

	// keep ticking
	return true;
}
Ejemplo n.º 12
0
bool FPerfCounters::ProcessRequest(uint8* Buffer, int32 BufferLen, FResponse& Response)
{
	bool bSuccess = false;

	// scan the buffer for a line
	FUTF8ToTCHAR WideBuffer(reinterpret_cast<const ANSICHAR*>(Buffer));
	const TCHAR* BufferEnd = FCString::Strstr(WideBuffer.Get(), TEXT("\r\n"));
	if (BufferEnd != nullptr)
	{
		// crack into pieces
		FString MainLine(BufferEnd - WideBuffer.Get(), WideBuffer.Get());
		TArray<FString> Tokens;
		MainLine.ParseIntoArrayWS(Tokens);
		if (Tokens.Num() >= 2)
		{
			FString ContentType(TEXT("application/json"));
			Response.Code = 200;

			// handle the request
			if (Tokens[0] != TEXT("GET"))
			{
				Response.Body = FString::Printf(TEXT("{ \"error\": \"Method %s not allowed\" }"), *Tokens[0]);
				Response.Code = 405;
			}
			else if (Tokens[1].StartsWith(TEXT("/stats")))
			{
				Response.Body = ToJson();

				// retrieving stats resets them by default, unless ?peek parameter is passed
				const int kStatsTokenLength = 6; // strlen("/stats");
				FString TokenRemainder = Tokens[1].Mid(kStatsTokenLength);
				if (TokenRemainder != TEXT("?peek"))
				{
					if (ExecCmdCallback.IsBound())
					{
						ExecCmdCallback.Execute(TEXT("perfcounters clear"), *GLog);
					}
					else
					{
						Exec(nullptr, TEXT("perfcounters clear"), *GLog);
					}
				}
			}
			else if (Tokens[1].StartsWith(TEXT("/exec?c=")))
			{
				FString ExecCmd = Tokens[1].Mid(8);
				FString ExecCmdDecoded = FPlatformHttp::UrlDecode(ExecCmd);

				FStringOutputDevice StringOutDevice;
				StringOutDevice.SetAutoEmitLineTerminator(true);

				bool bResult = false;
				if (ExecCmdCallback.IsBound())
				{
					bResult = ExecCmdCallback.Execute(ExecCmdDecoded, StringOutDevice);
					Response.Body = StringOutDevice;
					ContentType = TEXT("text/text");
				}
				else
				{
					Response.Body = FString::Printf(TEXT("{ \"error\": \"exec handler not found\" }"));
				}

				Response.Code = bResult ? 200 : 404;
			}
			else
			{
				Response.Body = FString::Printf(TEXT("{ \"error\": \"%s not found\" }"), *Tokens[1]);
				Response.Code = 404;
			}

			// send the response headers
			Response.Header = FString::Printf(TEXT("HTTP/1.0 %d\r\nContent-Length: %d\r\nContent-Type: %s\r\n\r\n"), Response.Code, Response.Body.Len(), *ContentType);
			bSuccess = true;
		}
		else
		{
			UE_LOG(LogPerfCounters, Warning, TEXT("Unable to parse HTTP request header: %s"), *MainLine);
		}
	}
	else
	{
		UE_LOG(LogPerfCounters, Warning, TEXT("Unable to immediately receive full request header"));
	}

	return bSuccess;
}