Пример #1
0
void log_api(uint32_t index, int is_success, uintptr_t return_value,
             uint64_t hash, last_error_t *lasterr, ...)
{
    va_list args;
    char idx[4];
    va_start(args, lasterr);

    EnterCriticalSection(&g_mutex);

    if(g_api_init[index] == 0) {
        log_explain(index);
        g_api_init[index] = 1;
    }

    LeaveCriticalSection(&g_mutex);

    bson b;

    bson_init_size(&b, mem_suggested_size(1024));
    bson_append_int(&b, "I", index);
    bson_append_int(&b, "T", get_current_thread_id());
    bson_append_int(&b, "t", get_tick_count() - g_starttick);
    bson_append_long(&b, "h", hash);

    // If failure has been determined, then log the last error as well.
    if(is_success == 0) {
        bson_append_int(&b, "e", lasterr->lasterror);
        bson_append_int(&b, "E", lasterr->nt_status);
    }

#if DEBUG
    if(index != sig_index_exception()) {
        _log_stacktrace(&b);
    }
#endif

    bson_append_start_array(&b, "args");
    bson_append_int(&b, "0", is_success);
    bson_append_long(&b, "1", return_value);

    int argnum = 2, override = 0;

    for (const char *fmt = sig_paramtypes(index); *fmt != 0; fmt++) {
        ultostr(argnum++, idx, 10);

        // Limitation override. Instead of displaying this right away in the
        // report we turn it into a buffer (much like the dropped files).
        if(*fmt == '!') {
            override = 1;
            argnum--;
            fmt++;
        }

        if(*fmt == 's') {
            const char *s = va_arg(args, const char *);
            log_string(&b, idx, s, copy_strlen(s));
        }
        else if(*fmt == 'S') {
Пример #2
0
static bson __update_form_req(void)
{
    bson broot;

    bson_init(&broot);

    bson_append_long(&broot, "mj", 789);
    bson_append_long(&broot, "mi", 234);
    bson_append_long(&broot, "rv", 12312);
    bson_append_long(&broot, "bd", 5454);

    bson_finish(&broot);

    return broot;
}
Пример #3
0
int init_suite(void) {
    assert(QRS < RS);
    jb = ejdbnew();
    if (!ejdbopen(jb, "dbt3", JBOWRITER | JBOCREAT | JBOTRUNC)) {
        return 1;
    }
    srand(tcmstime());
    recs = malloc(RS * sizeof (bson));
    if (!recs) {
        return 1;
    }
    for (int i = 0; i < RS; ++i) {
        bson bs;
        bson_init(&bs);
        bson_append_long(&bs, "ts", tcmstime());
        char str[128];
        int len = 0;
        do {
            len = rand() % 128;
        } while (len <= 0);
        str[0] = 'A' + (i % 26);
        for (int j = 1; j < len; ++j) {
            str[j] = 'a' + rand() % 26;
        }
        str[len] = '\0';
        bson_append_string(&bs, "rstring", str);
        bson_finish(&bs);
        recs[i] = bs;
    }

    return 0;
}
Пример #4
0
int update_filesize(struct inode * e, off_t newsize) {
    bson cond, doc;
    mongo * conn = get_conn();
    int res;

    if(newsize < e->size)
        return 0;

    e->size = newsize;

    bson_init(&cond);
    bson_append_oid(&cond, "_id", &e->oid);
    bson_finish(&cond);

    bson_init(&doc);
    bson_append_start_object(&doc, "$set");
    bson_append_long(&doc, "size", newsize);
    bson_append_finish_object(&doc);
    bson_finish(&doc);

    res = mongo_update(conn, inodes_name, &cond, &doc, 0, NULL);
    bson_destroy(&cond);
    bson_destroy(&doc);

    if(res != 0)
        return -EIO;
    return 0;
}
Пример #5
0
int mongodb_fmt_insert_arg(bot_t * bot, char *db, mongo_argument_t ** arg_array)
{
/* example: ^e |^mongotestfmt "%s=name %i=age %f=grade" Darqbot 50 99.9 */

	int i;
	bson b;

	debug(bot, "mongodb_fmt_insert_arg: Entered\n");

	if (!db || !arg_array)
		return -1;

	bson_init(&b);

	for (i = 0; arg_array[i] != NULL; i++) {
		switch (arg_array[i]->type) {
		case MONGODB_ARG_STRING:
			{
				bson_append_string(&b, arg_array[i]->name,
						   arg_array[i]->arg_str);
				break;
			}
		case MONGODB_ARG_INT:
			{
				bson_append_int(&b, arg_array[i]->name,
						arg_array[i]->arg_int);
				break;
			}
		case MONGODB_ARG_DOUBLE:
			{
				bson_append_double(&b, arg_array[i]->name,
						   arg_array[i]->arg_double);
				break;
			}
		case MONGODB_ARG_LONG:
			{
				bson_append_long(&b, arg_array[i]->name,
						 arg_array[i]->arg_long);
				break;
			}
		case MONGODB_ARG_OID:
			{
// FIX
				bson_append_oid(&b, arg_array[i]->name,
						&arg_array[i]->arg_oid);
				break;
			}
		default:
			break;
		}
	}

	bson_finish(&b);

	i = mongo_insert(&gi->mongo_conn, db, &b);

	bson_destroy(&b);

	return 0;
}
Пример #6
0
static bson __auth_form_req(void)
{
    bson broot;
//    char IMEI[15];

    bson_init(&broot);

    bson_append_long(&broot,   "login",  7);
    bson_append_string(&broot, "passwd", "PASS");
    bson_append_string(&broot, "imei",   "1234567890");
    bson_append_long(&broot,   "ver",    1111);

    bson_finish(&broot);

    return broot;
}
Пример #7
0
static void log_intptr(bson *b, const char *idx, intptr_t value)
{
#if __x86_64__
    bson_append_long(b, idx, value);
#else
    bson_append_int(b, idx, value);
#endif
}
Пример #8
0
int commit_inode(struct inode * e) {
    bson cond, doc;
    mongo * conn = get_conn();
    char istr[4];
    struct dirent * cde = e->dirents;
    int res;

    bson_init(&doc);
    bson_append_start_object(&doc, "$set");
    bson_append_start_array(&doc, "dirents");
    res = 0;
    while(cde) {
        bson_numstr(istr, res++);
        bson_append_string(&doc, istr, cde->path);
        cde = cde->next;
    }
    bson_append_finish_array(&doc);

    bson_append_int(&doc, "mode", e->mode);
    bson_append_long(&doc, "owner", e->owner);
    bson_append_long(&doc, "group", e->group);
    bson_append_long(&doc, "size", e->size);
    bson_append_time_t(&doc, "created", e->created);
    bson_append_time_t(&doc, "modified", e->modified);
    if(e->data && e->datalen > 0)
        bson_append_string_n(&doc, "data", e->data, e->datalen);
    bson_append_finish_object(&doc);
    bson_finish(&doc);

    bson_init(&cond);
    bson_append_oid(&cond, "_id", &e->oid);
    bson_finish(&cond);

    res = mongo_update(conn, inodes_name, &cond, &doc,
        MONGO_UPDATE_UPSERT, NULL);
    bson_destroy(&cond);
    bson_destroy(&doc);
    if(res != MONGO_OK) {
        fprintf(stderr, "Error committing inode %s\n",
            mongo_get_server_err_string(conn));
        return -EIO;
    }
    return 0;
}
Пример #9
0
void MongodbObject::EnableForEdit()
{
    bson *newObject = new bson();
    bson_init(newObject);
    
    bson_iterator it;
    bson_iterator_init(&it, objectData->object);

    while (bson_iterator_next(&it))
    {
        const char * key = bson_iterator_key(&it);
        bson_type type = bson_iterator_type(&it);
        
        switch (type)
        {
            case BSON_STRING:
                bson_append_string(newObject, key, bson_iterator_string(&it));
                break;

            case BSON_INT:
                bson_append_int(newObject, key, bson_iterator_int(&it));
                break;

            case BSON_LONG:
                bson_append_long(newObject, key, bson_iterator_long(&it));
                break;

            case BSON_DOUBLE:
                bson_append_double(newObject, key, bson_iterator_double(&it));
                break;

            case BSON_OBJECT:
                
                bson sub;
                bson_iterator_subobject(&it, &sub);
                bson_append_bson(newObject, key, &sub);
                break;
                
            case BSON_OID:
                bson_append_oid(newObject, key, bson_iterator_oid(&it));
                break;

                
            default:
                break;
        }
    }

    bson_destroy(objectData->object);
    SafeDelete(objectData->object);
    objectData->object = newObject;
}
Пример #10
0
void bson_from_json_type(bson *b, yajl_val value, const char* key)
{
    if( YAJL_IS_STRING( value ) )
    {
        char* string = YAJL_GET_STRING( value );
        bson_append_string( b, key, string );
    }
    else if( YAJL_IS_NUMBER( value ) )
    {
        char* string = value->u.number.r;
        size_t len = strlen( string );

        // Hack to detect a double, since 'flags' is always set to double.
        if( memchr( string, '.', len ) ||
                memchr( string, 'e', len ) ||
                memchr( string, 'E', len ) )
        {
            double number = YAJL_GET_DOUBLE( value );
            bson_append_double( b, key, number );
        }
        else
        {
            uint64_t number = YAJL_GET_INTEGER( value );

            if( number <= INT_MIN && number <= INT_MAX)
                bson_append_int( b, key, (int)number );
            else
                bson_append_long( b, key, number);
        }
    }
    else if ( YAJL_IS_FALSE( value ) )
    {
        bson_append_bool( b, key, 0 );
    }
    else if ( YAJL_IS_TRUE( value ) )
    {
        bson_append_bool( b, key, 1 );
    }
    else if ( YAJL_IS_ARRAY( value ) )
    {
        bson_append_start_array( b, key );
        bson_from_json_array( b, value );
        bson_append_finish_array( b );
    }
    else if ( YAJL_IS_OBJECT( value ) )
    {
        bson_append_start_object( b, key );
        bson_from_json_object( b, value );
        bson_append_finish_object( b );
    }
}
Пример #11
0
Файл: t1.c Проект: CowanSM/ejdb
void testSaveLoad() {
    CU_ASSERT_PTR_NOT_NULL_FATAL(jb);
    bson_oid_t oid;
    EJCOLL *ccoll = ejdbcreatecoll(jb, "contacts", NULL);
    CU_ASSERT_PTR_NOT_NULL(ccoll);

    //Save record
    bson a1;
    bson_init(&a1);

    bson_append_string(&a1, "name", "Петров Петр");
    bson_append_string(&a1, "phone", "333-222-333");
    bson_append_int(&a1, "age", 33);
    bson_append_long(&a1, "longage", 0xFFFFFFFFFF01LL);
    bson_append_double(&a1, "doubleage", 0.333333);
    bson_finish(&a1);
    ejdbsavebson(ccoll, &a1, &oid);
    bson_destroy(&a1);


    bson *lbson = ejdbloadbson(ccoll, &oid);
    CU_ASSERT_PTR_NOT_NULL(lbson);
    bson_iterator it1;
    bson_iterator_init(&it1, lbson);

    int btype = bson_iterator_next(&it1);
    CU_ASSERT(btype == BSON_OID);
    btype = bson_iterator_next(&it1);
    CU_ASSERT(btype == BSON_STRING);
    CU_ASSERT(!strcmp("name", bson_iterator_key(&it1)));
    CU_ASSERT(!strcmp("Петров Петр", bson_iterator_string(&it1)));
    btype = bson_iterator_next(&it1);
    CU_ASSERT(btype == BSON_STRING);
    CU_ASSERT(!strcmp("phone", bson_iterator_key(&it1)));
    CU_ASSERT(!strcmp("333-222-333", bson_iterator_string(&it1)));
    btype = bson_iterator_next(&it1);
    CU_ASSERT(btype == BSON_INT);
    CU_ASSERT(!strcmp("age", bson_iterator_key(&it1)));
    CU_ASSERT(33 == bson_iterator_int(&it1));
    btype = bson_iterator_next(&it1);
    CU_ASSERT(btype == BSON_LONG);
    CU_ASSERT(!strcmp("longage", bson_iterator_key(&it1)));
    CU_ASSERT(0xFFFFFFFFFF01LL == bson_iterator_long(&it1));
    btype = bson_iterator_next(&it1);
    CU_ASSERT(btype == BSON_DOUBLE);
    CU_ASSERT(!strcmp("doubleage", bson_iterator_key(&it1)));
    CU_ASSERT_DOUBLE_EQUAL(bson_iterator_double(&it1), 0.3, 0.1);
    btype = bson_iterator_next(&it1);
    CU_ASSERT(btype == BSON_EOO);
    bson_del(lbson);
}
Пример #12
0
 void InitWith(bson *obj)
 {
     bson_iterator it;
     bson_iterator_init(&it, obj);
     
     while (bson_iterator_next(&it))
     {
         const char * key = bson_iterator_key(&it);
         bson_type type = bson_iterator_type(&it);
         
         switch (type)
         {
             case BSON_STRING:
                 bson_append_string(object, key, bson_iterator_string(&it));
                 break;
                 
             case BSON_INT:
                 bson_append_int(object, key, bson_iterator_int(&it));
                 break;
                 
             case BSON_LONG:
                 bson_append_long(object, key, bson_iterator_long(&it));
                 break;
                 
             case BSON_DOUBLE:
                 bson_append_double(object, key, bson_iterator_double(&it));
                 break;
                 
             case BSON_OBJECT:
             {
                 bson sub;
                 
                 bson_iterator_subobject(&it, &sub);
                 bson_append_bson(object, key, &sub);
                 break;
             }
                 
             case BSON_OID:
                 bson_append_oid(object, key, bson_iterator_oid(&it));
                 break;
                 
                 
             default:
                 DVASSERT(false);
                 Logger::Error("[MongodbObjectInternalData::InitWith] Not implemented type: %d", type);
                 break;
         }
     }
 }
Пример #13
0
static int gridfs_insert_file2( gridfs *gfs, const char *name,
                                const bson_oid_t id, gridfs_offset length,
                                const char *contenttype, gridfile* gfile ) {
    bson command;
    bson ret;
    bson res;
    bson_iterator it;
    int result;
    int64_t d;

    /* Check run md5 */
    bson_init( &command );
    bson_append_oid( &command, "filemd5", &id );
    bson_append_string( &command, "root", gfs->prefix );
    bson_finish( &command );
    result = mongo_run_command( gfs->client, gfs->dbname, &command, &res );
    bson_destroy( &command );
    if (result != MONGO_OK)
        return result;

    /* Create and insert BSON for file metadata */
    bson_init( &ret );
    bson_append_oid( &ret, "_id", &id );
    if ( name != NULL && *name != '\0' ) {
        bson_append_string( &ret, "filename", name );
    }
    bson_append_long( &ret, "length", length );
    bson_append_int( &ret, "chunkSize", DEFAULT_CHUNK_SIZE );
    d = ( bson_date_t )1000*time( NULL );
    bson_append_date( &ret, "uploadDate", d);
    bson_find( &it, &res, "md5" );
    bson_append_string( &ret, "md5", bson_iterator_string( &it ) );
    bson_destroy( &res );
    if ( contenttype != NULL && *contenttype != '\0' ) {
        bson_append_string( &ret, "contentType", contenttype );
    }

    bson_append_bson(&ret, "metadata", gfile->meta);

    bson_finish( &ret );
    result = mongo_insert( gfs->client, gfs->files_ns, &ret );
    bson_destroy( &ret );

    return result;
}
Пример #14
0
static bson gridfs_insert_file( gridfs* gfs, const char* name,
             const bson_oid_t id, gridfs_offset length,
             const char* contenttype)
{
  bson command;
  bson res;
  bson ret;
  bson_buffer buf;
  bson_iterator it;

  /* Check run md5 */
  bson_buffer_init(&buf);
  bson_append_oid(&buf, "filemd5", &id);
  bson_append_string(&buf, "root", gfs->prefix);
  bson_from_buffer(&command, &buf);
  assert(mongo_run_command(gfs->client, gfs->dbname,
         &command, &res));
  bson_destroy(&command);

  /* Create and insert BSON for file metadata */
  bson_buffer_init(&buf);
  bson_append_oid(&buf, "_id", &id);
  if (name != NULL && *name != '\0') {
    bson_append_string(&buf, "filename", name);
  }
  bson_append_long(&buf, "length", length);
  bson_append_int(&buf, "chunkSize", DEFAULT_CHUNK_SIZE);
  bson_append_date(&buf, "uploadDate", (bson_date_t)1000*time(NULL));
  bson_find(&it, &res, "md5");
  bson_append_string(&buf, "md5", bson_iterator_string(&it));
  bson_destroy(&res);
  if (contenttype != NULL && *contenttype != '\0') {
    bson_append_string(&buf, "contentType", contenttype);
  }
  bson_from_buffer(&ret, &buf);
  mongo_insert(gfs->client, gfs->files_ns, &ret);

  return ret;
}
Пример #15
0
int do_trunc(struct inode * e, off_t off) {
    bson cond;
    int res;
    mongo * conn = get_conn();

    if(off > e->size) {
        e->size = off;
        return 0;
    }

    pthread_mutex_lock(&e->wr_lock);
    if(e->wr_extent) {
        if(off < 0 && (res = serialize_extent(e, e->wr_extent)) != 0)
            return res;
        e->wr_extent->nnodes = 0;
    }
    e->wr_age = time(NULL);
    pthread_mutex_unlock(&e->wr_lock);

    bson_init(&cond);
    bson_append_oid(&cond, "inode", &e->oid);
    if(off > 0) {
        bson_append_start_object(&cond, "start");
        bson_append_long(&cond, "$gte", off);
        bson_append_finish_object(&cond);
    }
    bson_finish(&cond);

    res = mongo_remove(conn, extents_name, &cond, NULL);
    bson_destroy(&cond);
    if(res != 0) {
        fprintf(stderr, "Error removing extents in do_truncate\n");
        return -EIO;
    }

    e->size = off;

    return 0;
}
Пример #16
0
static switch_status_t my_on_reporting(switch_core_session_t *session)
{
	switch_status_t status = SWITCH_STATUS_SUCCESS;
	switch_channel_t *channel = switch_core_session_get_channel(session);
	switch_event_header_t *hi;
	switch_caller_profile_t *caller_profile;
	switch_app_log_t *app_log;
	bson cdr;
	int is_b;
	char *tmp;

	if (globals.shutdown) {
		return SWITCH_STATUS_SUCCESS;
	}

	is_b = channel && switch_channel_get_originator_caller_profile(channel);
	if (!globals.log_b && is_b) {
		const char *force_cdr = switch_channel_get_variable(channel, SWITCH_FORCE_PROCESS_CDR_VARIABLE);
		if (!switch_true(force_cdr)) {
			return SWITCH_STATUS_SUCCESS;
		}
	}

	bson_init(&cdr);

	/* Channel data */
	bson_append_start_object(&cdr, "channel_data");
	bson_append_string(&cdr, "state", switch_channel_state_name(switch_channel_get_state(channel)));
	bson_append_string(&cdr, "direction", switch_channel_direction(channel) == SWITCH_CALL_DIRECTION_OUTBOUND ? "outbound" : "inbound");
	bson_append_int(&cdr, "state_number", switch_channel_get_state(channel));

	if ((tmp = switch_channel_get_flag_string(channel))) {
		bson_append_string(&cdr, "flags", tmp);
		free(tmp);
	}

	if ((tmp = switch_channel_get_cap_string(channel))) {
		bson_append_string(&cdr, "caps", tmp);
		free(tmp);
	}
	bson_append_finish_object(&cdr);				/* channel_data */


	/* Channel variables */
	bson_append_start_object(&cdr, "variables");

	if ((hi = switch_channel_variable_first(channel))) {
		for (; hi; hi = hi->next) {
			if (!zstr(hi->name) && !zstr(hi->value)) {
				bson_append_string(&cdr, hi->name, hi->value);
			}
		}
		switch_channel_variable_last(channel);
	}

	bson_append_finish_object(&cdr);				/* variables */


	/* App log */
	if ((app_log = switch_core_session_get_app_log(session))) {
		switch_app_log_t *ap;

		bson_append_start_object(&cdr, "app_log");
		for (ap = app_log; ap; ap = ap->next) {
			bson_append_start_object(&cdr, "application");
			bson_append_string(&cdr, "app_name", ap->app);
			bson_append_string(&cdr, "app_data", ap->arg);
			bson_append_long(&cdr, "app_stamp", ap->stamp);
			bson_append_finish_object(&cdr);		/* application */
		}

		bson_append_finish_object(&cdr);			/* app_log */
	}


	/* Callflow */
	caller_profile = switch_channel_get_caller_profile(channel);

	while (caller_profile) {
		bson_append_start_object(&cdr, "callflow");

		if (!zstr(caller_profile->dialplan)) {
			bson_append_string(&cdr, "dialplan", caller_profile->dialplan);
		}

		if (!zstr(caller_profile->profile_index)) {
			bson_append_string(&cdr, "profile_index", caller_profile->profile_index);
		}

		if (caller_profile->caller_extension) {
			switch_caller_application_t *ap;

			bson_append_start_object(&cdr, "extension");

			bson_append_string(&cdr, "name", caller_profile->caller_extension->extension_name);
			bson_append_string(&cdr, "number", caller_profile->caller_extension->extension_number);

			if (caller_profile->caller_extension->current_application) {
				bson_append_string(&cdr, "current_app", caller_profile->caller_extension->current_application->application_name);
			}

			for (ap = caller_profile->caller_extension->applications; ap; ap = ap->next) {
				bson_append_start_object(&cdr, "application");
				if (ap == caller_profile->caller_extension->current_application) {
					bson_append_bool(&cdr, "last_executed", 1);
				}
				bson_append_string(&cdr, "app_name", ap->application_name);
				bson_append_string(&cdr, "app_data", ap->application_data);
				bson_append_finish_object(&cdr);
			}

			if (caller_profile->caller_extension->children) {
				switch_caller_profile_t *cp = NULL;

				for (cp = caller_profile->caller_extension->children; cp; cp = cp->next) {

					if (!cp->caller_extension) {
						continue;
					}

					bson_append_start_object(&cdr, "sub_extensions");
					bson_append_start_object(&cdr, "extension");

					bson_append_string(&cdr, "name", cp->caller_extension->extension_name);
					bson_append_string(&cdr, "number", cp->caller_extension->extension_number);
					bson_append_string(&cdr, "dialplan", cp->dialplan);
					if (cp->caller_extension->current_application) {
						bson_append_string(&cdr, "current_app", cp->caller_extension->current_application->application_name);
					}

					for (ap = cp->caller_extension->applications; ap; ap = ap->next) {
						bson_append_start_object(&cdr, "application");
						if (ap == cp->caller_extension->current_application) {
							bson_append_bool(&cdr, "last_executed", 1);
						}
						bson_append_string(&cdr, "app_name", ap->application_name);
						bson_append_string(&cdr, "app_data", ap->application_data);
						bson_append_finish_object(&cdr);
					}

					bson_append_finish_object(&cdr);	/* extension */
					bson_append_finish_object(&cdr);	/* sub_extensions */
				}
			}

			bson_append_finish_object(&cdr);			/* extension */
		}

		bson_append_start_object(&cdr, "caller_profile");
		set_bson_profile_data(&cdr, caller_profile);

		if (caller_profile->origination_caller_profile) {
			switch_caller_profile_t *cp = NULL;

			bson_append_start_object(&cdr, "origination");
			for (cp = caller_profile->origination_caller_profile; cp; cp = cp->next) {
				bson_append_start_object(&cdr, "origination_caller_profile");
				set_bson_profile_data(&cdr, cp);
				bson_append_finish_object(&cdr);
			}
			bson_append_finish_object(&cdr);			/* origination */
		}

		if (caller_profile->originator_caller_profile) {
			switch_caller_profile_t *cp = NULL;

			bson_append_start_object(&cdr, "originator");
			for (cp = caller_profile->originator_caller_profile; cp; cp = cp->next) {
				bson_append_start_object(&cdr, "originator_caller_profile");
				set_bson_profile_data(&cdr, cp);
				bson_append_finish_object(&cdr);
			}
			bson_append_finish_object(&cdr);			/* originator */
		}

		if (caller_profile->originatee_caller_profile) {
			switch_caller_profile_t *cp = NULL;

			bson_append_start_object(&cdr, "originatee");
			for (cp = caller_profile->originatee_caller_profile; cp; cp = cp->next) {
				bson_append_start_object(&cdr, "originatee_caller_profile");
				set_bson_profile_data(&cdr, cp);
				bson_append_finish_object(&cdr);
			}
			bson_append_finish_object(&cdr);			/* originatee */
		}

		bson_append_finish_object(&cdr);				/* caller_profile */

		/* Timestamps */
		if (caller_profile->times) {
			bson_append_start_object(&cdr, "times");

			/* Insert timestamps as long ints (microseconds) to preserve accuracy */
			bson_append_long(&cdr, "created_time", caller_profile->times->created);
			bson_append_long(&cdr, "profile_created_time", caller_profile->times->profile_created);
			bson_append_long(&cdr, "progress_time", caller_profile->times->progress);
			bson_append_long(&cdr, "progress_media_time", caller_profile->times->progress_media);
			bson_append_long(&cdr, "answered_time", caller_profile->times->answered);
			bson_append_long(&cdr, "bridged_time", caller_profile->times->bridged);
			bson_append_long(&cdr, "last_hold_time", caller_profile->times->last_hold);
			bson_append_long(&cdr, "hold_accum_time", caller_profile->times->hold_accum);
			bson_append_long(&cdr, "hangup_time", caller_profile->times->hungup);
			bson_append_long(&cdr, "resurrect_time", caller_profile->times->resurrected);
			bson_append_long(&cdr, "transfer_time", caller_profile->times->transferred);
			bson_append_finish_object(&cdr);			/* times */
		}

		bson_append_finish_object(&cdr);				/* callflow */
		caller_profile = caller_profile->next;
	}

	bson_finish(&cdr);

	switch_mutex_lock(globals.mongo_mutex);

	if (mongo_insert(globals.mongo_conn, globals.mongo_namespace, &cdr) != MONGO_OK) {
		if (globals.mongo_conn->err == MONGO_IO_ERROR) {
			mongo_error_t db_status;
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "MongoDB connection failed; attempting reconnect...\n");
			db_status = mongo_reconnect(globals.mongo_conn);

			if (db_status != MONGO_OK) {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "MongoDB reconnect failed with error code %d\n", db_status);
				status = SWITCH_STATUS_FALSE;
			} else {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "MongoDB connection re-established.\n");
				if (mongo_insert(globals.mongo_conn, globals.mongo_namespace, &cdr) != MONGO_OK) {
					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "mongo_insert: error code %d\n", globals.mongo_conn->err);
					status = SWITCH_STATUS_FALSE;
				}
			}

		} else {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "mongo_insert: error code %d\n", globals.mongo_conn->err);
			status = SWITCH_STATUS_FALSE;
		}
	}

	switch_mutex_unlock(globals.mongo_mutex);
	bson_destroy(&cdr);

	return status;
}
Пример #17
0
void encodeValue(bson *bb, const char *name, v8::Local<v8::Value> element,
                 bool doJson)
{
    if (element.IsEmpty() || element->IsUndefined() || element->IsFunction())
        ;
    else if (element->IsNull())
        bson_append_null(bb, name);
    else if (element->IsDate())
        bson_append_date(bb, name, (bson_date_t) element->NumberValue());
    else if (element->IsBoolean())
        bson_append_bool(bb, name, element->IsTrue());
    else if (element->IsNumber() || element->IsNumberObject())
    {
        double value = element->NumberValue();
        int64_t num = (int64_t) value;

        if (value == (double) num)
        {
            if (num >= -2147483648ll && num <= 2147483647ll)
                bson_append_int(bb, name, (int) num);
            else
                bson_append_long(bb, name, num);
        }
        else
            bson_append_double(bb, name, value);
    }
    else if (element->IsArray())
        encodeArray(bb, name, element);
    else if (element->IsRegExp())
    {
        v8::Local<v8::RegExp> re = v8::Local<v8::RegExp>::Cast(element);
        v8::Local<v8::String> src = re->GetSource();
        v8::RegExp::Flags flgs = re->GetFlags();
        char flgStr[4];
        char *p = flgStr;

        if (flgs & v8::RegExp::kIgnoreCase)
            *p++ = 'i';
        if (flgs & v8::RegExp::kGlobal)
            *p++ = 'g';
        if (flgs & v8::RegExp::kMultiline)
            *p++ = 'm';

        *p = 0;

        bson_append_regex(bb, name, *v8::String::Utf8Value(src), flgStr);
    }
    else if (element->IsObject())
    {
        {
            obj_ptr<Int64> num = (Int64 *)Int64_base::getInstance(element);

            if (num)
            {
                if (num->m_num >= -2147483648ll && num->m_num <= 2147483647ll)
                    bson_append_int(bb, name, (int) num->m_num);
                else
                    bson_append_long(bb, name, num->m_num);
                return;
            }
        }

        {
            obj_ptr<Buffer_base> buf = Buffer_base::getInstance(element);

            if (buf)
            {
                std::string strBuf;

                buf->toString(strBuf);
                bson_append_binary(bb, name, BSON_BIN_BINARY, strBuf.c_str(),
                                   (int) strBuf.length());

                return;
            }
        }

        {
            obj_ptr<MongoID> oid = (MongoID *) MongoID_base::getInstance(
                                       element);

            if (oid)
            {
                bson_append_oid(bb, name, &oid->m_id);
                return;
            }
        }

        encodeObject(bb, name, element, doJson);
    }
    else
    {
        v8::String::Utf8Value v(element);
        bson_append_string(bb, name, ToCString(v));
    }
}
Пример #18
0
/*
 * Functions
 */
static bson *wm_create_bson (const data_set_t *ds, /* {{{ */
    const value_list_t *vl,
    _Bool store_rates)
{
  bson *ret;
  gauge_t *rates;

  ret = bson_alloc (); /* matched by bson_dealloc() */
  if (ret == NULL)
  {
    ERROR ("write_mongodb plugin: bson_create failed.");
    return (NULL);
  }

  if (store_rates)
  {
    rates = uc_get_rate (ds, vl);
    if (rates == NULL)
    {
      ERROR ("write_mongodb plugin: uc_get_rate() failed.");
      return (NULL);
    }
  }
  else
  {
    rates = NULL;
  }

  bson_init (ret); /* matched by bson_destroy() */
  bson_append_date (ret, "time", (bson_date_t) CDTIME_T_TO_MS (vl->time));
  bson_append_string (ret, "host", vl->host);
  bson_append_string (ret, "plugin", vl->plugin);
  bson_append_string (ret, "plugin_instance", vl->plugin_instance);
  bson_append_string (ret, "type", vl->type);
  bson_append_string (ret, "type_instance", vl->type_instance);

  bson_append_start_array (ret, "values"); /* {{{ */
  for (int i = 0; i < ds->ds_num; i++)
  {
    char key[16];

    ssnprintf (key, sizeof (key), "%i", i);

    if (ds->ds[i].type == DS_TYPE_GAUGE)
      bson_append_double(ret, key, vl->values[i].gauge);
    else if (store_rates)
      bson_append_double(ret, key, (double) rates[i]);
    else if (ds->ds[i].type == DS_TYPE_COUNTER)
      bson_append_long(ret, key, vl->values[i].counter);
    else if (ds->ds[i].type == DS_TYPE_DERIVE)
      bson_append_long(ret, key, vl->values[i].derive);
    else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
      bson_append_long(ret, key, vl->values[i].absolute);
    else
      assert (23 == 42);
  }
  bson_append_finish_array (ret); /* }}} values */

  bson_append_start_array (ret, "dstypes"); /* {{{ */
  for (int i = 0; i < ds->ds_num; i++)
  {
    char key[16];

    ssnprintf (key, sizeof (key), "%i", i);

    if (store_rates)
      bson_append_string (ret, key, "gauge");
    else
      bson_append_string (ret, key, DS_TYPE_TO_STRING (ds->ds[i].type));
  }
  bson_append_finish_array (ret); /* }}} dstypes */

  bson_append_start_array (ret, "dsnames"); /* {{{ */
  for (int i = 0; i < ds->ds_num; i++)
  {
    char key[16];

    ssnprintf (key, sizeof (key), "%i", i);
    bson_append_string (ret, key, ds->ds[i].name);
  }
  bson_append_finish_array (ret); /* }}} dsnames */

  bson_finish (ret);

  sfree (rates);
  return (ret);
} /* }}} bson *wm_create_bson */
Пример #19
0
static bcon_error_t bson_bcon_key_value(bson *b, const char *key, const char *typespec, const bcon bci) {
    bcon_error_t ret = BCON_OK;
    bson_oid_t oid;
    char ptype = typespec ? typespec[1] : '_';
    char utype = typespec ? typespec[2] : '_';
    switch (ptype) {
    case '_': /* kv(b, key, utype, bci) */
        switch (utype) {
        case '_': /* fall through */
        case 's': bson_append_string( b, key, bci.s ); break; /* common case */
        case 'f': bson_append_double( b, key, bci.f ); break;
        case 'D':
            bson_append_start_object( b, key );
            ret = bson_append_bcon( b, bci.D );
            bson_append_finish_object( b );
            break;
        case 'A':
            bson_append_start_array( b, key );
            ret = bson_append_bcon_array( b, bci.A );
            bson_append_finish_array( b );
            break;
        case 'o': if (*bci.o == '\0') bson_oid_gen( &oid ); else bson_oid_from_string( &oid, bci.o ); bson_append_oid( b, key, &oid ); break;
        case 'b': bson_append_bool( b, key, bci.b ); break;
        case 't': bson_append_time_t( b, key, bci.t ); break;
        case 'v': bson_append_null( b, key ); break; /* void */
        case 'x': bson_append_symbol( b, key, bci.x ); break;
        case 'i': bson_append_int( b, key, bci.i ); break;
        case 'l': bson_append_long( b, key, bci.l ); break;
        default: printf("\nptype:'%c' utype:'%c'\n", ptype, utype); assert(NOT_REACHED); break;
        }
        break;
    case 'R': /* krv(b, key, utype, bci) */
        switch (utype) {
        case 'f': bson_append_double( b, key, *bci.Rf ); break;
        case 's': bson_append_string( b, key, bci.Rs ); break;
        case 'D':
            bson_append_start_object( b, key );
            ret = bson_append_bcon( b, bci.RD );
            bson_append_finish_object( b );
            break;
        case 'A':
            bson_append_start_array( b, key );
            ret = bson_append_bcon_array( b, bci.RA );
            bson_append_finish_array( b );
            break;
        case 'o': if (*bci.o == '\0') bson_oid_gen( &oid ); else bson_oid_from_string( &oid, bci.o ); bson_append_oid( b, key, &oid ); break;
        case 'b': bson_append_bool( b, key, *bci.Rb ); break;
        case 't': bson_append_time_t( b, key, *bci.Rt ); break;
        case 'x': bson_append_symbol( b, key, bci.Rx ); break;
        case 'i': bson_append_int( b, key, *bci.Ri ); break;
        case 'l': bson_append_long( b, key, *bci.Rl ); break;
        default: printf("\nptype:'%c' utype:'%c'\n", ptype, utype); assert(NOT_REACHED); break;
        }
        break;
    case 'P': /* kpv(b, key, utype, bci) */
        if (*bci.Pv != 0) {
            switch (utype) {
            case 'f': bson_append_double( b, key, **bci.Pf ); break;
            case 's': bson_append_string( b, key, *bci.Ps ); break;
            case 'D':
                bson_append_start_object( b, key );
                ret = bson_append_bcon( b, *bci.PD );
                bson_append_finish_object( b );
                break;
            case 'A':
                bson_append_start_array( b, key );
                ret = bson_append_bcon_array( b, *bci.PA );
                bson_append_finish_array( b );
                break;
            case 'o': if (**bci.Po == '\0') bson_oid_gen( &oid );
                else bson_oid_from_string( &oid, *bci.Po );
                bson_append_oid( b, key, &oid );
                break;
            case 'b': bson_append_bool( b, key, **bci.Pb ); break;
            case 't': bson_append_time_t( b, key, **bci.Pt ); break;
            case 'x': if (*bci.Px != 0) bson_append_symbol( b, key, *bci.Px ); break;
            case 'i': bson_append_int( b, key, **bci.Pi ); break;
            case 'l': bson_append_long( b, key, **bci.Pl ); break;
            default: printf("\nptype:'%c' utype:'%c'\n", ptype, utype); assert(NOT_REACHED); break;
            }
        }
        break;
    default:
        printf("\nptype:'%c' utype:'%c'\n", ptype, utype); assert(NOT_REACHED);
        break;
    }
    return ret;
}
Пример #20
0
static void log_int64(bson *b, const char *idx, int64_t value)
{
    bson_append_long(b, idx, value);
}
Пример #21
0
static void
ngx_wirte_tracking_into_mongodb(ngx_http_request_t *r,
                                ngx_http_vesb_aio_log_main_conf_t *valcf,ngx_http_vesb_aio_log_loc_conf_t *vallcf,int timeuse)
{
    mongo                     conn[1];
    char                      *conn_str;
    int                       port,status,insertstatus;
    time_t                    timenow;
    ngx_list_part_t 		      *part = &r->headers_in.headers.part;
    ngx_table_elt_t 		      *header = part->elts;
    ngx_uint_t				        i;

    if(r->headers_out.status == NGX_HTTP_OK)
    {
        conn_str = (char *)valcf->mongodb_conn_str.data;
        port = (int)valcf->mongodb_conn_port;
        status = mongo_client( conn, conn_str, port );
        if( status == MONGO_OK ) {
            mongo_set_op_timeout( conn, 10000 );//time oust 10000 ms
            time ( &timenow );
            bson b[1];
            bson_init( b );
            bson_append_new_oid( b, "_id" );

            if( r->headers_in.x_forwarded_for == NULL )
            {
                bson_append_string_n( b, "realclientip" , (char *)r->connection->addr_text.data, r->connection->addr_text.len);
            }
            else
            {
                bson_append_string_n( b, "realclientip" , (char *)r->headers_in.x_forwarded_for->value.data,r->headers_in.x_forwarded_for->value.len);
            }

            bson_append_int( b,"statuscode",r->headers_out.status);
            bson_append_int( b,"usetime",timeuse);
            bson_append_long( b,"requestsize",r->request_length);
            bson_append_long( b,"responsesize",r->headers_out.content_length_n);
            bson_append_time_t( b,"invoketime",timenow );


            if(vallcf->app_name.data != NULL)
            {
                bson_append_string_n( b,"appname",(char *)vallcf->app_name.data,vallcf->app_name.len);
            }
            else
            {
                bson_append_string( b,"appname","undefine");
            }

            /*get method name*/
            for(i=0;/* void */; ++i)
            {
                if(i >= part->nelts)
                {
                    if(part->next == NULL)
                    {
                        break;
                    }

                    part = part->next;
                    header = part->elts;
                    i=0;
                }

                if(header[i].hash == 0)
                {
                    continue;
                }

                if(ngx_strstr(header[i].key.data,"SOAPAction") != NULL)
                {
                    bson_append_string_n( b,"SOAPAction",(char *)header[i].value.data,header[i].value.len);
                }
                else if(ngx_strstr(header[i].key.data,"Content-Type") != NULL)
                {
                    bson_append_string_n( b,"Content-Type",(char *)header[i].value.data,header[i].value.len);
                }
            }


            bson_finish( b );
            insertstatus = mongo_insert( conn,"vesb.tracking", b , NULL );

            if( insertstatus != MONGO_OK ) {
                ngx_log_error(NGX_LOG_NOTICE, r->connection->log, 0, "insert tracking log in mongodb is failed!(error:%d)",conn[0].err);
            }
            bson_destroy( b );
        }
        else
        {
            ngx_log_error(NGX_LOG_NOTICE, r->connection->log, 0, "mongodb is unconnection!(error:%d)",status);
        }

        mongo_destroy( conn );

    }
}
Пример #22
0
/**
 * \brief This function save current version o tag group to MongoDB
 */
static void vs_mongo_taggroup_save_version(struct VSTagGroup *tg,
		bson *bson_tg,
		uint32 version)
{
	bson bson_version;
	bson bson_tag;
	struct VBucket *bucket;
	struct VSTag *tag;
	char str_num[15];
	int item_id;

	bson_init(&bson_version);

	bson_append_int(&bson_version, "crc32", tg->crc32);

	bson_append_start_object(&bson_version, "tags");

	bucket = tg->tags.lb.first;
	while(bucket != NULL) {
		tag = (struct VSTag*)bucket->data;

		bson_init(&bson_tag);
		bson_append_int(&bson_tag, "data_type", tag->data_type);
		bson_append_int(&bson_tag, "count", tag->count);
		bson_append_int(&bson_tag, "custom_type", tag->custom_type);

		bson_append_start_array(&bson_tag, "data");
		switch(tag->data_type) {
		case VRS_VALUE_TYPE_UINT8:
			for(item_id = 0; item_id < tag->count; item_id++) {
				sprintf(str_num, "%d", item_id);
				bson_append_int(&bson_tag, str_num, ((uint8*)tag->value)[item_id]);
			}
			break;
		case VRS_VALUE_TYPE_UINT16:
			for(item_id = 0; item_id < tag->count; item_id++) {
				sprintf(str_num, "%d", item_id);
				bson_append_int(&bson_tag, str_num, ((uint16*)tag->value)[item_id]);
			}
			break;
		case VRS_VALUE_TYPE_UINT32:
			for(item_id = 0; item_id < tag->count; item_id++) {
				sprintf(str_num, "%d", item_id);
				bson_append_int(&bson_tag, str_num, ((uint32*)tag->value)[item_id]);
			}
			break;
		case VRS_VALUE_TYPE_UINT64:
			for(item_id = 0; item_id < tag->count; item_id++) {
				sprintf(str_num, "%d", item_id);
				bson_append_long(&bson_tag, str_num, ((uint64*)tag->value)[item_id]);
			}
			break;
		case VRS_VALUE_TYPE_REAL16:
			/* TODO */
			break;
		case VRS_VALUE_TYPE_REAL32:
			for(item_id = 0; item_id < tag->count; item_id++) {
				sprintf(str_num, "%d", item_id);
				bson_append_double(&bson_tag, str_num, ((float*)tag->value)[item_id]);
			}
			break;
		case VRS_VALUE_TYPE_REAL64:
			for(item_id = 0; item_id < tag->count; item_id++) {
				sprintf(str_num, "%d", item_id);
				bson_append_double(&bson_tag, str_num, ((double*)tag->value)[item_id]);
			}
			break;
		case VRS_VALUE_TYPE_STRING8:
			bson_append_string(&bson_tag, "0", (char*)tag->value);
			break;
		}
		bson_append_finish_array(&bson_tag);

		bson_finish(&bson_tag);

		sprintf(str_num, "%d", tag->id);
		bson_append_bson(&bson_version, str_num, &bson_tag);

		bucket = bucket->next;
	}

	bson_append_finish_object(&bson_version);

	bson_finish(&bson_version);

	sprintf(str_num, "%u", version);
	bson_append_bson(bson_tg, str_num, &bson_version);
}
Пример #23
0
int test_bson_generic( void ) {

   bson_iterator it, it2, it3;
   bson_oid_t oid;
   bson_timestamp_t ts;
   bson_timestamp_t ts_result;
   bson b[1];
   bson copy[1];
   bson scope[1];

   ts.i = 1;
   ts.t = 2;

   bson_init( b );
   bson_append_double( b, "d", 3.14 );
   bson_append_string( b, "s", "hello" );
   bson_append_string_n( b, "s_n", "goodbye cruel world", 7 );

   {
       bson_append_start_object( b, "o" );
       bson_append_start_array( b, "a" );
       bson_append_binary( b, "0", 8, "w\0rld", 5 );
       bson_append_finish_object( b );
       bson_append_finish_object( b );
   }

   bson_append_undefined( b, "u" );

   bson_oid_from_string( &oid, "010203040506070809101112" );
   ASSERT( !memcmp( oid.bytes, "\x001\x002\x003\x004\x005\x006\x007\x008\x009\x010\x011\x012", 12 ) );
   bson_append_oid( b, "oid", &oid );

   bson_append_bool( b, "b", 1 );
   bson_append_date( b, "date", 0x0102030405060708 );
   bson_append_null( b, "n" );
   bson_append_regex( b, "r", "^asdf", "imx" );
   /* no dbref test (deprecated) */
   bson_append_code( b, "c", "function(){}" );
   bson_append_code_n( b, "c_n", "function(){}garbage", 12 );
   bson_append_symbol( b, "symbol", "symbol" );
   bson_append_symbol_n( b, "symbol_n", "symbol and garbage", 6 );

   {
       bson_init( scope );
       bson_append_int( scope, "i", 123 );
       bson_finish( scope );

       bson_append_code_w_scope( b, "cws", "function(){return i}", scope );
       bson_destroy( scope );
   }

   bson_append_timestamp( b, "timestamp", &ts );
   bson_append_long( b, "l", 0x1122334455667788 );

   /* Ensure that we can't copy a non-finished object. */
   ASSERT( bson_copy( copy, b ) == BSON_ERROR );

   bson_finish( b );

   ASSERT( b->err == BSON_VALID );

   /* Test append after finish. */
   ASSERT( bson_append_string( b, "foo", "bar" ) == BSON_ERROR );
   ASSERT( b->err & BSON_ALREADY_FINISHED );

   ASSERT( bson_copy( copy, b ) == BSON_OK );

   ASSERT( 1 == copy->finished );
   ASSERT( 0 == copy->err );

   bson_destroy( copy );

   bson_print( b );

   bson_iterator_init( &it, b );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_DOUBLE );
   ASSERT( bson_iterator_type( &it ) == BSON_DOUBLE );
   ASSERT( !strcmp( bson_iterator_key( &it ), "d" ) );
   ASSERT( bson_iterator_double( &it ) == 3.14 );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_STRING );
   ASSERT( bson_iterator_type( &it ) == BSON_STRING );
   ASSERT( !strcmp( bson_iterator_key( &it ), "s" ) );
   ASSERT( !strcmp( bson_iterator_string( &it ), "hello" ) );
   ASSERT( strcmp( bson_iterator_string( &it ), "" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_STRING );
   ASSERT( bson_iterator_type( &it ) == BSON_STRING );
   ASSERT( !strcmp( bson_iterator_key( &it ), "s_n" ) );
   ASSERT( !strcmp( bson_iterator_string( &it ), "goodbye" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_OBJECT );
   ASSERT( bson_iterator_type( &it ) == BSON_OBJECT );
   ASSERT( !strcmp( bson_iterator_key( &it ), "o" ) );
   bson_iterator_subiterator( &it, &it2 );

   ASSERT( bson_iterator_more( &it2 ) );
   ASSERT( bson_iterator_next( &it2 ) == BSON_ARRAY );
   ASSERT( bson_iterator_type( &it2 ) == BSON_ARRAY );
   ASSERT( !strcmp( bson_iterator_key( &it2 ), "a" ) );
   bson_iterator_subiterator( &it2, &it3 );

   ASSERT( bson_iterator_more( &it3 ) );
   ASSERT( bson_iterator_next( &it3 ) == BSON_BINDATA );
   ASSERT( bson_iterator_type( &it3 ) == BSON_BINDATA );
   ASSERT( !strcmp( bson_iterator_key( &it3 ), "0" ) );
   ASSERT( bson_iterator_bin_type( &it3 ) == 8 );
   ASSERT( bson_iterator_bin_len( &it3 ) == 5 );
   ASSERT( !memcmp( bson_iterator_bin_data( &it3 ), "w\0rld", 5 ) );

   ASSERT( bson_iterator_more( &it3 ) );
   ASSERT( bson_iterator_next( &it3 ) == BSON_EOO );
   ASSERT( bson_iterator_type( &it3 ) == BSON_EOO );
   ASSERT( !bson_iterator_more( &it3 ) );

   ASSERT( bson_iterator_more( &it2 ) );
   ASSERT( bson_iterator_next( &it2 ) == BSON_EOO );
   ASSERT( bson_iterator_type( &it2 ) == BSON_EOO );
   ASSERT( !bson_iterator_more( &it2 ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_UNDEFINED );
   ASSERT( bson_iterator_type( &it ) == BSON_UNDEFINED );
   ASSERT( !strcmp( bson_iterator_key( &it ), "u" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_OID );
   ASSERT( bson_iterator_type( &it ) == BSON_OID );
   ASSERT( !strcmp( bson_iterator_key( &it ), "oid" ) );
   ASSERT( !memcmp( bson_iterator_oid( &it )->bytes, "\x001\x002\x003\x004\x005\x006\x007\x008\x009\x010\x011\x012", 12 ) );
   ASSERT( bson_iterator_oid( &it )->ints[0] == oid.ints[0] );
   ASSERT( bson_iterator_oid( &it )->ints[1] == oid.ints[1] );
   ASSERT( bson_iterator_oid( &it )->ints[2] == oid.ints[2] );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_BOOL );
   ASSERT( bson_iterator_type( &it ) == BSON_BOOL );
   ASSERT( !strcmp( bson_iterator_key( &it ), "b" ) );
   ASSERT( bson_iterator_bool( &it ) == 1 );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_DATE );
   ASSERT( bson_iterator_type( &it ) == BSON_DATE );
   ASSERT( !strcmp( bson_iterator_key( &it ), "date" ) );
   ASSERT( bson_iterator_date( &it ) == 0x0102030405060708 );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_NULL );
   ASSERT( bson_iterator_type( &it ) == BSON_NULL );
   ASSERT( !strcmp( bson_iterator_key( &it ), "n" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_REGEX );
   ASSERT( bson_iterator_type( &it ) == BSON_REGEX );
   ASSERT( !strcmp( bson_iterator_key( &it ), "r" ) );
   ASSERT( !strcmp( bson_iterator_regex( &it ), "^asdf" ) );
   ASSERT( !strcmp( bson_iterator_regex_opts( &it ), "imx" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_CODE );
   ASSERT( bson_iterator_type( &it ) == BSON_CODE );
   ASSERT( !strcmp( bson_iterator_code(&it), "function(){}") );
   ASSERT( !strcmp( bson_iterator_key( &it ), "c" ) );
   ASSERT( !strcmp( bson_iterator_string( &it ), "" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_CODE );
   ASSERT( bson_iterator_type( &it ) == BSON_CODE );
   ASSERT( !strcmp( bson_iterator_key( &it ), "c_n" ) );
   ASSERT( !strcmp( bson_iterator_string( &it ), "" ) );
   ASSERT( !strcmp( bson_iterator_code( &it ), "function(){}" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_SYMBOL );
   ASSERT( bson_iterator_type( &it ) == BSON_SYMBOL );
   ASSERT( !strcmp( bson_iterator_key( &it ), "symbol" ) );
   ASSERT( !strcmp( bson_iterator_string( &it ), "symbol" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_SYMBOL );
   ASSERT( bson_iterator_type( &it ) == BSON_SYMBOL );
   ASSERT( !strcmp( bson_iterator_key( &it ), "symbol_n" ) );
   ASSERT( !strcmp( bson_iterator_string( &it ), "symbol" ) );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_CODEWSCOPE );
   ASSERT( bson_iterator_type( &it ) == BSON_CODEWSCOPE );
   ASSERT( !strcmp( bson_iterator_key( &it ), "cws" ) );
   ASSERT( !strcmp( bson_iterator_code( &it ), "function(){return i}" ) );

   {
       bson scope;
       bson_iterator_code_scope( &it, &scope );
       bson_iterator_init( &it2, &scope );

       ASSERT( bson_iterator_more( &it2 ) );
       ASSERT( bson_iterator_next( &it2 ) == BSON_INT );
       ASSERT( bson_iterator_type( &it2 ) == BSON_INT );
       ASSERT( !strcmp( bson_iterator_key( &it2 ), "i" ) );
       ASSERT( bson_iterator_int( &it2 ) == 123 );

       ASSERT( bson_iterator_more( &it2 ) );
       ASSERT( bson_iterator_next( &it2 ) == BSON_EOO );
       ASSERT( bson_iterator_type( &it2 ) == BSON_EOO );
       ASSERT( !bson_iterator_more( &it2 ) );
   }

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_TIMESTAMP );
   ASSERT( bson_iterator_type( &it ) == BSON_TIMESTAMP );
   ASSERT( !strcmp( bson_iterator_key( &it ), "timestamp" ) );
   ts_result = bson_iterator_timestamp( &it );
   ASSERT( ts_result.i == 1 );
   ASSERT( ts_result.t == 2 );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_LONG );
   ASSERT( bson_iterator_type( &it ) == BSON_LONG );
   ASSERT( !strcmp( bson_iterator_key( &it ), "l" ) );
   ASSERT( bson_iterator_long( &it ) == 0x1122334455667788 );

   ASSERT( bson_iterator_more( &it ) );
   ASSERT( bson_iterator_next( &it ) == BSON_EOO );
   ASSERT( bson_iterator_type( &it ) == BSON_EOO );
   ASSERT( !bson_iterator_more( &it ) );

   bson_destroy( b );

   {
       bson bsrc[1];
       bson_init( bsrc );
       bson_append_double( bsrc, "d", 3.14 );
       bson_finish( bsrc );
       ASSERT( bsrc->err == BSON_VALID );
       bson_init( b );
       bson_append_double( b, "", 3.14 ); /* test empty name (in general) */
       bson_iterator_init( &it, bsrc );
       ASSERT( bson_iterator_more( &it ) );
       ASSERT( bson_iterator_next( &it ) == BSON_DOUBLE );
       ASSERT( bson_iterator_type( &it ) == BSON_DOUBLE );
       bson_append_element( b, "d", &it );
       bson_append_element( b, 0, &it ); /* test null */
       bson_append_element( b, "", &it ); /* test empty name */
       bson_finish( b );
       ASSERT( b->err == BSON_VALID );
       /* bson_print( b ); */
       bson_iterator_init( &it, b );
       ASSERT( bson_iterator_more( &it ) );
       ASSERT( bson_iterator_next( &it ) == BSON_DOUBLE );
       ASSERT( !strcmp( bson_iterator_key( &it ), "" ) );
       ASSERT( bson_iterator_double( &it ) == 3.14 );
       ASSERT( bson_iterator_more( &it ) );
       ASSERT( bson_iterator_next( &it ) == BSON_DOUBLE );
       ASSERT( !strcmp( bson_iterator_key( &it ), "d" ) );
       ASSERT( bson_iterator_double( &it ) == 3.14 );
       ASSERT( bson_iterator_more( &it ) );
       ASSERT( bson_iterator_next( &it ) == BSON_DOUBLE );
       ASSERT( !strcmp( bson_iterator_key( &it ), "d" ) );
       ASSERT( bson_iterator_double( &it ) == 3.14 );
       ASSERT( bson_iterator_more( &it ) );
       ASSERT( bson_iterator_next( &it ) == BSON_DOUBLE );
       ASSERT( !strcmp( bson_iterator_key( &it ), "" ) );
       ASSERT( bson_iterator_double( &it ) == 3.14 );
       ASSERT( bson_iterator_more( &it ) );
       ASSERT( bson_iterator_next( &it ) == BSON_EOO );
       ASSERT( !bson_iterator_more( &it ) );
       bson_destroy( bsrc );
       bson_destroy( b );
   }

   return 0;
}
Пример #24
0
INLINE void v_to_bson P3(bson *, out, char *, k, svalue_t *, v)
{
    switch(v->type) {
    case T_STRING:
    {
    	if(!strcmp(k,"_id") && strlen(v->u.string) == 24){
    		bson_oid_t oid[1];
    		bson_oid_from_string(oid,v->u.string);
    		bson_append_oid(out,k,oid);
    	}else{
    		bson_append_string(out,k,v->u.string);
    	}
	    return;
	}
    case T_CLASS:
    {
    	bson_append_string(out,k,"CLASS");
	    return;
	}
    case T_NUMBER:
    {
		bson_append_long(out,k,v->u.number);
	    return;
	}
    case T_REAL:
    {
		bson_append_double(out,k,v->u.real);
	    return;
	}
    case T_ARRAY:
	{
		int i;
		int size;
		char buf[20];
	    size = v->u.arr->size;
	    svalue_t *sv = v->u.arr->item;
	    bson_append_start_array(out, k);
	    for(i=0; i<size; i++) {
	    	sprintf(buf,"%d",i);
	    	v_to_bson(out,buf,sv++);
	    }
	    bson_append_finish_array( out );
	    return;
	}
    case T_MAPPING:
	{
		char num[25];
	    int j = v->u.map->table_size;
	    mapping_node_t **a = v->u.map->table, *elt;
	    bson_append_start_object(out, k);
	    do {
		for (elt = a[j]; elt; elt = elt = elt->next) {
			if(elt->values->type == T_STRING){
				v_to_bson(out,elt->values->u.string,elt->values+1);
			}else if(elt->values->type == T_NUMBER){
				sprintf(num,"%ld",v->u.number);
				v_to_bson(out,num,elt->values+1);
			}else{
				continue;
			}
		}
	    } while (j--);
	    bson_append_finish_object( out );
	    return;
	}
    }
}
Пример #25
0
int main(int argc, char *argv[])
{
    bson_buffer bb;
    bson b;
    bson_iterator it, it2, it3;
    bson_oid_t oid;

    bson_buffer_init(&bb);
    bson_append_double(&bb, "d", 3.14);
    bson_append_string(&bb, "s", "hello");

    {
        bson_buffer *obj = bson_append_start_object(&bb, "o");
        bson_buffer *arr = bson_append_start_array(obj, "a");
        bson_append_binary(arr, "0", 8, "w\0rld", 5);
        bson_append_finish_object(arr);
        bson_append_finish_object(obj);
    }

    bson_append_undefined(&bb, "u");

    bson_oid_from_string(&oid, "010203040506070809101112");
    ASSERT(!memcmp(oid.bytes, "\x001\x002\x003\x004\x005\x006\x007\x008\x009\x010\x011\x012", 12));
    bson_append_oid(&bb, "oid", &oid);

    bson_append_bool(&bb, "b", 1);
    bson_append_date(&bb, "date", 0x0102030405060708ULL);
    bson_append_null(&bb, "n");
    bson_append_regex(&bb, "r", "^asdf", "imx");
    /* no dbref test (deprecated) */
    bson_append_code(&bb, "c", "function(){}");
    bson_append_symbol(&bb, "symbol", "SYMBOL");

    {
        bson_buffer scope_buf;
        bson scope;
        bson_buffer_init(&scope_buf);
        bson_append_int(&scope_buf, "i", 123);
        bson_from_buffer(&scope, &scope_buf);

        bson_append_code_w_scope(&bb, "cws", "function(){return i}", &scope);
        bson_destroy(&scope);
    }

    /* no timestamp test (internal) */
    bson_append_long(&bb, "l", 0x1122334455667788ULL);

    bson_from_buffer(&b, &bb);

    bson_iterator_init(&it, b.data);
    
    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_double);
    ASSERT(bson_iterator_type(&it) == bson_double);
    ASSERT(!strcmp(bson_iterator_key(&it), "d"));
    ASSERT(bson_iterator_double(&it) == 3.14);

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_string);
    ASSERT(bson_iterator_type(&it) == bson_string);
    ASSERT(!strcmp(bson_iterator_key(&it), "s"));
    ASSERT(!strcmp(bson_iterator_string(&it), "hello"));

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_object);
    ASSERT(bson_iterator_type(&it) == bson_object);
    ASSERT(!strcmp(bson_iterator_key(&it), "o"));
    bson_iterator_subiterator(&it, &it2);

    ASSERT(bson_iterator_more(&it2));
    ASSERT(bson_iterator_next(&it2) == bson_array);
    ASSERT(bson_iterator_type(&it2) == bson_array);
    ASSERT(!strcmp(bson_iterator_key(&it2), "a"));
    bson_iterator_subiterator(&it2, &it3);

    ASSERT(bson_iterator_more(&it3));
    ASSERT(bson_iterator_next(&it3) == bson_bindata);
    ASSERT(bson_iterator_type(&it3) == bson_bindata);
    ASSERT(!strcmp(bson_iterator_key(&it3), "0"));
    ASSERT(bson_iterator_bin_type(&it3) == 8);
    ASSERT(bson_iterator_bin_len(&it3) == 5);
    ASSERT(!memcmp(bson_iterator_bin_data(&it3), "w\0rld", 5));
    
    ASSERT(bson_iterator_more(&it3));
    ASSERT(bson_iterator_next(&it3) == bson_eoo);
    ASSERT(bson_iterator_type(&it3) == bson_eoo);
    ASSERT(!bson_iterator_more(&it3));

    ASSERT(bson_iterator_more(&it2));
    ASSERT(bson_iterator_next(&it2) == bson_eoo);
    ASSERT(bson_iterator_type(&it2) == bson_eoo);
    ASSERT(!bson_iterator_more(&it2));

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_undefined);
    ASSERT(bson_iterator_type(&it) == bson_undefined);
    ASSERT(!strcmp(bson_iterator_key(&it), "u"));


    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_oid);
    ASSERT(bson_iterator_type(&it) == bson_oid);
    ASSERT(!strcmp(bson_iterator_key(&it), "oid"));
    ASSERT(!memcmp(bson_iterator_oid(&it)->bytes, "\x001\x002\x003\x004\x005\x006\x007\x008\x009\x010\x011\x012", 12));
    ASSERT(bson_iterator_oid(&it)->ints[0] == oid.ints[0]);
    ASSERT(bson_iterator_oid(&it)->ints[1] == oid.ints[1]);
    ASSERT(bson_iterator_oid(&it)->ints[2] == oid.ints[2]);

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_bool);
    ASSERT(bson_iterator_type(&it) == bson_bool);
    ASSERT(!strcmp(bson_iterator_key(&it), "b"));
    ASSERT(bson_iterator_bool(&it) == 1);

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_date);
    ASSERT(bson_iterator_type(&it) == bson_date);
    ASSERT(!strcmp(bson_iterator_key(&it), "date"));
    ASSERT(bson_iterator_date(&it) == 0x0102030405060708ULL);

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_null);
    ASSERT(bson_iterator_type(&it) == bson_null);
    ASSERT(!strcmp(bson_iterator_key(&it), "n"));

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_regex);
    ASSERT(bson_iterator_type(&it) == bson_regex);
    ASSERT(!strcmp(bson_iterator_key(&it), "r"));
    ASSERT(!strcmp(bson_iterator_regex(&it), "^asdf"));
    ASSERT(!strcmp(bson_iterator_regex_opts(&it), "imx"));

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_code);
    ASSERT(bson_iterator_type(&it) == bson_code);
    ASSERT(!strcmp(bson_iterator_key(&it), "c"));
    ASSERT(!strcmp(bson_iterator_string(&it), "function(){}"));
    ASSERT(!strcmp(bson_iterator_code(&it), "function(){}"));

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_symbol);
    ASSERT(bson_iterator_type(&it) == bson_symbol);
    ASSERT(!strcmp(bson_iterator_key(&it), "symbol"));
    ASSERT(!strcmp(bson_iterator_string(&it), "SYMBOL"));

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_codewscope);
    ASSERT(bson_iterator_type(&it) == bson_codewscope);
    ASSERT(!strcmp(bson_iterator_key(&it), "cws"));
    ASSERT(!strcmp(bson_iterator_code(&it), "function(){return i}"));

    {
        bson scope;
        bson_iterator_code_scope(&it, &scope);
        bson_iterator_init(&it2, scope.data);

        ASSERT(bson_iterator_more(&it2));
        ASSERT(bson_iterator_next(&it2) == bson_int);
        ASSERT(bson_iterator_type(&it2) == bson_int);
        ASSERT(!strcmp(bson_iterator_key(&it2), "i"));
        ASSERT(bson_iterator_int(&it2) == 123);

        ASSERT(bson_iterator_more(&it2));
        ASSERT(bson_iterator_next(&it2) == bson_eoo);
        ASSERT(bson_iterator_type(&it2) == bson_eoo);
        ASSERT(!bson_iterator_more(&it2));
    }

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_long);
    ASSERT(bson_iterator_type(&it) == bson_long);
    ASSERT(!strcmp(bson_iterator_key(&it), "l"));
    ASSERT(bson_iterator_long(&it) == 0x1122334455667788ULL);

    ASSERT(bson_iterator_more(&it));
    ASSERT(bson_iterator_next(&it) == bson_eoo);
    ASSERT(bson_iterator_type(&it) == bson_eoo);
    ASSERT(!bson_iterator_more(&it));
    
    return 0;
}
Пример #26
0
static void lua_val_to_bson(lua_State *L, const char *key, int vpos, bson *bs, int tref) {
    int vtype = lua_type(L, vpos);
    char nbuf[TCNUMBUFSIZ];
    if (key == NULL && vtype != LUA_TTABLE) {
        luaL_error(L, "lua_val_to_bson: Table must be on top of lua stack");
        return;
    }
    switch (vtype) {
        case LUA_TTABLE:
        {
            if (vpos < 0) {
                vpos = lua_gettop(L) + vpos + 1;
            }
            lua_checkstack(L, 3);
            int bsontype_found = luaL_getmetafield(L, vpos, "__bsontype");
            if (!bsontype_found) {
                lua_rawgeti(L, LUA_REGISTRYINDEX, tref); //+ reg table
                lua_pushvalue(L, vpos); //+ val
                lua_rawget(L, -2); //-val +reg table val
                if (lua_toboolean(L, -1)) { //already traversed
                    lua_pop(L, 2);
                    break;
                }
                lua_pop(L, 1); //-reg table val
                lua_pushvalue(L, vpos);
                lua_pushboolean(L, 1);
                lua_rawset(L, -3);
                lua_pop(L, 1); //-reg table

                int len = 0;
                bool query = false;
                bool array = true;

                if (luaL_getmetafield(L, vpos, "__query")) {
                    lua_pop(L, 1);
                    query = true;
                    array = false;
                }
                if (array) {
                    for (lua_pushnil(L); lua_next(L, vpos); lua_pop(L, 1)) {
                        ++len;
                        if ((lua_type(L, -2) != LUA_TNUMBER) || (lua_tointeger(L, -2) != len)) {
                            lua_pop(L, 2);
                            array = false;
                            break;
                        }
                    }
                }
                if (array) {
                    if (key) bson_append_start_array(bs, key);
                    int i;
                    for (i = 1; i <= len; ++i, lua_pop(L, 1)) {
                        lua_rawgeti(L, vpos, i);
                        bson_numstrn(nbuf, TCNUMBUFSIZ, (int64_t) i);
                        lua_val_to_bson(L, nbuf, -1, bs, tref);
                    }
                    if (key) bson_append_finish_array(bs);
                } else if (query) { //special query builder case
                    //oarr format:
                    //{ {fname1, v1, v2...}, {fname2, v21, v22,..}, ... }
                    //where: vN: {op, val} OR {val} with '__bval' metafield
                    //Eg: {fname : {$inc : {...}, $dec : {...}}} -> {fname, {$inc, {}}, {$dec, {}}}

                    lua_getfield(L, vpos, "_oarr"); //+oarr
                    if (!lua_istable(L, -1)) { //it is not array
                        lua_pop(L, 1);
                        break;
                    }
                    if (key) bson_append_start_object(bs, key);
                    //iterate over _oarr
                    int ipos = lua_gettop(L);
                    size_t ilen = lua_objlen(L, ipos);
                    lua_checkstack(L, 2);
                    size_t i;
                    for (i = 1; i <= ilen; ++i, lua_pop(L, 1)) {
                        lua_rawgeti(L, ipos, i);
                        //gettop == 3
                        if (!lua_istable(L, -1)) continue;
                        char *fname = NULL;
                        int jpos = lua_gettop(L);
                        size_t jlen = lua_objlen(L, jpos);
                        lua_checkstack(L, 3);
                        bool wrapped = false;
                        size_t j;
                        for (j = 1; j <= jlen; ++j, lua_pop(L, 1)) {
                            lua_rawgeti(L, jpos, j);
                            if (j == 1) {
                                fname = strdup(lua_tostring(L, -1));
                                continue;
                            }
                            if (!fname || !lua_istable(L, -1)) { //invalid state
                                lua_pop(L, 1); //pop val
                                break;
                            }
                            int vblkpos = lua_gettop(L);
                            if (j == 2 && luaL_getmetafield(L, -1, "__bval")) { //{val} single value +metafield
                                lua_pop(L, 1); //-metafield
                                lua_rawgeti(L, vblkpos, 1); //+val
                                lua_val_to_bson(L, fname, lua_gettop(L), bs, tref);
                                lua_pop(L, 2); //-val -lua_rawgeti
                                break; //Terminate due single val
                            } else { //{op, val} value
                                if (!wrapped) {
                                    bson_append_start_object(bs, fname);
                                    wrapped = true;
                                }
                                lua_rawgeti(L, vblkpos, 1); //+op
                                const char *op = lua_tostring(L, -1);
                                if (op) {
                                    lua_rawgeti(L, vblkpos, 2); //+val
                                    lua_val_to_bson(L, op, lua_gettop(L), bs, tref);
                                    lua_pop(L, 1); //-val
                                }
                                lua_pop(L, 1); //-op
                            }
                        }
                        if (wrapped) {
                            bson_append_finish_object(bs);
                        }
                        if (fname) {
                            free(fname);
                            fname = NULL;
                        }
                    }
                    if (key) bson_append_finish_object(bs);
                    lua_pop(L, 1); //-oarr
                } else {
                    if (key) bson_append_start_object(bs, key);
                    TCLIST *keys = tclistnew();
                    //we need to sort keys due to unordered nature of lua tables
                    for (lua_pushnil(L); lua_next(L, vpos);) {
                        lua_pop(L, 1); //-val
                        size_t ksize = 0;
                        int ktype = lua_type(L, -1);
                        if (ktype == LUA_TSTRING) { //accept only string keys
                            const char* key = lua_tolstring(L, -1, &ksize);
                            tclistpush(keys, key, ksize);
                        }
                    }
                    tclistsort(keys);
                    int i;
                    for (i = 0; i < TCLISTNUM(keys); ++i) {
                        int vkeysz = TCLISTVALSIZ(keys, i);
                        const char *vkey = TCLISTVALPTR(keys, i);
                        lua_pushlstring(L, vkey, vkeysz);
                        lua_rawget(L, vpos); //+val
                        if (key == NULL && lua_type(L, -1) == LUA_TSTRING &&
                                vkeysz == JDBIDKEYNAMEL && !strcmp(JDBIDKEYNAME, vkey)) { //root level OID as string
                            //pack OID as type table
                            lua_push_bsontype_table(L, BSON_OID); //+type table
                            lua_pushvalue(L, -2); //dup oid(val) on stack
                            lua_rawseti(L, -2, 1); //pop oid val
                            if (ejdbisvalidoidstr(lua_tostring(L, -2))) {
                                lua_val_to_bson(L, vkey, lua_gettop(L), bs, tref);
                            } else {
                                luaL_error(L, "OID _id='%s' is not valid", lua_tostring(L, -2));
                            }
                            lua_pop(L, 1); //-type table
                        } else {
                            lua_val_to_bson(L, vkey, lua_gettop(L), bs, tref);
                        }
                        lua_pop(L, 1); //-val
                    }
                    tclistdel(keys);
                    if (key) bson_append_finish_object(bs);
                }
            } else { //metafield __bsontype on top
                int bson_type = lua_tointeger(L, -1);
                if (!key && bson_type != BSON_OBJECT && bson_type != BSON_ARRAY) {
                    lua_pop(L, 1);
                    luaL_error(L, "Invalid object structure");
                }
                lua_pop(L, 1); //-metafield __bsontype
                lua_rawgeti(L, -1, 1); //get first value
                switch (bson_type) {
                    case BSON_OID:
                    {
                        const char* boid = lua_tostring(L, -1);
                        if (boid && strlen(boid) == 24) {
                            bson_oid_t oid;
                            bson_oid_from_string(&oid, boid);
                            bson_append_oid(bs, key, &oid);
                        }
                        break;
                    }
                    case BSON_DATE:
                        bson_append_date(bs, key, (bson_date_t) lua_tonumber(L, -1));
                        break;
                    case BSON_REGEX:
                    {
                        const char* regex = lua_tostring(L, -1);
                        lua_rawgeti(L, -2, 2); // re opts
                        const char* options = lua_tostring(L, -1);
                        if (regex && options) {
                            bson_append_regex(bs, key, regex, options);
                        }
                        lua_pop(L, 1);
                        break;
                    }
                    case BSON_BINDATA:
                    {
                        size_t len;
                        const char* cbuf = lua_tolstring(L, -1, &len);
                        bson_append_binary(bs, key, BSON_BIN_BINARY, cbuf, len);
                        break;
                    }
                    case BSON_NULL:
                        bson_append_null(bs, key);
                        break;
                    case BSON_UNDEFINED:
                        bson_append_undefined(bs, key);
                        break;
                    case BSON_OBJECT:
                        if (key) bson_append_start_object(bs, key);
                        lua_val_to_bson(L, NULL, vpos, bs, tref);
                        if (key) bson_append_finish_object(bs);
                        break;
                    case BSON_ARRAY:
                        if (key) bson_append_start_array(bs, key);
                        lua_val_to_bson(L, NULL, vpos, bs, tref);
                        if (key) bson_append_finish_array(bs);
                        break;
                    case BSON_DOUBLE:
                        bson_append_double(bs, key, (double) lua_tonumber(L, -1));
                        break;
                    case BSON_INT:
                        bson_append_int(bs, key, (int32_t) lua_tonumber(L, -1));
                        break;
                    case BSON_LONG:
                        bson_append_long(bs, key, (int64_t) lua_tonumber(L, -1));
                        break;
                    case BSON_BOOL:
                        bson_append_bool(bs, key, lua_toboolean(L, -1));
                        break;
                    default:
                        break;
                }
                lua_pop(L, 1); //-1 first value
            }
            break;
        }
        case LUA_TNIL:
            bson_append_null(bs, key);
            break;
        case LUA_TNUMBER:
        {
            lua_Number numval = lua_tonumber(L, vpos);
            if (numval == floor(numval)) {
                int64_t iv = (int64_t) numval;
                if (-(1LL << 31) <= iv && iv <= (1LL << 31)) {
                    bson_append_int(bs, key, iv);
                } else {
                    bson_append_long(bs, key, iv);
                }
            } else {
                bson_append_double(bs, key, numval);
            }
            break;
        }
        case LUA_TBOOLEAN:
            bson_append_bool(bs, key, lua_toboolean(L, vpos));
            break;

        case LUA_TSTRING:
            bson_append_string(bs, key, lua_tostring(L, vpos));
            break;
    }
}
Пример #27
0
EXPORT int  mongo_bson_buffer_append(struct bson_buffer* b, char* name, mxArray* value) {
    size_t numel = mxGetNumberOfElements(value);
    mxClassID cls = mxGetClassID(value);
    bson* _b = (bson*)b;
    mwSize i, j;
    mwSize dims[MAXDIM];
    mwSize ijk[MAXDIM];
    mwSize sizes[MAXDIM];
    mwSize ndims;
    const mwSize *odims;
    int depth = 0;
    int success;
    if (numel == 1) {
        /* Append a single element using the given name */
        switch (cls) {
        case mxLOGICAL_CLASS:
            return (bson_append_bool(_b, name, ((char*)mxGetData(value))[0]) == BSON_OK);
        case mxDOUBLE_CLASS:
            if (mxIsComplex(value))
                return mongo_bson_buffer_append_complex(b, name, mxGetPr(value)[0], mxGetPi(value)[0]);
            else
                return (bson_append_double(_b, name, mxGetPr(value)[0]) == BSON_OK);
        case mxSINGLE_CLASS:
            return (bson_append_double(_b, name, ((float*)mxGetData(value))[0]) == BSON_OK);
        case mxINT8_CLASS:
            return (bson_append_int(_b, name, ((signed char*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT8_CLASS:
            return (bson_append_int(_b, name, ((unsigned char*)mxGetData(value))[0]) == BSON_OK);
        case mxINT16_CLASS:
            return (bson_append_int(_b, name, ((short*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT16_CLASS:
            return (bson_append_int(_b, name, ((unsigned short*)mxGetData(value))[0]) == BSON_OK);
        case mxINT32_CLASS:
            return (bson_append_int(_b, name, ((int*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT32_CLASS:
            return (bson_append_int(_b, name, ((unsigned int*)mxGetData(value))[0]) == BSON_OK);
        case mxINT64_CLASS: ;
        case mxUINT64_CLASS:
            return (bson_append_long(_b, name, ((int64_t*)mxGetData(value))[0]) == BSON_OK);
        default:
            mexPrintf("BsonBuffer:append - Unhandled type: %s\n", mxGetClassName(value));
            return 0;
        }
    }
    success = (bson_append_start_array(_b, name) == BSON_OK);
    odims = mxGetDimensions(value);
    ndims = mxGetNumberOfDimensions(value);
    memcpy(dims, odims, ndims*sizeof(mwSize));
    if (ndims > 1)
        reverse(dims, ndims);
    i = ndims;
    /* calculate offset to multiply each dimension's index by */
    j = 1;
    do {
        i--;
        sizes[i] = j;
        j *= dims[i];
    } while (i > 0);
    if (ndims == 2 && dims[1] == 1)
        ndims--;  /* 1 dimensional row vector */
    if (ndims > 1) {
        /* reverse row and columns */
        j = dims[ndims-1];
        dims[ndims-1] = dims[ndims-2];
        dims[ndims-2] = j;
        j = sizes[ndims-1];
        sizes[ndims-1] = sizes[ndims-2];
        sizes[ndims-2] = j;
    }
    memset(ijk, 0, ndims * sizeof(mwSize));
    while (success && depth >= 0) {
        if (ijk[depth] < dims[depth]) {
            const char* num = numstr((int)(ijk[depth]++));
            if (depth < (int)(ndims - 1)) {
                depth++;
                success = (bson_append_start_array(_b, num) == BSON_OK);
            }
            else {
                i = 0;
                for (j = 0; j < ndims; j++)
                    i += (ijk[j]-1) * sizes[j];
                switch (cls) {
                case mxLOGICAL_CLASS:
                    success = (bson_append_bool(_b, num, ((char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxDOUBLE_CLASS:
                    if (mxIsComplex(value))
                        success = mongo_bson_buffer_append_complex(b, num, mxGetPr(value)[i], mxGetPi(value)[i]);
                    else
                        success = (bson_append_double(_b, num, mxGetPr(value)[i]) == BSON_OK);
                    break;
                case mxSINGLE_CLASS:
                    success = (bson_append_double(_b, num, ((float*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT8_CLASS:
                    success = (bson_append_int(_b, num, ((signed char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT8_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT16_CLASS:
                    success = (bson_append_int(_b, num, ((short*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT16_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned short*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT32_CLASS:
                    success = (bson_append_int(_b, num, ((int*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT32_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned int*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT64_CLASS: ;
                case mxUINT64_CLASS:
                    success = (bson_append_long(_b, num, ((int64_t*)mxGetData(value))[i]) == BSON_OK);
                    break;
                default:
                    mexPrintf("BsonBuffer:append - Unhandled type: %s\n", mxGetClassName(value));
                    return 0;
                }
            }
        }
        else {
            ijk[depth] = 0;
            success = (bson_append_finish_object(_b) == BSON_OK);
            depth--;
        }
    }
    return success;
}
Пример #28
0
void MongodbObject::AddInt64(const String &fieldname, int64 value)
{
    BSON_VERIFY(bson_append_long(objectData->object, fieldname.c_str(), value));
}