Esempio n. 1
0
static void test_remove(void)
{
    json_t *array, *five, *seven;

    array = json_array();
    five = json_integer(5);
    seven = json_integer(7);

    if(!array)
        fail("unable to create array");
    if(!five)
        fail("unable to create integer");
    if(!seven)
        fail("unable to create integer");


    if(!json_array_remove(array, 0))
        fail("able to remove an unexisting index");


    if(json_array_append(array, five))
        fail("unable to append");

    if(!json_array_remove(array, 1))
        fail("able to remove an unexisting index");

    if(json_array_remove(array, 0))
        fail("unable to remove");

    if(json_array_size(array) != 0)
        fail("array size is invalid after removing");


    if(json_array_append(array, five) ||
       json_array_append(array, seven) ||
       json_array_append(array, five) ||
       json_array_append(array, seven))
        fail("unable to append");

    if(json_array_remove(array, 2))
        fail("unable to remove");

    if(json_array_size(array) != 3)
        fail("array size is invalid after removing");

    if(json_array_get(array, 0) != five ||
       json_array_get(array, 1) != seven ||
       json_array_get(array, 2) != seven)
        fail("remove works incorrectly");

    json_decref(five);
    json_decref(seven);
    json_decref(array);
}
Esempio n. 2
0
static void test_equal_array()
{
    json_t *array1, *array2;

    array1 = json_array();
    array2 = json_array();
    if(!array1 || !array2)
        fail("unable to create arrays");

    if(!json_equal(array1, array2))
        fail("json_equal fails for two empty arrays");

    json_array_append_new(array1, json_integer(1));
    json_array_append_new(array2, json_integer(1));
    json_array_append_new(array1, json_string("foo"));
    json_array_append_new(array2, json_string("foo"));
    json_array_append_new(array1, json_integer(2));
    json_array_append_new(array2, json_integer(2));
    if(!json_equal(array1, array2))
        fail("json_equal fails for two equal arrays");

    json_array_remove(array2, 2);
    if(json_equal(array1, array2))
        fail("json_equal fails for two inequal arrays");

    json_array_append_new(array2, json_integer(3));
    if(json_equal(array1, array2))
        fail("json_equal fails for two inequal arrays");

    json_decref(array1);
    json_decref(array2);
}
Esempio n. 3
0
int
remove_metric_from_array (json_t *      json_array,
                          long          id)
{
    size_t      index;

    json_t *    json_metric;
    json_t *    json_metric_id;

    for (index = 0;
         index < json_array_size (json_array);
         index++) {
        json_metric = json_array_get (json_array, index);
        json_metric_id = json_object_get (json_metric, "id");
        if (!json_is_integer (json_metric_id)) {
            return (EVHTP_RES_SERVERR);
        }
        if (id == json_integer_value (json_metric_id)) {
            if (json_array_remove (json_array, index) == -1) {
                return (EVHTP_RES_SERVERR);
            }
            break ;
        }
    }
    return (0);
}
Esempio n. 4
0
void TeamCard::onIconClick(cocos2d::Ref *pSender)
{
    ImageView* rim=(ImageView*) pSender;
    int tag=rim->getTag();
    //下阵
    rim->setVisible(false);
    this->aoYiPanel->getChildByName("card"+Value(tag-1).asString())->setVisible(false);
    json_array_remove(this->cards, tag);
    this->initBag(nullptr);
    
    this->initAoYi();

}
Esempio n. 5
0
static void circular_references()
{
    /* Construct a JSON object/array with a circular reference:

       object: {"a": {"b": {"c": <circular reference to $.a>}}}
       array: [[[<circular reference to the $[0] array>]]]

       Encode it, remove the circular reference and encode again.
    */

    json_t *json;
    char *result;

    json = json_object();
    json_object_set_new(json, "a", json_object());
    json_object_set_new(json_object_get(json, "a"), "b", json_object());
    json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
                    json_object_get(json, "a"));

    if(json_dumps(json, 0))
        fail("json_dumps encoded a circular reference!");

    json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c");

    result = json_dumps(json, 0);
    if(!result || strcmp(result, "{\"a\": {\"b\": {}}}"))
        fail("json_dumps failed!");
    free(result);

    json_decref(json);

    json = json_array();
    json_array_append_new(json, json_array());
    json_array_append_new(json_array_get(json, 0), json_array());
    json_array_append(json_array_get(json_array_get(json, 0), 0),
                      json_array_get(json, 0));

    if(json_dumps(json, 0))
        fail("json_dumps encoded a circular reference!");

    json_array_remove(json_array_get(json_array_get(json, 0), 0), 0);

    result = json_dumps(json, 0);
    if(!result || strcmp(result, "[[[]]]"))
        fail("json_dumps failed!");
    free(result);

    json_decref(json);
}
Esempio n. 6
0
File: exc.c Progetto: latchset/jose
static int
jcmd_jwk_exc(int argc, char *argv[])
{
    jcmd_opt_auto_t opt = {};
    json_auto_t *key = NULL;
    json_t *tmpl = NULL;

    if (!jcmd_opt_parse(argc, argv, cfgs, &opt, prefix))
        return EXIT_FAILURE;

    if (json_array_size(opt.keys) > 1 && json_array_remove(opt.keys, 0) < 0)
        return EXIT_FAILURE;

    if (json_array_size(opt.lcl) != 1) {
        fprintf(stderr, "Local JWK must be specified exactly once!\n");
        return EXIT_FAILURE;
    }

    if (json_array_size(opt.rem) != 1) {
        fprintf(stderr, "Remote JWK must be specified exactly once!\n");
        return EXIT_FAILURE;
    }

    key = jose_jwk_exc(NULL, json_array_get(opt.lcl, 0),
                       json_array_get(opt.rem, 0));
    if (!key) {
        fprintf(stderr, "Error performing exchange!\n");
        return EXIT_FAILURE;
    }

    tmpl = json_array_get(opt.keys, json_array_size(opt.keys) - 1);

    if (json_object_update(tmpl, key) < 0)
        return EXIT_FAILURE;

    if (json_dumpf(tmpl, opt.output, JSON_COMPACT | JSON_SORT_KEYS) < 0) {
        fprintf(stderr, "Error writing JWK!\n");
        return EXIT_FAILURE;
    }

    if (isatty(fileno(opt.output)))
        fprintf(opt.output, "\n");

    return EXIT_SUCCESS;
}
Esempio n. 7
0
//native json_array_remove(Handle:hArray, iIndex);
static cell_t Native_json_array_remove(IPluginContext *pContext, const cell_t *params) {
	HandleError err;
	HandleSecurity sec;
	sec.pOwner = NULL;
	sec.pIdentity = myself->GetIdentity();

	// Param 1: hArray
	json_t *object;
	Handle_t hndlObject = static_cast<Handle_t>(params[1]);
	if ((err=g_pHandleSys->ReadHandle(hndlObject, htJanssonObject, &sec, (void **)&object)) != HandleError_None)
    {
        return pContext->ThrowNativeError("Invalid <Array> handle %x (error %d)", hndlObject, err);
    }

	// Param 2: iIndex
	int iIndex = params[2];

	return (json_array_remove(object, iIndex) == 0);
}
Esempio n. 8
0
static void database_worker_save(uv_work_t * req)
{
    save_t * saving = (save_t *) req->data;
    json_t * obj = saving->data;
    json_t * result;
    short short_insert = 0;

    LOCK
        if (!(result = dictFetchValue(db, saving->channel))) {
            result = json_array();
            short_insert = 1;
        }
        json_array_append(result, obj);
        if (json_array_size(result) > config->web_history) {
            json_array_remove(result, 0);
        }
        if (short_insert) {
            dictAdd(db, saving->channel, result);
        }
    RELEASE
}
Esempio n. 9
0
/**
 * remove summary (if any) and pipe hat. This is typicaly used for simulations
 */
void ssm_pipe_hat(FILE *stream, json_t *jparameters, ssm_input_t *input, ssm_hat_t *hat, ssm_par_t *par, ssm_calc_t *calc, ssm_nav_t *nav, ssm_options_t *opts, double t)
{
    int i, index;
    double x;

    json_t *jresources = json_object_get(jparameters, "resources");
    json_t *jsummary = NULL;
    int index_summary;
	
    for(index=0; index< json_array_size(jresources); index++){
        json_t *el = json_array_get(jresources, index);

        const char* name = json_string_value(json_object_get(el, "name"));
        if (strcmp(name, "values") == 0) {
            json_t *values = json_object_get(el, "data");

            for(i=0; i<nav->theta_all->length; i++){
                x = nav->theta_all->p[i]->f_2prior(gsl_vector_get(input, nav->theta_all->p[i]->offset), hat, par, calc, t);
                json_object_set_new(values, nav->theta_all->p[i]->name, json_real(x));
            }
        } else if (strcmp(name, "summary") == 0){
	    jsummary = el;
	    index_summary = index;
	}
    }

    if(jsummary){
	json_array_remove(jresources, index_summary);       
    }

    if(strcmp(opts->next, "") != 0){
	char path[SSM_STR_BUFFSIZE];
	snprintf(path, SSM_STR_BUFFSIZE, "%s/%s%d.json", opts->root, opts->next, opts->id);
	json_dump_file(jparameters, path, JSON_INDENT(2));
    } else {
	json_dumpf(jparameters, stdout, JSON_COMPACT); printf("\n");
	fflush(stdout);	
    }
}
Esempio n. 10
0
int main()
{
    json_t *json;
    char *result;

    /* Encode an empty object/array, add an item, encode again */

    json = json_object();
    result = json_dumps(json, 0);
    if(!result || strcmp(result, "{}"))
      fail("json_dumps failed");
    free(result);

    json_object_set_new(json, "foo", json_integer(5));
    result = json_dumps(json, 0);
    if(!result || strcmp(result, "{\"foo\": 5}"))
      fail("json_dumps failed");
    free(result);

    json_decref(json);

    json = json_array();
    result = json_dumps(json, 0);
    if(!result || strcmp(result, "[]"))
      fail("json_dumps failed");
    free(result);

    json_array_append_new(json, json_integer(5));
    result = json_dumps(json, 0);
    if(!result || strcmp(result, "[5]"))
      fail("json_dumps failed");
    free(result);

    json_decref(json);

    /* Construct a JSON object/array with a circular reference:

       object: {"a": {"b": {"c": <circular reference to $.a>}}}
       array: [[[<circular reference to the $[0] array>]]]

       Encode it, remove the circular reference and encode again.
    */
    json = json_object();
    json_object_set_new(json, "a", json_object());
    json_object_set_new(json_object_get(json, "a"), "b", json_object());
    json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
                    json_object_get(json, "a"));

    if(json_dumps(json, 0))
        fail("json_dumps encoded a circular reference!");

    json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c");

    result = json_dumps(json, 0);
    if(!result || strcmp(result, "{\"a\": {\"b\": {}}}"))
        fail("json_dumps failed!");
    free(result);

    json_decref(json);

    json = json_array();
    json_array_append_new(json, json_array());
    json_array_append_new(json_array_get(json, 0), json_array());
    json_array_append(json_array_get(json_array_get(json, 0), 0),
                      json_array_get(json, 0));

    if(json_dumps(json, 0))
        fail("json_dumps encoded a circular reference!");

    json_array_remove(json_array_get(json_array_get(json, 0), 0), 0);

    result = json_dumps(json, 0);
    if(!result || strcmp(result, "[[[]]]"))
        fail("json_dumps failed!");
    free(result);

    json_decref(json);

    return 0;
}
Esempio n. 11
0
// paste payload into existing .json
int pasteJSON(json_t *payload, const char *clientName) {
    // Extract data from payload
    const char * name = json_string_value(json_object_get(payload, "name"));
    int type = json_integer_value(json_object_get(payload, "type"));
    
    
    // Type 2: CSV
    if (type == 2) {
        FILE *fp;
        char* file = composeFileName(clientName, name, "csv");
        const char * output = json_string_value(json_object_get(payload, "payload"));
        fp = fopen(file, "w");
        fprintf(fp, "%s",output); 
        fclose(fp);
        return 1;
    }

    json_t *array = json_object_get(payload, "payload");
    
    json_t *root, *dataseq, *graph, *arry;
    json_error_t error;

    // Load *.json
    const char* file = composeFileName(clientName, name, "json");

    root = json_load_file(file, 0, &error);
    // Check for Errors
    if (!root) {
        syslog(LOG_ERR, "Unable to load json File! error: on line %d: %s\n", error.line, error.text); 
        exit(1);
    }
    // Get old Data
    graph = json_object_get(root, "graph");
    dataseq = getDataSequences(graph);
    if (!check(dataseq)) {
        printError(name);
    }
    // Process Every Datasequence
    size_t j;
    for (j = 0; j < json_array_size(dataseq); j++) {
        // If Type is 0 /Line (standard case) append new value at the bottom 
        arry = getSingleSeqeunce(dataseq, j);
        if (strncmp(getType(root), "line", 2) == 0) {
            if (json_array_size(arry) >= (size_t) getMaxCount()) {
                 if (json_array_remove(arry,0)) {
                     syslog(LOG_ERR, "error in processing %s.json\n", name);
                     return 0;
                 }
            }
            if (json_array_append_new(arry, json_array_get(array, j))) {
                syslog(LOG_ERR, "error in appending new entry in %s.json\n", name);
                return 0;
            }
        // When Type is Bar, every Entry has its own name and you change the value
        } else {
            size_t k;
            for (k = 0; k < json_array_size(arry); k++) {
                if (json_real_set(json_object_get(json_array_get(arry, k), "value"), json_real_value(json_array_get(array, k))) ) {
                    return 0;
                }
                    syslog(LOG_ERR, "error in changing entry in %s.json\n", name);
            }
        }
    }
    dumpJSON(root, file);
    return 1;

}
Esempio n. 12
0
void LSCompiler::linkRootAssembly(const utString& sjson)
{
    json_error_t jerror;
    json_t       *json = json_loadb((const char *)sjson.c_str(), sjson.length(), 0, &jerror);

    lmAssert(json, "Error linking assembly");

    json_t *ref_array = json_object_get(json, "references");
    lmAssert(json, "Error linking assembly, can't get executable references");

    for (UTsize i = 0; i < rootBuildDependencies.size(); i++)
    {
        BuildInfo *buildInfo     = rootBuildDependencies.at(i);
        utString  assemblySource = buildInfo->getOutputDir() + platform_getFolderDelimiter() + buildInfo->getAssemblyName() + ".loomlib";

        utArray<unsigned char> rarray;
        lmAssert(utFileStream::tryReadToArray(assemblySource, rarray), "Unable to load library assembly %s", assemblySource.c_str());

        utBase64 base64 = utBase64::encode64(rarray);

        for (size_t j = 0; j < json_array_size(ref_array); j++)
        {
            json_t   *jref = json_array_get(ref_array, j);
            utString jname = json_string_value(json_object_get(jref, "name"));
            if (buildInfo->getAssemblyName() == jname)
            {
                logVerbose("Linking: %s", jname.c_str());

                json_object_set(jref, "binary", json_string(base64.getBase64().c_str()));
                json_object_set(jref, "uid", json_string(readAssemblyUID(rarray)));
                break;
            }
        }
    }

    // filter the reference array by the import assemblies
    utStack<int> filter;
    for (size_t j = 0; j < json_array_size(ref_array); j++)
    {
        json_t   *jref = json_array_get(ref_array, j);
        utString jname = json_string_value(json_object_get(jref, "name"));

        bool found = false;

        // always find the System assembly, so we don't have to explicitly import from it
        if (jname == "System")
        {
            found = true;
        }

        for (UTsize k = 0; k < importedAssemblies.size() && !found; k++)
        {
            if (importedAssemblies.at(k)->getName() == jname)
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
            filter.push((int)j);
        }
    }

    while (filter.size())
    {
        json_array_remove(ref_array, filter.pop());
    }

    for (UTsize i = 0; i < rootLibDependencies.size(); i++)
    {
        utString libName = rootLibDependencies.at(i);

        for (size_t j = 0; j < json_array_size(ref_array); j++)
        {
            json_t   *jref = json_array_get(ref_array, j);
            utString jname = json_string_value(json_object_get(jref, "name"));

            if (libName != jname)
            {
                continue;
            }

            log("Linking: %s", libName.c_str());

            utString delim   = platform_getFolderDelimiter();
            utString libPath = sdkPath + delim + "libs" + delim + libName + ".loomlib";

            utArray<unsigned char> rarray;

            if (libName == "System" && embeddedSystemAssembly)
            {
                size_t embeddedSystemAssemblyLength = strlen(embeddedSystemAssembly);
                rarray.resize((int)(embeddedSystemAssemblyLength + 1));
                memcpy(&rarray[0], embeddedSystemAssembly, embeddedSystemAssemblyLength + 1);
            }
            else
            {
                lmAssert(utFileStream::tryReadToArray(libPath, rarray), "Unable to load library assembly %s at %s", libName.c_str(), libPath.c_str());    
            }

            utBase64 base64 = utBase64::encode64(rarray);
            json_object_set(jref, "binary", json_string(base64.getBase64().c_str()));
            json_object_set(jref, "uid", json_string(readAssemblyUID(rarray)));

            break;
        }
    }

    json_object_set(json, "executable", json_true());

    utString execSource = rootBuildInfo->getOutputDir() + utString(platform_getFolderDelimiter()) + rootBuildInfo->getAssemblyName() + ".loom";

    // generate binary assembly for executable
    BinWriter::writeExecutable(execSource.c_str(), json);

    log("Compile Successful: %s\n", execSource.c_str());
}
Esempio n. 13
0
int la_codec_array_remove(la_codec_value_t *array, size_t index)
{
    return json_array_remove((json_t*) array, index);
}
Esempio n. 14
0
void TeamCard::onButtonClick(cocos2d::Ref *pSender)
{
    Button* btn=(Button*) pSender;
    int tag=btn->getTag();
    log("tag:%d,index:%d",btn->getTag(),tabBar->getIndex());
    switch (tag) {
        case 1000: //gohome
        {
            Manager::getInstance()->switchScence(HomeScene::createScene());
            break;
        }
        case 1001: //返回
        {
            Team2* team=dynamic_cast<Team2*>(this->preUI);
            json_object_set(data, "cards", this->cards);
            json_array_set(team->teamsJson, this->index, this->data);
            team->resetUI();

            this->clear(true);
            break;
        }
        case 1002: //tab0 黑白红绿蓝黄
        case 1003: //tab1
        case 1004: //tab2
        case 1005: //tab4
        case 1006: //tab5
        case 1007: //tab6
        {
            this->tabBar->setIndex(tag-1002);
            this->filterCard(tag-1002);
            break;
        }
        case 1008: //上场
        {
            this->aoYiPanel->setVisible(true);
            this->cardPanel->setVisible(false);
            json_object_set(this->card->data, "isUsed", json_boolean(true));
            json_array_append(this->cards, this->card->data);
            
            this->card->setUse(true);
            this->initAoYi();

            this->initCard();
            break;
        }
        case 1009: //下场
        {
            this->aoYiPanel->setVisible(true);
            this->cardPanel->setVisible(false);
            for (int i=0; i<json_array_size(cards); i++) {
                json_t* json=json_array_get(cards, i);
                int xid=json_integer_value(json_object_get(json, "xid"));
                int cid=json_integer_value(json_object_get(this->card->data, "xid"));
                if(xid==cid){
                    json_array_remove(cards, i);
                    break;
                }
            }
            json_array_set(cards, 0, json_object());

            this->card->setUse(false);
            this->initCard();
            this->initAoYi();
            break;
        }

    }
}
Esempio n. 15
0
void MltRuntime::erase_runtime_entry(const JsonPath& path) throw(Exception)
{
	JsonPath::PathCompCIter it = path.path.begin();
	json_t* curObj = json_serialize;
	if ( path.path.size() == 0 ) {
		throw_error_v(ErrorRuntimeUuidPathInvalid, "root path not allowd for erase");
	}

	for (; it != path.path.end(); ) {
		json_t* se = json_object_get(curObj, it->name.c_str());
		if (!se) {
			throw_error(ErrorRuntimeUuidPathInvalid);
		}
		if ( it->type == JsonPathComponent::PathArray) {
			if ( !json_is_array(se) ) {
				throw_error(ErrorRuntimeUuidPathInvalid);
			}

			int asz = json_array_size(se);
			int idx = it->arr_idx;
			if (idx < 0) idx = asz + idx;
			if ( idx < 0 || idx >= asz ) {
				if (it->arr_idx >= asz) {
					throw_error(ErrorRuntimeUuidPathInvalid);
				}
			}

			json_t* ae = json_array_get(se, idx);
			if (!json_is_object(ae)) {
				throw_error(ErrorRuntimeUuidPathInvalid);
			}
			curObj = ae;
			it++;
			if ( it == path.path.end()) {
				JsonPath dummy;
				parse_struct(ae,dummy,uuid_pathmap, 1);
				json_array_remove(se, idx);
				break;
			}
			else
				continue;
		}
		else if ( it->type == JsonPathComponent::PathObject) {
			if ( !json_is_object(se)) {
				throw_error(ErrorRuntimeUuidPathInvalid);
			}

			it++;
			if ( it == path.path.end()) {
				JsonPath dummy;
				parse_struct(se, dummy, uuid_pathmap, 1);
				json_object_del(curObj, it->name.c_str());
				break;
			}
			else {
				curObj = se;
				continue;
			}
		}
	}

	json_version++;
	return;
}
Esempio n. 16
0
static void *perf_log_thread(void *unused) {
  json_t *samples = NULL;
  char **envp;
  json_t *perf_cmd;
  int64_t sample_batch;

  unused_parameter(unused);

  w_set_thread_name("perflog");

  // Prep some things that we'll need each time we run a command
  {
    uint32_t env_size;
    w_ht_t *envpht = w_envp_make_ht();
    char *statedir = dirname(strdup(watchman_state_file));
    w_envp_set_cstring(envpht, "WATCHMAN_STATE_DIR", statedir);
    w_envp_set_cstring(envpht, "WATCHMAN_SOCK", get_sock_name());
    envp = w_envp_make_from_ht(envpht, &env_size);
  }

  perf_cmd = cfg_get_json(NULL, "perf_logger_command");
  if (json_is_string(perf_cmd)) {
    perf_cmd = json_pack("[O]", perf_cmd);
  }
  if (!json_is_array(perf_cmd)) {
    w_log(
        W_LOG_FATAL,
        "perf_logger_command must be either a string or an array of strings\n");
  }

  sample_batch =
      cfg_get_int(NULL, "perf_logger_command_max_samples_per_call", 4);

  while (true) {
    pthread_mutex_lock(&perf_log_lock);
    if (!perf_log_samples) {
      pthread_cond_wait(&perf_log_cond, &perf_log_lock);
    }
    samples = perf_log_samples;
    perf_log_samples = NULL;

    pthread_mutex_unlock(&perf_log_lock);

    if (samples) {
      while (json_array_size(samples) > 0) {
        int i = 0;
        json_t *cmd = json_array();
        posix_spawnattr_t attr;
        posix_spawn_file_actions_t actions;
        pid_t pid;
        char **argv = NULL;

        json_array_extend(cmd, perf_cmd);

        while (i < sample_batch && json_array_size(samples) > 0) {
          char *stringy = json_dumps(json_array_get(samples, 0), 0);
          json_array_append(cmd, typed_string_to_json(stringy, W_STRING_MIXED));
          free(stringy);
          json_array_remove(samples, 0);
          i++;
        }

        argv = w_argv_copy_from_json(cmd, 0);
        if (!argv) {
          char *dumped = json_dumps(cmd, 0);
          w_log(W_LOG_FATAL, "error converting %s to an argv array\n", dumped);
        }

        posix_spawnattr_init(&attr);
#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
        posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT);
#endif
        posix_spawn_file_actions_init(&actions);
        posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null",
                                         O_RDONLY, 0666);
        posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "/dev/null",
                                         O_WRONLY, 0666);
        posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null",
                                         O_WRONLY, 0666);

        if (posix_spawnp(&pid, argv[0], &actions, &attr, argv, envp) == 0) {
          // There's no sense waiting here, because w_reap_children is called
          // by the reaper thread.
        } else {
          int err = errno;
          w_log(W_LOG_ERR, "failed to spawn %s: %s\n", argv[0],
                strerror(err));
        }

        posix_spawnattr_destroy(&attr);
        posix_spawn_file_actions_destroy(&actions);

        free(argv);
        json_decref(cmd);
      }
      json_decref(samples);
    }
  }

  return NULL;
}
Esempio n. 17
0
void move(json_t *src_list, size_t src_index, json_t *dest_list)
{
    json_array_append(dest_list, json_array_get(src_list, src_index));
    json_array_remove(src_list, src_index);
}
Esempio n. 18
0
void test_suite_5(void) {
	JSON_Value *val_from_file = json_parse_file("tests/test_5.txt");

	JSON_Value *val = NULL;
	JSON_Object *obj = NULL;
	JSON_Array *interests_arr = NULL;

	val = json_value_init_object();
	TEST(val != NULL);

	obj = json_value_get_object(val);
	TEST(obj != NULL);

	TEST(json_object_set_string(obj, "first", "John") == JSONSuccess);
	TEST(json_object_set_string(obj, "last", "Doe") == JSONSuccess);
	TEST(json_object_set_number(obj, "age", 25) == JSONSuccess);
	TEST(json_object_set_boolean(obj, "registered", 1) == JSONSuccess);

	TEST(json_object_set_value(obj, "interests", json_value_init_array()) == JSONSuccess);
	interests_arr = json_object_get_array(obj, "interests");
	TEST(interests_arr != NULL);
	TEST(json_array_append_string(interests_arr, "Writing") == JSONSuccess);
	TEST(json_array_append_string(interests_arr, "Mountain Biking") == JSONSuccess);
	TEST(json_array_replace_string(interests_arr, 0, "Reading") == JSONSuccess);

	TEST(json_object_dotset_string(obj, "favorites.color", "blue") == JSONSuccess);
	TEST(json_object_dotset_string(obj, "favorites.sport", "running") == JSONSuccess);
	TEST(json_object_dotset_string(obj, "favorites.fruit", "apple") == JSONSuccess);
	TEST(json_object_dotremove(obj, "favorites.fruit") == JSONSuccess);
	TEST(json_object_set_string(obj, "utf string", "lorem ipsum") == JSONSuccess);
	TEST(json_object_set_string(obj, "utf-8 string", "あいうえお") == JSONSuccess);
	TEST(json_object_set_string(obj, "surrogate string", "lorem𝄞ipsum𝍧lorem") == JSONSuccess);
	TEST(json_object_set_string(obj, "windows path", "C:\\Windows\\Path") == JSONSuccess);
	TEST(json_value_equals(val_from_file, val));

	TEST(json_object_set_string(obj, NULL, "") == JSONFailure);
	TEST(json_object_set_string(obj, "last", NULL) == JSONFailure);
	TEST(json_object_set_string(obj, NULL, NULL) == JSONFailure);
	TEST(json_object_set_value(obj, NULL, NULL) == JSONFailure);

	TEST(json_object_dotset_string(obj, NULL, "") == JSONFailure);
	TEST(json_object_dotset_string(obj, "favorites.color", NULL) == JSONFailure);
	TEST(json_object_dotset_string(obj, NULL, NULL) == JSONFailure);
	TEST(json_object_dotset_value(obj, NULL, NULL) == JSONFailure);

	TEST(json_array_append_string(NULL, "lorem") == JSONFailure);
	TEST(json_array_append_value(interests_arr, NULL) == JSONFailure);
	TEST(json_array_append_value(NULL, NULL) == JSONFailure);

	TEST(json_array_remove(NULL, 0) == JSONFailure);
	TEST(json_array_replace_value(interests_arr, 0, NULL) == JSONFailure);
	TEST(json_array_replace_string(NULL, 0, "lorem") == JSONFailure);
	TEST(json_array_replace_string(interests_arr, 100, "not existing") == JSONFailure);

	TEST(json_array_append_string(json_object_get_array(obj, "interests"), NULL) == JSONFailure);


	/* UTF-8 tests */
	TEST(json_object_set_string(obj, "correct string", "κόσμε") == JSONSuccess);

	TEST(json_object_set_string(obj, "boundary 1", "\xed\x9f\xbf") == JSONSuccess);
	TEST(json_object_set_string(obj, "boundary 2", "\xee\x80\x80") == JSONSuccess);
	TEST(json_object_set_string(obj, "boundary 3", "\xef\xbf\xbd") == JSONSuccess);
	TEST(json_object_set_string(obj, "boundary 4", "\xf4\x8f\xbf\xbf") == JSONSuccess);

	TEST(json_object_set_string(obj, "first continuation byte", "\x80") == JSONFailure);
	TEST(json_object_set_string(obj, "last continuation byte", "\xbf") == JSONFailure);

	TEST(json_object_set_string(obj, "impossible sequence 1", "\xfe") == JSONFailure);
	TEST(json_object_set_string(obj, "impossible sequence 2", "\xff") == JSONFailure);
	TEST(json_object_set_string(obj, "impossible sequence 3", "\xfe\xfe\xff\xff") == JSONFailure);

	TEST(json_object_set_string(obj, "overlong 1", "\xc0\xaf") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong 2", "\xc1\xbf") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong 3", "\xe0\x80\xaf") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong 4", "\xe0\x9f\xbf") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong 5", "\xf0\x80\x80\xaf") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong 6", "\xf0\x8f\xbf\xbf") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong 7", "\xf0\x8f\xbf\xbf") == JSONFailure);

	TEST(json_object_set_string(obj, "overlong null 1", "\xc0\x80") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong null 2", "\xe0\x80\x80") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong null 3", "\xf0\x80\x80\x80") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong null 4", "\xf8\x80\x80\x80\x80") == JSONFailure);
	TEST(json_object_set_string(obj, "overlong null 5", "\xfc\x80\x80\x80\x80\x80") == JSONFailure);

	TEST(json_object_set_string(obj, "single surrogate 1", "\xed\xa0\x80") == JSONFailure);
	TEST(json_object_set_string(obj, "single surrogate 2", "\xed\xaf\xbf") == JSONFailure);
	TEST(json_object_set_string(obj, "single surrogate 3", "\xed\xbf\xbf") == JSONFailure);
}
Esempio n. 19
0
void PerfLogThread::loop() {
  json_ref samples;
  char **envp;
  json_ref perf_cmd;
  int64_t sample_batch;

  w_set_thread_name("perflog");

  // Prep some things that we'll need each time we run a command
  {
    uint32_t env_size;
    auto envpht = w_envp_make_ht();
    char *statedir = dirname(strdup(watchman_state_file));
    w_envp_set_cstring(envpht, "WATCHMAN_STATE_DIR", statedir);
    w_envp_set_cstring(envpht, "WATCHMAN_SOCK", get_sock_name());
    envp = w_envp_make_from_ht(envpht, &env_size);
  }

  perf_cmd = cfg_get_json("perf_logger_command");
  if (json_is_string(perf_cmd)) {
    perf_cmd = json_array({perf_cmd});
  }
  if (!json_is_array(perf_cmd)) {
    w_log(
        W_LOG_FATAL,
        "perf_logger_command must be either a string or an array of strings\n");
  }

  sample_batch = cfg_get_int("perf_logger_command_max_samples_per_call", 4);

  while (!w_is_stopping()) {
    {
      auto wlock = samples_.wlock();
      if (!*wlock) {
        cond_.wait(wlock.getUniqueLock());
      }

      samples = nullptr;
      std::swap(samples, *wlock);
    }

    if (samples) {
      while (json_array_size(samples) > 0) {
        int i = 0;
        auto cmd = json_array();
        posix_spawnattr_t attr;
        posix_spawn_file_actions_t actions;
        pid_t pid;
        char **argv = NULL;

        json_array_extend(cmd, perf_cmd);

        while (i < sample_batch && json_array_size(samples) > 0) {
          char *stringy = json_dumps(json_array_get(samples, 0), 0);
          if (stringy) {
            json_array_append_new(
                cmd, typed_string_to_json(stringy, W_STRING_MIXED));
            free(stringy);
          }
          json_array_remove(samples, 0);
          i++;
        }

        argv = w_argv_copy_from_json(cmd, 0);
        if (!argv) {
          char *dumped = json_dumps(cmd, 0);
          w_log(W_LOG_FATAL, "error converting %s to an argv array\n", dumped);
        }

        posix_spawnattr_init(&attr);
#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
        posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT);
#endif
        posix_spawn_file_actions_init(&actions);
        posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null",
                                         O_RDONLY, 0666);
        posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "/dev/null",
                                         O_WRONLY, 0666);
        posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null",
                                         O_WRONLY, 0666);

        if (posix_spawnp(&pid, argv[0], &actions, &attr, argv, envp) == 0) {
          int status;
          while (waitpid(pid, &status, 0) != pid) {
            if (errno != EINTR) {
              break;
            }
          }
        } else {
          int err = errno;
          w_log(W_LOG_ERR, "failed to spawn %s: %s\n", argv[0],
                strerror(err));
        }

        posix_spawnattr_destroy(&attr);
        posix_spawn_file_actions_destroy(&actions);

        free(argv);
      }
    }
  }
}
Esempio n. 20
0
int ast_json_array_remove(struct ast_json *array, size_t index)
{
	return json_array_remove((json_t *)array, index);
}
Esempio n. 21
0
void circular_references()
{
    /* Construct a JSON object/array with a circular reference:

       object: {"a": {"b": {"c": <circular reference to $.a>}}}
       array: [[[<circular reference to the $[0] array>]]]

       Encode it, remove the circular reference and encode again.
    */

    json_t *json, *jsonArray;
    char *result;

    json = json_object();

	/*
	jsonArray = json_array(); 
    
    json_array_append_new(jsonArray, json_integer(5));
    json_array_append_new(jsonArray, json_integer(10));
    
    json_object_set_new(json, "a", json_string("aaa"));
    json_object_set_new(json, "b", json_object());
    json_object_set(json_object_get(json, "b"), "c", jsonArray);
    //json_object_set_new(json_object_get(json, "a"), "b", json_object());
//    json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
//                    json_object_get(json, "a"));

//		json_array_append_new(jsonArray, json_integer(5));
//    json_array_append_new(jsonArray, json_integer(10));
//	 	json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
//                     jsonArray);
   
   	                

    //if(json_dumps(json, 0))
    //    printf("json_dumps encoded a circular reference!");

    //json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c");

    result = json_dumps(json, 0);
//    if(!result || strcmp(result, "{\"a\": {\"b\": {}}}"))
//        printf("json_dumps failed!");
    
    printf("circular_references() result1 = %s\n", result); 
    
    free(result);

		json_decref(jsonArray);
    json_decref(json);

*/


    json = json_array();
    json_array_append_new(json, json_array());
    json_array_append_new(json_array_get(json, 0), json_array());
    json_array_append(json_array_get(json_array_get(json, 0), 0),
                      json_array_get(json, 0));

		result = json_dumps(json, 0);
    if(result)
        printf("json_dumps encoded a circular reference!");

		printf("circular_references() result2 = %s\n", result); 
		
    json_array_remove(json_array_get(json_array_get(json, 0), 0), 0);

    result = json_dumps(json, 0);
    if(!result || strcmp(result, "[[[]]]"))
        printf("json_dumps failed!");
    
    printf("circular_references() result3 = %s\n", result); 
    
    free(result);

    json_decref(json);
}
Esempio n. 22
0
void popEvent(EventHistory_t* history)
{
    json_array_remove(history->root, 0);
}