Esempio n. 1
0
char *virJSONValueToString(virJSONValuePtr object,
                           bool pretty)
{
    yajl_gen g;
    const unsigned char *str;
    char *ret = NULL;
    yajl_size_t len;
# ifndef WITH_YAJL2
    yajl_gen_config conf = { pretty ? 1 : 0, pretty ? "    " : " "};
# endif

    VIR_DEBUG("object=%p", object);

# ifdef WITH_YAJL2
    g = yajl_gen_alloc(NULL);
    if (g) {
        yajl_gen_config(g, yajl_gen_beautify, pretty ? 1 : 0);
        yajl_gen_config(g, yajl_gen_indent_string, pretty ? "    " : " ");
        yajl_gen_config(g, yajl_gen_validate_utf8, 1);
    }
# else
    g = yajl_gen_alloc(&conf, NULL);
# endif
    if (!g) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to create JSON formatter"));
        goto cleanup;
    }

    if (virJSONValueToStringOne(object, g) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (yajl_gen_get_buf(g, &str, &len) != yajl_gen_status_ok) {
        virReportOOMError();
        goto cleanup;
    }

    ignore_value(VIR_STRDUP(ret, (const char *)str));

cleanup:
    yajl_gen_free(g);

    VIR_DEBUG("result=%s", NULLSTR(ret));

    return ret;
}
Esempio n. 2
0
char *virJSONValueToString(virJSONValuePtr object)
{
    yajl_gen g;
    const unsigned char *str;
    char *ret = NULL;
    yajl_size_t len;
# ifndef HAVE_YAJL2
    yajl_gen_config conf = { 0, " " }; /* Turns off pretty printing since QEMU can't cope */
# endif

    VIR_DEBUG("object=%p", object);

# ifdef HAVE_YAJL2
    g = yajl_gen_alloc(NULL);
    if (g) {
        yajl_gen_config(g, yajl_gen_beautify, 0);
        yajl_gen_config(g, yajl_gen_indent_string, " ");
        yajl_gen_config(g, yajl_gen_validate_utf8, 1);
    }
# else
    g = yajl_gen_alloc(&conf, NULL);
# endif
    if (!g) {
        virJSONError(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Unable to create JSON formatter"));
        goto cleanup;
    }

    if (virJSONValueToStringOne(object, g) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (yajl_gen_get_buf(g, &str, &len) != yajl_gen_status_ok) {
        virReportOOMError();
        goto cleanup;
    }

    if (!(ret = strdup((const char *)str)))
        virReportOOMError();

cleanup:
    yajl_gen_free(g);

    VIR_DEBUG("result=%s", NULLSTR(ret));

    return ret;
}
Esempio n. 3
0
static gchar *
_j4status_i3bar_output_generate_header(J4statusPluginContext *context)
{
    yajl_gen json_gen;
    json_gen = yajl_gen_alloc(NULL);

    yajl_gen_map_open(json_gen);
    yajl_gen_string(json_gen, (const unsigned char *)"version", strlen("version"));
    yajl_gen_integer(json_gen, 1);
    yajl_gen_string(json_gen, (const unsigned char *)"stop_signal", strlen("stop_signal"));
    yajl_gen_integer(json_gen, SIGUSR2);
    yajl_gen_string(json_gen, (const unsigned char *)"cont_signal", strlen("cont_signal"));
    yajl_gen_integer(json_gen, SIGUSR1);
    if ( ! context->no_click_events )
    {
        yajl_gen_string(json_gen, (const unsigned char *)"click_events", strlen("click_events"));
        yajl_gen_bool(json_gen, 1);
    }
    yajl_gen_map_close(json_gen);

    const unsigned char *buffer;
    size_t length;
    yajl_gen_get_buf(json_gen, &buffer, &length);

    gchar *header;

    header = g_strdup_printf("%s\n[[]\n", buffer);
    yajl_gen_free(json_gen);

    return header;
}
Esempio n. 4
0
xlw::XlfOper HttpProtocol::Execute(const char* name, bool sendCaller, xlw::XlfOper* args, int argc)
{
	REQUEST_CONTEXT context;
	context.hEvent = CreateEvent(0, 1, 0, 0);
	context.hConnect = WinHttpConnect(hSession, host, urlc.nPort, 0);
	int flags = WINHTTP_FLAG_BYPASS_PROXY_CACHE;
	if(urlc.nScheme == INTERNET_SCHEME_HTTPS)
		flags |= WINHTTP_FLAG_SECURE;
	context.hRequest = WinHttpOpenRequest(context.hConnect, L"POST", path, 0, 0, 0, 
		flags);
	context.conf.beautify = 0;
	context.conf.indentString = "";
	context.g = yajl_gen_alloc(&context.conf, 0);
	context.px = xlw::XlfOper();
	//context.px->xltype = xltypeNil | xlbitDLLFree;
	GenerateRequest(context.g, name, sendCaller, args, argc);
	const unsigned char * buf;
    unsigned int len = 0;
    yajl_gen_get_buf(context.g, &buf, &len);
	BOOL res = FALSE;
	res = WinHttpSendRequest(context.hRequest, 0, 0, (LPVOID) buf, len, len, (DWORD_PTR) &context);
	if(!res) {
		const char* err = "#Could not connect to server";
		Log::Error(err);
		WinHttpCloseHandle(context.hRequest);
		WinHttpCloseHandle(context.hConnect);
		context.px = xlw::XlfOper(err);
		return context.px;
	}
	// TODO timeout/background
	res = WinHttpReceiveResponse(context.hRequest, 0);
	if(!res) {
		const char* err = "#Error retrieving server response";
		Log::Error(err);
		WinHttpCloseHandle(context.hRequest);
		WinHttpCloseHandle(context.hConnect);
		context.px = xlw::XlfOper(err);
		return context.px;
	}
	// Check http response code
	DWORD status;
	DWORD statusLength = 4;
	res = WinHttpQueryHeaders(context.hRequest, WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER,
		NULL, &status, &statusLength, 0);
	if(!res || status != 200) {
		Log::Error("Status code: %d", status);
		const char* err = "#Server returned an error";
		WinHttpCloseHandle(context.hRequest);
		WinHttpCloseHandle(context.hConnect);
		context.px = xlw::XlfOper(err);
		return context.px;
	}
	ReadData(&context);
	WinHttpCloseHandle(context.hRequest);
	WinHttpCloseHandle(context.hConnect);
    yajl_gen_clear(context.g);
	yajl_gen_free(context.g);
	//context.px->xltype |= xlbitDLLFree;
	return context.px;
}
Esempio n. 5
0
IoYajlGen *IoYajlGen_proto(void *state)
{
	IoYajlGen *self = IoObject_new(state);
	IoObject_tag_(self, IoYajlGen_newTag(state));

	yajl_gen_config config = { 0, "" };
	IoObject_setDataPointer_(self, yajl_gen_alloc(&config, NULL));

	IoState_registerProtoWithFunc_(state, self, IoYajlGen_proto);

	{
		IoMethodTable methodTable[] = 
		{
			{"pushNull", IoYajlGen_pushNull},
			{"pushString", IoYajlGen_pushString},
			{"pushInteger", IoYajlGen_pushInteger},
			{"pushDouble", IoYajlGen_pushDouble},
			{"pushNumberString", IoYajlGen_pushNumberString},
			{"pushBool", IoYajlGen_pushBool},
			{"openMap", IoYajlGen_openMap},
			{"closeMap", IoYajlGen_closeMap},
			{"openArray", IoYajlGen_openArray},
			{"closeArray", IoYajlGen_closeArray},
			{"generate", IoYajlGen_generate},
			{NULL, NULL},
		};
		IoObject_addMethodTable_(self, methodTable);
	}
		
	return self;
}
Esempio n. 6
0
ngx_http_tfs_json_gen_t *
ngx_http_tfs_json_init(ngx_log_t *log, ngx_pool_t *pool)
{
    yajl_gen                  g;
    ngx_http_tfs_json_gen_t  *tj_gen;

    g = yajl_gen_alloc(NULL);
    if (g == NULL) {
        ngx_log_error(NGX_LOG_ERR, log, errno, "alloc yajl_gen failed");
        return NULL;
    }

    tj_gen = ngx_pcalloc(pool, sizeof(ngx_http_tfs_json_gen_t));
    if (tj_gen == NULL) {
        return NULL;
    }

    yajl_gen_config(g, yajl_gen_beautify, 1);

    tj_gen->gen = g;
    tj_gen->pool = pool;
    tj_gen->log = log;

    return tj_gen;
}
Esempio n. 7
0
json_writer::json_writer(boost::shared_ptr<output_buffer> &out, bool indent)
    : pimpl(new pimpl_()) {
#ifdef HAVE_YAJL2
  pimpl->gen = yajl_gen_alloc(NULL);

#else  /* older version of YAJL */
  // setup whether the generator should produce pretty output
  if (indent) {
    pimpl->config.beautify = 1;
    pimpl->config.indentString = " ";
  } else {
    pimpl->config.beautify = 0;
    pimpl->config.indentString = "";
  }

  pimpl->gen = yajl_gen_alloc2(&wrap_write, &pimpl->config, NULL, out.get());
#endif /* HAVE_YAJL2 */

  if (pimpl->gen == 0) {
    throw std::runtime_error("error creating json writer.");
  }

#ifdef HAVE_YAJL2
  if (indent) {
    yajl_gen_config(pimpl->gen, yajl_gen_beautify, 1);
    yajl_gen_config(pimpl->gen, yajl_gen_indent_string, " ");
  } else {
    yajl_gen_config(pimpl->gen, yajl_gen_beautify, 0);
    yajl_gen_config(pimpl->gen, yajl_gen_indent_string, "");
  }
  yajl_gen_config(pimpl->gen, yajl_gen_print_callback, &wrap_write,
                  (void *)out.get());
#endif /* HAVE_YAJL2 */
}
Esempio n. 8
0
gboolean
log_save(gchar *filename)
{
    gzFile gzfp = NULL;
    FILE *fp = NULL;
    gchar *ext;
    gboolean compression;
    yajl_gen gen;
    const guchar *json_string;
    size_t json_length;
    gint wrote;

    ext = strrchr(filename, '.');
    compression = (ext && !g_ascii_strcasecmp(ext, ".gz"));

    if(compression)
        gzfp = gzopen(filename, "wb");
    else
        fp = fopen(filename, "w");

    if(!gzfp && !fp)
    {
        ui_dialog(ui.window,
                  GTK_MESSAGE_ERROR,
                  "Error",
                  "Unable to save a file:\n%s", filename);
        return FALSE;
    }

    gen = yajl_gen_alloc(NULL);
    //yajl_gen_config(gen, yajl_gen_beautify, 1);
    yajl_gen_map_open(gen);
    gtk_tree_model_foreach(GTK_TREE_MODEL(ui.model->store), log_save_foreach, gen);
    yajl_gen_map_close(gen);
    yajl_gen_get_buf(gen, &json_string, &json_length);

    if(compression)
    {
        wrote = gzwrite(gzfp, json_string, json_length);
        gzclose(gzfp);
    }
    else
    {
        wrote = fwrite(json_string, sizeof(gchar), json_length, fp);
        fclose(fp);
    }

    yajl_gen_free(gen);

    if(json_length != wrote)
    {
        ui_dialog(ui.window,
                  GTK_MESSAGE_ERROR,
                  "Error",
                  "Unable to save a file:\n%s\n\nWrote only %d of %d uncompressed bytes.",
                  filename, wrote, json_length);
        return FALSE;
    }
    return TRUE;
}
Esempio n. 9
0
luvit_generator_t* generator_new(lua_State *L) {
  luvit_generator_t *generator = lua_newuserdata(L, sizeof(*generator));
  generator->gen = yajl_gen_alloc(NULL);
  luaL_getmetatable(L, JSON_GENERATOR_HANDLE);
  lua_setmetatable(L, -2);
  return generator;
}
Esempio n. 10
0
IoYajlGen *IoYajlGen_rawClone(IoYajlGen *proto)
{
	IoObject *self = IoObject_rawClonePrimitive(proto);
	yajl_gen_config config = { 0, "" };
	IoObject_setDataPointer_(self, yajl_gen_alloc(&config, NULL));
	return self;
}
Esempio n. 11
0
/*
 * Format (prometheus/alertmanager v1):
 *
 * [{
 *   "labels": {
 *     "alertname": "collectd_cpu",
 *     "instance":  "host.example.com",
 *     "severity":  "FAILURE",
 *     "service":   "collectd",
 *     "cpu":       "0",
 *     "type":      "wait"
 *   },
 *   "annotations": {
 *     "summary": "...",
 *     // meta
 *   },
 *   "startsAt": <rfc3339 time>,
 *   "endsAt": <rfc3339 time>, // not used
 * }]
 */
int format_json_notification(char *buffer, size_t buffer_size, /* {{{ */
                             notification_t const *n) {
  yajl_gen g;
  unsigned char const *out;
#if HAVE_YAJL_V2
  size_t unused_out_len;
#else
  unsigned int unused_out_len;
#endif

  if ((buffer == NULL) || (n == NULL))
    return EINVAL;

#if HAVE_YAJL_V2
  g = yajl_gen_alloc(NULL);
  if (g == NULL)
    return -1;
#if COLLECT_DEBUG
  yajl_gen_config(g, yajl_gen_beautify, 1);
  yajl_gen_config(g, yajl_gen_validate_utf8, 1);
#endif

#else /* !HAVE_YAJL_V2 */
  yajl_gen_config conf = {0};
#if COLLECT_DEBUG
  conf.beautify = 1;
  conf.indentString = "  ";
#endif
  g = yajl_gen_alloc(&conf, NULL);
  if (g == NULL)
    return -1;
#endif

  if (format_alert(g, n) != 0) {
    yajl_gen_clear(g);
    yajl_gen_free(g);
    return -1;
  }

  /* copy to output buffer */
  yajl_gen_get_buf(g, &out, &unused_out_len);
  sstrncpy(buffer, (void *)out, buffer_size);

  yajl_gen_clear(g);
  yajl_gen_free(g);
  return 0;
} /* }}} format_json_notification */
Esempio n. 12
0
File: util.c Progetto: Fresne/i3-1
char *store_restart_layout(void) {
    setlocale(LC_NUMERIC, "C");
    yajl_gen gen = yajl_gen_alloc(NULL);

    dump_node(gen, croot, true);

    setlocale(LC_NUMERIC, "");

    const unsigned char *payload;
    size_t length;
    y(get_buf, &payload, &length);

    /* create a temporary file if one hasn't been specified, or just
     * resolve the tildes in the specified path */
    char *filename;
    if (config.restart_state_path == NULL) {
        filename = get_process_filename("restart-state");
        if (!filename)
            return NULL;
    } else {
        filename = resolve_tilde(config.restart_state_path);
    }

    int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        perror("open()");
        free(filename);
        return NULL;
    }

    size_t written = 0;
    while (written < length) {
        int n = write(fd, payload + written, length - written);
        /* TODO: correct error-handling */
        if (n == -1) {
            perror("write()");
            free(filename);
            close(fd);
            return NULL;
        }
        if (n == 0) {
            DLOG("write == 0?\n");
            free(filename);
            close(fd);
            return NULL;
        }
        written += n;
        DLOG("written: %zd of %zd\n", written, length);
    }
    close(fd);

    if (length > 0) {
        DLOG("layout: %.*s\n", (int)length, payload);
    }

    y(free);

    return filename;
}
Esempio n. 13
0
static int json_init(struct formatter *fmt)
{
	struct json_formatter_data *priv = fmt->priv;
	if((priv->yajl = yajl_gen_alloc(NULL)) == NULL)
		return -1;
	yajl_gen_array_open(priv->yajl);
	return 0;
}
Esempio n. 14
0
void VertexServer_setupYajl(VertexServer *self)
{
	if(self->yajl) 	yajl_gen_free(self->yajl);

	yajl_gen_config config = { 0, "" };
	self->yajl = yajl_gen_alloc(&config, NULL);
	PDB_setYajl_(self->pdb, self->yajl);
}
Esempio n. 15
0
IoYajlGen *IoYajlGen_rawClone(IoYajlGen *proto)
{
	IoObject *self = IoObject_rawClonePrimitive(proto);

	yajl_gen yg = yajl_gen_alloc(NULL);
	//yajl_gen_config(yg, yajl_gen_beautify, 0);

	IoObject_setDataPointer_(self, yg);
	return self;
}
Esempio n. 16
0
static int json_start(struct asfd *asfd)
{
	if(!yajl)
	{
		if(!(yajl=yajl_gen_alloc(NULL)))
			return -1;
		yajl_gen_config(yajl, yajl_gen_beautify, pretty_print);
	}
	if(yajl_map_open_w()) return -1;
	return 0;
}
Esempio n. 17
0
yajl_gen bson_to_yajl(bson *b)
{
    bson_iterator it[1];
    bson_iterator_init( it, b );

    yajl_gen g = yajl_gen_alloc( NULL );
    yajl_gen_config( g, yajl_gen_beautify, 1 );

    json_from_bson_object( &g, it );

    return g;
}
Esempio n. 18
0
/* OVS DB echo request handler. When OVS DB sends
 * "echo" request to the client, client should generate
 * "echo" replay with the same content received in the
 * request */
static int ovs_db_table_echo_cb(const ovs_db_t *pdb, yajl_val jnode) {
  yajl_val jparams;
  yajl_val jid;
  yajl_gen jgen;
  size_t resp_len = 0;
  const char *resp = NULL;
  const char *params_path[] = {"params", NULL};
  const char *id_path[] = {"id", NULL};
  yajl_gen_status yajl_gen_ret;

  if ((jgen = yajl_gen_alloc(NULL)) == NULL)
    return -1;

  /* check & get request attributes */
  if ((jparams = yajl_tree_get(jnode, params_path, yajl_t_array)) == NULL ||
      ((jid = yajl_tree_get(jnode, id_path, yajl_t_any)) == NULL)) {
    OVS_ERROR("parse echo request failed");
    goto yajl_gen_failure;
  }

  /* generate JSON echo response */
  OVS_YAJL_CALL(yajl_gen_map_open, jgen);

  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "result");
  OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jparams);

  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "error");
  OVS_YAJL_CALL(yajl_gen_null, jgen);

  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "id");
  OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jid);

  OVS_YAJL_CALL(yajl_gen_map_close, jgen);
  OVS_YAJL_CALL(yajl_gen_get_buf, jgen, (const unsigned char **)&resp,
                &resp_len);

  /* send the response */
  OVS_DEBUG("response: %s", resp);
  if (ovs_db_data_send(pdb, resp, resp_len) < 0) {
    OVS_ERROR("send echo reply failed");
    goto yajl_gen_failure;
  }
  /* clean up and return success */
  yajl_gen_clear(jgen);
  return 0;

yajl_gen_failure:
  /* release memory */
  yajl_gen_clear(jgen);
  return -1;
}
Esempio n. 19
0
veBool pubnub_atPublishN(struct PubnubAt* nubat, char const *buf, size_t buf_len)
{
	struct PubnubRequest *nubreq;
	u8 const *json;
	size_t json_len;

	/* allocate request */
	if (!nubat->g) {
		nubat->g = yajl_gen_alloc(NULL);
		if (!nubat->g)
			return veFalse;
	}

	nubreq = (struct PubnubRequest *) ve_malloc(sizeof(struct PubnubRequest));
	if (!nubreq) {
		/* reuse the nubat->q next time */
		return veFalse;
	}

	pubnub_req_init(&nubat->nub, nubreq, 512, 512);

	/* build json data.. */
	if (yajl_gen_string(nubat->g, (u8*) buf, buf_len) != yajl_gen_status_ok) {
		ve_error("json: not a valid string");
		goto error;
	}

	if (yajl_gen_get_buf(nubat->g, &json, &json_len) != yajl_gen_status_ok) {
		ve_error("json: could not get buf");
		return veFalse;
	}

	/* sent it */
	if (pubnub_publish(nubreq, (char*) json, publish_callback) != RET_OK) {
		ve_error("could not pubnub_publish");
		goto error;
	}

	yajl_gen_clear(nubat->g);	/* empty buffers */
	yajl_gen_free(nubat->g);
	nubat->g = NULL;
	return veTrue;

error:
	pubnub_req_deinit(nubreq);
	ve_free(nubreq);
	yajl_gen_free(nubat->g);
	nubat->g = NULL;

	return veFalse;
}
Esempio n. 20
0
/*
 * Document-method: new
 *
 * call-seq: initialize([:pretty => false[, :indent => '  '][, :terminator => "\n"]])
  *
  * :pretty will enable/disable beautifying or "pretty priting" the output string.
  *
  * :indent is the character(s) used to indent the output string.
  *
  * :terminator allows you to specify a character to be used as the termination character after a full JSON string has been generated by
  * the encoder. This would be especially useful when encoding in chunks (via a block or callback during the encode process), to be able to
  * determine when the last chunk of the current encode is sent.
  * If you specify this option to be nil, it will be ignored if encoding directly to an IO or simply returning a string. But if a block is used,
  * the encoder will still pass it - I hope that makes sense ;).
 */
static VALUE rb_yajl_encoder_new(int argc, VALUE * argv, VALUE klass) {
    yajl_encoder_wrapper * wrapper;
    yajl_gen_config cfg;
    VALUE opts, obj, indent;
    unsigned char *indentString = NULL, *actualIndent = NULL;
    int beautify = 0, htmlSafe = 0;

    /* Scan off config vars */
    if (rb_scan_args(argc, argv, "01", &opts) == 1) {
        Check_Type(opts, T_HASH);

        if (rb_hash_aref(opts, sym_pretty) == Qtrue) {
            beautify = 1;
            indent = rb_hash_aref(opts, sym_indent);
            if (indent != Qnil) {
#ifdef HAVE_RUBY_ENCODING_H
                indent = rb_str_export_to_enc(indent, utf8Encoding);
#endif
                Check_Type(indent, T_STRING);
                indentString = (unsigned char*)malloc(RSTRING_LEN(indent)+1);
                memcpy(indentString, RSTRING_PTR(indent), RSTRING_LEN(indent));
                indentString[RSTRING_LEN(indent)] = '\0';
                actualIndent = indentString;
            }
        }
        if (rb_hash_aref(opts, sym_html_safe) == Qtrue) {
          htmlSafe = 1;
        }
    }
    if (!indentString) {
      indentString = defaultIndentString;
    }
    cfg = (yajl_gen_config){beautify, (const char *)indentString, htmlSafe};

    obj = Data_Make_Struct(klass, yajl_encoder_wrapper, yajl_encoder_wrapper_mark, yajl_encoder_wrapper_free, wrapper);
    wrapper->indentString = actualIndent;
    wrapper->encoder = yajl_gen_alloc(&cfg, NULL);
    wrapper->on_progress_callback = Qnil;
    if (opts != Qnil && rb_funcall(opts, intern_has_key, 1, sym_terminator) == Qtrue) {
        wrapper->terminator = rb_hash_aref(opts, sym_terminator);
#ifdef HAVE_RUBY_ENCODING_H
        if (TYPE(wrapper->terminator) == T_STRING) {
            wrapper->terminator = rb_str_export_to_enc(wrapper->terminator, utf8Encoding);
        }
#endif
    } else {
        wrapper->terminator = 0;
    }
    rb_obj_call_init(obj, 0, 0);
    return obj;
}
Esempio n. 21
0
void reformat(ErlDrvPort port, char* buf, int len)
{
    yajl_handle hand;
    /* generator config */
    yajl_gen_config conf = { 1, "  " };
	yajl_gen g;
    yajl_status stat;
    /* allow comments */
    yajl_parser_config cfg = { 1, 1 };

    g = yajl_gen_alloc(&conf, NULL);

    /* ok.  open file.  let's read and parse */
    hand = yajl_alloc(&callbacks, &cfg, NULL, (void *) g);
    
    /* read file data, pass to parser */
    stat = yajl_parse(hand, (unsigned char*) buf, len);

    if (stat != yajl_status_ok &&
        stat != yajl_status_insufficient_data)
    {
        char* err = (char*) yajl_get_error(hand, 1, (unsigned char*) buf, len);
        int len = strlen(err);

        ErlDrvTermData msg[] = {
            ERL_DRV_ATOM, driver_mk_atom("error"), 
            ERL_DRV_BUF2BINARY, (ErlDrvTermData) err, (ErlDrvUInt) len,
            ERL_DRV_TUPLE, 2
        };

        driver_send_term(port, driver_caller(port), msg, sizeof(msg) / sizeof(msg[0]));
    } else {
        const unsigned char* json;
        unsigned int len;
        yajl_gen_get_buf(g, &json, &len);

        ErlDrvTermData msg[] = {
            ERL_DRV_ATOM, driver_mk_atom("ok"),
            ERL_DRV_BUF2BINARY, (ErlDrvTermData) json, (ErlDrvUInt) len,
            ERL_DRV_TUPLE, 2
        };

        driver_send_term(port, driver_caller(port), msg, sizeof(msg) / sizeof(msg[0]));

        yajl_gen_clear(g);
    }

    yajl_gen_free(g);
    yajl_free(hand);
}
Esempio n. 22
0
static VALUE rb_yajl_encoder_new(int argc, VALUE * argv, VALUE klass) {
    yajl_encoder_wrapper * wrapper;
    yajl_gen_config cfg;
    VALUE opts, obj, indent;
    const char * indentString = "  ";
    int beautify = 0;
    int ascii_only = default_to_ascii_only == Qtrue ? 1 : 0;

    /* Scan off config vars */
    if (rb_scan_args(argc, argv, "01", &opts) == 1) {
        Check_Type(opts, T_HASH);

        if (rb_hash_aref(opts, sym_pretty) == Qtrue) {
            beautify = 1;
            indent = rb_hash_aref(opts, sym_indent);
            if (indent != Qnil) {
#ifdef HAVE_RUBY_ENCODING_H
                indent = rb_str_export_to_enc(indent, utf8Encoding);
#endif
                Check_Type(indent, T_STRING);
                indentString = RSTRING_PTR(indent);
            }
        }

        if (rb_hash_aref(opts, sym_ascii_only) == Qtrue) {
            ascii_only= 1;
        }
        if (rb_hash_aref(opts, sym_ascii_only) == Qfalse) {
            ascii_only= 0;
        }

    }
    cfg = (yajl_gen_config){beautify, indentString, ascii_only};

    obj = Data_Make_Struct(klass, yajl_encoder_wrapper, yajl_encoder_wrapper_mark, yajl_encoder_wrapper_free, wrapper);
    wrapper->encoder = yajl_gen_alloc(&cfg, NULL);
    wrapper->on_progress_callback = Qnil;
    if (opts != Qnil && rb_funcall(opts, intern_has_key, 1, sym_terminator) == Qtrue) {
        wrapper->terminator = rb_hash_aref(opts, sym_terminator);
#ifdef HAVE_RUBY_ENCODING_H
        if (TYPE(wrapper->terminator) == T_STRING) {
            wrapper->terminator = rb_str_export_to_enc(wrapper->terminator, utf8Encoding);
        }
#endif
    } else {
        wrapper->terminator = 0;
    }
    rb_obj_call_init(obj, 0, 0);
    return obj;
}
Esempio n. 23
0
static bool convert(options_t* options) {
    FILE* in_file;
    if (options->in_filename) {
        in_file = fopen(options->in_filename, "rb");
        if (in_file == NULL) {
            fprintf(stderr, "%s: could not open \"%s\" for reading.\n", options->command, options->in_filename);
            return false;
        }
    } else {
        in_file = stdin;
    }

    if (options->out_filename) {
        out_file = fopen(options->out_filename, "wb");
        if (out_file == NULL) {
            fprintf(stderr, "%s: could not open \"%s\" for writing.\n", options->command, options->out_filename);
            if (in_file != stdin)
                fclose(in_file);
            return false;
        }
    } else {
        out_file = stdout;
    }

    yajl_gen gen = yajl_gen_alloc(NULL);
    if (options->pretty)
        yajl_gen_config(gen, yajl_gen_beautify);
    if (options->debug)
        yajl_gen_config(gen, yajl_gen_allow_non_string_keys);
    yajl_gen_config(gen, yajl_gen_print_callback, print, out_file);

    mpack_reader_t reader;
    mpack_reader_init_stack(&reader);
    mpack_reader_set_fill(&reader, fill);
    mpack_reader_set_context(&reader, in_file);

    bool ret = element(&reader, gen, options, 0);

    mpack_error_t error = mpack_reader_destroy(&reader);
    yajl_gen_free(gen);

    if (out_file != stdout)
        fclose(out_file);
    if (in_file != stdin)
        fclose(in_file);

    if (!ret || error != mpack_ok)
        fprintf(stderr, "%s: parse error %i\n", options->command, (int)error);
    return ret;
}
Esempio n. 24
0
IoObject *IoYajlGen_generate(IoYajlGen *self, IoObject *locals, IoMessage *m)
{
	const unsigned char *jsonBuffer;
	unsigned int jsonBufferLength;
		
	yajl_gen_get_buf(DATA(self), &jsonBuffer, &jsonBufferLength);
	
	IoSeq *out = IOSEQ(jsonBuffer, jsonBufferLength);
	
	yajl_gen_free(DATA(self));
	yajl_gen_config config = { 0, "" };
	IoObject_setDataPointer_(self, yajl_gen_alloc(&config, NULL));
	
    return out;  
}
Esempio n. 25
0
IoObject *IoYajlGen_generate(IoYajlGen *self, IoObject *locals, IoMessage *m)
{
	const unsigned char *jsonBuffer;
	size_t jsonBufferLength;

	yajl_gen_get_buf(DATA(self), &jsonBuffer, &jsonBufferLength);

	IoSeq *out = IOSEQ(jsonBuffer, jsonBufferLength);

	yajl_gen_free(DATA(self));
	yajl_gen yg = yajl_gen_alloc(NULL);
	//yajl_gen_config(yg, yajl_gen_beautify, 0);
	IoObject_setDataPointer_(self, yg);

    return out;
}
Esempio n. 26
0
static VALUE mEncoder_do_yajl_encode(VALUE self, VALUE obj, VALUE yajl_gen_opts, VALUE json_opts) {
  ID sym_ffi_yajl = rb_intern("ffi_yajl");
  VALUE sym_yajl_gen_beautify = ID2SYM(rb_intern("yajl_gen_beautify"));
  VALUE sym_yajl_gen_validate_utf8 = ID2SYM(rb_intern("yajl_gen_validate_utf8"));
  VALUE sym_yajl_gen_indent_string = ID2SYM(rb_intern("yajl_gen_indent_string"));
  yajl_gen yajl_gen;
  const unsigned char *buf;
  size_t len;
  VALUE state;
  VALUE ret;
  VALUE indent_string;
  VALUE rb_yajl_gen;

  yajl_gen = yajl_gen_alloc(NULL);

  if ( rb_hash_aref(yajl_gen_opts, sym_yajl_gen_beautify) == Qtrue ) {
    yajl_gen_config(yajl_gen, yajl_gen_beautify, 1);
  }
  if ( rb_hash_aref(yajl_gen_opts, sym_yajl_gen_validate_utf8) == Qtrue ) {
    yajl_gen_config(yajl_gen, yajl_gen_validate_utf8, 1);
  }

  indent_string = rb_hash_aref(yajl_gen_opts, sym_yajl_gen_indent_string);
  if (indent_string != Qnil) {
    yajl_gen_config(yajl_gen, yajl_gen_indent_string, RSTRING_PTR(indent_string));
  } else {
    yajl_gen_config(yajl_gen, yajl_gen_indent_string, " ");
  }

  state = rb_hash_new();

  rb_hash_aset(state, rb_str_new2("processing_key"), Qfalse);

  rb_hash_aset(state, rb_str_new2("json_opts"), json_opts);

  rb_yajl_gen = Data_Wrap_Struct(cYajl_Gen, NULL, NULL, yajl_gen);

  rb_funcall(obj, sym_ffi_yajl, 2, rb_yajl_gen, state);

  yajl_gen_get_buf(yajl_gen, &buf, &len);

  ret = rb_str_new2((char *)buf);

  yajl_gen_free(yajl_gen);

  return ret;
}
Esempio n. 27
0
static package
bf_generate_json(Var arglist, Byte next, void *vdata, Objid progr)
{
    yajl_gen g;
    yajl_gen_config cfg = { 0, "" };

    struct generate_context gctx;
    gctx.mode = MODE_COMMON_SUBSET;

    const char *buf;
    unsigned int len;

    Var json;

    package pack;

    if (1 < arglist.v.list[0].v.num) {
	if (!mystrcasecmp(arglist.v.list[2].v.str, "common-subset")) {
	    gctx.mode = MODE_COMMON_SUBSET;
	} else if (!mystrcasecmp(arglist.v.list[2].v.str, "embedded-types")) {
	    gctx.mode = MODE_EMBEDDED_TYPES;
	} else {
	    free_var(arglist);
	    return make_error_pack(E_INVARG);
	}
    }

    g = yajl_gen_alloc(&cfg, NULL);

    if (yajl_gen_status_ok == generate(g, arglist.v.list[1], &gctx)) {
	yajl_gen_get_buf(g, (const unsigned char **)&buf, &len);

	json.type = TYPE_STR;
	json.v.str = str_dup(buf);

	pack = make_var_pack(json);
    } else {
	pack = make_error_pack(E_INVARG);
    }

    yajl_gen_clear(g);
    yajl_gen_free(g);

    free_var(arglist);
    return pack;
}
Esempio n. 28
0
/* Encode an IB list into JSON */
ib_status_t ib_json_encode(
    ib_mpool_t       *mpool,
    const ib_list_t  *list,
    bool              pretty,
    char            **obuf,
    size_t           *olen)
{
    assert(mpool != NULL);
    assert(list != NULL);
    assert(obuf != NULL);

    yajl_gen handle;
    json_yajl_alloc_context_t alloc_ctx = { mpool, IB_OK };
    ib_status_t rc;
    yajl_gen_status status;
    yajl_alloc_funcs alloc_fns = {
        json_yajl_alloc,
        json_yajl_realloc,
        json_yajl_free,
        &alloc_ctx
    };

    handle = yajl_gen_alloc(&alloc_fns);
    /* Probably should validate the handle here, but it's not clear from the
     * YAJL documentation how to do that */

    /* Set pretty option */
    if (pretty) {
        int opt = yajl_gen_config(handle, yajl_gen_beautify);
        if (opt == 0) {
            return IB_EINVAL;
        }
    }

    rc = encode_list(handle, NULL, 0, list);
    if (rc != IB_OK) {
        return rc;
    }
    status = yajl_gen_get_buf(handle, (const unsigned char **)obuf, olen);
    if (status != yajl_gen_status_ok) {
        return IB_EUNKNOWN;
    }

    return rc;
}
Esempio n. 29
0
void
rb_journalist_socket_init() {

  gen = yajl_gen_alloc(NULL);
  yajl_gen_config(gen, yajl_gen_beautify, 0);

  pid_t pid = getpid();

  char path[1024];
  snprintf(
    path,
    1024,
    journalist_file_path_fmt,
    pid
  );

  journalist_file = fopen(path, "w");
}
Esempio n. 30
0
LKStreamTranslator::LKStreamTranslator(LKTranslator &translator, std::string lastPathComponent):
	ctx { translator, nullptr, nullptr, lastPathComponent }
{
	callbacks.yajl_null = &LKStreamTranslator::handle_null;
	callbacks.yajl_boolean = &LKStreamTranslator::handle_boolean;
	callbacks.yajl_number = &LKStreamTranslator::handle_number;
	callbacks.yajl_string = &LKStreamTranslator::handle_string;
	callbacks.yajl_start_map = &LKStreamTranslator::handle_start_map;
	callbacks.yajl_map_key = &LKStreamTranslator::handle_map_key;
	callbacks.yajl_end_map = &LKStreamTranslator::handle_end_map;
	callbacks.yajl_start_array = &LKStreamTranslator::handle_start_array;
	callbacks.yajl_end_array = &LKStreamTranslator::handle_end_array;
	
	ctx.parser = yajl_alloc(&callbacks, NULL, &ctx);
	ctx.gen = yajl_gen_alloc(NULL);
	ctx.translator = translator;
	ctx.lastPathComponent = lastPathComponent;
}