Пример #1
0
/**
 * @brief Special handling of cases related to closing in non-final
 * situation.
 *
 * Closes the name in the middle (first unequal), so it must be executed
 * after iterating. (Because closing is in reverse order)
 *
 * Following situations are possible:
 *
 * (X1)
 * cur:  #/#
 * next: #
 * -> closing array (only if levels <0, because it might be outside
 *  array with iterating one level deeper)
 *
 * (X2)
 * cur:  #/_
 * next: #
 * -> array iteration, but with anon map
 *
 * (X3)
 * cur:  #
 * next: #
 * -> array iteration, so do not close array
 *
 * (X4)
 * cur:  _/#
 * next: _
 * -> closing map, but only if levels <= 0 (means iteration did nothing)
 *    (otherwise iteration already closed it)
 *
 * (X5)
 * cur:  _/_
 * next: _
 * -> closing map (only if levels <= 0, because iteration did not do it)
 *
 * (X6)
 * cur:  _
 * next: _
 * -> map iteration on same level, doing nothing
 *
 * @param g to generate to
 * @param pcur pointer to current name
 * @param csize size where cur has next level
 * @param pnext pointer to next name
 * @param levels how many levels were handled before (see examples
 * above)
 */
static void elektraGenCloseFirst(yajl_gen g, const char* pcur,
                                 size_t csize,
                                 const char * pnext,
                                 int levels)
{
    lookahead_t lookahead = elektraLookahead(pcur, csize);
#ifdef ELEKTRA_YAJL_VERBOSE
    printf ("elektraGenCloseFirst %s -> %s, levels: %d, lookahead: %d\n",
            pcur,
            pnext,
            levels,
            lookahead);
#endif
    if (*pcur == '#' && *pnext == '#')
    {
        if (levels <= 0 && lookahead == LOOKAHEAD_ARRAY)
        {
#ifdef ELEKTRA_YAJL_VERBOSE
            printf("GEN (X1) closing array in array\n");
#endif
            yajl_gen_array_close(g);
        }
        else if (lookahead == LOOKAHEAD_MAP)
        {
#ifdef ELEKTRA_YAJL_VERBOSE
            printf("GEN (X2) next anon-map\n");
#endif
            yajl_gen_map_close(g);
        }
        else
        {
#ifdef ELEKTRA_YAJL_VERBOSE
            printf("(X3) array iteration\n");
#endif
        }
    }
    else if (*pcur != '#')
    {
        if (levels <= 0 && lookahead == LOOKAHEAD_ARRAY)
        {
#ifdef ELEKTRA_YAJL_VERBOSE
            printf("GEN (X4) closing array\n");
#endif
            yajl_gen_array_close(g);
        }
        else if (lookahead == LOOKAHEAD_MAP)
        {
#ifdef ELEKTRA_YAJL_VERBOSE
            printf("GEN (X5) closing map\n");
#endif
            yajl_gen_map_close(g);
        }
        else
        {
#ifdef ELEKTRA_YAJL_VERBOSE
            printf("(X6) same level iteration\n");
#endif
        }
    }
}
Пример #2
0
/**
 * @brief Close given number of levels of key
 *
 * @pre there is some needed special handling at begin at end,
 * the caller needs to do that
 *
 * For the basename of cur nothing needs to be done
 * (it was either a value or an array entry)
 *
 * Then for every level do:
 *
 *
 * (C1)
 * #/_
 * (lookahead says it is a map in the array)
 * -> close the anonymous map and then the array
 *
 * (C2)
 * _/#
 * _/___empty_map
 * (lookahead says it is not a map)
 * -> don't do anything
 *
 * (C3)
 * #
 * -> close the array
 *
 * (C4)
 * _
 * -> close the map
 *
 *
 * @param g to yield json information
 * @param cur the key which name is used for closing
 * @param levels the number of levels to close
 */
static void elektraGenCloseIterate(yajl_gen g, const Key *cur,
                                   int levels)
{
    keyNameReverseIterator curIt =
        elektraKeyNameGetReverseIterator(cur);

    // jump last element
    elektraKeyNameReverseNext(&curIt);

    for (int i=0; i<levels; ++i)
    {
        elektraKeyNameReverseNext(&curIt);

        lookahead_t lookahead = elektraLookahead(curIt.current,
                                curIt.size);

        if (curIt.current[0] == '#')
        {
            if (lookahead == LOOKAHEAD_MAP)
            {
#ifdef ELEKTRA_YAJL_VERBOSE
                printf ("GEN (C1) anon map close\n");
#endif
                yajl_gen_map_close(g);

            }
#ifdef ELEKTRA_YAJL_VERBOSE
            printf ("GEN (C3) array close\n");
#endif
            yajl_gen_array_close(g);
        }
        else
        {
            if (lookahead == LOOKAHEAD_MAP)
            {
#ifdef ELEKTRA_YAJL_VERBOSE
                printf ("GEN (C4) map close\n");
#endif
                yajl_gen_map_close(g);
            }
            else
            {
#ifdef ELEKTRA_YAJL_VERBOSE
                printf ("(C2) lookahead not a map: nothing to do\n");
#endif
            }
        }
    }
}
Пример #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;
}
Пример #4
0
static int js_generator_close(lua_State *L) {
    lua_Integer type;

    /* Why doesn't yajl_gen keep track of this!? */
    lua_getfenv(L, 1);
    lua_getfield(L, -1, "stack");
    lua_rawgeti(L, -1, lua_objlen(L, -1));
    if ( lua_isnil(L, -1) ) {
        lua_pushfstring(L, "StackUnderflow: Attempt to call close() when no array or object has been opened at %s line %d", __FILE__, __LINE__);
        lua_error(L);
    }
    type = lua_tointeger(L, -1);
    switch ( type ) {
    case JS_OPEN_OBJECT:
        js_generator_assert(L,
                            yajl_gen_map_close(*js_check_generator(L, 1)),
                            __FILE__, __LINE__);
        break;
    case JS_OPEN_ARRAY:
        js_generator_assert(L,
                            yajl_gen_array_close(*js_check_generator(L, 1)),
                            __FILE__, __LINE__);
        break;
    default:
        lua_pushfstring(L, "Unreachable: internal 'stack' contained invalid integer (%d) at %s line %d", type, __FILE__, __LINE__);
        lua_error(L);
    }
    /* delete the top of the "stack": */
    lua_pop(L, 1);
    lua_pushnil(L);
    lua_rawseti(L, -2, lua_objlen(L, -2));

    return 0;
}
static int reformat_end_map(void* ctx) {
	ccJSONContext* jc = (ccJSONContext*)ctx;
	jc->objStack->pop_back();
	jc->flagStack->pop_back();

    return yajl_gen_status_ok == yajl_gen_map_close(jc->g);
}
Пример #6
0
int PNode_op_sizes(PNode *self, Datum *d)
{	
	PNode *tmpNode = PDB_allocNode(self->pdb);
	Datum *k;
	PQuery *q = PNode_startQuery(self);
	
	yajl_gen_map_open(self->yajl);
	
	while (k = PQuery_key(q))
	{
		if(!Datum_beginsWithCString_(k, "_"))
		{			
			yajl_gen_datum(self->yajl, PNode_key(self));
		
			PNode_setPid_(tmpNode, PNode_value(self));
			yajl_gen_integer(self->yajl, PNode_size(tmpNode));
		}
		
		if (q) { PQuery_enumerate(q); } else { PNode_next(self); }
	}
	
	yajl_gen_map_close(self->yajl);
	Datum_appendYajl_(d, self->yajl);
	return 0;  
}
Пример #7
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;
}
Пример #8
0
void galleryd::response::generate(galleryd::request &req, galleryd::queue &q)
{
    yajl_gen_clear(handle_);
    yajl_gen_map_open(handle_);

    try
    {

    if(req.method == "status")
    {
        constexpr const unsigned char key_states[] = {'s', 't', 'a', 't', 'e'};

        yajl_gen_string(handle_, key_states, sizeof(key_states));
        yajl_gen_array_open(handle_);
        for(auto state : q.status(req.items, req.category))
            yajl_gen_integer(handle_, state);
        yajl_gen_array_close(handle_);
    }

    else if(req.method == "add")
    {
        q.add(req.items, req.category);
    }

    else if(req.method == "open")
    {
        auto path = q.open(req.items, req.category);
        if(not path.empty())
        {
            path += '/';
            path += req.items[0];

            if(fork() == 0)
            {
                int fd = open("/dev/null", O_WRONLY);
                dup2(fd, 2);  // redirect stderr
                execl("/usr/bin/geeqie", "/usr/bin/geeqie", "-r", path.c_str(), nullptr);
                exit(1); // in case execl returns with an error
            }
        }
        else
        {
            // TODO error handling
        }
    }

    }
    catch(const std::exception &e)
    {
        constexpr const unsigned char key_error[] = {'e', 'r', 'r', 'o', 'r'};
        const char  *err = e.what();
        const size_t len = strlen(err);

        yajl_gen_string(handle_, key_error, sizeof(key_error));
        yajl_gen_string(handle_, reinterpret_cast<const unsigned char *>(err), len);
    }

    yajl_gen_map_close(handle_);
}
Пример #9
0
static yajl_gen_status
generate(yajl_gen g, Var v, void *ctx)
{
    struct generate_context *gctx = (struct generate_context *)ctx;

    switch (v.type) {
    case TYPE_INT:
	return yajl_gen_integer(g, v.v.num);
    case TYPE_FLOAT:
	return yajl_gen_double(g, *v.v.fnum);
    case TYPE_OBJ:
    case TYPE_ERR:
	{
	    const char *tmp = value_to_literal(v);
	    if (MODE_EMBEDDED_TYPES == gctx->mode)
		tmp = append_type(tmp, v.type);
	    return yajl_gen_string(g, (const unsigned char *)tmp, strlen(tmp));
	}
    case TYPE_STR:
	{
	    const char *tmp = v.v.str;
	    size_t len = strlen(tmp);
	    if (MODE_EMBEDDED_TYPES == gctx->mode)
		if (TYPE_NONE != valid_type(&tmp, &len))
		    tmp = append_type(tmp, v.type);
	    return yajl_gen_string(g, (const unsigned char *)tmp, strlen(tmp));
	}
    case TYPE_MAP:
	{
	    struct do_map_closure dmc;
	    dmc.g = g;
	    dmc.gctx = gctx;
	    dmc.status = yajl_gen_status_ok;
	    yajl_gen_map_open(g);
	    if (mapforeach(v, do_map, &dmc))
		return dmc.status;
	    yajl_gen_map_close(g);
	    return yajl_gen_status_ok;
	}
    case TYPE_LIST:
	{
	    int i;
	    yajl_gen_status status;
	    yajl_gen_array_open(g);
	    for (i = 1; i <= v.v.list[0].v.num; i++) {
		status = generate(g, v.v.list[i], ctx);
		if (yajl_gen_status_ok != status)
		    return status;
	    }
	    yajl_gen_array_close(g);
	    return yajl_gen_status_ok;
	}
    default:
	panic("Unsupported type in generate()");
    }

    return -1;
}
Пример #10
0
yajl_gen_status GenVal(yajl_gen g, yajl_val v) {
	yajl_gen_status status;
	switch (v->type) {
	case yajl_t_string:	return yajl_gen_string(g, (unsigned char*)v->u.string, strlen(v->u.string));

	case yajl_t_number: 
		{
			char buffer[100];
			char *num = buffer;
			size_t len;
			//if (YAJL_IS_INTEGER(v)) // buggy
			if (v->u.number.flags & YAJL_NUMBER_INT_VALID)
				len = sprintf(num, "%lld", YAJL_GET_INTEGER(v));
			//else if (YAJL_IS_DOUBLE(v))	// buggy
			else if (v->u.number.flags & YAJL_NUMBER_DOUBLE_VALID)
				len = sprintf(num, "%g", YAJL_GET_DOUBLE(v));
			else {
				num = YAJL_GET_NUMBER(v);
				len = strlen(buffer);
			}
			return yajl_gen_number(g, num, len);
		}

	case yajl_t_object:
		status = yajl_gen_map_open(g);
		if (status != yajl_gen_status_ok)
			return status;
		
		for (size_t i = 0; i < v->u.object.len; i++) {
			status = yajl_gen_string(g, (unsigned char *)v->u.object.keys[i], strlen(v->u.object.keys[i]));
			if (status != yajl_gen_status_ok)
				return status;
			status = GenVal(g, v->u.object.values[i]);
			if (status != yajl_gen_status_ok)
				return status;
		}
		return yajl_gen_map_close(g);

	case yajl_t_array:
		status = yajl_gen_array_open(g);
		if (status != yajl_gen_status_ok)
			return status;
		
		for (size_t i = 0; i < v->u.array.len; i++) {
			status = GenVal(g, v->u.array.values[i]);
			if (status != yajl_gen_status_ok)
				return status;
		}

		return yajl_gen_array_close(g);

	case yajl_t_true: return yajl_gen_bool(g, 1);
	case yajl_t_false: return yajl_gen_bool(g, 0);
	case yajl_t_null: return yajl_gen_null(g);
	case yajl_t_any: break;
	}
	return yajl_gen_in_error_state;
}
Пример #11
0
bool
JSONGenerator::closeMap()
{
  VALIDATE_STATE();
  if (yajl_gen_map_close(mState->mGen) != yajl_gen_status_ok) {
    return false;
  }
  return true;
}
Пример #12
0
void class_to_json(yajl_gen gen, struct class_t c)
{
    const char* id_field =      "id";
    const char* name_field =    "name";
    
    yajl_gen_map_open(gen);
    json_insert_int(gen, id_field, c.id);
    json_insert_str(gen, name_field, c.name);
    yajl_gen_map_close(gen);
}
Пример #13
0
/* encode a hash close */
VALUE gen_map_close(VALUE rb_yajl_gen) {
  yajl_gen_status status;
  struct yajl_gen_t *yajl_gen;
  Data_Get_Struct(rb_yajl_gen, struct yajl_gen_t, yajl_gen);

  if ((status = yajl_gen_map_close(yajl_gen)) != yajl_gen_status_ok) {
    rb_funcall(mEncoder2, rb_intern("raise_error_for_status"), 2, INT2FIX(status), rb_str_new2("}"));
  }

  return Qnil;
}
Пример #14
0
/**
 * @brief Close the last element
 *
 * Needs less special handling because cur is fully below next.
 *
 * Will fully iterate over all elements.
 *
 * @param g handle to yield close events
 * @param cur current key
 * @param next the last key (the parentKey)
 */
void elektraGenCloseFinally(yajl_gen g, const Key *cur, const Key *next)
{
    int curLevels = elektraKeyCountLevel(cur);
#ifdef ELEKTRA_YAJL_VERBOSE
    int nextLevels = elektraKeyCountLevel(next);
#endif
    int equalLevels = elektraKeyCountEqualLevel(cur, next);

    // 1 for last level not to iterate, 1 after equal
    int levels = curLevels - equalLevels - 1;

    const char *pcur = keyName(cur);
    size_t csize = 0;
    const char *pnext = keyName(next);
    size_t nsize = 0;
    for (int i=0; i < equalLevels+1; ++i)
    {
        pcur=keyNameGetOneLevel(pcur+csize,&csize);
        pnext=keyNameGetOneLevel(pnext+nsize, &nsize);
    }

#ifdef ELEKTRA_YAJL_VERBOSE
    printf ("elektraGenFinally, eq: %d, cur: %s %d, next: %s %d, "
            "levels: %d\n",
            equalLevels,
            pcur, curLevels,
            pnext, nextLevels,
            levels);
#endif
    // fixes elektraGenCloseIterate for the special handling of
    // arrays finally
    elektraGenCloseLast(g, cur);

    // now we iterate over the middle part
    elektraGenCloseIterate(g, cur, levels);

    // now we look at the first unequal element
    // this is the very last element we are about to close
    if (pcur && *pcur == '#')
    {
#ifdef ELEKTRA_YAJL_VERBOSE
        printf ("array close FINAL\n");
#endif
    }
    else
    {
#ifdef ELEKTRA_YAJL_VERBOSE
        printf ("GEN map close FINAL\n");
#endif
        yajl_gen_map_close(g);
    }


}
Пример #15
0
void race_to_json(yajl_gen gen, struct race_t race)
{
    /* Field names */
    const char* id_field =              "id";
    const char* name_field =            "name";
    const char* sprite_sheet_field =    "sprite_sheet";
    const char* sprite_height_field =   "sprite_height";
    
    yajl_gen_map_open(gen);
    json_insert_int(gen, id_field, race.id);
    json_insert_str(gen, name_field, race.name);
    json_insert_str(gen, sprite_sheet_field, race.sprite_sheet);
    json_insert_int(gen, sprite_height_field, race.sprite_height);
    yajl_gen_map_close(gen);
}
Пример #16
0
void json_from_bson_object(yajl_gen *g, bson_iterator *it)
{
    yajl_gen_map_open( *g );

    while( bson_iterator_next( it ) )
    {
        bson_type t = bson_iterator_type( it );
        const char* key = bson_iterator_key( it );

        yajl_gen_string( *g, (const unsigned char*)key, strlen(key) );

        json_from_bson_type( t, g, it );
    }

    yajl_gen_map_close( *g );
}
Пример #17
0
int PNode_op_object(PNode *self, Datum *d)
{
	PQuery *q = PNode_startQuery(self);
	Datum *k;
	
	yajl_gen_map_open(self->yajl);
	
	while (k = PQuery_key(q))
	{
		yajl_gen_datum(self->yajl, k);
		yajl_gen_datum(self->yajl, PNode_value(self));
		PQuery_enumerate(q);
	}
	
	yajl_gen_map_close(self->yajl);
	if(d) Datum_appendYajl_(d, self->yajl);
	return 0;
}
Пример #18
0
int VertexServer_api_collectGarbage(VertexServer *self)
{
	time_t t1 = time(NULL);
	long savedCount = PDB_collectGarbage(self->pdb);
	double dt = difftime(time(NULL), t1);
	
	yajl_gen_map_open(self->yajl);
	yajl_gen_cstring(self->yajl, "saved");
	yajl_gen_integer(self->yajl, savedCount);
	yajl_gen_cstring(self->yajl, "seconds");
	yajl_gen_integer(self->yajl, (int)dt);
	yajl_gen_map_close(self->yajl);
	
	Datum_appendYajl_(self->result, self->yajl);
	Log_Printf_("gc: %s\n", Datum_data(self->result));

	return 0;
}
Пример #19
0
int orderly_write_json2(yajl_gen g, const orderly_json * j)
{
    yajl_gen_status s;
    int rv = 1;

    if (j) {
        if (j->k) yajl_gen_string(g, (const unsigned char *) j->k, strlen(j->k));

        switch (j->t) {
            case orderly_json_none:
                return 0;
            case orderly_json_null:
                s = yajl_gen_null(g);
                break;
            case orderly_json_string:
                s = yajl_gen_string(g, (const unsigned char *) j->v.s, strlen(j->v.s));
                break;
            case orderly_json_boolean:
                s = yajl_gen_bool(g, j->v.b);
                break;
            case orderly_json_integer:
                s = yajl_gen_integer(g, j->v.i);
                break;
            case orderly_json_number:
                s = yajl_gen_double(g, j->v.n);
                break;
            case orderly_json_object:
                s = yajl_gen_map_open(g);
                rv = orderly_write_json2(g, j->v.children.first);
                s = yajl_gen_map_close(g);
                break;
            case orderly_json_array:
                s = yajl_gen_array_open(g);
                rv = orderly_write_json2(g, j->v.children.first);
                s = yajl_gen_array_close(g);
                break;
        }

        if (rv && j->next) rv = orderly_write_json2(g, j->next);
    }

    return rv;
}
Пример #20
0
static int json_format(struct formatter *fmt, struct recordset *rset)
{
	struct record *r;
	struct json_formatter_data *priv = fmt->priv;
	yajl_gen_map_open(priv->yajl);
        int repeat = 0;
	for_each_record(r, rset) {
		if(r->type != RECORD_TYPE_RSET || !repeat)
			yajl_gen_string(priv->yajl, (unsigned char*)r->name, r->len_n-1);
                if(r->type != RECORD_TYPE_RSET) {
                  if(repeat) yajl_gen_array_close(priv->yajl);
                repeat = 0;
                }

		switch(r->type) {
		case RECORD_TYPE_STRING:
			yajl_gen_string(priv->yajl, (unsigned char*)r->value_str, r->len_v-1);
			break;
		case RECORD_TYPE_INT:
			yajl_gen_integer(priv->yajl, r->value_int);
			break;
		case RECORD_TYPE_UINT:
		case RECORD_TYPE_HEX:
			yajl_gen_integer(priv->yajl, r->value_uint);
			break;
		case RECORD_TYPE_DOUBLE:
			yajl_gen_double(priv->yajl, r->value_double);
			break;
		case RECORD_TYPE_RSET:
                  if(!repeat) yajl_gen_array_open(priv->yajl);
			json_format(fmt, r->value_rset);

			repeat = 1;
			break;
		default:
			break;
		}
	}
        if(repeat) yajl_gen_array_close(priv->yajl);
	yajl_gen_map_close(priv->yajl);
	json_print(fmt->f, priv->yajl);
	return 0;
}
Пример #21
0
int
enc_map(Encoder* enc, ERL_NIF_TERM head, ERL_NIF_TERM tail)
{
    int arity;
    const ERL_NIF_TERM* tuple;

    if(yajl_gen_map_open(enc->handle) != yajl_gen_status_ok)
    {
        enc->error = enif_make_atom(enc->env, "failed_to_open_map");
        return ERROR;
    }

    do {
        if(!enif_get_tuple(enc->env, head, &arity, &tuple))
        {
            enc->error = enif_make_tuple(enc->env, 2,
                enif_make_atom(enc->env, "badarg"),
                head
            );
            return ERROR;
        }
        if(arity != 2)
        {
            enc->error = enif_make_tuple(enc->env, 2,
                enif_make_atom(enc->env, "badarity"),
                head
            );
            return ERROR;
        }
        if(enc_key(enc, tuple[0]) != OK) return ERROR;
        if(enc_json(enc, tuple[1]) != OK) return ERROR;
    } while(enif_get_list_cell(enc->env, tail, &head, &tail));
    
    if(yajl_gen_map_close(enc->handle) != yajl_gen_status_ok)
    {
        enc->error = enif_make_atom(enc->env, "failed_to_close_map");
        return ERROR;
    }
    
    return OK;
}
Пример #22
0
void message_bus_write_json(yajl_gen g, void *context) {
    state *state = context;

    yajl_val output_values = state_get_json(state, STATE_OUTPUT_VALUES);

    assert(YAJL_IS_ARRAY(output_values));

    yajl_gen_map_open(g);

    int len = YAJL_GET_ARRAY(output_values)->len;
    for (int i = 0; i < len; i++) {
        char *k = YAJL_GET_STRING(YAJL_GET_ARRAY(output_values)->values[i]);

        state_value_type type = state_get_value_type(state, k);

        yajl_gen_string(g, (unsigned char *)k, strlen(k));

        float float_value;
        int int_value;
        yajl_val json_value;
        switch (type) {
            case state_value_type_float:
                float_value = state_get_float(state, k);
                yajl_gen_double(g, (double)float_value);
                break;
            case state_value_type_int:
                int_value = state_get_int(state, k);
                yajl_gen_integer(g, int_value);
                break;
            case state_value_type_json:
                json_value = state_get_json(state, k);
                json_write_value(g, json_value);
                break;
            default:
                assert(0);
                break;
        }
    }

    yajl_gen_map_close(g);
}
Пример #23
0
void GenerateRequest(yajl_gen g, const char* fn, bool sendCaller, xlw::XlfOper* argv, int argc)
{
	yajl_gen_map_open(g);
	yajl_gen_string(g, (const unsigned char*) REQ_TYPE_NAME, strlen(REQ_TYPE_NAME));
	yajl_gen_string(g, (const unsigned char*) REQ_TYPE_VAL, strlen(REQ_TYPE_VAL));
	yajl_gen_string(g, (const unsigned char*) REQ_VER_NAME, strlen(REQ_VER_NAME));
	yajl_gen_string(g, (const unsigned char*) REQ_VER_VAL, strlen(REQ_VER_VAL));
	if(sendCaller) {
		xlw::XlfOper xlRef, xlSheetName;
		xlw::XlfExcel::Instance().Call(xlfCaller, (xlw::LPXLFOPER)xlRef, 0);	
		xlw::XlfExcel::Instance().Call(xlSheetNm, (xlw::LPXLFOPER)xlSheetName, 1, (xlw::LPXLFOPER)xlRef);
		if(xlRef.IsSRef()) {
			yajl_gen_string(g, (const unsigned char*) REQ_CALLER_NAME, strlen(REQ_CALLER_NAME));
			JSONCodec::Encode(g, &xlRef);
		}
		if( xlSheetName.IsString() ) {
			std::string name_ = xlSheetName.AsString();
			yajl_gen_string(g, (const unsigned char*) REQ_SHEET_NAME, strlen(REQ_SHEET_NAME));
			yajl_gen_string(g, (const unsigned char*) name_.c_str(), name_.size());
		}
	}
	yajl_gen_string(g, (const unsigned char*) REQ_NAME_NAME, strlen(REQ_NAME_NAME));
	yajl_gen_string(g, (const unsigned char*) fn, strlen(fn));
	yajl_gen_string(g, (const unsigned char*) REQ_ARGS_NAME, strlen(REQ_ARGS_NAME));
	yajl_gen_array_open(g);

	// Find last non-missing value
	while(argc>0) {
		if(argv[argc-1].IsMissing())
			argc--;
		else
			break;
	}

	for(int i = 0; i < argc; i++) {
		JSONCodec::Encode(g, argv[i]);
	}
	yajl_gen_array_close(g);
	yajl_gen_map_close(g);
}
Пример #24
0
static VALUE rb_cHash_ffi_yajl(VALUE self, VALUE rb_yajl_gen, VALUE state) {
    yajl_gen_status status;
    VALUE extra;
    struct yajl_gen_t *yajl_gen;
    Data_Get_Struct(rb_yajl_gen, struct yajl_gen_t, yajl_gen);

    extra = rb_hash_new();  /* FIXME: reduce garbage */

    rb_hash_aset(extra, rb_str_new2("yajl_gen"), rb_yajl_gen);

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

    CHECK_STATUS(
        yajl_gen_map_open(yajl_gen)
    );
    rb_hash_foreach(self, rb_cHash_ffi_yajl_callback, extra);
    CHECK_STATUS(
        yajl_gen_map_close(yajl_gen)
    );

    return Qnil;
}
static
ngx_int_t ngx_http_metrics_gen_status_counters(yajl_gen g)
{
    YAJL_CHECK(yajl_gen_cstring(g, "status_codes"));

    YAJL_CHECK(yajl_gen_map_open(g));

    ngx_int_t i = 0;
    char buf[4];

    for (i = 0; i < NGX_HTTP_NUM_STATUS_CODES; i++) {
      if (ngx_http_metrics_status_codes[i] > 0) {
        snprintf(buf, 4, "%ld", NGX_HTTP_OK + i);
        YAJL_CHECK(yajl_gen_cstring(g, buf));
        YAJL_CHECK(yajl_gen_integer(g, ngx_http_metrics_status_codes[i]));
      }
    }

    YAJL_CHECK(yajl_gen_map_close(g));

    return NGX_OK;
}
Пример #26
0
void writejson(FILE * out, char *stamp, char *line, size_t len, int fragment)
{
	yajl_gen g;

	const unsigned char *buf;
	size_t buflen;

	g = yajl_gen_alloc(NULL);

	yajl_gen_config(g, yajl_gen_beautify, 0);
	yajl_gen_config(g, yajl_gen_validate_utf8, 1);

	chk(yajl_gen_map_open(g));

	chk(yajl_gen_string(g, (const unsigned char *)"timestamp", 9));
	chk(yajl_gen_string(g, (const unsigned char *)stamp, TIMESTAMP));

	chk(yajl_gen_string(g, (const unsigned char *)"message", 7));
	chk(yajl_gen_string(g, (const unsigned char *)line, len));

	if (fragment >= 0) {
		char fragmentStr[30];

		snprintf(fragmentStr, 30, "%d", fragment);

		chk(yajl_gen_string(g, (const unsigned char *)"fragmentId", 10));
		chk(yajl_gen_number(g, fragmentStr, strlen(fragmentStr)));
	}

	chk(yajl_gen_map_close(g));

	yajl_gen_get_buf(g, &buf, &buflen);
	fwrite(buf, 1, buflen, out);
	yajl_gen_clear(g);
	yajl_gen_free(g);

	putc('\n', out);
}
Пример #27
0
IoObject *IoYajlGen_closeMap(IoYajlGen *self, IoObject *locals, IoMessage *m)
{
	yajl_gen_map_close(DATA(self));
	return self;
}
Пример #28
0
void yajl_encode_part(void * wrapper, VALUE obj, VALUE io) {
    VALUE str, outBuff, otherObj;
    yajl_encoder_wrapper * w = wrapper;
    yajl_gen_status status;
    int idx = 0;
    const unsigned char * buffer;
    const char * cptr;
    unsigned int len;

    if (io != Qnil || w->on_progress_callback != Qnil) {
        status = yajl_gen_get_buf(w->encoder, &buffer, &len);
        if (len >= WRITE_BUFSIZE) {
            outBuff = rb_str_new((const char *)buffer, len);
            if (io != Qnil) {
                rb_io_write(io, outBuff);
            } else if (w->on_progress_callback != Qnil) {
                rb_funcall(w->on_progress_callback, intern_call, 1, outBuff);
            }
            yajl_gen_clear(w->encoder);
        }
    }

    switch (TYPE(obj)) {
        case T_HASH:
            status = yajl_gen_map_open(w->encoder);

            /* TODO: itterate through keys in the hash */
            VALUE keys = rb_funcall(obj, intern_keys, 0);
            VALUE entry, keyStr;
            for(idx=0; idx<RARRAY_LEN(keys); idx++) {
                entry = rb_ary_entry(keys, idx);
                keyStr = rb_funcall(entry, intern_to_s, 0); /* key must be a string */
                /* the key */
                yajl_encode_part(w, keyStr, io);
                /* the value */
                yajl_encode_part(w, rb_hash_aref(obj, entry), io);
            }

            status = yajl_gen_map_close(w->encoder);
            break;
        case T_ARRAY:
            status = yajl_gen_array_open(w->encoder);
            for(idx=0; idx<RARRAY_LEN(obj); idx++) {
                otherObj = rb_ary_entry(obj, idx);
                yajl_encode_part(w, otherObj, io);
            }
            status = yajl_gen_array_close(w->encoder);
            break;
        case T_NIL:
            status = yajl_gen_null(w->encoder);
            break;
        case T_TRUE:
            status = yajl_gen_bool(w->encoder, 1);
            break;
        case T_FALSE:
            status = yajl_gen_bool(w->encoder, 0);
            break;
        case T_FIXNUM:
        case T_FLOAT:
        case T_BIGNUM:
            str = rb_funcall(obj, intern_to_s, 0);
            cptr = RSTRING_PTR(str);
            len = RSTRING_LEN(str);
            if (memcmp(cptr, "NaN", 3) == 0 || memcmp(cptr, "Infinity", 8) == 0 || memcmp(cptr, "-Infinity", 9) == 0) {
                rb_raise(cEncodeError, "'%s' is an invalid number", cptr);
            }
            status = yajl_gen_number(w->encoder, cptr, len);
            break;
        case T_STRING:
            cptr = RSTRING_PTR(obj);
            len = RSTRING_LEN(obj);
            status = yajl_gen_string(w->encoder, (const unsigned char *)cptr, len);
            break;
        default:
            if (rb_respond_to(obj, intern_to_json)) {
                str = rb_funcall(obj, intern_to_json, 0);
                cptr = RSTRING_PTR(str);
                len = RSTRING_LEN(str);
                status = yajl_gen_number(w->encoder, cptr, len);
            } else {
                str = rb_funcall(obj, intern_to_s, 0);
                cptr = RSTRING_PTR(str);
                len = RSTRING_LEN(str);
                status = yajl_gen_string(w->encoder, (const unsigned char *)cptr, len);
            }
            break;
    }
}
Пример #29
0
static int POST_post(BlogRef const blog,
                     SLNSessionRef const session,
                     HTTPConnectionRef const conn,
                     HTTPMethod const method,
                     strarg_t const URI,
                     HTTPHeadersRef const headers)
{
	if(HTTP_POST != method) return -1;
	if(0 != uripathcmp("/post", URI, NULL)) return -1;

	// TODO: CSRF token
	strarg_t const formtype = HTTPHeadersGet(headers, "content-type"); 
	uv_buf_t boundary[1];
	int rc = MultipartBoundaryFromType(formtype, boundary);
	if(rc < 0) return 400;

	MultipartFormRef form = NULL;
	rc = MultipartFormCreate(conn, boundary, &form);
	if(rc < 0) {
		return 500;
	}

	SLNSubmissionRef sub = NULL;
	SLNSubmissionRef meta = NULL;
	str_t *title = NULL;
	rc = parse_file(blog, session, form, &sub, &meta, &title);
	if(UV_EACCES == rc) {
		MultipartFormFree(&form);
		return 403;
	}
	if(rc < 0) {
		MultipartFormFree(&form);
		return 500;
	}


	SLNSubmissionRef extra = NULL;
	yajl_gen json = NULL;
	str_t *target_QSEscaped = NULL;
	str_t *location = NULL;

	strarg_t const target = SLNSubmissionGetPrimaryURI(sub);
	if(!target) rc = UV_ENOMEM;
	if(rc < 0) goto cleanup;
	target_QSEscaped = QSEscape(target, strlen(target), true);
	if(!target_QSEscaped) rc = UV_ENOMEM;
	if(rc < 0) goto cleanup;

	rc = SLNSubmissionCreate(session, NULL, target, &extra);
	if(rc < 0) goto cleanup;
	rc = SLNSubmissionSetType(extra, SLN_META_TYPE);
	if(rc < 0) goto cleanup;

	SLNSubmissionWrite(extra, (byte_t const *)target, strlen(target));
	SLNSubmissionWrite(extra, (byte_t const *)STR_LEN("\n\n"));

	json = yajl_gen_alloc(NULL);
	if(!json) rc = UV_ENOMEM;
	if(rc < 0) goto cleanup;
	yajl_gen_config(json, yajl_gen_print_callback, (void (*)())SLNSubmissionWrite, extra);
	yajl_gen_config(json, yajl_gen_beautify, (int)true);

	yajl_gen_map_open(json);

	if(title) {
		yajl_gen_string(json, (unsigned char const *)STR_LEN("title"));
		yajl_gen_string(json, (unsigned char const *)title, strlen(title));
	}

	// TODO: Comment or description?

	strarg_t const username = SLNSessionGetUsername(session);
	if(username) {
		yajl_gen_string(json, (unsigned char const *)STR_LEN("submitter-name"));
		yajl_gen_string(json, (unsigned char const *)username, strlen(username));
	}

	strarg_t const reponame = SLNRepoGetName(blog->repo);
	if(reponame) {
		yajl_gen_string(json, (unsigned char const *)STR_LEN("submitter-repo"));
		yajl_gen_string(json, (unsigned char const *)reponame, strlen(reponame));
	}

	time_t const now = time(NULL);
	struct tm t[1];
	gmtime_r(&now, t); // TODO: Error checking?
	str_t tstr[31+1];
	size_t const tlen = strftime(tstr, sizeof(tstr), "%FT%TZ", t); // ISO 8601
	if(tlen) {
		yajl_gen_string(json, (unsigned char const *)STR_LEN("submission-time"));
		yajl_gen_string(json, (unsigned char const *)tstr, tlen);
	}

	yajl_gen_string(json, (unsigned char const *)STR_LEN("submission-software"));
	yajl_gen_string(json, (unsigned char const *)STR_LEN("StrongLink Blog"));

	str_t *fulltext = aasprintf("%s\n%s",
		title ?: "",
		NULL ?: ""); // TODO: Description, GNU-ism
	if(fulltext) {
		yajl_gen_string(json, (unsigned char const *)STR_LEN("fulltext"));
		yajl_gen_string(json, (unsigned char const *)fulltext, strlen(fulltext));
	}
	FREE(&fulltext);

	yajl_gen_map_close(json);

	rc = SLNSubmissionEnd(extra);
	if(rc < 0) goto cleanup;


	SLNSubmissionRef subs[] = { sub, meta, extra };
	rc = SLNSubmissionStoreBatch(subs, numberof(subs));

	location = aasprintf("/?q=%s", target_QSEscaped);
	if(!location) rc = UV_ENOMEM;
	if(rc < 0) goto cleanup;

	HTTPConnectionSendRedirect(conn, 303, location);

cleanup:
	if(json) { yajl_gen_free(json); json = NULL; }
	FREE(&title);
	SLNSubmissionFree(&sub);
	SLNSubmissionFree(&meta);
	SLNSubmissionFree(&extra);
	MultipartFormFree(&form);
	FREE(&target_QSEscaped);
	FREE(&location);

	if(rc < 0) return 500;
	return 0;
}
Пример #30
0
static void log_logstash_print (yajl_gen g, int severity,
	   	cdtime_t timestamp_time)
{
	FILE *fh;
	_Bool do_close = 0;
	struct tm timestamp_tm;
	char timestamp_str[64];
	const unsigned char *buf;
	time_t tt;
#if HAVE_YAJL_V2
	size_t len;
#else
	unsigned int len;
#endif

	if (yajl_gen_string(g, (u_char *)"@level", strlen("@level")) !=
	    yajl_gen_status_ok)
		goto err;

	switch (severity) {
	case LOG_ERR:
		if (yajl_gen_string(g, (u_char *)"error", strlen("error")) !=
		    yajl_gen_status_ok)
			goto err;
		break;
	case LOG_WARNING:
		if (yajl_gen_string(g, (u_char *)"warning",
				    strlen("warning")) !=
		    yajl_gen_status_ok)
			goto err;
		break;
	case LOG_NOTICE:
		if (yajl_gen_string(g, (u_char *)"notice", strlen("notice")) !=
		    yajl_gen_status_ok)
			goto err;
		break;
	case LOG_INFO:
		if (yajl_gen_string(g, (u_char *)"info", strlen("info")) !=
		    yajl_gen_status_ok)
			goto err;
		break;
	case LOG_DEBUG:
		if (yajl_gen_string(g, (u_char *)"debug", strlen("debug")) !=
		    yajl_gen_status_ok)
			goto err;
		break;
	default:
		if (yajl_gen_string(g, (u_char *)"unknown",
				    strlen("unknown")) !=
		    yajl_gen_status_ok)
			goto err;
		break;
	}

	if (yajl_gen_string(g, (u_char *)"@timestamp", strlen("@timestamp")) !=
	    yajl_gen_status_ok)
		goto err;

	tt = CDTIME_T_TO_TIME_T (timestamp_time);
	gmtime_r (&tt, &timestamp_tm);

	/*
	 * format time as a UTC ISO 8601 compliant string
	 */
	strftime (timestamp_str, sizeof (timestamp_str),
		  "%Y-%m-%d %H:%M:%SZ", &timestamp_tm);
	timestamp_str[sizeof (timestamp_str) - 1] = '\0';

	if (yajl_gen_string(g, (u_char *)timestamp_str,
			    strlen(timestamp_str)) !=
	    yajl_gen_status_ok)
		goto err;

	if (yajl_gen_map_close(g) != yajl_gen_status_ok)
		goto err;

	if (yajl_gen_get_buf(g, &buf, &len) != yajl_gen_status_ok)
		goto err;
	pthread_mutex_lock (&file_lock);

	if (log_file == NULL)
	{
		fh = fopen (DEFAULT_LOGFILE, "a");
		do_close = 1;
	} else if (strcasecmp(log_file, "stdout") == 0) {
        fh = stdout;
        do_close = 0;
	} else if (strcasecmp(log_file, "stderr") == 0) {
        fh = stderr;
        do_close = 0;
	} else {
		fh = fopen (log_file, "a");
		do_close = 1;
	}

	if (fh == NULL)
	{
			char errbuf[1024];
			fprintf (stderr, "log_logstash plugin: fopen (%s) failed: %s\n",
					(log_file == NULL) ? DEFAULT_LOGFILE : log_file,
					sstrerror (errno, errbuf, sizeof (errbuf)));
	}
	else
	{
		fprintf(fh, "%s\n", buf);
		if (do_close) {
			fclose (fh);
		} else {
			fflush(fh);
		}
	}
	pthread_mutex_unlock (&file_lock);
	yajl_gen_free(g);
	return;

 err:
	yajl_gen_free(g);
	fprintf(stderr, "Could not correctly generate JSON message\n");
	return;
} /* void log_logstash_print */