示例#1
0
    User *User::authenticate(const string &username, const string &password)
    {

        Client client;

        JSON body;

        body.set_string("username", username);

        body.set_string("password", password);

        client.setPayload(body.to_string());

        client.get("login");

        JSON response;

        try
        {
            response = client.getJSONResponse();
        }
        catch (const exception &e)
        {
            return NULL;
        }

        if (currentUser_ != NULL)
            delete currentUser_;

        currentUser_ = new User();

        currentUser_->setUsername(username);

        currentUser_->setPassword(password);

        currentUser_->merge(response);

        return currentUser_;
    }
示例#2
0
文件: query.cpp 项目: FritzX6/osquery
Status deserializeQueryLogItem(const JSON& doc, QueryLogItem& item) {
  if (!doc.doc().IsObject()) {
    return Status(1);
  }

  if (doc.doc().HasMember("diffResults")) {
    auto status =
        deserializeDiffResults(doc.doc()["diffResults"], item.results);
    if (!status.ok()) {
      return status;
    }
  } else if (doc.doc().HasMember("snapshot")) {
    auto status =
        deserializeQueryData(doc.doc()["snapshot"], item.snapshot_results);
    if (!status.ok()) {
      return status;
    }
  }

  getLegacyFieldsAndDecorations(doc, item);
  return Status();
}
示例#3
0
void Settings::SaveOnly(const Array<const char*> &varNames)
{
	if(settingsJSON == NULL) return;

	for(int i = 0; i < variables.GetSizeI(); i++)
	{
		IVariable* var = variables[i];
		bool found = false;
		for(int namesIndex = 0; namesIndex < varNames.GetSizeI(); namesIndex++)
		{
			if(strcmp(var->name, varNames[namesIndex]) == 0)
			{
				found = true;
				break;
			}
		}
		if(!found)
		{
			continue;
		}
		var->SaveValue();

		JSON* varJSON = var->json;
		if(varJSON == NULL)
		{
			varJSON = settingsJSON->GetItemByName(var->name);
			var->json = varJSON;
		}
		if(varJSON == NULL)
		{
			settingsJSON->AddItem(var->name,var->Serialize());
		}
		else
		{
			varJSON->ReplaceNodeWith(var->Serialize());
		}
	}
	rootSettingsJSON->Save(settingsFileName);
}
示例#4
0
	uint AuthUserAccount(const char *email, const wchar_t *password)
	{
		JSON json;
		if (!BackendQuery(&json, GAME_AUTH_ACCOUNT, email, password))
			return WIC_INVALID_ACCOUNT;

		int j_status;
		if (!json.ReadInt("status", &j_status) || j_status == 0)
		{
			DatabaseLog("CreateUserAccount: JSON status failed.");
			return WIC_INVALID_ACCOUNT;
		}

		uint j_profileId;
		if (!json.ReadUInt("profileId", &j_profileId))
		{
			DatabaseLog("Error: Server returned invalid profile ID.");
			return WIC_INVALID_ACCOUNT;
		}

		return j_profileId;
	}
示例#5
0
//-----------------------------------------------------------------------------
Profile* ProfileManager::GetTaggedProfile(const char** tag_names, const char** tags, int num_tags)
{
    Lock::Locker lockScope(&ProfileLock);

    if (ProfileCache == NULL)
    {   // Load the cache
        LoadCache(false);
        if (ProfileCache == NULL)
            return NULL;
    }

    JSON* tagged_data = ProfileCache->GetItemByName("TaggedData");
    OVR_ASSERT(tagged_data);
    if (tagged_data == NULL)
        return NULL;
    
    Profile* profile = new Profile(BasePath);
    
    JSON* vals = FindTaggedData(tagged_data, tag_names, tags, num_tags);
    if (vals)
    {   
        JSON* item = vals->GetFirstItem();
        while (item)
        {
            //printf("Add %s, %s\n", item->Name.ToCStr(), item->Value.ToCStr());
            //profile->Settings.Set(item->Name, item->Value);
            profile->SetValue(item);
            item = vals->GetNextItem(item);
        }

        return profile;
    }
    else
    {
        profile->Release();
        return NULL;
    }
}
示例#6
0
文件: query.cpp 项目: FritzX6/osquery
Status serializeDiffResults(const DiffResults& d,
                            const ColumnNames& cols,
                            JSON& doc,
                            rj::Document& obj) {
  // Serialize and add "removed" first.
  // A property tree is somewhat ordered, this provides a loose contract to
  // the logger plugins and their aggregations, allowing them to parse chunked
  // lines. Note that the chunking is opaque to the database functions.
  auto removed_arr = doc.getArray();
  auto status = serializeQueryData(d.removed, cols, doc, removed_arr);
  if (!status.ok()) {
    return status;
  }
  doc.add("removed", removed_arr, obj);

  auto added_arr = doc.getArray();
  status = serializeQueryData(d.added, cols, doc, added_arr);
  if (!status.ok()) {
    return status;
  }
  doc.add("added", added_arr, obj);
  return Status();
}
示例#7
0
JSON* JSON::GetItemByIndex(unsigned index)
{
    unsigned i     = 0;
    JSON*    child = 0;

    if (!Children.IsEmpty())
    {
        child = Children.GetFirst();

        while (i < index)
        {   
            if (Children.IsLast(child))
            {
                child = 0;
                break;
            }
            child = child->GetNext();
            i++;
        }
    }
  
    return child;
}
示例#8
0
void Settings::DeleteVar(const char* varName)
{
	if(settingsJSON == NULL) return;

	// Undefine the variable
	for(int i = 0; i < variables.GetSizeI(); i++)
	{
		if(strcmp(variables[i]->name, varName) == 0)
		{
			IVariable* toDel = variables[i];
			variables.RemoveAtUnordered(i);
			delete(toDel);
			break;
		}
	}

	JSON* valJSON = settingsJSON->GetItemByName(varName);
	if(valJSON)
	{
		valJSON->RemoveNode();
		valJSON->Release();
		rootSettingsJSON->Save(settingsFileName);
	}
}
示例#9
0
 bool
 JSON::optJSONObject(int index, JSON& value, bool copy) const
 {
     JTRACE;
     cJSON *elem = getItem(index, true);
     if(0 != elem)
     {
         switch(elem->type)
         {
         case cJSON_Object:
             value.removeSelf();
             value.m_node = elem;
             if(copy)
                 value.m_root = elem;
             else
                 value.addSelf(this);
             return true;
         default:
             if(copy)
                 cJSON_Delete(elem);
         }
     }
     return false;
 }
示例#10
0
JSON * JSON::parse_array(Lexer *lexer)
{
    JSON *array = new_array();
    unsigned int index = 0;
    
    if (lexer->end_of_array())
        return array;  // empty array
        
    for (;;)
    {
        JSON *item = parse_private(lexer);
    
        if (item)
            array->insert_array_item(index++, item);
        else
        {
#ifdef DEBUG
            PRINTLN(F("missing array item"));
#endif
            break;
        }
 
        Json_Token token = lexer->get_token();
        
        if (token == Array_stop_token)
            return array;
            
        if (token != Comma_token)
            break;
    }

#ifdef DEBUG
    PRINTLN(F("JSON syntax error in array"));
#endif
    return null;
}
示例#11
0
文件: query.cpp 项目: FritzX6/osquery
inline void getLegacyFieldsAndDecorations(const JSON& doc, QueryLogItem& item) {
  if (doc.doc().HasMember("decorations")) {
    if (doc.doc()["decorations"].IsObject()) {
      for (const auto& i : doc.doc()["decorations"].GetObject()) {
        item.decorations[i.name.GetString()] = i.value.GetString();
      }
    }
  }

  item.name = doc.doc()["name"].GetString();
  item.identifier = doc.doc()["hostIdentifier"].GetString();
  item.calendar_time = doc.doc()["calendarTime"].GetString();
  item.time = doc.doc()["unixTime"].GetUint64();
}
示例#12
0
std::pair<JSON, QueryData> getSerializedQueryDataWithColumnOrder() {
  auto r = getSerializedRow(true);
  QueryData q = {r.second, r.second};
  JSON doc = JSON::newArray();
  auto arr1 = doc.getArray();
  doc.copyFrom(r.first.doc(), arr1);
  doc.push(arr1);

  auto arr2 = doc.getArray();
  doc.copyFrom(r.first.doc(), arr2);
  doc.push(arr2);

  return std::make_pair(std::move(doc), q);
}
示例#13
0
		void LogInfoReporter::CreateReportMsg(int iLogType, const char* szTypeName, const char* szLogContent, int64_t date, bool pd)
		{
			JSON* joMsg = JSON::CreateObject();

			joMsg->AddNumberItem("date", date);
			joMsg->AddNumberItem("eid", iLogType);
			joMsg->AddStringItem("tname", szTypeName);
			joMsg->AddStringItem("content", szLogContent);
			joMsg->AddBoolItem("pd", pd);
			char *pJsonValue = joMsg->PrintValue(0, false);
			SetReportMsg(pJsonValue);
			MJ_FREE(pJsonValue);

			SetReportType(5);
		}
示例#14
0
	bool base_function::setJSON(const JSON& aJSON)
	{
		base_function backup(*this);
		bool result = true, found = false;
		if (aJSON.exists("title"))
		{
			found = true;
			this->setTitle(aJSON.get("title"));
		}
		if (aJSON.exists("description"))
		{
			found = true;
			this->setDescription(aJSON.get("description"));
		}
		
		//This executes the function
		if (aJSON.exists("parameters"))
		{
			found = true;
			//Make sens of params. It should be a JSON hash, from
			//string -> string, where key is the param name, and value is the
			//string representation of the value
			std::string params = aJSON.get("parameters");
			JSON jparams(params);
			typedef std::vector<std::string>::const_iterator iter;
			std::vector<std::string> parameters;
			for (iter itr = mParameters.begin(); itr != mParameters.end(); ++itr)
			{
				if (jparams.exists(*itr))
				{
					parameters.push_back(jparams.get(*itr));
				}
				else
				{
					result = false;
					break;
				}
			}
			
			if (result)
			{
				//Call function
				mpManager->execute_function(this->getTitle(), parameters);
			}
		}

		if(!result)
		{
			*this = backup;
		}
		return result && found;
	}
示例#15
0
    void
    JSON::addItem(const string& key, const JSON& value)
    {
        JTRACE;

        if(0 == m_node)
            THROW_MSG(Exception, "JSON node NULL");

        if(m_node->type != cJSON_Object)
            THROW_MSG(Exception, "expected JSON object");

        if(0 == value.m_node)
            THROW_MSG(Exception, "child JSON node NULL");

        if(!value.m_root)
            THROW_MSG(Exception, "child does not own JSON node");

        cJSON_AddItemToObject(m_node, key.c_str(), value.m_node);
        value.m_self->m_root = 0;
        value.addSelf(this);
    }
示例#16
0
    void
    JSON::replaceItem(int index, const JSON& value)
    {
        JTRACE;

        if(0 == m_node)
            THROW_MSG(Exception, "JSON node NULL");

        if(m_node->type != cJSON_Array)
            THROW_MSG(Exception, "expected JSON array");

        if(0 == value.m_node)
            THROW_MSG(Exception, "child JSON node NULL");

        if(!value.m_root)
            THROW_MSG(Exception, "child does not own JSON node");

        cJSON_ReplaceItemInArray(m_node, index, value.m_node);
        value.m_self->m_root = 0;
        value.addSelf(this);
    }
示例#17
0
文件: json.cpp 项目: PowerKiller/code
/// "anims": { "#import" : { "file": "generics.json", "key": "animations", "replace": { "arg4" : "codefragment" }
/// "anims": { "#import" : { "file": "generics.json", "key": "animations", "replace": { "arg4" : { "#import": } }
/// "$moreanims": { "#import" : "generics.json" },
/// "anims": [ "anim1", "anim2", "anim3", "$moreanims"]
bool JSON_ResolveImport(JSON *g)
{
    JSON *j = g->getchild(IMPORTPHRASE);
    JSON *f = NULL;       // the exporting file: "generics.json"
    JSON *newg = NULL;    // the JSON which will replace the old section

    if(!j) return false;

    JSON *src = j->getchild("file");
    JSON *key = j->getchild("key");
    JSON *replace = j->getchild("replace");

    if(!src) { return false; }
    const char *srcname = src->valuestring;
    f = loadjson(srcname);

    if(!f) { return false; }

    if(key) {
        newg = f->getchild(key->valuestring);
    }
    else newg = f;

    if(!newg){ return false; }

    JSON_ResolveReplacements(newg, replace);

    // Replace g with newg:
    if(g->name) copystring(newg->name, g->name, strlen(g->name)); // "anims"
    newg->parent = g->parent;

    newg->next = g->next;
    newg->prev = g->prev;

    // tell the others
    if(g->next) g->next->prev = newg;
    if(g->parent->firstchild == g) g->parent->firstchild = newg;
    else g->prev->next = newg;

    newg->original = g;
    return true;
}
示例#18
0
static JSON* FindTaggedData(JSON* data, const char** tag_names, const char** qtags, int num_qtags)
{
    if (data == NULL || !(data->Name == "TaggedData") || data->Type != JSON_Array)
        return NULL;

    JSON* tagged_item = data->GetFirstItem();
    while (tagged_item)
    {
        JSON* tags = tagged_item->GetItemByName("tags");
        if (tags->Type == JSON_Array && num_qtags == tags->GetArraySize())
        {   // Check for a full tag match on each item
            int num_matches = 0;
            
            for (int k=0; k<num_qtags; k++)
            {
                JSON* tag = tags->GetFirstItem();
                while (tag)
                {
                    JSON* tagval = tag->GetFirstItem();
                    if (tagval && tagval->Name == tag_names[k])
                    {
                        if (tagval->Value == qtags[k])
                            num_matches++;
                        break;
                    }
                    tag = tags->GetNextItem(tag);
                }
            }

            // if all tags were matched then copy the values into this Profile
            if (num_matches == num_qtags)
            {
                JSON* vals = tagged_item->GetItemByName("vals");
                return vals;
            }
        }

        tagged_item = data->GetNextItem(tagged_item);
    }

    return NULL;
}
示例#19
0
//-----------------------------------------------------------------------------
void Profile::SetDoubleValues(const char* key, const double* vals, int num_vals)
{
    JSON* value = NULL;
    int val_count = 0;
    if (ValMap.Get(key, &value))
    {
        if (value->Type == JSON_Array)
        {
            // truncate the existing array if fewer entries provided
            int num_existing_vals = value->GetArraySize();
            for (int i=num_vals; i<num_existing_vals; i++)
                value->RemoveLast();
            
            JSON* item = value->GetFirstItem();
            while (item && val_count < num_vals)
            {
                if (item->Type == JSON_Number)
                    item->dValue = vals[val_count];

                item = value->GetNextItem(item);
                val_count++;
            }
        }
        else
        {
            return;  // Maybe we should change the data type?
        }
    }
    else
    {
        value = JSON::CreateArray();
        value->Name = key;

        Values.PushBack(value);
        ValMap.Set(key, value);
    }

    for (; val_count < num_vals; val_count++)
        value->AddArrayNumber(vals[val_count]);
}
示例#20
0
文件: query.cpp 项目: FritzX6/osquery
Status serializeQueryLogItem(const QueryLogItem& item, JSON& doc) {
  if (item.results.added.size() > 0 || item.results.removed.size() > 0) {
    auto obj = doc.getObject();
    auto status = serializeDiffResults(item.results, item.columns, doc, obj);
    if (!status.ok()) {
      return status;
    }

    doc.add("diffResults", obj);
  } else {
    auto arr = doc.getArray();
    auto status =
        serializeQueryData(item.snapshot_results, item.columns, doc, arr);
    if (!status.ok()) {
      return status;
    }

    doc.add("snapshot", arr);
    doc.addRef("action", "snapshot");
  }

  addLegacyFieldsAndDecorations(item, doc, doc.doc());
  return Status();
}
示例#21
0
文件: json.cpp 项目: PowerKiller/code
/// Basic and really simplistic routine to fix malformatted .json files
/// It will replace the old version of your file on success and create a backup of the old one (called <filename>_backup.json)
/// Currently it fixes: double commata, missing " for non-numeric strings
int JSON_Fix(const char *filename)
{
    string s;
    copystring(s, filename);
    const char *found = findfile(path(s), "");
    char *buf = loadfile(found, NULL);
    if(!buf) return -1;
    JSON_Minify(buf);

    size_t len = strlen(buf);

    char *newbuf = new char[len + 1];

    size_t pos = 0; //current position in the newbuf
    for(size_t i = 0; i < len; i++)
    {
        if(buf[i] == ',')
        {
                if(!i) i++;                     //buf starts with a commata
                else if(buf[i + 1] == ',') i++; //two subsequent commata
                else
                {
                    newbuf[pos] = buf[i];
                    pos++;
                }
        }
        else if(isalpha(buf[i]))
        {
            if(!i) //todo worst case: is it an array or object?
                return 0;
            else if(buf[i - 1] != '\"') {
                newbuf[pos] = '\"'; pos++;
            } //string was missing a leading "
            newbuf[pos] = buf[i];
            pos++;
        }
        else
        {
            if(i && isalpha(i - 1)) {
                newbuf[pos] = '\"'; pos++;
            } //string was missing a trailing "
            newbuf[pos] = buf[i];
            pos++;
        }
    }

    JSON *j = JSON_Parse(newbuf);
    if(j)
    {
        conoutf("%s was malformatted but has been fixed automatically. \nThe original file has been overwritten, but backuped", found);
        //cutextension .. getextension
        defformatstring(backupname, "%s_backup", found);
        if(!rename(found, backupname)) j->save(found);
        delete j;
        delete[] buf;
        delete[] newbuf;
        return 1;
    }

    delete[] buf;
    delete[] newbuf;
    return 0;
}
示例#22
0
SInt64 JSON::cmp_string(const JSON& a, const JSON& b)
{
	return UTF16::comparef(a.as_string(), b.as_string());
}
示例#23
0
SInt64 JSON::cmp_bool(const JSON& a, const JSON& b)
{
	return (a.as_bool() ? 1 : 0) - (b.as_bool() ? 1 : 0);
}
示例#24
0
static void AddParameter(JSON &json, CGparameter param)
{
    const char * const parameterName = cgGetParameterName(param);

    if (sVerbose)
    {
        puts(parameterName);
    }

    json.AddObject(parameterName);

    const CGtype type = cgGetParameterType(param);
    const CGtype baseType = cgGetParameterBaseType(param);
    int numRows = cgGetParameterRows(param);
    const int numColumns = cgGetParameterColumns(param);
    if (CG_ARRAY == type)
    {
        const int totalArraySize = cgGetArrayTotalSize(param);
        numRows *= totalArraySize;
    }
    json.AddString("type", cgGetTypeString(baseType));
    if (1 < numRows)
    {
        json.AddValue("rows", numRows);
    }
    if (1 < numColumns)
    {
        json.AddValue("columns", numColumns);
    }

    const int maxNumElements = (numColumns * numRows);
    int n;
    if (CG_FLOAT == baseType)
    {
        float * const values = (float *)malloc(maxNumElements * sizeof(float));
        const int numValues = cgGetParameterValuefr(param, maxNumElements, values);
        if (numValues)
        {
            for (n = 0; n < numValues; n++)
            {
                if (values[n] != 0.0f)
                {
                    break;
                }
            }
            if (n < numValues)
            {
                json.AddArray("values", true);
                json.BeginData(true);
                for (n = 0; n < numValues; n++)
                {
                    json.AddData(values[n]);
                }
                json.EndData();
                json.CloseArray(true);
            }
        }
        free(values);
    }
    else if (CG_INT == baseType)
    {
        int * const values = (int *)malloc(maxNumElements * sizeof(int));
        const int numValues = cgGetParameterValueir(param, maxNumElements, values);
        if (numValues)
        {
            for (n = 0; n < numValues; n++)
            {
                if (values[n])
                {
                    break;
                }
            }
            if (n < numValues)
            {
                json.AddArray("values", true);
                json.BeginData(true);
                for (n = 0; n < numValues; n++)
                {
                    json.AddData(values[n]);
                }
                json.EndData();
                json.CloseArray(true);
            }
        }
        free(values);
    }
    else if (CG_BOOL == baseType)
    {
        int * const values = (int *)malloc(maxNumElements * sizeof(int));
        const int numValues = cgGetParameterValueir(param, maxNumElements, values);
        if (numValues)
        {
            for (n = 0; n < numValues; n++)
            {
                if (values[n])
                {
                    break;
                }
            }
            if (n < numValues)
            {
                json.AddArray("values", true);
                json.BeginData(true);
                for (n = 0; n < numValues; n++)
                {
                    json.AddData(values[n]);
                }
                json.EndData();
                json.CloseArray(true);
            }
        }
        free(values);
    }

    json.CloseObject(); // parameter
}
示例#25
0
static bool AddPass(CGtechnique technique, JSON &json, CGpass pass, UniformsMap &uniformRemapping)
{
    bool success = true;
    json.AddObject(NULL);

    const char * const passName = cgGetPassName(pass);
    if (NULL != passName)
    {
        json.AddString("name", passName);
    }

    bool firstParameter = true;

#if CG_VERSION_NUM >= 3000
    const int CG_NUMBER_OF_DOMAINS = (CG_TESSELLATION_EVALUATION_DOMAIN + 1);
#endif

    for (int domain = CG_FIRST_DOMAIN; domain < CG_NUMBER_OF_DOMAINS; domain++)
    {
        const CGprogram program = cgGetPassProgram(pass, (CGdomain)domain);
        if (NULL != program)
        {
            const char * const programString = cgGetProgramString(program, CG_COMPILED_PROGRAM);

            CGparameter param = cgGetFirstParameter(program, CG_GLOBAL);
            while (NULL != param)
            {
                if (cgIsParameterUsed(param, program) &&
                    CG_UNIFORM == cgGetParameterVariability(param))
                {
                    if (firstParameter)
                    {
                        firstParameter = false;
                        json.AddArray("parameters", true);
                        json.BeginData(true);
                    }
                    const char * const paramName = cgGetParameterName(param);
                    AddMappedParameter(json, paramName, programString, uniformRemapping);
                }
                param = cgGetNextParameter(param);
            }

            param = cgGetFirstParameter(program, CG_PROGRAM);
            while (NULL != param)
            {
                if (cgIsParameterUsed(param, program) &&
                    CG_UNIFORM == cgGetParameterVariability(param))
                {
                    if (firstParameter)
                    {
                        firstParameter = false;
                        json.AddArray("parameters", true);
                        json.BeginData(true);
                    }
                    const char * const paramName = cgGetParameterName(param);
                    AddMappedParameter(json, paramName, programString, uniformRemapping);
                }
                param = cgGetNextParameter(param);
            }
        }
    }

    if (!firstParameter)
    {
        json.EndData();
        json.CloseArray(true); // parameters
    }


    json.AddArray("semantics", true);
    json.BeginData(true);

    CGprogram vertexProgram = cgGetPassProgram(pass, CG_VERTEX_DOMAIN);
    CGparameter vertexInputParameter = cgGetFirstLeafParameter(vertexProgram, CG_PROGRAM);
    while (NULL != vertexInputParameter)
    {
        const CGenum variability = cgGetParameterVariability(vertexInputParameter);
        if (CG_VARYING == variability)
        {
            const CGenum direction = cgGetParameterDirection(vertexInputParameter);
            if (CG_IN == direction ||
                CG_INOUT == direction)
            {
                const char * const semantic = cgGetParameterSemantic(vertexInputParameter);
                json.AddData(semantic, strlen(semantic));
            }
        }
        vertexInputParameter = cgGetNextLeafParameter(vertexInputParameter);
    }

    json.EndData();
    json.CloseArray(true); // semantics


    json.AddObject("states");

    CGstateassignment state = cgGetFirstStateAssignment(pass);
    if (NULL != state)
    {
        do
        {
            success &= AddState(json, state);
            state = cgGetNextStateAssignment(state);
        }
        while (NULL != state);
    }

    json.CloseObject(); // states


    json.AddArray("programs", true);
    json.BeginData(true);

    for (int domain = CG_FIRST_DOMAIN; domain < CG_NUMBER_OF_DOMAINS; domain++)
    {
        const CGprogram program = cgGetPassProgram(pass, (CGdomain)domain);
        if (NULL != program)
        {
            const char * const entryPoint = cgGetProgramString(program, CG_PROGRAM_ENTRY);
            json.AddData(entryPoint, strlen(entryPoint));
        }
        else if (domain == CG_VERTEX_DOMAIN)
        {

            ErrorMessage("%s : No vertex program.", cgGetTechniqueName(technique));
            success = false;
        }
        else if(domain == CG_FRAGMENT_DOMAIN)
        {
            ErrorMessage("%s : No fragment program.", cgGetTechniqueName(technique));
            success = false;
        }
    }

    json.EndData();
    json.CloseArray(true); // programs

    json.CloseObject(); // pass

    return success;
}
示例#26
0
static void AddMappedParameter(JSON &json,
                               const char *paramName,
                               const char *programString,
                               UniformsMap &uniformRemapping)
{
    const bool isAssembly = (0 == memcmp(programString, "!!ARB", 5));
    const char * const vars = strstr(programString, (isAssembly ? "#var" : "//var"));
    if (NULL != vars)
    {
        const size_t paramNameLength = strlen(paramName);

        const char *var = vars;
        do
        {
            // to skip previous search
            var += 1;
            var = strstr(var, paramName);
        }
        while (NULL != var &&
               ' ' != var[paramNameLength] &&
               ':' != var[paramNameLength] &&
               '[' != var[paramNameLength]);

        if (NULL != var)
        {
            const char * const semantic = strchr(var, ':');
            if (NULL != semantic)
            {
                const char *mappedVariable = strchr((semantic + 1), ':');
                if (NULL != mappedVariable)
                {
                    do
                    {
                        mappedVariable++;
                    }
                    while (*mappedVariable <= ' ');
                    const char *mappedVariableEnd = mappedVariable;
                    while (' ' != *mappedVariableEnd &&
                           ':' != *mappedVariableEnd &&
                           '[' != *mappedVariableEnd &&
                           ',' != *mappedVariableEnd &&
                           0 != *mappedVariableEnd)
                    {
                        mappedVariableEnd++;
                    }

                    const size_t mappedVariableLength = (size_t)(mappedVariableEnd - mappedVariable);

                    if (isAssembly)
                    {
                        if (0 < mappedVariableLength)
                        {
                            // Append location to end of string
                            std::string paramString(paramName, paramNameLength);
                            paramString += ':';
                            // mappedVariable should have the format 'c[{location}]' or 'texunit {location}'
                            const char *location = mappedVariableEnd;
                            while (0 != *location &&
                                   ('0' > *location  ||
                                    '9' < *location))
                            {
                                location++;
                            }
                            if (0 != *location)
                            {
                                const char *locationEnd = location;
                                do
                                {
                                    locationEnd++;
                                }
                                while (0 != *locationEnd &&
                                       '0' <= *locationEnd &&
                                       '9' >= *locationEnd);
                                if (0 != *locationEnd)
                                {
                                    paramString.append(location, (size_t)(locationEnd - location));
                                    json.AddData(paramString.c_str(), paramString.size());
                                }
                            }
                        }
                        return;
                    }

                    const std::string mappedVariableString(mappedVariable, mappedVariableLength);
                    const char * const mappedVariableName = mappedVariableString.c_str();

                    // Check that it is actually used
                    const char * const main = strstr(mappedVariableEnd, "main()");
                    if (NULL != main)
                    {
                        const boost::xpressive::cregex re(boost::xpressive::_b >> mappedVariableString >> boost::xpressive::_b);
                        if (!regex_search((main + 6), re))
                        {
                            return;
                        }
                    }

                    json.AddData(paramName, paramNameLength);

                    const UniformsMap::const_iterator it = uniformRemapping.find(mappedVariableString);
                    if (it == uniformRemapping.end())
                    {
                        uniformRemapping[mappedVariableString] = paramName;
                    }
                    else if (it->second != paramName)
                    {
                        printf("\nUniform variable conflict '%s':\n\t%s\n\t%s\n",
                               mappedVariableName,
                               it->second.c_str(),
                               paramName);
                        exit(1);
                    }
                }
            }
        }
    }
}
示例#27
0
static bool AddState(JSON &json, CGstateassignment sa)
{
    const CGstate state = cgGetStateAssignmentState(sa);
    const char * const stateName = cgGetStateName(state);
    if (false == IsValidState(stateName))
    {
        ErrorMessage("Invalid state for OpenGL ES 2.0 %s", stateName);
        return false;
    }

    const CGtype type = cgGetStateType(state);
    int nValues;
    switch (type)
    {
    case CG_PROGRAM_TYPE:
        return true;

    case CG_FLOAT:
    case CG_FLOAT1:
        {
            const float * const fvalues = cgGetFloatStateAssignmentValues(sa, &nValues);
            json.AddValue(stateName, fvalues[0]);
        }
        break;

    case CG_FLOAT2:
    case CG_FLOAT3:
    case CG_FLOAT4:
        {
            const float * const fvalues = cgGetFloatStateAssignmentValues(sa, &nValues);
            json.AddArray(stateName, true);
            json.BeginData(true);
            for (int n = 0; n < nValues; ++n)
            {
                json.AddData(fvalues[n]);
            }
            json.EndData();
            json.CloseArray(true);
        }
        break;

    case CG_INT:
    case CG_INT1:
        {
            const int * const ivalues = cgGetIntStateAssignmentValues(sa, &nValues);
            json.AddValue(stateName, ivalues[0]);
        }
        break;

    case CG_INT2:
    case CG_INT3:
    case CG_INT4:
        {
            const int * const ivalues = cgGetIntStateAssignmentValues(sa, &nValues);
            json.AddArray(stateName, true);
            json.BeginData(true);
            for (int n = 0; n < nValues; ++n)
            {
                json.AddData(ivalues[n]);
            }
            json.EndData();
            json.CloseArray(true);
        }
        break;

    case CG_BOOL:
    case CG_BOOL1:
        {
            const CGbool * const bvalues = cgGetBoolStateAssignmentValues(sa, &nValues);
            json.AddBoolean(stateName, (bvalues[0] ? true : false));
        }
        break;

    case CG_BOOL2:
    case CG_BOOL3:
    case CG_BOOL4:
        {
            const CGbool * const bvalues = cgGetBoolStateAssignmentValues(sa, &nValues);
            json.AddArray(stateName, true);
            json.BeginData(true);
            for (int n = 0; n < nValues; ++n)
            {
                json.AddData(bvalues[n]);
            }
            json.EndData();
            json.CloseArray(true);
        }
        break;

    case CG_STRING:
        json.AddString(stateName, cgGetStringStateAssignmentValue(sa));
        break;

    default:
        ErrorMessage("UNEXPECTED State Assignment Type: %s 0x%x (%d)\n",
                        cgGetTypeString(type), type, type);
        return false;
    }
    return true;
}
示例#28
0
void Proxy::register_observer(Symbol event, EventFunc handler)
{
    JSON *node = JSON::new_function((GenericFn)handler);
    JSON *events = WebThings::get_json(this->events);
    events->insert_property(event, node);
}
示例#29
0
// set the response handler for the named action
void Proxy::register_response_handler(Symbol action, ResponseFunc handler)
{
    JSON *func = JSON::new_function((GenericFn)handler);
    JSON *actions = WebThings::get_json(this->actions);
    actions->insert_property(action, func);
}
TEST(SEQUENCE_HEURISTIC, IS_VALID)
{
    Heuristic * heuristic = Factory<Heuristic>::getInstance()->create("Sequence");

    StringMap settings;
    settings["heuristics.Sequence.minimumChanges"] = "1";
    settings["heuristics.Sequence.minimumDuration"] = "2";
    settings["heuristics.Sequence.motionDelayTime"] = "1000";
    settings["heuristics.Sequence.noMotionDelayTime"] = "1000";
    heuristic->setup(settings);

    // ----------------------------
    // Mocking image

    Image image;
    ImageVector images;

    JSON json;
    JSON::AllocatorType& allocator = json.GetAllocator();

    json.SetObject();
    json.AddMember("numberOfChanges", 0, allocator);

    // --------------------
    // Nothing changed thus false.
    bool isValid = heuristic->isValid(image, images, json);
    EXPECT_EQ(false, isValid);

    // ---------------------
    // Changed, but this is only the first occurence thus again false.
    json.RemoveMember ("numberOfChanges");
    json.AddMember("numberOfChanges", 1, allocator);
    isValid = heuristic->isValid(image, images, json);
    EXPECT_EQ(false, isValid);

    // ---------------------
    // Changed and the second occurence thus true.
    isValid = heuristic->isValid(image, images, json);
    EXPECT_EQ(true, isValid);
}