Example #1
0
static int
watchman_send(struct watchman_connection *conn,
              json_t *query, struct watchman_error *error)
{
    int result;
    if (use_bser_encoding) {
        result = bser_write_to_file(query, conn->fp) == 0;
    } else {
        result = json_dumpf(query, conn->fp, JSON_COMPACT);
        fputc('\n', conn->fp);
    }
    if (result) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            watchman_err(error, WATCHMAN_ERR_TIMEOUT,
                         "Timeout sending to watchman");
        } else {
            char *dump = json_dumps(query, 0);
            watchman_err(error, WATCHMAN_ERR_OTHER,
                     "Failed to send watchman query %s", dump);
            free(dump);
        }
        return 1;
    }
    return 0;
}
Example #2
0
void ssm_json_dumpf(FILE *stream, const char *id, json_t *data)
{
    json_t *root = json_pack("{s,s,s,o}", "id", id, "data", data);
    json_dumpf(root, stdout, JSON_COMPACT); printf("\n");
    fflush(stdout);
    json_decref(root);
}
Example #3
0
static int
watchman_send_simple_command(struct watchman_connection *conn,
                             struct watchman_error *error, ...)
{
    int result = 0;
    json_t *cmd_array = json_array();
    va_list argptr;
    va_start(argptr, error);
    char *arg;
    while ((arg = va_arg(argptr, char *))) {
        json_array_append_new(cmd_array, json_string(arg));
    }
    if (use_bser_encoding) {
        result = bser_write_to_file(cmd_array, conn->fp) == 0;
    } else {
        result = json_dumpf(cmd_array, conn->fp, JSON_COMPACT);
        fputc('\n', conn->fp);
    }
    if (result) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            watchman_err(error, WATCHMAN_ERR_TIMEOUT,
                         "Timeout sending simple watchman command");
        } else {
            watchman_err(error, WATCHMAN_ERR_WATCHMAN_BROKEN,
                         "Failed to send simple watchman command");
        }
        result = 1;
    }

    json_decref(cmd_array);
    return result;
}
Example #4
0
int main( int argc, char *argv[] ) {
	(void) argc;
	GError *err = NULL;

	ruminate_init(argv[0], &err);
	die_if_error(err);

	RType *rt = ruminate_get_type(stdout, &err);
	die_if_error(err);

	JsonState *st = json_state_new();
	json_state_add_hook(st, g_quark_from_static_string("void"), &void_hook);
	json_state_add_hook(st, g_quark_from_static_string("char *"), &char_ptr_hook);
	json_state_set_flags(st, JSON_FLAG_SKIP_UNKNOWN);

	printf("Hello World!");
	json_t *serialized = json_serialize(st, rt, &stdout, &err);
	die_if_error(err);

	printf("\n");
	json_dumpf(serialized, stdout, 0);
	printf("\n");

	json_decref(serialized);
	r_type_unref(rt);
	return EXIT_SUCCESS;
}
/**
 * print empirical matrix of variance covariance
 */
void print_covariance(FILE *p_file_cov, gsl_matrix *covariance, struct s_data *p_data)
{

    int i, k, row, ii, kk, col, col_csv;
    double x;
#if FLAG_JSON
    json_t *root;
    json_t *json_print = json_array();
    json_t *json_print_n;
#endif

    struct s_iterator *p_it = p_data->p_it_all_no_theta_remainder;
    struct s_router **routers = p_data->routers;


    for (i=0; i< p_it->length; i++) {
	for(k=0; k< routers[ p_it->ind[i] ]->n_gp; k++) {
	    row = p_it->offset[i]+k;

#if FLAG_JSON
	    json_print_n = json_array();
#endif
	    col_csv = 0;
	    for (ii=0; ii< p_it->length; ii++) {
		for(kk=0; kk< routers[ p_it->ind[ii] ]->n_gp; kk++) {
		    col = p_it->offset[ii]+kk;

		    x = gsl_matrix_get(covariance, row, col);
#if FLAG_JSON
		    json_array_append_new(json_print_n, json_real(x));
#else
		    fprintf(p_file_cov,"%g%s", x, (col_csv < (p_it->nbtot-1)) ? ",": "");
#endif
		    col_csv++;
		}
	    }

#if FLAG_JSON
	    json_array_append_new(json_print, json_print_n);
#else
	    fprintf(p_file_cov,"\n");
#endif

	}
    }


#if FLAG_JSON
    root = json_pack("{s,s,s,o}", "flag", "cov", "msg", json_print);
    json_dumpf(root, stdout, JSON_COMPACT); printf("\n");
    fflush(stdout);
    json_decref(root);
#endif

}
Example #6
0
int ast_json_dump_file_format(struct ast_json *root, FILE *output, enum ast_json_encoding_format format)
{
	/* Jansson's json_dump*, even though it's a read operation, isn't
	 * thread safe for concurrent reads. Locking is necessary.
	 * See http://www.digip.org/jansson/doc/2.4/portability.html#thread-safety. */
	SCOPED_JSON_LOCK(root);
	if (!root || !output) {
		return -1;
	}
	return json_dumpf((json_t *)root, output, dump_flags(format));
}
Example #7
0
void encode_other_than_array_or_object()
{
    /* Encoding anything other than array or object should only
     * succeed if the JSON_ENCODE_ANY flag is used */

    json_t *json;
    FILE *fp = NULL;
    char *result;

    json = json_string("foo");
    if(json_dumps(json, 0) != NULL)
        printf("json_dumps encoded a string!");
    if(json_dumpf(json, fp, 0) == 0)
        printf("json_dumpf encoded a string!");

    result = json_dumps(json, JSON_ENCODE_ANY);
    if(!result || strcmp(result, "\"foo\"") != 0)
        printf("json_dumps failed to encode a string with JSON_ENCODE_ANY");

		printf("encode_other_than_array_or_object() result1 = %s\n", result); 
		
    free(result);
    json_decref(json);

    json = json_integer(42);
    if(json_dumps(json, 0) != NULL)
        printf("json_dumps encoded an integer!");
    if(json_dumpf(json, fp, 0) == 0)
        printf("json_dumpf encoded an integer!");

    result = json_dumps(json, JSON_ENCODE_ANY);
    if(!result || strcmp(result, "42") != 0)
        printf("json_dumps failed to encode an integer with JSON_ENCODE_ANY");

		printf("encode_other_than_array_or_object() result2 = %s\n", result);
		
    free(result);
    json_decref(json);


}
Example #8
0
void ssm_print_err(char *data)
{
#if SSM_JSON
    json_t *root;
    root = json_pack("{s,s,s,s}", "id", "err", "data", data);
    json_dumpf(root, stderr, JSON_COMPACT); fprintf(stderr,"\n");
    fflush(stderr);
    json_decref(root);
#else
    fprintf(stderr, "%s\n", data);
#endif
}
Example #9
0
void ssm_print_log(char *data)
{
#if SSM_JSON
    json_t *root;
    root = json_pack("{s,s,s,s}", "id", "log", "data", data);
    json_dumpf(root, stdout, JSON_COMPACT); printf("\n");
    fflush(stdout);
    json_decref(root);
#else
    printf("%s\n", data);
#endif
}
Example #10
0
static bool read_response(w_jbuffer_t *reader, int fd)
{
  json_t *j;
  json_error_t jerr;

  if (no_pretty) {
    // Just pass through what we get from the server.
    // We use the buffer space from reader.
    int x;
    size_t res;
    char *buf;
    bool is_done = false;

    while (!is_done) {
      x = read(fd, reader->buf, reader->allocd);
      if (x <= 0) {
        return true;
      }

      if (memchr(reader->buf, '\n', x)) {
        is_done = true;
      }

      buf = reader->buf;
      while (x > 0) {
        res = fwrite(buf, 1, x, stdout);
        if (res == 0) {
          break;
        }
        buf += res;
        x -= res;
      }
    }

    return true;
  }

  j = w_json_buffer_next(reader, fd, &jerr);

  if (!j) {
    w_log(W_LOG_ERR, "failed to parse response: %s\n",
        jerr.text);
    return false;
  }

  // Let's just pretty print the JSON response
  json_dumpf(j, stdout, JSON_INDENT(4));
  printf("\n");

  json_decref(j);

  return true;
}
Example #11
0
static void encode_null()
{
    if(json_dumps(NULL, JSON_ENCODE_ANY) != NULL)
        fail("json_dumps didn't fail for NULL");

    if(json_dumpf(NULL, stderr, JSON_ENCODE_ANY) != -1)
        fail("json_dumpf didn't fail for NULL");

    /* Don't test json_dump_file to avoid creating a file */

    if(json_dump_callback(NULL, encode_null_callback, NULL, JSON_ENCODE_ANY) != -1)
        fail("json_dump_callback didn't fail for NULL");
}
Example #12
0
int main(int argc, const char* const argv[]){
  if (argc < 2) {
    printf("Usage: %s header.h\n", argv[0]);
    printf("Standard clang arguments (-I, -D, etc.) may be used\n");
    exit(1);
  }
  unsigned i;

  char filename[] = "ffigen.tmp.XXXXXX";
  int fd = mkstemp(filename);
  FILE* file = fdopen(fd, "w");
  fprintf(file, "#define _SIZE_T\n");
  fprintf(file, "#define _PTRDIFF_T\n");
  fprintf(file, "typedef __SIZE_TYPE__ size_t;\n");
  fprintf(file, "typedef __PTRDIFF_TYPE__ ptrdiff_t;\n");
  fprintf(file, "#include <%s>\n", argv[1]);
  fclose(file);

  int clang_argc = argc + 1;
  const char** clang_argv = malloc(sizeof(char*) * clang_argc);
  clang_argv[0] = "-x";
  clang_argv[1] = "c";
  clang_argv[2] = filename;
  for (i=3; i < clang_argc; i++) {
    clang_argv[i] = argv[i-1];
  }

  CXIndex Index = clang_createIndex(0, 0);
  TU = clang_parseTranslationUnit(Index, 0, clang_argv, clang_argc,
                                  0, 0, CXTranslationUnit_DetailedPreprocessingRecord);
  json_t* json = json_object();
  clang_visitChildren(clang_getTranslationUnitCursor(TU), visit_program, (CXClientData)json);


  json_dumpf(json, stdout, JSON_INDENT(2) | JSON_PRESERVE_ORDER);
  printf("\n");
  json_decref(json);


  for (i=0; i<clang_getNumDiagnostics(TU); i++) {
    putstring(clang_formatDiagnostic(clang_getDiagnostic(TU, i), clang_defaultDiagnosticDisplayOptions()));
  }


  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(Index);
  free(clang_argv);
  unlink(filename);

  return 0;
}
Example #13
0
static int
watchman_send(struct watchman_connection *conn,
              json_t *query, struct watchman_error *error)
{
    int json_result = json_dumpf(query, conn->fp, JSON_COMPACT);
    if (json_result) {
        char *dump = json_dumps(query, 0);
        watchman_err(error, "Failed to send watchman query %s", dump);
        free(dump);
        return 1;
    }
    fputc('\n', conn->fp);
    return 0;
}
void CPUUsagePrintfIntervalJSON(CPUUsageContext_t *ctxt, FILE *outfile, size_t intervalIndex)
{
    assert(ctxt);
    assert(outfile);

    CPUUsageIntervalStats_t *interval = CPUUsageGetInterval(ctxt, intervalIndex);
    if (interval)
    {

        json_t *intervalJSON = CPUUsageIntervalToJSON(interval);
        json_dumpf(intervalJSON, outfile, 0);
    }
    else 
    {
        fprintf(outfile, "Invalid interval number %ld.\n", intervalIndex);
    }
}
Example #15
0
bool try_client_mode_command(const json_ref& cmd, bool pretty) {
  auto client = std::make_shared<watchman_client>();
  bool res;

  client->client_mode = true;
  res = dispatch_command(client.get(), cmd, CMD_CLIENT);

  if (!client->responses.empty()) {
    json_dumpf(
        client->responses.front(),
        stdout,
        pretty ? JSON_INDENT(4) : JSON_COMPACT);
    printf("\n");
  }

  return res;
}
Example #16
0
File: exc.c Project: 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;
}
Example #17
0
int main(int argc, char *argv[])
{
    int indent = 0;
    size_t flags = 0;

    json_t *json;
    json_error_t error;

    if(argc != 1) {
        fprintf(stderr, "usage: %s\n", argv[0]);
        return 2;
    }

    indent = getenv_int("JSON_INDENT");
    if(indent < 0 || indent > 255) {
        fprintf(stderr, "invalid value for JSON_INDENT: %d\n", indent);
        return 2;
    }

    if(indent > 0)
        flags |= JSON_INDENT(indent);

    if(getenv_int("JSON_COMPACT") > 0)
        flags |= JSON_COMPACT;

    if(getenv_int("JSON_ENSURE_ASCII"))
        flags |= JSON_ENSURE_ASCII;

    if(getenv_int("JSON_PRESERVE_ORDER"))
        flags |= JSON_PRESERVE_ORDER;

    if(getenv_int("JSON_SORT_KEYS"))
        flags |= JSON_SORT_KEYS;

    json = json_loadf(stdin, 0, &error);
    if(!json) {
        fprintf(stderr, "%d\n%s\n", error.line, error.text);
        return 1;
    }

    json_dumpf(json, stdout, flags);
    json_decref(json);

    return 0;
}
Example #18
0
/* encode a tpl (kv frame) as json. */
void *enc_worker(void *thread_id) {
  char buf[MAX_BUF], *key, *val;
  json_t *o = json_object();
  int rc=-1, len, nc;
  tpl_node *tn;

  while (CF.shutdown == 0) {
    len = nn_recv(CF.ingress_socket_pull, buf, MAX_BUF, 0);
    if (len < 0) {
      fprintf(stderr,"nn_recv: %s\n", nn_strerror(errno));
      goto done;
    }
    /* decode, then re-encode as json */
    json_object_clear(o);
    tn = tpl_map("A(ss)",&key,&val); assert(tn);
    if (tpl_load(tn,TPL_MEM,buf,len) < 0) goto done;
    while(tpl_unpack(tn,1) > 0) {
      json_t *jval = json_string(val);
      json_object_set_new(o, key, jval); 
      free(key); key=NULL;
      free(val); val=NULL;
    }
    tpl_free(tn);

    /* dump the json object, then newline-terminate it. */
    if (CF.verbose>1) json_dumpf(o, stderr, JSON_INDENT(1));
    char *dump = json_dumps(o, JSON_INDENT(0));
    size_t dump_len = strlen(dump);

    /* give the buffer to nano, from here it goes to kaf thread */
    nc = nn_send(CF.egress_socket_push, dump, dump_len, 0);
    free(dump);
    if (nc < 0) {
      fprintf(stderr,"nn_send: %s\n", nn_strerror(errno));
      goto done;
    }
  }

  rc = 0;

 done:
  CF.shutdown = 1;
  json_decref(o);
  return NULL;
}
Example #19
0
static void output_data_json(void)
{
	json_t *obj = json_object();
	assert(obj != NULL);

	output_json_txid(obj);
	bp_json_set_new_int(obj, "version", tx.nVersion);
	bp_json_set_new_int(obj, "locktime", tx.nLockTime);
	output_json_vin(obj);
	output_json_vout(obj);

	int rc = json_dumpf(obj, stdout, JSON_INDENT(4) | JSON_SORT_KEYS);
	assert(rc == 0);

	printf("\n");

	if (opt_strict_free)
		json_decref(obj);
}
void CPUUsagePrintfAllIntervalsJSON(CPUUsageContext_t *ctxt, FILE *outfile)
{
    json_t *jWindow = json_object();
    json_t *jIntervalsArray = json_array();

    int numInterval = CPUUsageGetNumIntervals(ctxt);

    for (int i = 0 ; i < numInterval; i++)
    {
        CPUUsageIntervalStats_t *curInterval = CPUUsageGetInterval(ctxt, i);
        json_t *jCurInterval = CPUUsageIntervalToJSON(curInterval);
        json_array_append_new(jIntervalsArray, jCurInterval);
    }

    json_object_set(jWindow, WINDOW_ALL_INTERVALS_KEY, jIntervalsArray);
    json_decref(jIntervalsArray);
    json_dumpf(jWindow, outfile, 0);
    json_decref(jWindow);
}
Example #21
0
static int
jwk_create (tc_argsd_t *arguments)
{

  int rc;
  gcry_sexp_t keyparm, key;
  json_t *jwk;

  rc = gcry_sexp_build (&keyparm, NULL,
                        "(genkey\n"
                        " (ecc\n"
                        "  (curve \"NIST P-256\")\n"
                        "  (flags param)"
                        "))");

  if (rc) return rc;

  rc = gcry_pk_genkey (&key, keyparm);

  if (rc) return rc;

  if (arguments->verbose)
    show_sexp ("Gen key:\n", key);

  gcry_sexp_release (keyparm);

  jwk = gcry_pubkey2jwk (&key);

  char *d = gcry_prikey2jwk (&key);

  assert (NULL != d);

  assert (0 == json_object_set (jwk, "d", json_string (d)));

  json_dumpf(jwk, stdout, JSON_INDENT(2));
  printf("\n");



  return rc;

}
Example #22
0
extern void error (
		const errorSelection selection, const char *const format, ...)
{
	va_list ap;

	va_start (ap, format);
	if (Option.json) {
		char *reason;
		vasprintf (&reason, format, ap);

		json_t *response = json_object ();
		json_object_set_new (response, "error", json_string (reason));
		if (selected (selection, WARNING))
			json_object_set_new (response, "warning", json_true ());
		if (selected (selection, FATAL))
			json_object_set_new (response, "fatal", json_true ());
		if (selected (selection, PERROR)) {
			json_object_set_new (response, "errno", json_integer (errno));
			json_object_set_new (response, "perror", json_string (strerror (errno)));
		}
		json_dumpf (response, stdout, 0);
		fprintf (stdout, "\n");

		json_decref (response);
		free (reason);
	} else {
		fprintf (errout, "%s: %s", getExecutableName (),
				selected (selection, WARNING) ? "Warning: " : "");
		vfprintf (errout, format, ap);
		if (selected (selection, PERROR))
#ifdef HAVE_STRERROR
			fprintf (errout, " : %s", strerror (errno));
#else
			perror (" ");
#endif
		fputs ("\n", errout);
	}
	va_end (ap);
	if (! Option.json && selected (selection, FATAL))
		exit (1);
}
Example #23
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);	
    }
}
Example #24
0
static int
watchman_send_simple_command(struct watchman_connection *conn,
                             struct watchman_error *error, ...)
{
    int result = 0;
    json_t *cmd_array = json_array();
    va_list argptr;
    va_start(argptr, error);
    char *arg;
    while ((arg = va_arg(argptr, char *))) {
        json_array_append_new(cmd_array, json_string(arg));
    }
    int json_result = json_dumpf(cmd_array, conn->fp, JSON_COMPACT);
    if (json_result) {
        watchman_err(error, "Failed to send simple watchman command");
        result = 1;
    }
    fputc('\n', conn->fp);

    json_decref(cmd_array);
    return result;
}
/**
 * for the webApp, we print the smoothed values
 */
void print_acceptance_rates(FILE *p_file, struct s_mcmc_calc_data *p, int m_full_iteration)
{
    int k;

#if FLAG_JSON
    json_t *root;
    json_t *j_print = json_array();
#endif

#if FLAG_JSON
    json_array_append_new(j_print, json_integer(m_full_iteration));
    json_array_append_new(j_print, json_real(p->epsilon));
    json_array_append_new(j_print, json_real(p->smoothed_global_acceptance_rate));
#else
    fprintf(p_file, "%d,%g,%g", m_full_iteration, p->epsilon, p->global_acceptance_rate);
#endif

    /* parameter specific acceptance rates */
    if (!OPTION_FULL_UPDATE) {
        for(k=0; k< (p->n_acceptance_rates); k++) {
#if FLAG_JSON
            json_array_append_new(j_print, json_real(p->smoothed_acceptance_rates[k]));
#else
	    fprintf(p_file, ",%g", p->acceptance_rates[k]);
#endif
        }
    }

#if FLAG_JSON
    root = json_pack("{s,s,s,o}", "flag", "pmcmc", "msg", j_print);
    json_dumpf(root, stdout, JSON_COMPACT); printf("\n");
    fflush(stdout);
    json_decref(root);
#else
    fprintf(p_file, "\n");
#endif

}
Example #26
0
static void output_to_json(nghttp2_hd_deflater *deflater,
                           const uint8_t *buf, size_t len, size_t inputlen,
                           nghttp2_nv *nva, size_t nvlen,
                           int seq)
{
  json_t *obj;
  char *hex = NULL;

  if(len > 0) {
    hex = malloc(len * 2);
  }
  obj = json_object();
  json_object_set_new(obj, "seq", json_integer(seq));
  json_object_set_new(obj, "input_length", json_integer(inputlen));
  json_object_set_new(obj, "output_length", json_integer(len));
  json_object_set_new(obj, "percentage_of_original_size",
                      json_real((double)len / inputlen * 100));
  to_hex(hex, buf, len);
  if(len == 0) {
    json_object_set_new(obj, "wire", json_string(""));
  } else {
    json_object_set_new(obj, "wire", json_pack("s#", hex, len * 2));
  }
  json_object_set_new(obj, "headers", dump_headers(nva, nvlen));
  if(seq == 0) {
    /* We only change the header table size only once at the beginning */
    json_object_set_new(obj, "header_table_size",
                        json_integer(config.table_size));
  }
  if(config.dump_header_table) {
    json_object_set_new(obj, "header_table",
                        dump_header_table(&deflater->ctx));
  }
  json_dumpf(obj, stdout, JSON_PRESERVE_ORDER | JSON_INDENT(2));
  printf("\n");
  json_decref(obj);
  free(hex);
}
Example #27
0
//database functions
void dbsave()
{
    dprintf("saving database...");
    DWORD ticks = GetTickCount();
    JSON root = json_object();
    CommentCacheSave(root);
    LabelCacheSave(root);
    BookmarkCacheSave(root);
    FunctionCacheSave(root);
    LoopCacheSave(root);
    BpCacheSave(root);
    WString wdbpath = StringUtils::Utf8ToUtf16(dbpath);
    if(json_object_size(root))
    {
        FILE* jsonFile = 0;
        if(_wfopen_s(&jsonFile, wdbpath.c_str(), L"wb"))
        {
            dputs("failed to open database file for editing!");
            json_decref(root); //free root
            return;
        }
        if(json_dumpf(root, jsonFile, JSON_INDENT(4)) == -1)
        {
            dputs("couldn't write JSON to database file...");
            json_decref(root); //free root
            return;
        }
        fclose(jsonFile);
        if(!settingboolget("Engine", "DisableCompression"))
            LZ4_compress_fileW(wdbpath.c_str(), wdbpath.c_str());
    }
    else //remove database when nothing is in there
        DeleteFileW(wdbpath.c_str());
    dprintf("%ums\n", GetTickCount() - ticks);
    json_decref(root); //free root
}
Example #28
0
int save_policy_config(dnssec_kasp_policy_t *policy, const char *filename)
{
	assert(policy);
	assert(filename);

	_json_cleanup_ json_t *config = NULL;
	int r = encode_object(POLICY_ATTRS, policy, &config);
	if (r != DNSSEC_EOK) {
		return r;
	}

	_cleanup_fclose_ FILE *file = fopen(filename, "w");
	if (!file) {
		return DNSSEC_NOT_FOUND;
	}

	r = json_dumpf(config, file, JSON_DUMP_OPTIONS);
	if (r != DNSSEC_EOK) {
		return r;
	}

	fputc('\n', file);
	return DNSSEC_EOK;
}
void MapFormat::saveToFile(String filename)
{
	FILE* file = fopen(filename.c_str(), "w");
	if (file)
	{
		json_t* rootObject = json_object();
		json_t* nameJson = json_string(name);
		json_t* descriptionJson = json_string(description);
		json_t* firstRespawnJson = json_integer(firstRespawnOffset);
//		json_t* sizeXjson = json_integer(Math::ICeil(size.x));
//		json_t* sizeXjson = json_integer(Math::ICeil(size.y));
//		json_t* sizeXjson = json_integer(Math::ICeil(size.z));
		int blockSize = blocks.size();
		json_t* blocksJson = json_array();

		json_object_set(rootObject, "name", nameJson);
		json_object_set(rootObject, "description", descriptionJson);
		json_object_set(rootObject, "first-respawn", firstRespawnJson);
		
//		
//		fwrite(name, sizeof(char), sizeof(name), file);
//		fwrite(description, sizeof(char), sizeof(description), file);
////		fwrite(&respawnTime, sizeof(respawnTime), 1, file);
//		fwrite(&firstRespawnOffset, sizeof(firstRespawnOffset), 1, file);
//		fwrite(&size, sizeof(size), 1, file);
//		int a;
//		fwrite(&a, sizeof(a), 1, file);
//
//		int blockSize = blocks.size();
//		fwrite(&(blockSize), sizeof(blockSize), 1, file);
		for (int i = 0; i < blocks.size(); i++)
		{
			Block* block = blocks[i];
			json_t* indBlock = json_object();
			
			json_object_set(indBlock, "extra-args", json_integer(block->extraArgsBit));
			json_object_set(indBlock, "origin-x", json_integer(Math::ICeil(block->origin.x)));
			json_object_set(indBlock, "origin-y", json_integer(Math::ICeil(block->origin.y)));
			json_object_set(indBlock, "origin-z", json_integer(Math::ICeil(block->origin.z)));

			json_object_set(indBlock, "material-index", json_integer(block->materialIndex));
			
			if (block->isPoint)
			{
				json_object_set(indBlock, "is-point", json_boolean(block->isPoint));
			}
			else if (block->isRespawn)
			{
				json_object_set(indBlock, "is-respawn", json_boolean(block->isRespawn));
			}

			if (Math::IFloor(block->rotation.valueDegrees()) != 0)
			{
				json_object_set(indBlock, "rotation", json_integer(Math::IFloor(block->rotation.valueDegrees())));
			}

			if ((block->linearSpeed && Math::IFloor(block->linearLocation.length()) > 0)|| block->rotationSpeed)
			{
				json_t* movableArgs = json_object();
				if (block->linearSpeed > 0 && Math::IFloor(block->linearLocation.length()) > 0)
				{
					json_object_set(movableArgs, "linear-speed", json_integer(block->linearSpeed));
					json_object_set(movableArgs, "linear-location-x", json_integer(Math::ICeil(block->linearLocation.x)));
					json_object_set(movableArgs, "linear-location-y", json_integer(Math::ICeil(block->linearLocation.y)));
					json_object_set(movableArgs, "linear-location-z", json_integer(Math::ICeil(block->linearLocation.z)));
					if (block->isRotationMovement)
					{
						json_object_set(movableArgs, "rotation-movement", json_integer(1));
						json_object_set(movableArgs, "is-rotation-right", json_integer(block->isRightRotationMovement ? 1 : 0));
					}
				}
				if (block->rotationSpeed)
				{
					json_object_set(movableArgs, "rotation-speed", json_integer(Math::ICeil(block->rotationSpeed)));
				}

				json_object_set(indBlock, "movable-args", movableArgs);
			}

			if (block->specialBlockId != -1)
			{
				json_object_set(indBlock, "special-block", json_integer(block->specialBlockId));
			}

			json_array_append(blocksJson, indBlock);
			
		}
		
		json_object_set(rootObject, "blocks", blocksJson);

		json_dumpf(rootObject, file, JSON_INDENT(4));
		
		json_delete(rootObject);
		fclose(file);
	}
}
Example #30
0
int main(void)
{


    json_t *jwk;
    struct MemoryStruct res;
    struct timeval tval_before, tval_after, tval_result;

    lca_init();

    int fd = start();

    if (lca_load_signing_key ("test_keys/atmel.key", &signing_key))
        return -1;

    jwk = gcry_pubkey2jwk (&signing_key);

    assert (NULL != jwk);

    json_dumpf (jwk, stdout, 0);


    char *m1 = build_key_post (jwk);

    printf ("Post key: %s\n", m1);

    char *b = combine (postkey, m1);
    char *c = combine (getkey, m1);

    /* char *b = malloc (strlen(m1) + strlen(postkey) + 1); */
    /* memset (b, 0, strlen(m1) + strlen(postkey) + 1); */

    /* printf ("here"); */

    /* strcpy (b, postkey); */
    /* strcat (postkey, m1); */



  curl_global_init(CURL_GLOBAL_ALL);


  res = get (b);

  free (res.memory);

  res = get (c);

  json_t *dm_key = get_dm_key (res.memory);

  free (res.memory);

  char *hello = build_hello (sub);

  gettimeofday(&tval_before, NULL);

  char *d = combine (posthello, hello);

  res = get (d);

  json_t *hello_rsp = verify_hello (res.memory, dm_key);
  free (res.memory);

  char *done = build_hello_rsp (sub, hello_rsp);
  char *e = combine (postdone, done);

  res = get (e);

  json_t *done_rsp = verify_done (res.memory, dm_key);
  free (res.memory);

  gettimeofday(&tval_after, NULL);

  free (e);
  free (d);
  free (b);
  free (c);
  /* we're done with libcurl, so clean it up */
  curl_global_cleanup();

  timersub(&tval_after, &tval_before, &tval_result);

  printf("Time elapsed: %ld.%06ld\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);

  return 0;

}