bool ModelImporter::SaveSettingsInternal()
{
    if (!AssetImporter::SaveSettingsInternal())
        return false;

    JSONValue save = jsonRoot_.CreateChild("ModelImporter");

    save.SetFloat("scale", scale_);
    save.SetBool("importAnimations", importAnimations_);

    JSONValue animInfo = save.CreateChild("animInfo", JSON_ARRAY);

    for (unsigned i = 0; i < animationInfo_.Size(); i++)
    {
        const SharedPtr<AnimationImportInfo>& info = animationInfo_[i];
        JSONValue jinfo = animInfo.CreateChild();
        jinfo.SetString("name", info->GetName());
        jinfo.SetFloat("startTime", info->GetStartTime());
        jinfo.SetFloat("endTime", info->GetEndTime());
    }

    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);
			}
		}
Esempio n. 3
0
// load .asset
bool Asset::Load()
{
    FileSystem* fs = GetSubsystem<FileSystem>();
    AssetDatabase* db = GetSubsystem<AssetDatabase>();

    String assetFilename = GetDotAssetFilename();

    SharedPtr<File> file(new File(context_, assetFilename));
    json_ = new JSONFile(context_);
    json_->Load(*file);
    file->Close();

    JSONValue root = json_->GetRoot();

    assert(root.Get("version").GetInt() == ASSET_VERSION);

    guid_ = root.Get("guid").GetString();

    db->RegisterGUID(guid_);

    dirty_ = false;
    if (!CheckCacheFile())
    {
        LOGINFOF("CheckCacheFile:false - %s", path_.CString());
        dirty_ = true;
    }

    // handle import

    if (importer_.NotNull())
        importer_->LoadSettings(root);

    json_ = 0;

    return true;

}
    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;
    }
Esempio n. 5
0
bool NETToolSystem::InspectAssembly(const String& pathToAssembly, JSONValue &json)
{
    json.SetType(JSON_NULL);

    if (!inspectAssemblyFunction_)
        return false;

    String jsonString = inspectAssemblyFunction_(pathToAssembly.CString());

    if (!jsonString.Length())
        return false;

    return JSONFile::ParseJSON(jsonString, json);

}
void IOSBuildSettings::Write(JSONValue& parent)
{
    JSONValue json;

    json.Set("appName", appName_);
    json.Set("packageName", packageName_);
    json.Set("companyName", companyName_);
    json.Set("productName", productName_);

    json.Set("provisionFile", provisionFile_);
    json.Set("appIDPrefix", appidPrefix_);

    parent.Set("IOSBuildSettings", json);

}
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();

}
Esempio n. 8
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;
}
Esempio n. 9
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();
}
Esempio n. 10
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;
}
bool ResourceMapRouter::Load(const JSONValue& json)
{
    const JSONValue& assetMap = json.Get("assetMap");

    if (!assetMap.IsObject())
        return false;

    ConstJSONObjectIterator itr = assetMap.Begin();
    while (itr != assetMap.End())
    {
        StringVector tags = itr->first_.Split(';');

        if (tags.Size() == 2)
        {
            resourceMap_[tags[0]][tags[1]] = itr->second_.GetString();
        }

        itr++;
    }

    return true;
}
Esempio n. 12
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());
}
Esempio n. 13
0
  void QuizSubmission::save(QuizQuestion const* qq,
                            JSONValue &document,
                            Session &session,
                            AsyncCallback callback) const {
    document["validation_token"] = validationToken();
    document["attempt"] = attempt();
    document["access_code"] = mQuiz->accessCode();

    session.put(qq->answerUrl(*this),
      document.toStyledString(),
      [&, callback](bool success, HTTP::Response response) {
        if (!success) {
          if (callback) {
            callback(false);
          }
          return;
        }

        if (callback) {
          callback(true);
        }
      });
  }
Esempio n. 14
0
bool ObjectAnimation::SaveJSON(JSONValue& dest) const
{
    JSONValue attributeAnimationsValue;

    for (HashMap<String, SharedPtr<ValueAnimationInfo> >::ConstIterator i = attributeAnimationInfos_.Begin();
         i != attributeAnimationInfos_.End(); ++i)
    {
        JSONValue animValue;
        animValue.Set("name", i->first_);

        const ValueAnimationInfo* info = i->second_;
        if (!info->GetAnimation()->SaveJSON(animValue))
            return false;

        animValue.Set("wrapmode", wrapModeNames[info->GetWrapMode()]);
        animValue.Set("speed", (float) info->GetSpeed());

        attributeAnimationsValue.Set(i->first_, animValue);
    }

    dest.Set("attributeanimations", attributeAnimationsValue);
    return true;
}
Esempio n. 15
0
bool Animatable::SaveJSON(JSONValue& dest) const
{
    if (!Serializable::SaveJSON(dest))
        return false;

    // Object animation without name
    if (objectAnimation_ && objectAnimation_->GetName().Empty())
    {
        JSONValue objectAnimationValue;
        if (!objectAnimation_->SaveJSON(objectAnimationValue))
            return false;
        dest.Set("objectanimation", objectAnimationValue);
    }

    JSONValue attributeAnimationValue;

    for (HashMap<String, SharedPtr<AttributeAnimationInfo> >::ConstIterator i = attributeAnimationInfos_.Begin();
         i != attributeAnimationInfos_.End(); ++i)
    {
        ValueAnimation* attributeAnimation = i->second_->GetAnimation();
        if (attributeAnimation->GetOwner())
            continue;

        const AttributeInfo& attr = i->second_->GetAttributeInfo();
        JSONValue attributeValue;
        attributeValue.Set("name", attr.name_);
        if (!attributeAnimation->SaveJSON(attributeValue))
            return false;

        attributeValue.Set("wrapmode", wrapModeNames[i->second_->GetWrapMode()]);
        attributeValue.Set("speed", (float) i->second_->GetSpeed());

        attributeAnimationValue.Set(attr.name_, attributeValue);
    }

    return true;
}
Esempio n. 16
0
JSONValue::JSONValue(const JSONValue &v) {
  m_type = v.getType();

  switch (m_type) {
  case JSONValue::NULLTYPE:
    break; // nothing to do
  case JSONValue::BOOL:
    if (!v.getValue(m_bool))
      throw(JSONCopyException("Failed to copy boolean"));
    break;
  case JSONValue::NUMBER:
    if (!v.getValue(m_num))
      throw(JSONCopyException("Failed to copy float"));
    break;
  case JSONValue::STRING:
    mp_string = new string;
    if (!v.getValue(*mp_string)) {
      delete mp_string; // Make sure we don't leak memory in the event of a
                        // failure
      throw(JSONCopyException("Failed to copy string"));
    }
    break;
  case JSONValue::ARRAY:
    mp_array = new JSONArray;
    if (!v.getValue(*mp_array)) {
      delete mp_array;
      throw(JSONCopyException("Failed to copy array"));
    }
    break;
  case JSONValue::OBJECT:
    mp_object = new JSONObject;
    if (!v.getValue(*mp_object)) {
      delete mp_object;
      throw(JSONCopyException("Failed to copy object"));
    }
    break;
  default:
    // Should never hit this!
    throw(JSONCopyException("Unknown JSON type!!"));
  }
}
Esempio n. 17
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;
}
bool UnknownComponent::SaveJSON(JSONValue& dest) const
{
    if (!useXML_)
        ATOMIC_LOGWARNING("UnknownComponent loaded in binary mode, attributes will be empty for JSON save");

    // Write type and ID
    dest.Set("type", GetTypeName());
    dest.Set("id", (int) id_);

    JSONArray attributesArray;
    attributesArray.Reserve(xmlAttributeInfos_.Size());
    for (unsigned i = 0; i < xmlAttributeInfos_.Size(); ++i)
    {
        JSONValue attrVal;
        attrVal.Set("name", xmlAttributeInfos_[i].name_);
        attrVal.Set("value", xmlAttributes_[i]);
        attributesArray.Push(attrVal);
    }
    dest.Set("attributes", attributesArray);

    return true;
}
Esempio n. 19
0
bool ModelImporter::LoadSettingsInternal()
{
    if (!AssetImporter::LoadSettingsInternal())
        return false;

    JSONValue import = jsonRoot_.GetChild("ModelImporter", JSON_OBJECT);

    SetDefaults();

    if (import.HasMember("scale"))
        scale_ = import.GetFloat("scale");

    if (import.HasMember("importAnimations"))
        importAnimations_ = import.GetBool("importAnimations");

    if (import.HasMember("animInfo"))
    {
        JSONValue animInfo = import.GetChild("animInfo");
        for (unsigned i = 0; i < animInfo.GetSize(); i++)
        {
            JSONValue anim = animInfo.GetChild(i);

            SharedPtr<AnimationImportInfo> info(new AnimationImportInfo(context_));

            info->name_ = anim.GetString("name");
            info->SetStartTime(anim.GetFloat("startTime"));
            info->SetEndTime(anim.GetFloat("endTime"));

            animationInfo_.Push(info);

        }
    }

    return true;
}
Esempio n. 20
0
 void Student::Login::deserialize(JSONValue& root) {
   mUserId = root.get("user_id", 0).asUInt();
 }
    bool CSComponentAssembly::ParseComponentClassJSON(const JSONValue& json)
    {
        if (!typeMap_.Size())
            InitTypeMap();

        String className = json.Get("name").GetString();

        classNames_.Push(className);

        const JSONValue& jfields = json.Get("fields");

        PODVector<StringHash> enumsAdded;

        if (jfields.IsArray())
        {
            for (unsigned i = 0; i < jfields.GetArray().Size(); i++)
            {
                const JSONValue& jfield = jfields.GetArray().At(i);

                VariantType varType = VAR_NONE;

                bool isEnum = jfield.Get("isEnum").GetBool();
                String typeName = jfield.Get("typeName").GetString();
                String fieldName = jfield.Get("name").GetString();
                String defaultValue = jfield.Get("defaultValue").GetString();

                if (!defaultValue.Length())
                {
                    JSONArray caPos = jfield.Get("caPos").GetArray();
                    if (caPos.Size())
                        defaultValue = caPos[0].GetString();
                }

                if (!defaultValue.Length())
                {
                    JSONObject caNamed = jfield.Get("caNamed").GetObject();
                    if (caNamed.Contains("DefaultValue"))
                        defaultValue = caNamed["DefaultValue"].GetString();
                }

                if (isEnum && assemblyEnums_.Contains(typeName) && !enumsAdded.Contains(fieldName))
                {
                    varType = VAR_INT;
                    enumsAdded.Push(fieldName);
                    const Vector<EnumInfo>& einfos = assemblyEnums_[typeName];
                    for (unsigned i = 0; i < einfos.Size(); i++)
                        AddEnum(/*typeName*/fieldName, einfos[i], className);
                }

                if (varType == VAR_NONE && typeMap_.Contains(typeName))
                    varType = typeMap_[typeName];

                if (varType == VAR_NONE)
                {
                    // FIXME: We need to be able to test if a type is a ResourceRef, this isn't really the way to achieve that
                    const HashMap<StringHash, SharedPtr<ObjectFactory>>& factories = context_->GetObjectFactories();
                    HashMap<StringHash, SharedPtr<ObjectFactory>>::ConstIterator itr = factories.Begin();

                    while (itr != factories.End())
                    {
                        if (itr->second_->GetTypeName() == typeName)
                        {
                            varType = VAR_RESOURCEREF;
                            break;
                        }

                        itr++;
                    }

                    if (varType == VAR_NONE)
                    {
                        ATOMIC_LOGERRORF("Component Class %s contains unmappable type %s in field %s",
                            className.CString(), typeName.CString(), fieldName.CString());

                        continue;
                    }

                }

                if (!defaultValue.Length() && varType == VAR_RESOURCEREF)
                {
                    // We still need a default value for ResourceRef's so we know the classtype
                    AddDefaultValue(fieldName, ResourceRef(typeName), className);
                }
                else
                {
                    Variant value;

                    if (varType == VAR_RESOURCEREF)
                    {
                        ResourceRef rref(typeName);
                        rref.name_ = defaultValue;
                        value = rref;
                    }
                    else
                    {
                        value.FromString(varType, defaultValue);
                    }

                    AddDefaultValue(fieldName, value, className);
                }

                AddField(fieldName, varType, className);

            }

        }

        return true;
    }
Esempio n. 22
0
bool Animation::BeginLoad(Deserializer& source)
{
    unsigned memoryUse = sizeof(Animation);

    // Check ID
    if (source.ReadFileID() != "UANI")
    {
        URHO3D_LOGERROR(source.GetName() + " is not a valid animation file");
        return false;
    }

    // Read name and length
    animationName_ = source.ReadString();
    animationNameHash_ = animationName_;
    length_ = source.ReadFloat();
    tracks_.Clear();

    unsigned tracks = source.ReadUInt();
    memoryUse += tracks * sizeof(AnimationTrack);

    // Read tracks
    for (unsigned i = 0; i < tracks; ++i)
    {
        AnimationTrack* newTrack = CreateTrack(source.ReadString());
        newTrack->channelMask_ = source.ReadUByte();

        unsigned keyFrames = source.ReadUInt();
        newTrack->keyFrames_.Resize(keyFrames);
        memoryUse += keyFrames * sizeof(AnimationKeyFrame);

        // Read keyframes of the track
        for (unsigned j = 0; j < keyFrames; ++j)
        {
            AnimationKeyFrame& newKeyFrame = newTrack->keyFrames_[j];
            newKeyFrame.time_ = source.ReadFloat();
            if (newTrack->channelMask_ & CHANNEL_POSITION)
                newKeyFrame.position_ = source.ReadVector3();
            if (newTrack->channelMask_ & CHANNEL_ROTATION)
                newKeyFrame.rotation_ = source.ReadQuaternion();
            if (newTrack->channelMask_ & CHANNEL_SCALE)
                newKeyFrame.scale_ = source.ReadVector3();
        }
    }

    // Optionally read triggers from an XML file
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    String xmlName = ReplaceExtension(GetName(), ".xml");

    SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
    if (file)
    {
        XMLElement rootElem = file->GetRoot();
        XMLElement triggerElem = rootElem.GetChild("trigger");
        while (triggerElem)
        {
            if (triggerElem.HasAttribute("normalizedtime"))
                AddTrigger(triggerElem.GetFloat("normalizedtime"), true, triggerElem.GetVariant());
            else if (triggerElem.HasAttribute("time"))
                AddTrigger(triggerElem.GetFloat("time"), false, triggerElem.GetVariant());

            triggerElem = triggerElem.GetNext("trigger");
        }

        memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
        SetMemoryUse(memoryUse);
        return true;
    }

    // Optionally read triggers from a JSON file
    String jsonName = ReplaceExtension(GetName(), ".json");

    SharedPtr<JSONFile> jsonFile(cache->GetTempResource<JSONFile>(jsonName, false));
    if (jsonFile)
    {
        const JSONValue& rootVal = jsonFile->GetRoot();
        JSONArray triggerArray = rootVal.Get("triggers").GetArray();

        for (unsigned i = 0; i < triggerArray.Size(); i++)
        {
            const JSONValue& triggerValue = triggerArray.At(i);
            JSONValue normalizedTimeValue = triggerValue.Get("normalizedTime");
            if (!normalizedTimeValue.IsNull())
                AddTrigger(normalizedTimeValue.GetFloat(), true, triggerValue.GetVariant());
            else
            {
                JSONValue timeVal = triggerValue.Get("time");
                if (!timeVal.IsNull())
                    AddTrigger(timeVal.GetFloat(), false, triggerValue.GetVariant());
            }
        }

        memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
        SetMemoryUse(memoryUse);
        return true;
    }

    SetMemoryUse(memoryUse);
    return true;
}
void AssetDatabase::Scan()
{
    PruneOrphanedDotAssetFiles();

    FileSystem* fs = GetSubsystem<FileSystem>();
    const String& resourcePath = project_->GetResourcePath();

    Vector<String> allResults;

    fs->ScanDir(allResults, resourcePath, "", SCAN_FILES | SCAN_DIRS, true);

    Vector<String> filteredResults;

    filteredResults.Push(RemoveTrailingSlash(resourcePath));

    for (unsigned i = 0; i < allResults.Size(); i++)
    {
        allResults[i] = resourcePath + allResults[i];

        const String& path = allResults[i];

        if (path.StartsWith(".") || path.EndsWith("."))
            continue;

        String ext = GetExtension(path);

        if (ext == ".asset")
            continue;

        filteredResults.Push(path);
    }

    for (unsigned i = 0; i < filteredResults.Size(); i++)
    {
        const String& path = filteredResults[i];

        String dotAssetFilename = GetDotAssetFilename(path);

        if (!fs->FileExists(dotAssetFilename))
        {
            // new asset
            SharedPtr<Asset> asset(new Asset(context_));

            if (asset->SetPath(path))
                AddAsset(asset);
        }
        else
        {
            SharedPtr<File> file(new File(context_, dotAssetFilename));
            SharedPtr<JSONFile> json(new JSONFile(context_));
            json->Load(*file);
            file->Close();

            JSONValue root = json->GetRoot();

            assert(root.Get("version").GetInt() == ASSET_VERSION);

            String guid = root.Get("guid").GetString();

            if (!GetAssetByGUID(guid))
            {
                SharedPtr<Asset> asset(new Asset(context_));
                asset->SetPath(path);
                AddAsset(asset);
            }

        }

    }

    PreloadAssets();

    if (ImportDirtyAssets())
        Scan();

}
bool ValueAnimation::SaveJSON(JSONValue& dest) const
{
    dest.Set("interpolationmethod", interpMethodNames[interpolationMethod_]);
    if (interpolationMethod_ == IM_SPLINE)
        dest.Set("splinetension", (float) splineTension_);

    JSONArray keyFramesArray;
    keyFramesArray.Reserve(keyFrames_.Size());
    for (unsigned i = 0; i < keyFrames_.Size(); ++i)
    {
        const VAnimKeyFrame& keyFrame = keyFrames_[i];
        JSONValue keyFrameVal;
        keyFrameVal.Set("time", keyFrame.time_);
        JSONValue valueVal;
        valueVal.SetVariant(keyFrame.value_);
        keyFrameVal.Set("value", valueVal);
        keyFramesArray.Push(keyFrameVal);
    }
    dest.Set("keyframes", keyFramesArray);

    JSONArray eventFramesArray;
    eventFramesArray.Reserve(eventFrames_.Size());
    for (unsigned i = 0; i < eventFrames_.Size(); ++i)
    {
        const VAnimEventFrame& eventFrame = eventFrames_[i];
        JSONValue eventFrameVal;
        eventFrameVal.Set("time", eventFrame.time_);
        eventFrameVal.Set("eventtype", eventFrame.eventType_.Value());
        JSONValue eventDataVal;
        eventDataVal.SetVariantMap(eventFrame.eventData_);
        eventFrameVal.Set("eventdata", eventDataVal);

        eventFramesArray.Push(eventFrameVal);
    }
    dest.Set("eventframes", eventFramesArray);

    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);
				}
			}
		}
	}



}
Esempio n. 26
0
    bool IoDisk::save(Image & image, JSON & data)
    {
        // ----------------------------------------
        // The naming convention that will be used
        // for the image.
        
        std::string pathToImage = getFileFormat();

        // ------------------------------------------
        // Stringify data object: build image path
        // with data information.
        
        static const std::string kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
        for (JSONValue::ConstMemberIterator itr = data.MemberBegin(); itr != data.MemberEnd(); ++itr)
        {
            std::string name = itr->name.GetString();
            std::string type = kTypeNames[itr->value.GetType()];
            
            if(type == "String")
            {
                std::string value = itr->value.GetString();
                kerberos::helper::replace(pathToImage, name, value);
            }
            else if(type == "Number")
            {
                std::string value = kerberos::helper::to_string(itr->value.GetInt());
                kerberos::helper::replace(pathToImage, name, value);
            }
            else if(type == "Array")
            {
                std::string arrayString = "";
                for (JSONValue::ConstValueIterator itr2 = itr->value.Begin(); itr2 != itr->value.End(); ++itr2)
                {
                    type = kTypeNames[itr2->GetType()];
                    
                    if(type == "String")
                    {
                        arrayString += itr2->GetString();
                    }
                    else if(type == "Number")
                    {
                       arrayString += kerberos::helper::to_string(itr2->GetInt());
                    }
                    
                    arrayString += "-";
                }
                kerberos::helper::replace(pathToImage, name, arrayString.substr(0, arrayString.size()-1));
            }
        }
        
        /// ---------------------
        // Replace variables

        pathToImage = buildPath(pathToImage);

        // -------------------------------------------------------
        // Add path to JSON object, so other IO devices can use it
        
        JSONValue path;
        JSON::AllocatorType& allocator = data.GetAllocator();
        path.SetString(pathToImage.c_str(), allocator);
        data.AddMember("pathToImage", path, allocator);
        
        // ------------------
        // Draw date on image
        
        drawDateOnImage(image, data["timestamp"].GetString());
        
        // -------------------------
        // Save original version

        BINFO << "IoDisk: saving image " + pathToImage;
        return m_fileManager.save(image, pathToImage);
    }
Esempio n. 27
0
void Server::Update(float frametime)
{
    TundraLogic* tundraLogic = framework_->Module<TundraLogic>();
    ::Server* tundraServer = tundraLogic->Server();

    // Clean dead requestedConnections
    if (!connections_.Empty())
    {
        WebSocket::UserConnectionList::Iterator cleanupIter = connections_.Begin();
        while (cleanupIter != connections_.End())
        {
            WebSocket::UserConnectionPtr connection = *cleanupIter;
            if (!connection)
            {
                cleanupIter = connections_.Erase(cleanupIter);
            }
            else if (connection->webSocketConnection.expired())
            {
                // If user was already registered to the Tundra server, remove from there
                tundraServer->RemoveExternalUser(Urho3D::StaticCast<::UserConnection>(connection));
                if (!connection->userID)
                    LogDebug(LC + "Removing non-logged in WebSocket connection.");
                else
                    LogInfo(LC + "Removing expired WebSocket connection with ID " + String(connection->userID));
                cleanupIter = connections_.Erase(cleanupIter);
            }
            else
            {
                ++cleanupIter;
            }
        }
    }
    
    Vector<SocketEvent*> processEvents;
    {
        Urho3D::MutexLock lockEvents(mutexEvents_);
        if (events_.Size() == 0)
            return;
        // Make copy of current event queue for processing
        processEvents = events_;
        events_.Clear();
    }

    Vector<UserConnectionPtr> toDisconnect;

    // Process events pushed from the websocket thread(s)
    for (uint i=0; i < processEvents.Size(); ++i)
    {
        SocketEvent *event = processEvents[i];
        if (!event)
            continue;

        // User connected
        if (event->type == SocketEvent::Connected)
        {
            if (!UserConnection(event->connection))
            {
                WebSocket::UserConnectionPtr userConnection(new WebSocket::UserConnection(context_, event->connection));
                connections_.Push(userConnection);

                // The connection does not yet have an ID assigned. Tundra server will assign on login
                LogDebug(LC + String("New WebSocket connection."));
            }
        }
        // User disconnected
        else if (event->type == SocketEvent::Disconnected)
        {
            for(UserConnectionList::Iterator iter = connections_.Begin(); iter != connections_.End(); ++iter)
            {
                if ((*iter) && (*iter)->WebSocketConnection() == event->connection)
                {
                    tundraServer->RemoveExternalUser(Urho3D::StaticCast<::UserConnection>(*iter));
                    if (!(*iter)->userID)
                        LogDebug(LC + "Removing non-logged in WebSocket connection.");
                    else
                        LogInfo(LC + "Removing WebSocket connection with ID " + String((*iter)->userID));
                    connections_.Erase(iter);
                    break;
                }
            }
        }
        // Data message
        else if (event->type == SocketEvent::Data && event->data.get())
        {
            WebSocket::UserConnectionPtr userConnection = UserConnection(event->connection);
            if (userConnection)
            {
                kNet::DataDeserializer dd(event->data->GetData(), event->data->BytesFilled());
                u16 messageId = dd.Read<u16>();

                // LoginMessage
                if (messageId == cLoginMessage)
                {
                    bool ok = false;
                    String loginDataString = ReadUtf8String(dd);
                    // Read optional protocol version
                    if (dd.BytesLeft())
                        userConnection->protocolVersion = (NetworkProtocolVersion)dd.ReadVLE<kNet::VLE8_16_32>();

                    JSONValue json;
                    ok = json.FromString(loginDataString);
                    if (ok)
                    {
                        JSONObject jsonObj = json.GetObject();
                        for (JSONObject::ConstIterator i = jsonObj.Begin(); i != jsonObj.End(); ++i)
                            userConnection->properties[i->first_] = i->second_.ToVariant();
                        userConnection->properties["authenticated"] = true;
                        bool success = tundraServer->AddExternalUser(Urho3D::StaticCast<::UserConnection>(userConnection));
                        if (!success)
                        {
                            LogInfo(LC + "Connection ID " + String(userConnection->userID) + " login refused");
                            toDisconnect.Push(userConnection);
                        }
                        else
                            LogInfo(LC + "Connection ID " + String(userConnection->userID) + " login successful");
                    }
                }
                else
                {
                    // Only signal messages from authenticated users
                    if (userConnection->properties["authenticated"].GetBool() == true)
                    {
                        // Signal network message. As per kNet tradition the message ID is given separately in addition with the rest of the data
                        NetworkMessageReceived.Emit(userConnection.Get(), messageId, event->data->GetData() + sizeof(u16), event->data->BytesFilled() - sizeof(u16));
                        // Signal network message on the Tundra server so that it can be globally picked up
                        tundraServer->EmitNetworkMessageReceived(userConnection.Get(), 0, messageId, event->data->GetData() + sizeof(u16), event->data->BytesFilled() - sizeof(u16));
                    }
                }
            }
            else
                LogError(LC + "Received message from unauthorized connection, ignoring.");

            event->data.reset();
        }
        else
            event->data.reset();
        
        SAFE_DELETE(event);
    }

    for (uint i = 0; i < toDisconnect.Size(); ++i)
    {
        if (toDisconnect[i])
            toDisconnect[i]->Disconnect();
    }
}
Esempio n. 28
0
// Dialog proc for the Windows window
int CALLBACK DialogProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
		case WM_INITDIALOG:
			hDlg = hWnd;
			break;

		case WM_CLOSE:
			EndDialog(hWnd, 0);
			break;

		case WM_DESTROY:
			PostQuitMessage(0);
			break;

		case WM_COMMAND:
		{
			if (HIWORD(wParam) != BN_CLICKED)
				break;

			SetWindowText(GetDlgItem(hWnd, IDC_OUTPUT), L"");

			switch (LOWORD(wParam))
			{
				case IDC_VERIFY:
				case IDC_ECHO:
				{
					int size = GetWindowTextLength(GetDlgItem(hWnd, IDC_INPUT));
					wchar_t* text = new wchar_t[size + 1];
					GetWindowText(GetDlgItem(hWnd, IDC_INPUT), text, size + 1);

					JSONValue *value = JSON::Parse(text);

					if (value == NULL)
					{
						SetWindowText(GetDlgItem(hWnd, IDC_OUTPUT), L"The JSON text *is not* valid");
					}
					else
					{
						if (LOWORD(wParam) == IDC_ECHO)
							SetWindowText(GetDlgItem(hWnd, IDC_OUTPUT), value->Stringify().c_str());
						else
							SetWindowText(GetDlgItem(hWnd, IDC_OUTPUT), L"The JSON text *is* valid");
						delete value;
					}

					delete text;
					break;
				}

				case IDC_EX1:
					extern const wchar_t *EXAMPLE;
					SetWindowText(GetDlgItem(hDlg, IDC_INPUT), EXAMPLE);
					example1();
					break;

				case IDC_EX2:
					SetWindowText(GetDlgItem(hDlg, IDC_INPUT), L"Example 2:\r\n\r\nKey 'test_string' has a value 'hello world'\r\nKey 'sample_array' is an array of 10 random numbers");
					example2();
					break;

				case IDC_TESTCASES:
					SetWindowText(GetDlgItem(hWnd, IDC_INPUT), L"");
					run_tests();
					break;
			}

			break;
		}
	}

	return 0;
}
const char* WebModelUnified::website_search(const char* req){
    JSONObject root;
    JSONArray jsarray;
    Connection* conn = connect();
    Query query = conn->query();

    string reqstr(req);
    string reqstr_spaced = replaceChar(reqstr, '+', ' ');
    vector<string> splittedstr;
    split(splittedstr, reqstr_spaced, boost::algorithm::is_any_of(" "));

    int titleForce = 10;
    int descriptionForce = 1;
    int urlForce = 3;

    query << "SELECT * , ";
    //Occurences total
    for(size_t i1 = 0; i1 < splittedstr.size(); i1++)
    {
        string s = splittedstr[i1];
        if(i1 != 0){
            query << " + ";
        }

        query << "((" <<
          titleForce << " * (char_length(title) - char_length(replace(title,'" << s << "',''))) + " <<
          descriptionForce << " * (char_length(description) - char_length(replace(description,'" << s << "',''))) + " <<
          urlForce << " * (char_length(url) - char_length(replace(url,'" << s << "','')))" <<
        ") / char_length('" << s << "'))";
    }
    query << " as Occurances " << " FROM website ";

    //Where clause
    for(size_t i1 = 0; i1 < splittedstr.size(); i1++)
    {
        string s = splittedstr[i1];
        if(i1 == 0) {
            query << "WHERE ";
        } else {
            query << "OR ";
        }
        query << "(url LIKE '%" << s << "%' or title LIKE '%" << s << "%' or description LIKE '%" << s << "%') ";
    }

    query << " ORDER BY " << "Occurances desc, title ASC ";

    StoreQueryResult ares = query.store();
    unsigned int numrow = ares.num_rows();

    for(unsigned int i = 0; i < numrow; i++)
    {
        JSONObject result;

        result[L"title"] = new JSONValue(wchartFromChar(ares[i]["title"]));
        result[L"description"] = new JSONValue(wchartFromChar(ares[i]["description"]));
        result[L"url"] = new JSONValue(wchartFromChar(ares[i]["url"]));
        JSONValue* resultVal = new JSONValue(result);

        jsarray.push_back(resultVal);
    }

    root[L"results"] = new JSONValue(jsarray);

    JSONValue* jvalue = new JSONValue(root);

    const char* returnStr = fromWString(jvalue->Stringify());
    delete jvalue;
    return returnStr;
}
Esempio n. 30
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;
}