Exemplo n.º 1
0
static void event_callback (struct em_event* e)
{
	const unsigned long a1 = e->a1;
	int a2 = e->a2;
	const char *a3 = e->a3;
	const unsigned long a4 = e->a4;

	if (a2 == EM_CONNECTION_READ) {
		VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
		VALUE q = rb_hash_aref (t, ULONG2NUM (a1));
		if (q == Qnil)
			rb_raise (EM_eConnectionNotBound, "received %d bytes of data for unknown signature: %lu", a4, a1);
		rb_funcall (q, Intern_receive_data, 1, rb_str_new (a3, a4));
	}
	else if (a2 == EM_CONNECTION_NOTIFY_READABLE) {
		VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
		VALUE q = rb_hash_aref (t, ULONG2NUM (a1));
		if (q == Qnil)
			rb_raise (EM_eConnectionNotBound, "unknown connection: %lu", a1);
		rb_funcall (q, Intern_notify_readable, 0);
	}
	else if (a2 == EM_CONNECTION_NOTIFY_WRITABLE) {
		VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
		VALUE q = rb_hash_aref (t, ULONG2NUM (a1));
		if (q == Qnil)
			rb_raise (EM_eConnectionNotBound, "unknown connection: %lu", a1);
		rb_funcall (q, Intern_notify_writable, 0);
	}
	else if (a2 == EM_LOOPBREAK_SIGNAL) {
		rb_funcall (EmModule, Intern_run_deferred_callbacks, 0);
	}
	else if (a2 == EM_TIMER_FIRED) {
		VALUE t = rb_ivar_get (EmModule, Intern_at_timers);
		VALUE q = rb_funcall (t, Intern_delete, 1, ULONG2NUM (a4));
		if (q == Qnil) {
			rb_raise (EM_eUnknownTimerFired, "no such timer: %lu", a4);
		} else if (q == Qfalse) {
			/* Timer Canceled */
		} else {
			rb_funcall (q, Intern_call, 0);
		}
	}
	#ifdef WITH_SSL
	else if (a2 == EM_SSL_HANDSHAKE_COMPLETED) {
		VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
		VALUE q = rb_hash_aref (t, ULONG2NUM (a1));
		if (q == Qnil)
			rb_raise (EM_eConnectionNotBound, "unknown connection: %lu", a1);
		rb_funcall (q, Intern_ssl_handshake_completed, 0);
	}
	else if (a2 == EM_SSL_VERIFY) {
		VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
		VALUE q = rb_hash_aref (t, ULONG2NUM (a1));
		if (q == Qnil)
			rb_raise (EM_eConnectionNotBound, "unknown connection: %lu", a1);
		VALUE r = rb_funcall (q, Intern_ssl_verify_peer, 1, rb_str_new(a3, a4));
		if (RTEST(r))
			evma_accept_ssl_peer (a1);
	}
	#endif
	else if (a2 == EM_PROXY_TARGET_UNBOUND) {
		VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
		VALUE q = rb_hash_aref (t, ULONG2NUM (a1));
		if (q == Qnil)
			rb_raise (EM_eConnectionNotBound, "unknown connection: %lu", a1);
		rb_funcall (q, Intern_proxy_target_unbound, 0);
	}
	else
		rb_funcall (EmModule, Intern_event_callback, 3, ULONG2NUM(a1), INT2FIX(a2), a3 ? rb_str_new(a3,a4) : ULONG2NUM(a4));
}
Exemplo n.º 2
0
void make_graphcommand(char *command, VALUE hash)
{
  VALUE val;
  if (TYPE(hash) == T_STRING) {
    sprintf(command, "graph -T X -g 3 %s", STR2CSTR(hash));
    return;
  }
    
  strcpy(command, "graph");
  if (TYPE(hash) != T_HASH) rb_raise(rb_eTypeError, 
				     "wrong argument type %s (Hash expected)",
				     rb_class2name(CLASS_OF(hash)));
  if ((val = rb_hash_aref(hash, rb_str_new2("T"))) != Qnil)
    sprintf(command, "%s -T %s", command, STR2CSTR(val));
  else
    sprintf(command, "%s -T X", command);

  val = rb_hash_aref(hash, rb_str_new2("C"));
  if (val == Qtrue)
    sprintf(command, "%s -C", command);

  if ((val = rb_hash_aref(hash, rb_str_new2("g"))) != Qnil)
    sprintf(command, "%s -g %d", command, (int) FIX2INT(val));
  else
    sprintf(command, "%s -g 3", command);

  if ((val = rb_hash_aref(hash, rb_str_new2("B"))) == Qtrue)
    sprintf(command, "%s -B", command);
  if ((val = rb_hash_aref(hash, rb_str_new2("E"))) != Qnil)
    sprintf(command, "%s -E %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("f"))) != Qnil)
    sprintf(command, "%s -f %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("F"))) != Qnil)
    sprintf(command, "%s -F %s", command, STR2CSTR(val));

  if ((val = rb_hash_aref(hash, rb_str_new2("h"))) != Qnil)
    sprintf(command, "%s -h %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("k"))) != Qnil)
    sprintf(command, "%s -k %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("K"))) != Qnil)
    sprintf(command, "%s -K %d", command, (int) FIX2INT(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("l"))) != Qnil) {
    if (str_tail_grep(STR2CSTR(val), "xy") || str_tail_grep(STR2CSTR(val), "x/y"))
      sprintf(command, "%s -l x -l y", command);
    else
      sprintf(command, "%s -l %s", command, STR2CSTR(val));
  }

  if ((val = rb_hash_aref(hash, rb_str_new2("L"))) != Qnil)
    sprintf(command, "%s -L \"%s\"", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("N"))) != Qnil)
    sprintf(command, "%s -N %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("r"))) != Qnil)
    sprintf(command, "%s -r %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("R"))) != Qnil)
    sprintf(command, "%s -R %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("s"))) == Qtrue)
    sprintf(command, "%s -s", command);
  if ((val = rb_hash_aref(hash, rb_str_new2("t"))) == Qtrue)
    sprintf(command, "%s -t", command);
  if ((val = rb_hash_aref(hash, rb_str_new2("u"))) != Qnil)
    sprintf(command, "%s -u %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("w"))) != Qnil)
    sprintf(command, "%s -w %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("x"))) != Qnil)
    sprintf(command, "%s -x %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("X"))) != Qnil)
    sprintf(command, "%s -X \"%s\"", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("y"))) != Qnil)
    sprintf(command, "%s -y %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("Y"))) != Qnil)
    sprintf(command, "%s -Y \"%s\"", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("bg-color"))) != Qnil)
    sprintf(command, "%s --bg-color %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("bitmap-size"))) != Qnil)
    sprintf(command, "%s --bitmap-size %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("frame-color"))) != Qnil)
    sprintf(command, "%s --frame-color %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("frame-line-width"))) != Qnil)
    sprintf(command, "%s --frame-line-width %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("max-line-length"))) != Qnil)
    sprintf(command, "%s --max-line-length %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("page-size"))) != Qnil)
    sprintf(command, "%s --page-size %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("pen-colors"))) != Qnil)
    sprintf(command, "%s --pen-colors %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("rotation"))) != Qnil)
    sprintf(command, "%s --rotation %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("title-font-name"))) != Qnil)
    sprintf(command, "%s --title-font-name %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("title-font-size"))) != Qnil)
    sprintf(command, "%s --title-font-size %f", command, NUM2DBL(val));

  if ((val = rb_hash_aref(hash, rb_str_new2("toggle-rotate-y-label"))) == Qtrue)
    sprintf(command, "%s --toggle-rotate-y-label", command);

  if ((val = rb_hash_aref(hash, rb_str_new2("m"))) != Qnil)
    sprintf(command, "%s -m %d", command, (int) FIX2INT(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("S"))) != Qnil)
    sprintf(command, "%s -S %d", command, (int) FIX2INT(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("W"))) != Qnil)
    sprintf(command, "%s -W %f", command, NUM2DBL(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("q"))) != Qnil)
    sprintf(command, "%s -q %f", command, NUM2DBL(val));

  if ((val = rb_hash_aref(hash, rb_str_new2("symbol-font-name"))) != Qnil)
    sprintf(command, "%s --symbol-font-name %s", command, STR2CSTR(val));

  if ((val = rb_hash_aref(hash, rb_str_new2("reposition"))) != Qnil)
    sprintf(command, "%s --reposition %s", command, STR2CSTR(val));
  if ((val = rb_hash_aref(hash, rb_str_new2("blankout"))) != Qnil)
    sprintf(command, "%s --blankout %s", command, STR2CSTR(val));

  if ((val = rb_hash_aref(hash, rb_str_new2("O"))) == Qtrue)
    sprintf(command, "%s -O", command);
}
Exemplo n.º 3
0
static VALUE param_hash_aref(VALUE self, VALUE key) {
  if (TYPE(key) == T_SYMBOL) {
    key = rb_sym_to_s(key);
  }
  return rb_hash_aref(self, key);
}
/**
 * call-seq:
 *   Amalgalite::Requires::Bootstrap.lift( 'dbfile' => "lib.db", 'table_name' => "bootload", 'rowid_column' => "id", 'filename_column' => "filename",  'content_column' => "contents" )
 *
 * *WARNING* *WARNING* *WARNING* *WARNING* *WARNING* *WARNING* *WARNING*
 *
 * This is a boostrap mechanism to eval all the code in a particular column in a
 * specially formatted table in an sqlite database.  It should only be used for
 * a specific purpose, mainly loading the Amalgalite ruby code directly from an
 * sqlite table.  
 *
 * Amalgalite::Requires adds in the ability to _require_ code that is in an
 * sqlite database.  Since Amalgalite::Requires is itself ruby code, if
 * Amalgalite::Requires was in an sqlite database, it could not _require_
 * itself.  Therefore this method is made available.  It is a pure C extension
 * method that directly calls the sqlite3 C functions directly and uses the ruby
 * C api to eval the data in the table.
 *
 * This method attaches to an sqlite3 database (filename) and then does:
 *
 *     SELECT filename_column_name, content_column_name 
 *       FROM table_name
 *   ORDER BY rowid_column_name
 *
 * For each row returned it does an _eval_ on the code in the
 * *content_column_name* and then updates _$LOADED_FEATURES_ directly with the value from
 * *filename_column_name*.
 *
 * The database to be opened by _lift_ *must* be an sqlite3 UTF-8 database.
 *
 */
VALUE am_bootstrap_lift( VALUE self, VALUE args )
{
    sqlite3*        db = NULL;
    sqlite3_stmt* stmt = NULL;
    int             rc;
    int  last_row_good; 
    char raise_msg[BUFSIZ];

    VALUE     am_db_c     = rb_const_get( cARB, rb_intern("DEFAULT_DB") );
    VALUE    am_tbl_c     = rb_const_get( cARB, rb_intern("DEFAULT_BOOTSTRAP_TABLE") );
    VALUE     am_pk_c     = rb_const_get( cARB, rb_intern("DEFAULT_ROWID_COLUMN") );
    VALUE  am_fname_c     = rb_const_get( cARB, rb_intern("DEFAULT_FILENAME_COLUMN") );
    VALUE am_content_c    = rb_const_get( cARB, rb_intern("DEFAULT_CONTENTS_COLUMN") );

    char*     dbfile = NULL;
    char*    tbl_name = NULL;
    char*      pk_col = NULL;
    char*   fname_col = NULL;
    char* content_col = NULL;

    char             sql[BUFSIZ];
    const char* sql_tail = NULL;
    int        sql_bytes = 0;
    
    const unsigned char* result_text = NULL;
    int                result_length = 0;

    VALUE     require_name = Qnil;  /* ruby string of the file name for use in eval */
    VALUE   eval_this_code = Qnil;  /* ruby string of the code to eval from the db  */
    VALUE toplevel_binding = rb_const_get( rb_cObject, rb_intern("TOPLEVEL_BINDING") ) ;
    VALUE              tmp = Qnil;

    ID             eval_id = rb_intern("eval");


    if (   Qnil == args  ) {
        args = rb_hash_new();
    } else {
        args = rb_ary_shift( args );
    }

    Check_Type( args, T_HASH );
    
    /* get the arguments */
    dbfile      = ( Qnil == (tmp = rb_hash_aref( args, rb_str_new2( "dbfile"          ) ) ) ) ? StringValuePtr( am_db_c )      : StringValuePtr( tmp );
    tbl_name    = ( Qnil == (tmp = rb_hash_aref( args, rb_str_new2( "table_name"      ) ) ) ) ? StringValuePtr( am_tbl_c )     : StringValuePtr( tmp );
    pk_col      = ( Qnil == (tmp = rb_hash_aref( args, rb_str_new2( "rowid_column"    ) ) ) ) ? StringValuePtr( am_pk_c )      : StringValuePtr( tmp );
    fname_col   = ( Qnil == (tmp = rb_hash_aref( args, rb_str_new2( "filename_column" ) ) ) ) ? StringValuePtr( am_fname_c )   : StringValuePtr( tmp );
    content_col = ( Qnil == (tmp = rb_hash_aref( args, rb_str_new2( "contents_column" ) ) ) ) ? StringValuePtr( am_content_c ) : StringValuePtr( tmp );


    /* open the database */
    rc = sqlite3_open_v2( dbfile , &db, SQLITE_OPEN_READONLY, NULL);
    if ( SQLITE_OK != rc ) {
        memset( raise_msg, 0, BUFSIZ );
        snprintf(raise_msg, BUFSIZ, "Failure to open database %s for bootload: [SQLITE_ERROR %d] : %s", dbfile, rc, sqlite3_errmsg( db ) );
        am_bootstrap_cleanup_and_raise( raise_msg, db, stmt );
    }

    /* prepare the db query */
    memset( sql, 0, BUFSIZ );
    sql_bytes = snprintf( sql, BUFSIZ, "SELECT %s, %s FROM %s ORDER BY %s", fname_col, content_col, tbl_name, pk_col );
    rc = sqlite3_prepare_v2( db, sql, sql_bytes, &stmt, &sql_tail ) ;
    if ( SQLITE_OK != rc) {
        memset( raise_msg, 0, BUFSIZ );
        snprintf( raise_msg, BUFSIZ,
                  "Failure to prepare bootload select statement table = '%s', rowid col = '%s', filename col ='%s', contents col = '%s' : [SQLITE_ERROR %d] %s\n",
                  tbl_name, pk_col, fname_col, content_col, rc, sqlite3_errmsg( db ));
        am_bootstrap_cleanup_and_raise( raise_msg, db, stmt );
    }

    /* loop over the resulting rows, eval'ing and loading $LOADED_FEATURES */
    last_row_good = -1;
    while ( SQLITE_ROW == ( rc = sqlite3_step( stmt ) ) ) {
        /* file name */
        result_text   = sqlite3_column_text( stmt, 0 );
        result_length = sqlite3_column_bytes( stmt, 0 );
        require_name  = rb_str_new( (const char*)result_text, result_length );

        /* ruby code */
        result_text    = sqlite3_column_text( stmt, 1 );
        result_length  = sqlite3_column_bytes( stmt, 1 );
        eval_this_code = rb_str_new( (const char*)result_text, result_length );

        /* Kernel.eval( code, TOPLEVEL_BINDING, filename, 1 ) */ 
        rb_funcall(rb_mKernel, eval_id, 4, eval_this_code, toplevel_binding, require_name, INT2FIX(1) );

        /* TODO: for ruby 1.9 -- put in ? sqlite3://path/to/database?tablename=tbl_name#require_name */
        /* update $LOADED_FEATURES */
        rb_ary_push( rb_gv_get( "$LOADED_FEATURES" ), require_name );
    }

    /* if there was some sqlite error in the processing of the rows */
    if ( SQLITE_DONE != rc ) {
        memset( raise_msg, 0, BUFSIZ );
        snprintf( raise_msg, BUFSIZ, "Failure in bootloading, last successfully loaded rowid was %d : [SQLITE_ERROR %d] %s\n", 
                  last_row_good, rc, sqlite3_errmsg( db ) );
        am_bootstrap_cleanup_and_raise( raise_msg, db, stmt );
    }

    /* finalize the statement */    
    rc = sqlite3_finalize( stmt );
    if ( SQLITE_OK != rc ) {
        memset( raise_msg, 0, BUFSIZ );
        snprintf( raise_msg, BUFSIZ, "Failure to finalize bootload statement : [SQLITE_ERROR %d] %s\n", rc, sqlite3_errmsg( db ) );
        am_bootstrap_cleanup_and_raise( raise_msg, db, stmt );
    }

    stmt = NULL;

    /* close the database */
    rc = sqlite3_close( db );
    if ( SQLITE_OK != rc ) {
        memset( raise_msg, 0, BUFSIZ );
        snprintf( raise_msg, BUFSIZ, "Failure to close database : [SQLITE_ERROR %d] : %s\n", rc, sqlite3_errmsg( db )),
        am_bootstrap_cleanup_and_raise( raise_msg, db,stmt );
    }

    return Qnil;
}
Exemplo n.º 5
0
void do_postgres_full_connect(VALUE self, PGconn *db) {
  VALUE r_host;
  char *host = NULL;

  if ((r_host = rb_iv_get(self, "@host")) != Qnil) {
    host = StringValuePtr(r_host);
  }

  VALUE r_user;
  char *user = NULL;

  if ((r_user = rb_iv_get(self, "@user")) != Qnil) {
    user = StringValuePtr(r_user);
  }

  VALUE r_password;
  char *password = NULL;

  if ((r_password = rb_iv_get(self, "@password")) != Qnil) {
    password = StringValuePtr(r_password);
  }

  VALUE r_port;
  const char *port = "5432";

  if ((r_port = rb_iv_get(self, "@port")) != Qnil) {
    port = StringValuePtr(r_port);
  }

  VALUE r_path;
  char *path = NULL;
  char *database = NULL;

  if ((r_path = rb_iv_get(self, "@path")) != Qnil) {
    path = StringValuePtr(r_path);
    database = strtok(path, "/");
  }

  if (!database || !*database) {
    database = NULL;
  }

  VALUE r_query = rb_iv_get(self, "@query");
  const char *search_path = data_objects_get_uri_option(r_query, "search_path");

  db = PQsetdbLogin(
    host,
    port,
    NULL,
    NULL,
    database,
    user,
    password
  );

  if (PQstatus(db) == CONNECTION_BAD) {
    rb_raise(eDO_ConnectionError, "%s", PQerrorMessage(db));
  }

  PGresult *result;

  if (search_path) {
    char *search_path_query;

    if (!(search_path_query = calloc(256, sizeof(char)))) {
      rb_memerror();
    }

    snprintf(search_path_query, 256, "set search_path to %s;", search_path);

    r_query = rb_str_new2(search_path_query);
    result = do_postgres_cCommand_execute(Qnil, self, db, r_query);

    if (PQresultStatus(result) != PGRES_COMMAND_OK) {
      free(search_path_query);
      do_postgres_raise_error(self, result, r_query);
    }

    free(search_path_query);
  }

  const char *backslash_off = "SET backslash_quote = off";
  const char *standard_strings_on = "SET standard_conforming_strings = on";
  const char *warning_messages = "SET client_min_messages = warning";
  const char *date_format = "SET datestyle = ISO";
  VALUE r_options;

  r_options = rb_str_new2(backslash_off);
  result = do_postgres_cCommand_execute(Qnil, self, db, r_options);

  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
    rb_warn("%s", PQresultErrorMessage(result));
  }

  r_options = rb_str_new2(standard_strings_on);
  result = do_postgres_cCommand_execute(Qnil, self, db, r_options);

  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
    rb_warn("%s", PQresultErrorMessage(result));
  }

  r_options = rb_str_new2(warning_messages);
  result = do_postgres_cCommand_execute(Qnil, self, db, r_options);

  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
    rb_warn("%s", PQresultErrorMessage(result));
  }

  r_options = rb_str_new2(date_format);
  result = do_postgres_cCommand_execute(Qnil, self, db, r_options);

  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
    rb_warn("%s", PQresultErrorMessage(result));
  }

  VALUE encoding = rb_iv_get(self, "@encoding");
#ifdef HAVE_PQSETCLIENTENCODING
  VALUE pg_encoding = rb_hash_aref(data_objects_const_get(mDO_PostgresEncoding, "MAP"), encoding);

  if (pg_encoding != Qnil) {
    if (PQsetClientEncoding(db, rb_str_ptr_readonly(pg_encoding))) {
      rb_raise(eDO_ConnectionError, "Couldn't set encoding: %s", rb_str_ptr_readonly(encoding));
    }
    else {
#ifdef HAVE_RUBY_ENCODING_H
      rb_iv_set(self, "@encoding_id", INT2FIX(rb_enc_find_index(rb_str_ptr_readonly(encoding))));
#endif
      rb_iv_set(self, "@pg_encoding", pg_encoding);
    }
  }
  else {
    rb_warn("Encoding %s is not a known Ruby encoding for PostgreSQL\n", rb_str_ptr_readonly(encoding));

    rb_iv_set(self, "@encoding", rb_str_new2("UTF-8"));
#ifdef HAVE_RUBY_ENCODING_H
    rb_iv_set(self, "@encoding_id", INT2FIX(rb_enc_find_index("UTF-8")));
#endif
    rb_iv_set(self, "@pg_encoding", rb_str_new2("UTF8"));
  }
#endif

  rb_iv_set(self, "@connection", Data_Wrap_Struct(rb_cObject, 0, 0, db));
}
Exemplo n.º 6
0
VALUE rho_ruby_hash_aref(VALUE hash, const char* key)
{
    return rb_hash_aref( hash, rb_str_new2(key));
}
Exemplo n.º 7
0
/*
 * call-seq: configure(opts)
 *
 * Configure this State instance with the Hash _opts_, and return
 * itself.
 */
static VALUE cState_configure(VALUE self, VALUE opts)
{
    VALUE tmp;
    GET_STATE(self);
    tmp = rb_check_convert_type(opts, T_HASH, "Hash", "to_hash");
    if (NIL_P(tmp)) tmp = rb_convert_type(opts, T_HASH, "Hash", "to_h");
    opts = tmp;
    tmp = rb_hash_aref(opts, ID2SYM(i_indent));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->indent = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->indent_len = len;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_space));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->space = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->space_len = len;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_space_before));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->space_before = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->space_before_len = len;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_array_nl));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->array_nl = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->array_nl_len = len;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_object_nl));
    if (RTEST(tmp)) {
        unsigned long len;
        Check_Type(tmp, T_STRING);
        len = RSTRING_LEN(tmp);
        state->object_nl = fstrndup(RSTRING_PTR(tmp), len + 1);
        state->object_nl_len = len;
    }
    tmp = ID2SYM(i_max_nesting);
    state->max_nesting = 100;
    if (option_given_p(opts, tmp)) {
        VALUE max_nesting = rb_hash_aref(opts, tmp);
        if (RTEST(max_nesting)) {
            Check_Type(max_nesting, T_FIXNUM);
            state->max_nesting = FIX2LONG(max_nesting);
        } else {
            state->max_nesting = 0;
        }
    }
    tmp = ID2SYM(i_depth);
    state->depth = 0;
    if (option_given_p(opts, tmp)) {
        VALUE depth = rb_hash_aref(opts, tmp);
        if (RTEST(depth)) {
            Check_Type(depth, T_FIXNUM);
            state->depth = FIX2LONG(depth);
        } else {
            state->depth = 0;
        }
    }
    tmp = ID2SYM(i_buffer_initial_length);
    if (option_given_p(opts, tmp)) {
        VALUE buffer_initial_length = rb_hash_aref(opts, tmp);
        if (RTEST(buffer_initial_length)) {
            long initial_length;
            Check_Type(buffer_initial_length, T_FIXNUM);
            initial_length = FIX2LONG(buffer_initial_length);
            if (initial_length > 0) state->buffer_initial_length = initial_length;
        }
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_allow_nan));
    state->allow_nan = RTEST(tmp);
    tmp = rb_hash_aref(opts, ID2SYM(i_ascii_only));
    state->ascii_only = RTEST(tmp);
    tmp = rb_hash_aref(opts, ID2SYM(i_quirks_mode));
    state->quirks_mode = RTEST(tmp);
    return self;
}
Exemplo n.º 8
0
/*
  call-seq: draw(hash = nil) { ... }

  Three keys are checked in the given hash : ":buffer" which is the buffer
  on which manipulation are done (by default, the actual buffer is taken),
  ":painter", which tell us to yield a +Joyau::Painter+ instead of a
  +Joyau::Buffer+ when true (false by default), and ":auto_update" which
  tell us whether we should update the buffer (true by default).

  It is mandatory to give a block to this function.

  Examples:
    Joyau.draw(:buffer => a_buffer, :painter => true)
    Joyau.draw(:auto_update => false)
    Joyau.draw(:painter => true)
    Joyau.draw(:buffer => a_buffer)
*/
VALUE Joyau_draw(int argc, VALUE *argv, VALUE self) {
   static bool can_draw = false;

   VALUE hash, block;
   rb_scan_args(argc, argv, "01&", &hash, &block);

   OSL_IMAGE *oldBuffer = oslGetDrawBuffer();
   Buffer *buffer = NULL;
   VALUE rbPainter = Qnil;
   bool painter = false;
   bool auto_update = true;
   bool ruby_buf = false;

   bool could_draw = can_draw;

   if (!NIL_P(hash)) {
      if (TYPE(hash) != T_HASH)
	 rb_raise(rb_eTypeError, "Hash expected for Joyau::draw.");
      
      VALUE rbBuffer = rb_hash_aref(hash, ID2SYM(rb_intern("buffer")));
      
      if (rb_obj_is_kind_of(rbBuffer, getClass("Buffer")) == Qfalse) {
	 if (rbBuffer != Qnil)
	    rb_raise(rb_eTypeError, ":buffer should be a Buffer (or nil).");
      }
      else {
	 buffer = getPtr<Buffer>(rbBuffer);
	 ruby_buf = true;
      }

      if (!buffer)
	 buffer = new Buffer(oldBuffer);

      if (rb_hash_aref(hash, ID2SYM(rb_intern("painter"))) == Qtrue) {
	 painter = true;
	 Painter painter(buffer);
	 rbPainter = createObject(getClass("Painter"), painter);
      }
      
      if (rb_hash_aref(hash, ID2SYM(rb_intern("auto_update"))) == Qfalse)
	 auto_update = false;
   }
   else {
      if (!buffer)
	 buffer = new Buffer(oldBuffer);
   }

   if (buffer->isScreen() && !can_draw) {
      can_draw = true;
      Graphics_startDraw(Qnil);
   }
   if (!NIL_P(block)) {
      buffer->setActual();
      
      if (painter)
	 rb_yield(rbPainter);
      else {
	 VALUE rbBuffer = createObject(getClass("Buffer"), *buffer, true);
	 rb_yield(rbBuffer);
      }

      if (buffer->isScreen() && !could_draw) {
	 can_draw = false;
	 Graphics_endDraw(Qnil);
      }
      if (auto_update && buffer->isScreen())
	 Graphics_sync(Qnil);
   }
   else
      rb_raise(rb_eArgError, "Block expected.");

   if (!ruby_buf) // We do not delete the buffer if it comes from Ruby.
      delete buffer;

   oslSetDrawBuffer(oldBuffer);

   return Qnil;
}
Exemplo n.º 9
0
/*
 *  call-seq:
 *    commit.amend(data = {}) -> oid
 *
 *  Amend a commit object, with the given +data+
 *  arguments, passed as a +Hash+:
 *
 *  - +:message+: a string with the full text for the commit's message
 *  - +:committer+ (optional): a hash with the signature for the committer,
 *    defaults to the signature from the configuration
 *  - +:author+ (optional): a hash with the signature for the author,
 *    defaults to the signature from the configuration
 *  - +:tree+: the tree for this amended commit, represented as a <tt>Rugged::Tree</tt>
 *    instance or an OID +String+.
 *  - +:update_ref+ (optional): a +String+ with the name of a reference in the
 *  repository which should be updated to point to this amended commit (e.g. "HEAD")
 *
 *  When the amended commit is successfully written to disk, its +oid+ will be
 *  returned as a hex +String+.
 *
 *    author = {:email=>"*****@*****.**", :time=>Time.now, :name=>"Vicent Mart\303\255"}
 *
 *    commit.amend(
 *      :author => author,
 *      :message => "Updated Hello world\n\n",
 *      :committer => author,
 *      :tree => some_tree) #=> "f148106ca58764adc93ad4e2d6b1d168422b9796"
 */
static VALUE rb_git_commit_amend(VALUE self, VALUE rb_data)
{
	VALUE rb_message, rb_tree, rb_ref, owner;
	int error = 0;
	git_commit *commit_to_amend;
	char *message = NULL;
	git_tree *tree = NULL;
	git_signature *author = NULL, *committer = NULL;
	git_oid commit_oid;
	git_repository *repo;
	const char *update_ref = NULL;

	Check_Type(rb_data, T_HASH);

	Data_Get_Struct(self, git_commit, commit_to_amend);

	owner = rugged_owner(self);
	Data_Get_Struct(owner, git_repository, repo);

	rb_ref = rb_hash_aref(rb_data, CSTR2SYM("update_ref"));
	if (!NIL_P(rb_ref)) {
		Check_Type(rb_ref, T_STRING);
		update_ref = StringValueCStr(rb_ref);
	}

	rb_message = rb_hash_aref(rb_data, CSTR2SYM("message"));
	if (!NIL_P(rb_message)) {
		Check_Type(rb_message, T_STRING);
		message = StringValueCStr(rb_message);
	}

	rb_tree = rb_hash_aref(rb_data, CSTR2SYM("tree"));
	if (!NIL_P(rb_tree))
		tree = (git_tree *)rugged_object_get(repo, rb_tree, GIT_OBJ_TREE);

	if (!NIL_P(rb_hash_aref(rb_data, CSTR2SYM("committer")))) {
		committer = rugged_signature_get(
			rb_hash_aref(rb_data, CSTR2SYM("committer")), repo
		);
	}

	if (!NIL_P(rb_hash_aref(rb_data, CSTR2SYM("author")))) {
		author = rugged_signature_get(
			rb_hash_aref(rb_data, CSTR2SYM("author")), repo
		);
	}

	error = git_commit_amend(
		&commit_oid,
		commit_to_amend,
		update_ref,
		author,
		committer,
		NULL,
		message,
		tree);

	git_signature_free(author);
	git_signature_free(committer);

	git_object_free((git_object *)tree);

	rugged_exception_check(error);

	return rugged_create_oid(&commit_oid);
}
Exemplo n.º 10
0
Arquivo: rcsv.c Projeto: fiksu/rcsv
/* An rb_rescue()-compatible Ruby pseudo-method that handles the actual parsing */
VALUE rcsv_raw_parse(VALUE ensure_container) {
  /* Unpacking multiple variables from a single Ruby VALUE */
  VALUE options = rb_ary_entry(ensure_container, 0);
  VALUE csvio   = rb_ary_entry(ensure_container, 1);
  struct rcsv_metadata * meta = (struct rcsv_metadata *)NUM2LONG(rb_ary_entry(ensure_container, 2));
  struct csv_parser * cp = (struct csv_parser *)NUM2LONG(rb_ary_entry(ensure_container, 3));

  /* Helper temporary variables */
  VALUE option, csvstr, buffer_size;

  /* libcsv-related temporary variables */
  char * csv_string;
  size_t csv_string_len;
  int error;

  /* Generic iterator */
  size_t i = 0;

  /* IO buffer size can be controller via an option */
  buffer_size = rb_hash_aref(options, ID2SYM(rb_intern("buffer_size")));

  /* By default, parse as Array of Arrays */
  option = rb_hash_aref(options, ID2SYM(rb_intern("row_as_hash")));
  if (option && (option != Qnil)) {
    meta->row_as_hash = true;
  }

  /* :col_sep sets the column separator, default is comma (,) */
  option = rb_hash_aref(options, ID2SYM(rb_intern("col_sep")));
  if (option != Qnil) {
    csv_set_delim(cp, (unsigned char)*StringValuePtr(option));
  }

  /* :quote_char sets the character used for quoting data; default is double-quote (") */
  option = rb_hash_aref(options, ID2SYM(rb_intern("quote_char")));
  if (option != Qnil) {
    csv_set_quote(cp, (unsigned char)*StringValuePtr(option));
  }

  /* Specify how many rows to skip from the beginning of CSV */
  option = rb_hash_aref(options, ID2SYM(rb_intern("offset_rows")));
  if (option != Qnil) {
    meta->offset_rows = (size_t)NUM2INT(option);
  }

  /* Specify the character encoding of the input data */
  option = rb_hash_aref(options, ID2SYM(rb_intern("output_encoding")));
  if (option && (option != Qnil)) {
    meta->encoding_index = RB_ENC_FIND_INDEX(StringValueCStr(option));
  }

  /* :only_rows is a list of values where row is only parsed
     if its fields match those in the passed array.
     [nil, nil, ["ABC", nil, 1]] skips all rows where 3rd column isn't equal to "ABC", nil or 1 */
  option = rb_hash_aref(options, ID2SYM(rb_intern("only_rows")));
  if (option != Qnil) {
    meta->num_only_rows = (size_t)RARRAY_LEN(option);
    meta->only_rows = (VALUE *)malloc(meta->num_only_rows * sizeof(VALUE));

    for (i = 0; i < meta->num_only_rows; i++) {
      VALUE only_row = rb_ary_entry(option, i);
      meta->only_rows[i] = validate_filter_row("only_rows", only_row);
    }
  }

  /* :except_rows is a list of values where row is only parsed
     if its fields don't match those in the passed array.
     [nil, nil, ["ABC", nil, 1]] skips all rows where 3rd column is equal to "ABC", nil or 1 */
  option = rb_hash_aref(options, ID2SYM(rb_intern("except_rows")));
  if (option != Qnil) {
    meta->num_except_rows = (size_t)RARRAY_LEN(option);
    meta->except_rows = (VALUE *)malloc(meta->num_except_rows * sizeof(VALUE));

    for (i = 0; i < meta->num_except_rows; i++) {
      VALUE except_row = rb_ary_entry(option, i);
      meta->except_rows[i] = validate_filter_row("except_rows", except_row);
    }
  }

  /* :row_defaults is an array of default values that are assigned to fields containing empty strings
     according to matching field positions */
  option = rb_hash_aref(options, ID2SYM(rb_intern("row_defaults")));
  if (option != Qnil) {
    meta->num_row_defaults = RARRAY_LEN(option);
    meta->row_defaults = (VALUE*)malloc(meta->num_row_defaults * sizeof(VALUE*));

    for (i = 0; i < meta->num_row_defaults; i++) {
      VALUE row_default = rb_ary_entry(option, i);
      meta->row_defaults[i] = row_default;
    }
  }

  /* :row_conversions specifies Ruby types that CSV field values should be converted into.
     Each char of row_conversions string represents Ruby type for CSV field with matching position. */
  option = rb_hash_aref(options, ID2SYM(rb_intern("row_conversions")));
  if (option != Qnil) {
    meta->num_row_conversions = RSTRING_LEN(option);
    meta->row_conversions = StringValuePtr(option);
  }

 /* Column names should be declared explicitly when parsing fields as Hashes */
  if (meta->row_as_hash) { /* Only matters for hash results */
    option = rb_hash_aref(options, ID2SYM(rb_intern("column_names")));
    if (option == Qnil) {
      rb_raise(rcsv_parse_error, ":row_as_hash requires :column_names to be set.");
    } else {
      meta->last_entry = rb_hash_new();

      meta->num_columns = (size_t)RARRAY_LEN(option);
      meta->column_names = (VALUE*)malloc(meta->num_columns * sizeof(VALUE*));

      for (i = 0; i < meta->num_columns; i++) {
        meta->column_names[i] = rb_ary_entry(option, i);
      }
    }
  } else {
    meta->last_entry = rb_ary_new();
  }

  while(true) {
    csvstr = rb_funcall(csvio, rb_intern("read"), 1, buffer_size);
    if ((csvstr == Qnil) || (RSTRING_LEN(csvstr) == 0)) { break; }

    csv_string = StringValuePtr(csvstr);
    csv_string_len = strlen(csv_string);

    /* Actual parsing and error handling */
    if (csv_string_len != csv_parse(cp, csv_string, csv_string_len,
                                    &end_of_field_callback, &end_of_line_callback, meta)) {
      error = csv_error(cp);
      switch(error) {
        case CSV_EPARSE:
          rb_raise(rcsv_parse_error, "Error when parsing malformed data");
          break;
        case CSV_ENOMEM:
          rb_raise(rcsv_parse_error, "No memory");
          break;
        case CSV_ETOOBIG:
          rb_raise(rcsv_parse_error, "Field data is too large");
          break;
        case CSV_EINVALID:
          rb_raise(rcsv_parse_error, "%s", (const char *)csv_strerror(error));
        break;
        default:
          rb_raise(rcsv_parse_error, "Failed due to unknown reason");
      }
    }
  }

  /* Flushing libcsv's buffer */
  csv_fini(cp, &end_of_field_callback, &end_of_line_callback, meta);

  return Qnil;
}
Exemplo n.º 11
0
Arquivo: rcsv.c Projeto: fiksu/rcsv
/* The main method that handles parsing */
static VALUE rb_rcsv_raw_parse(int argc, VALUE * argv, VALUE self) {
  struct rcsv_metadata meta;
  VALUE csvio, options, option;
  VALUE ensure_container = rb_ary_new(); /* [] */

  struct csv_parser cp;
  unsigned char csv_options = CSV_STRICT_FINI | CSV_APPEND_NULL;

  /* Setting up some sane defaults */
  meta.row_as_hash = false;
  meta.empty_field_is_nil = false;
  meta.skip_current_row = false;
  meta.encoding_index = -1;
  meta.num_columns = 0;
  meta.current_col = 0;
  meta.current_row = 0;
  meta.offset_rows = 0;
  meta.num_only_rows = 0;
  meta.num_except_rows = 0;
  meta.num_row_defaults = 0;
  meta.num_row_conversions = 0;
  meta.only_rows = NULL;
  meta.except_rows = NULL;
  meta.row_defaults = NULL;
  meta.row_conversions = NULL;
  meta.column_names = NULL;
  meta.result = (VALUE[]){rb_ary_new()}; /* [] */

  /* csvio is required, options is optional (pun intended) */
  rb_scan_args(argc, argv, "11", &csvio, &options);

  /* options ||= {} */
  if (NIL_P(options)) {
    options = rb_hash_new();
  }

  /* First of all, we parse libcsv-related params so that it fails early if something is wrong with them */

  /* By default, parsing is strict */
  option = rb_hash_aref(options, ID2SYM(rb_intern("nostrict")));
  if (!option || (option == Qnil)) {
    csv_options |= CSV_STRICT;
  }

  /* By default, empty strings are treated as Nils and quoted empty strings are treated as empty Ruby strings */
  option = rb_hash_aref(options, ID2SYM(rb_intern("parse_empty_fields_as")));
  if ((option == Qnil) || (option == ID2SYM(rb_intern("nil_or_string")))) {
    csv_options |= CSV_EMPTY_IS_NULL;
  } else if (option == ID2SYM(rb_intern("nil"))) {
    meta.empty_field_is_nil = true;
  } else if (option == ID2SYM(rb_intern("string"))) {
    meta.empty_field_is_nil = false;
  } else {
    rb_raise(rcsv_parse_error, "The only valid options for :parse_empty_fields_as are :nil, :string and :nil_or_string, but %s was supplied.", RSTRING_PTR(rb_inspect(option)));
  }

  /* rb_ensure() only expects callback functions to accept and return VALUEs */
  /* This ugly hack converts C pointers into Ruby Fixnums in order to pass them in Array */
  rb_ary_push(ensure_container, options);               /* [options] */
  rb_ary_push(ensure_container, csvio);                 /* [options, csvio] */
  rb_ary_push(ensure_container, LONG2NUM((long)&meta)); /* [options, csvio, &meta] */
  rb_ary_push(ensure_container, LONG2NUM((long)&cp));   /* [options, csvio, &meta, &cp] */

  /* Try to initialize libcsv */
  if (csv_init(&cp, csv_options) == -1) {
    rb_raise(rcsv_parse_error, "Couldn't initialize libcsv");
  }

  /* From now on, cp handles allocated data and should be free'd on exit or exception */
  rb_ensure(rcsv_raw_parse, ensure_container, rcsv_free_memory, ensure_container);

  /* Remove the last row if it's empty. That happens if CSV file ends with a newline. */
  if (RARRAY_LEN(*(meta.result)) && /* meta.result.size != 0 */
      RARRAY_LEN(rb_ary_entry(*(meta.result), -1)) == 0) {
    rb_ary_pop(*(meta.result));
  }

  if (rb_block_given_p()) {
    return Qnil; /* STREAMING */
  } else {
    return *(meta.result); /* Return accumulated result */
  }
}
Exemplo n.º 12
0
static VALUE rb_tinytds_connect(VALUE self, VALUE opts) {
  /* Parsing options hash to local vars. */
  VALUE user, pass, dataserver, database, app, version, ltimeout, timeout, charset, azure;
  user = rb_hash_aref(opts, sym_username);
  pass = rb_hash_aref(opts, sym_password);
  dataserver = rb_hash_aref(opts, sym_dataserver);
  database = rb_hash_aref(opts, sym_database);
  app = rb_hash_aref(opts, sym_appname);
  version = rb_hash_aref(opts, sym_tds_version);
  ltimeout = rb_hash_aref(opts, sym_login_timeout);
  timeout = rb_hash_aref(opts, sym_timeout);
  charset = rb_hash_aref(opts, sym_encoding);
  azure = rb_hash_aref(opts, sym_azure);
  /* Dealing with options. */
  if (dbinit() == FAIL) {
    rb_raise(cTinyTdsError, "failed dbinit() function");
    return self;
  }
  dberrhandle(tinytds_err_handler);
  dbmsghandle(tinytds_msg_handler);
  GET_CLIENT_WRAPPER(self);
  cwrap->login = dblogin();
  if (!NIL_P(version))
    dbsetlversion(cwrap->login, NUM2INT(version));
  if (!NIL_P(user))
    dbsetluser(cwrap->login, StringValuePtr(user));
  if (!NIL_P(pass))
    dbsetlpwd(cwrap->login, StringValuePtr(pass));
  if (!NIL_P(app))
    dbsetlapp(cwrap->login, StringValuePtr(app));
  if (!NIL_P(ltimeout))
    dbsetlogintime(NUM2INT(ltimeout));
  if (!NIL_P(timeout))
    dbsettime(NUM2INT(timeout));
  if (!NIL_P(charset))
    DBSETLCHARSET(cwrap->login, StringValuePtr(charset));
  if (!NIL_P(database) && (azure == Qtrue)) {
    #ifdef DBSETLDBNAME
      DBSETLDBNAME(cwrap->login, StringValuePtr(database));
      cwrap->userdata->continue_on_timeout = 0; // Send INT_CANCEL on timeout with Azure
    #else
      rb_warn("TinyTds: Azure connections not supported in this version of FreeTDS.\n");
    #endif
  }
  cwrap->client = dbopen(cwrap->login, StringValuePtr(dataserver));
  if (cwrap->client) {
    cwrap->closed = 0;
    cwrap->charset = charset;
    if (!NIL_P(version))
      dbsetversion(NUM2INT(version));
    dbsetuserdata(cwrap->client, (BYTE*)cwrap->userdata);
    cwrap->userdata->closed = 0;
    if (!NIL_P(database) && (azure != Qtrue)) {
      dbuse(cwrap->client, StringValuePtr(database));
    }
    VALUE transposed_encoding = rb_funcall(cTinyTdsClient, intern_transpose_iconv_encoding, 1, charset);
    cwrap->encoding = rb_enc_find(StringValuePtr(transposed_encoding));
    if (dbtds(cwrap->client) <= 7) {
      cwrap->identity_insert_sql = "SELECT CAST(@@IDENTITY AS bigint) AS Ident";
    } else {
      cwrap->identity_insert_sql = "SELECT CAST(SCOPE_IDENTITY() AS bigint) AS Ident";
    }
  }
  return self;
}
Exemplo n.º 13
0
VALUE Traverser_Clone2_traverse_item(VALUE self ) {
    VALUE vals[0];
    VALUE it ,__result=Qnil,_autovar=Qnil,_autovar_2=Qnil,_autovar_3=Qnil,_ar=Qnil,_it=Qnil,_autovar_4=Qnil;
    VALUE bind2=bind_new2(2);
    cstruct *ptr;
    Data_Get_Struct(self,cstruct,ptr);
    switch(FIX2LONG(rb_hash_aref(switchhash_Traverser_Clone2_1,rb_obj_class(ame_curobj2(ptr))))) {
    case 0/*AmethystAST*/:
        ;
        int oldpos1=ptr->pos;
        int cut1=0;
alt1_1:
        if(!ptr->branches)ptr->discard=ptr->pos;
        ptr->branches+=3;
        it=rb_funcall(self,sy_visit,0);
        if (it==failobj) {
            it=failobj;
            goto revert1;
        }
        __result=it;;

        ;
        goto accept2;
revert1:
        ;
        goto alt1_2;
accept2:
        ;

        ;
        ptr->branches-=3;
        goto accept1;
alt1_2:
        ptr->pos=oldpos1;
        ptr->branches-=1;
        it=ptr->ary[ptr->pos];            ;
        ptr->pos++;
        _autovar=it;;
        cstruct oldpass1=*ptr;
        ptr->pos=ptr->len=0;
        ptr->ary=NULL;
        ame_setsrc2(self,_autovar);
        it=Traverser_Clone2_traverse(self );
        if (it==failobj) {
            it=failobj;
            goto pass1;
        }
        _autovar_2=it;;

        goto success1;
pass1:
        *ptr=oldpass1;
        if (1) {
            it=failobj;
            goto revert2;
        }
success1:
        *ptr=oldpass1;
        it=_autovar_2;
        __result=it;;

        ;
        goto accept3;
revert2:
        ;
        goto alt1_3;
accept3:
        ;

        ;
        ptr->branches-=2;
        goto accept1;
alt1_3:
        ptr->pos=oldpos1;
        ptr->branches-=1;
        it=AmethystCore_anything(self );
        if (it==failobj) {
            it=failobj;
            goto revert3;
        }
        __result=it;;

        ;
        goto accept4;
revert3:
        ;
        goto alt1_4;
accept4:
        ;

        ;
        ptr->branches-=1;
        goto accept1;
alt1_4:
        ptr->pos=oldpos1;
        ptr->branches-=1;
        if (1) {
            it=failobj;
            goto fail;
        };
accept1:
        ;
        break;
    case 1/*Array*/:
        ;
        int oldpos2=ptr->pos;
        int cut2=0;
alt2_1:
        if(!ptr->branches)ptr->discard=ptr->pos;
        ptr->branches+=2;
        it=rb_funcall(self,sy_visit,0);
        if (it==failobj) {
            it=failobj;
            goto revert4;
        }
        __result=it;;

        ;
        goto accept6;
revert4:
        ;
        goto alt2_2;
accept6:
        ;

        ;
        ptr->branches-=2;
        goto accept5;
alt2_2:
        ptr->pos=oldpos2;
        ptr->branches-=1;
        it=ptr->ary[ptr->pos];            ;
        ptr->pos++;
        _autovar_3=it;;
        cstruct oldpass2=*ptr;
        ptr->pos=ptr->len=0;
        ptr->ary=NULL;
        ame_setsrc2(self,_autovar_3);
        it=rb_ary_new3(0);
        _ar=it;;
        int stop1=0;
        while(!stop1) {
            int oldpos3=ptr->pos;
            int cut3=0;
alt3_1:
            if(!ptr->branches)ptr->discard=ptr->pos;
            ptr->branches+=2;
            it=Traverser_Clone2_traverse_item(self );
            if (it==failobj) {
                it=failobj;
                goto revert6;
            }
            _it=it;;
            bind_aset(bind2,1,_ar);
            bind_aset(bind2,2,_it);
            it=rb_funcall(self,sy_Traverser_Clone2_bind_lb_1_rb__lt__7b20,1,bind2);
            _ar=bind_aget(bind2,1);;
            _it=bind_aget(bind2,2);;
            ;
            goto accept9;
revert6:
            ;
            goto alt3_2;
accept9:
            ;

            ;
            ptr->branches-=2;
            goto accept8;
alt3_2:
            ptr->pos=oldpos3;
            ptr->branches-=1;
            stop1=1;
            ;
            goto accept10;
revert7:
            ;
            goto alt3_3;
accept10:
            ;

            ;
            ptr->branches-=1;
            goto accept8;
alt3_3:
            ptr->pos=oldpos3;
            ptr->branches-=1;
            if (1) {
                it=failobj;
                goto pass2;
            };
accept8:
            ;
        }
        it=_ar;
        _autovar_4=it;;

        goto success2;
pass2:
        *ptr=oldpass2;
        if (1) {
            it=failobj;
            goto revert5;
        }
success2:
        *ptr=oldpass2;
        it=_autovar_4;
        __result=it;;

        ;
        goto accept7;
revert5:
        ;
        goto alt2_3;
accept7:
        ;

        ;
        ptr->branches-=1;
        goto accept5;
alt2_3:
        ptr->pos=oldpos2;
        ptr->branches-=1;
        if (1) {
            it=failobj;
            goto fail;
        };
accept5:
        ;
        break;
    case 2/*Object*/:
        ;
        int oldpos4=ptr->pos;
        int cut4=0;
alt4_1:
        if(!ptr->branches)ptr->discard=ptr->pos;
        ptr->branches+=2;
        it=rb_funcall(self,sy_visit,0);
        if (it==failobj) {
            it=failobj;
            goto revert8;
        }
        __result=it;;

        ;
        goto accept12;
revert8:
        ;
        goto alt4_2;
accept12:
        ;

        ;
        ptr->branches-=2;
        goto accept11;
alt4_2:
        ptr->pos=oldpos4;
        ptr->branches-=1;
        it=AmethystCore_anything(self );
        if (it==failobj) {
            it=failobj;
            goto revert9;
        }
        __result=it;;

        ;
        goto accept13;
revert9:
        ;
        goto alt4_3;
accept13:
        ;

        ;
        ptr->branches-=1;
        goto accept11;
alt4_3:
        ptr->pos=oldpos4;
        ptr->branches-=1;
        if (1) {
            it=failobj;
            goto fail;
        };
accept11:
        ;
        break;
    }
fail:
    return it;
}
Exemplo n.º 14
0
static VALUE rb_redcarpet_html_init(int argc, VALUE *argv, VALUE self)
{
	struct rb_redcarpet_rndr *rndr;
	unsigned int render_flags = 0;
	VALUE hash, link_attr = Qnil;

	Data_Get_Struct(self, struct rb_redcarpet_rndr, rndr);

	if (rb_scan_args(argc, argv, "01", &hash) == 1) {
		Check_Type(hash, T_HASH);

		/* escape_html */
		if (rb_hash_aref(hash, CSTR2SYM("escape_html")) == Qtrue)
			render_flags |= HTML_ESCAPE;

		/* filter_html */
		if (rb_hash_aref(hash, CSTR2SYM("filter_html")) == Qtrue)
			render_flags |= HTML_SKIP_HTML;

		/* no_image */
		if (rb_hash_aref(hash, CSTR2SYM("no_images")) == Qtrue)
			render_flags |= HTML_SKIP_IMAGES;

		/* no_links */
		if (rb_hash_aref(hash, CSTR2SYM("no_links")) == Qtrue)
			render_flags |= HTML_SKIP_LINKS;

		/* prettify */
		if (rb_hash_aref(hash, CSTR2SYM("prettify")) == Qtrue)
			render_flags |= HTML_PRETTIFY;

		/* filter_style */
		if (rb_hash_aref(hash, CSTR2SYM("no_styles")) == Qtrue)
			render_flags |= HTML_SKIP_STYLE;

		/* safelink */
		if (rb_hash_aref(hash, CSTR2SYM("safe_links_only")) == Qtrue)
			render_flags |= HTML_SAFELINK;

		if (rb_hash_aref(hash, CSTR2SYM("with_toc_data")) == Qtrue)
			render_flags |= HTML_TOC;

		if (rb_hash_aref(hash, CSTR2SYM("hard_wrap")) == Qtrue)
			render_flags |= HTML_HARD_WRAP;

		if (rb_hash_aref(hash, CSTR2SYM("xhtml")) == Qtrue)
			render_flags |= HTML_USE_XHTML;

		link_attr = rb_hash_aref(hash, CSTR2SYM("link_attributes"));
	}

	sdhtml_renderer(&rndr->callbacks, (struct html_renderopt *)&rndr->options.html, render_flags);
	rb_redcarpet__overload(self, rb_cRenderHTML);

	if (!NIL_P(link_attr)) {
		rndr->options.link_attributes = link_attr;
		rndr->options.html.link_attributes = &rndr_link_attributes;
	}

	return Qnil;
}
Exemplo n.º 15
0
void wsf_util_pack_attachments (
    axutil_env_t *env,
    axiom_node_t *node,
    VALUE 		  attach_ht,
    int 		  enable_mtom,
    char 		 *default_cnt_type)
{
    axiom_element_t *node_element = NULL;
    axiom_element_t *child_element = NULL;
    axiom_child_element_iterator_t *child_element_ite = NULL;
    axiom_node_t *child_node = NULL;
    int attachment_done = 0;
    axis2_char_t *element_localname = NULL;
    axiom_namespace_t *element_namespace = NULL;
    axis2_char_t *namespace_uri = NULL;

    if (!node)
        return;

    if (axiom_node_get_node_type(node, env) == AXIOM_ELEMENT)
    {
        node_element = axiom_node_get_data_element(node, env);
        if (node_element)
        {
            child_element_ite = axiom_element_get_child_elements(node_element, env, node);
            if (child_element_ite)
            {
                child_node = axiom_child_element_iterator_next(child_element_ite, env);
                attachment_done = 0;

                while (child_node && !attachment_done)
                {
                    child_element = axiom_node_get_data_element(child_node, env);

                    element_localname = axiom_element_get_localname(child_element, env);
                    if (element_localname && (axutil_strcmp(element_localname, AXIS2_ELEMENT_LN_INCLUDE) == 0))
                    {
                        element_namespace = axiom_element_get_namespace(child_element, env, child_node);
                        if (element_namespace)
                        {
                            namespace_uri = axiom_namespace_get_uri(element_namespace, env);
                            if (namespace_uri && (axutil_strcmp(namespace_uri, AXIS2_NAMESPACE_URI_INCLUDE) == 0))
                            {
                                axis2_char_t *cnt_type = NULL;
                                axis2_char_t *content_type = NULL;
                                axis2_char_t *href = NULL;
                                axis2_char_t* pos = NULL;

                                cnt_type = axiom_element_get_attribute_value_by_name(node_element, env, AXIS2_ELEMENT_ATTR_NAME_CONTENT_TYPE);
                                content_type = !cnt_type ? default_cnt_type : cnt_type;

                                href = axiom_element_get_attribute_value_by_name(child_element, env, AXIS2_ELEMENT_ATTR_NAME_HREF);

                                if ((axutil_strlen(href) > 4) && (pos = axutil_strstr (href, "cid:")))
                                {
                                    axis2_char_t* cid = NULL;
                                    VALUE content_tmp;
                                    void* content = NULL;
                                    unsigned int content_length = 0;

                                    cid = href + 4;

                                    content_tmp = rb_hash_aref(attach_ht, rb_str_new2(cid));
                                    content_length = RSTRING(content_tmp)->len;

                                    content = malloc(sizeof (char) * content_length);
                                    memcpy (content, (const void*)STR2CSTR(content_tmp), content_length);

                                    if (content)
                                    {
                                        void *data_buffer = NULL;
                                        axiom_data_handler_t *data_handler = NULL;
                                        axiom_node_t *text_node = NULL;
                                        axiom_text_t *text = NULL;

                                        data_buffer = AXIS2_MALLOC (env->allocator, sizeof (char) * content_length);
                                        if (data_buffer)
                                        {
                                            memcpy (data_buffer, content, content_length);

                                            data_handler = axiom_data_handler_create (env, NULL, content_type);
                                            if (data_handler)
                                            {
                                                axiom_data_handler_set_binary_data (data_handler, env, (axis2_byte_t *)content, content_length);

                                                text = axiom_text_create_with_data_handler (env, node, data_handler, &text_node);

                                                if (enable_mtom == AXIS2_FALSE)
                                                    axiom_text_set_optimize (text, env, AXIS2_FALSE);

                                                axiom_node_detach (child_node, env);
                                            }
                                        }

                                        attachment_done = 1;
                                    }
                                }
                            }
                        }
                    }

                    child_node = axiom_child_element_iterator_next(child_element_ite, env);
                }
            }
        }
    }

    // Process child nodes
    child_node = axiom_node_get_first_child(node, env);
    while (child_node)
    {
        wsf_util_pack_attachments(env, child_node, attach_ht, enable_mtom, default_cnt_type);

        child_node = axiom_node_get_next_sibling(child_node, env);
    }
}
Exemplo n.º 16
0
/*
 *  call-seq:
 *    Commit.create(repository, data = {}) -> oid
 *
 *  Write a new +Commit+ object to +repository+, with the given +data+
 *  arguments, passed as a +Hash+:
 *
 *  - +:message+: a string with the full text for the commit's message
 *  - +:committer+ (optional): a hash with the signature for the committer,
 *    defaults to the signature from the configuration
 *  - +:author+ (optional): a hash with the signature for the author,
 *    defaults to the signature from the configuration
 *  - +:parents+: an +Array+ with zero or more parents for this commit,
 *    represented as <tt>Rugged::Commit</tt> instances, or OID +String+.
 *  - +:tree+: the tree for this commit, represented as a <tt>Rugged::Tree</tt>
 *    instance or an OID +String+.
 *  - +:update_ref+ (optional): a +String+ with the name of a reference in the
 *    repository which should be updated to point to this commit (e.g. "HEAD")
 *
 *  When the commit is successfully written to disk, its +oid+ will be
 *  returned as a hex +String+.
 *
 *    author = {:email=>"*****@*****.**", :time=>Time.now, :name=>"Vicent Mart\303\255"}
 *
 *    Rugged::Commit.create(r,
 *      :author => author,
 *      :message => "Hello world\n\n",
 *      :committer => author,
 *      :parents => ["2cb831a8aea28b2c1b9c63385585b864e4d3bad1"],
 *      :tree => some_tree) #=> "f148106ca58764adc93ad4e2d6b1d168422b9796"
 */
static VALUE rb_git_commit_create(VALUE self, VALUE rb_repo, VALUE rb_data)
{
	VALUE rb_message, rb_tree, rb_parents, rb_ref;
	VALUE rb_err_obj = Qnil;
	int parent_count, i, error = 0;
	const git_commit **parents = NULL;
	git_commit **free_list = NULL;
	git_tree *tree;
	git_signature *author, *committer;
	git_oid commit_oid;
	git_repository *repo;
	const char *update_ref = NULL;

	Check_Type(rb_data, T_HASH);

	rugged_check_repo(rb_repo);
	Data_Get_Struct(rb_repo, git_repository, repo);

	rb_ref = rb_hash_aref(rb_data, CSTR2SYM("update_ref"));
	if (!NIL_P(rb_ref)) {
		Check_Type(rb_ref, T_STRING);
		update_ref = StringValueCStr(rb_ref);
	}

	rb_message = rb_hash_aref(rb_data, CSTR2SYM("message"));
	Check_Type(rb_message, T_STRING);

	committer = rugged_signature_get(
		rb_hash_aref(rb_data, CSTR2SYM("committer")), repo
	);

	author = rugged_signature_get(
		rb_hash_aref(rb_data, CSTR2SYM("author")), repo
	);

	rb_parents = rb_hash_aref(rb_data, CSTR2SYM("parents"));
	Check_Type(rb_parents, T_ARRAY);

	rb_tree = rb_hash_aref(rb_data, CSTR2SYM("tree"));
	tree = (git_tree *)rugged_object_get(repo, rb_tree, GIT_OBJ_TREE);

	parents = alloca(RARRAY_LEN(rb_parents) * sizeof(void *));
	free_list = alloca(RARRAY_LEN(rb_parents) * sizeof(void *));
	parent_count = 0;

	for (i = 0; i < (int)RARRAY_LEN(rb_parents); ++i) {
		VALUE p = rb_ary_entry(rb_parents, i);
		git_commit *parent = NULL;
		git_commit *free_ptr = NULL;

		if (NIL_P(p))
			continue;

		if (TYPE(p) == T_STRING) {
			git_oid oid;

			error = git_oid_fromstr(&oid, StringValueCStr(p));
			if (error < GIT_OK)
				goto cleanup;

			error = git_commit_lookup(&parent, repo, &oid);
			if (error < GIT_OK)
				goto cleanup;

			free_ptr = parent;

		} else if (rb_obj_is_kind_of(p, rb_cRuggedCommit)) {
			Data_Get_Struct(p, git_commit, parent);
		} else {
			rb_err_obj = rb_exc_new2(rb_eTypeError, "Invalid type for parent object");
			goto cleanup;
		}

		parents[parent_count] = parent;
		free_list[parent_count] = free_ptr;
		parent_count++;
	}

	error = git_commit_create(
		&commit_oid,
		repo,
		update_ref,
		author,
		committer,
		NULL,
		StringValueCStr(rb_message),
		tree,
		parent_count,
		parents);

cleanup:
	git_signature_free(author);
	git_signature_free(committer);

	git_object_free((git_object *)tree);

	for (i = 0; i < parent_count; ++i)
		git_object_free((git_object *)free_list[i]);

	if (!NIL_P(rb_err_obj))
		rb_exc_raise(rb_err_obj);

	rugged_exception_check(error);

	return rugged_create_oid(&commit_oid);
}
Exemplo n.º 17
0
Arquivo: port.c Projeto: n-tada/trema
static VALUE
port_init( VALUE self, VALUE attributes ) {
    VALUE number = rb_hash_aref( attributes, ID2SYM( rb_intern( "number" ) ) );
    rb_iv_set( self, "@number", number );
    return self;
}
Exemplo n.º 18
0
static void write_doc(bson_buffer_t buffer, VALUE hash, VALUE check_keys, VALUE move_id) {
    bson_buffer_position start_position = bson_buffer_get_position(buffer);
    bson_buffer_position length_location = bson_buffer_save_space(buffer, 4);
    bson_buffer_position length;
    int allow_id;
    int max_size;
    int (*write_function)(VALUE, VALUE, VALUE) = NULL;
    VALUE id_str = rb_str_new2("_id");
    VALUE id_sym = ID2SYM(rb_intern("_id"));

    if (length_location == -1) {
        rb_raise(rb_eNoMemError, "failed to allocate memory in buffer.c");
    }

    // write '_id' first if move_id is true. then don't allow an id to be written.
    if(move_id == Qtrue) {
        allow_id = 0;
        if (rb_funcall(hash, rb_intern("has_key?"), 1, id_str) == Qtrue) {
            VALUE id = rb_hash_aref(hash, id_str);
            write_element_with_id(id_str, id, pack_extra(buffer, check_keys));
        } else if (rb_funcall(hash, rb_intern("has_key?"), 1, id_sym) == Qtrue) {
            VALUE id = rb_hash_aref(hash, id_sym);
            write_element_with_id(id_sym, id, pack_extra(buffer, check_keys));
        }
    }
    else {
        allow_id = 1;
        // Ensure that hash doesn't contain both '_id' and :_id
        if ((rb_obj_classname(hash), "Hash") == 0) {
            if ((rb_funcall(hash, rb_intern("has_key?"), 1, id_str) == Qtrue) &&
                   (rb_funcall(hash, rb_intern("has_key?"), 1, id_sym) == Qtrue)) {
                      VALUE oid_sym = rb_hash_delete(hash, id_sym);
                      rb_funcall(hash, rb_intern("[]="), 2, id_str, oid_sym);
            }
        }
    }

    if(allow_id == 1) {
        write_function = write_element_with_id;
    }
    else {
        write_function = write_element_without_id;
    }

    // we have to check for an OrderedHash and handle that specially
    if (strcmp(rb_obj_classname(hash), "BSON::OrderedHash") == 0) {
        int i;
        VALUE keys = rb_funcall(hash, rb_intern("keys"), 0);

        for(i = 0; i < RARRAY_LEN(keys); i++) {
            VALUE key = rb_ary_entry(keys, i);
            VALUE value = rb_hash_aref(hash, key);

            write_function(key, value, pack_extra(buffer, check_keys));
        }
    } else if (rb_obj_is_kind_of(hash, RB_HASH) == Qtrue) {
        rb_hash_foreach(hash, write_function, pack_extra(buffer, check_keys));
    } else {
        bson_buffer_free(buffer);
        rb_raise(InvalidDocument, "BSON.serialize takes a Hash but got a %s", rb_obj_classname(hash));
    }

    // write null byte and fill in length
    SAFE_WRITE(buffer, &zero, 1);
    length = bson_buffer_get_position(buffer) - start_position;

    // make sure that length doesn't exceed the max size (determined by server, defaults to 4mb)
    max_size = bson_buffer_get_max_size(buffer);
    if (length > max_size) {
        bson_buffer_free(buffer);
        rb_raise(InvalidDocument,
            "Document too large: This BSON document is limited to %d bytes.",
            max_size);
    }
    SAFE_WRITE_AT_POS(buffer, length_location, (const char*)&length, 4);
}
Exemplo n.º 19
0
/* 
 *  call-seq:
 *     QueryParser.new(options = {}) -> QueryParser
 *
 *  Create a new QueryParser. The QueryParser is used to convert string
 *  queries into Query objects. The options are;
 *
 *  === Options
 *
 *  :default_field::        Default: "*" (all fields). The default field to
 *                          search when no field is specified in the search
 *                          string. It can also be an array of fields.
 *  :analyzer::             Default: StandardAnalyzer. Analyzer used by the
 *                          query parser to parse query terms
 *  :wild_card_downcase::   Default: true. Specifies whether wild-card queries
 *                          should be downcased or not since they are not
 *                          passed through the parser
 *  :fields::               Default: []. Lets the query parser know what
 *                          fields are available for searching, particularly
 *                          when the "*" is specified as the search field
 *  :tokenized_fields::     Default: :fields. Lets the query parser know which
 *                          fields are tokenized so it knows which fields to
 *                          run the analyzer over.
 *  :validate_fields::      Default: false. Set to true if you want an
 *                          exception to be raised if there is an attempt to
 *                          search a non-existent field
 *  :or_default::           Default: true. Use "OR" as the default boolean
 *                          operator
 *  :default_slop::         Default: 0. Default slop to use in PhraseQuery
 *  :handle_parser_errors:: Default: true. QueryParser will quietly handle all
 *                          parsing errors internally. If you'd like to handle
 *                          them yourself, set this parameter to false.
 *  :clean_string::         Default: true. QueryParser will do a quick
 *                          once-over the query string make sure that quotes
 *                          and brackets match up and special characters are
 *                          escaped
 *  :max_clauses::          Default: 512. the maximum number of clauses
 *                          allowed in boolean queries and the maximum number
 *                          of terms allowed in multi, prefix, wild-card or
 *                          fuzzy queries when those queries are generated by
 *                          rewriting other queries
 */                   
static VALUE
frt_qp_init(int argc, VALUE *argv, VALUE self)
{
    VALUE roptions;
    VALUE rval;
    Analyzer *analyzer = NULL;
    bool has_options = false;

    HashSet *all_fields = NULL;
    HashSet *tkz_fields = NULL;
    HashSet *def_fields = NULL;
    QParser *qp;

    if (rb_scan_args(argc, argv, "01", &roptions) > 0) {
        if (TYPE(roptions) == T_HASH) {
            has_options = true;
            if (Qnil != (rval = rb_hash_aref(roptions, sym_default_field))) {
                def_fields = frt_get_fields(rval);
            }
            if (Qnil != (rval = rb_hash_aref(roptions, sym_analyzer))) {
                analyzer = frt_get_cwrapped_analyzer(rval);
            }
            if (Qnil != (rval = rb_hash_aref(roptions, sym_all_fields))) {
                all_fields = frt_get_fields(rval);
            }
            if (Qnil != (rval = rb_hash_aref(roptions, sym_fields))) {
                all_fields = frt_get_fields(rval);
            }
            if (Qnil != (rval = rb_hash_aref(roptions, sym_tkz_fields))) {
                tkz_fields = frt_get_fields(rval);
            }
        } else {
            def_fields = frt_get_fields(roptions);
        }
    }
    if (all_fields == NULL) {
        all_fields = hs_new_str(&free);
    }

    if (!analyzer) {
        analyzer = mb_standard_analyzer_new(true);
    }

    qp = qp_new(all_fields, def_fields, tkz_fields, analyzer);
    qp->allow_any_fields = true;
    qp->clean_str = true;
    /* handle options */
    if (argc > 0) {
        if (Qnil != (rval = rb_hash_aref(roptions, sym_handle_parse_errors))) {
            qp->handle_parse_errors = RTEST(rval);
        }
        if (Qnil != (rval = rb_hash_aref(roptions, sym_validate_fields))) {
            qp->allow_any_fields = !RTEST(rval);
        }
        if (Qnil != (rval = rb_hash_aref(roptions, sym_wild_card_downcase))) {
            qp->wild_lower = RTEST(rval);
        }
        if (Qnil != (rval = rb_hash_aref(roptions, sym_or_default))) {
            qp->or_default = RTEST(rval);
        }
        if (Qnil != (rval = rb_hash_aref(roptions, sym_default_slop))) {
            qp->def_slop = FIX2INT(rval);
        }
        if (Qnil != (rval = rb_hash_aref(roptions, sym_clean_string))) {
            qp->clean_str = RTEST(rval);
        }
        if (Qnil != (rval = rb_hash_aref(roptions, sym_max_clauses))) {
            qp->max_clauses = FIX2INT(rval);
        }
    }
    Frt_Wrap_Struct(self, frt_qp_mark, frt_qp_free, qp);
    object_add(qp, self);
    return self;
}
Exemplo n.º 20
0
/* grpc_run_batch_stack_fill_ops fills the run_batch_stack ops array from
 * ops_hash */
static void grpc_run_batch_stack_fill_ops(run_batch_stack* st, VALUE ops_hash) {
  VALUE this_op = Qnil;
  VALUE this_value = Qnil;
  VALUE ops_ary = rb_ary_new();
  size_t i = 0;

  /* Create a ruby array with just the operation keys */
  rb_hash_foreach(ops_hash, grpc_rb_call_check_op_keys_hash_cb, ops_ary);

  /* Fill the ops array */
  for (i = 0; i < (size_t)RARRAY_LEN(ops_ary); i++) {
    this_op = rb_ary_entry(ops_ary, i);
    this_value = rb_hash_aref(ops_hash, this_op);
    switch(NUM2INT(this_op)) {
      case GRPC_OP_SEND_INITIAL_METADATA:
        /* N.B. later there is no need to explicitly delete the metadata keys
         * and values, they are references to data in ruby objects. */
        grpc_rb_md_ary_convert(this_value, &st->send_metadata);
        st->ops[st->op_num].data.send_initial_metadata.count =
            st->send_metadata.count;
        st->ops[st->op_num].data.send_initial_metadata.metadata =
            st->send_metadata.metadata;
        break;
      case GRPC_OP_SEND_MESSAGE:
        st->ops[st->op_num].data.send_message =
            grpc_rb_s_to_byte_buffer(RSTRING_PTR(this_value),
                                     RSTRING_LEN(this_value));
        break;
      case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
        break;
      case GRPC_OP_SEND_STATUS_FROM_SERVER:
        /* N.B. later there is no need to explicitly delete the metadata keys
         * and values, they are references to data in ruby objects. */
        grpc_rb_op_update_status_from_server(&st->ops[st->op_num],
                                             &st->send_trailing_metadata,
                                             this_value);
        break;
      case GRPC_OP_RECV_INITIAL_METADATA:
        st->ops[st->op_num].data.recv_initial_metadata = &st->recv_metadata;
        break;
      case GRPC_OP_RECV_MESSAGE:
        st->ops[st->op_num].data.recv_message = &st->recv_message;
        break;
      case GRPC_OP_RECV_STATUS_ON_CLIENT:
        st->ops[st->op_num].data.recv_status_on_client.trailing_metadata =
            &st->recv_trailing_metadata;
        st->ops[st->op_num].data.recv_status_on_client.status =
            &st->recv_status;
        st->ops[st->op_num].data.recv_status_on_client.status_details =
            &st->recv_status_details;
        st->ops[st->op_num].data.recv_status_on_client.status_details_capacity =
            &st->recv_status_details_capacity;
        break;
      case GRPC_OP_RECV_CLOSE_ON_SERVER:
        st->ops[st->op_num].data.recv_close_on_server.cancelled =
            &st->recv_cancelled;
        break;
      default:
        grpc_run_batch_stack_cleanup(st);
        rb_raise(rb_eTypeError, "invalid operation : bad value %d",
                 NUM2INT(this_op));
    };
    st->ops[st->op_num].op = (grpc_op_type)NUM2INT(this_op);
    st->op_num++;
  }
}
Exemplo n.º 21
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 (strcmp(cptr, "NaN") == 0 || strcmp(cptr, "Infinity") == 0 || strcmp(cptr, "-Infinity") == 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_as_json)) {
                obj = rb_funcall(obj, intern_as_json, 0);
                yajl_encode_part(w, obj, io);
            } else 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;
    }
}
Exemplo n.º 22
0
static VALUE
stackprof_start(int argc, VALUE *argv, VALUE self)
{
    struct sigaction sa;
    struct itimerval timer;
    VALUE opts = Qnil, mode = Qnil, interval = Qnil, out = Qfalse;
    int raw = 0, aggregate = 1;

    if (_stackprof.running)
	return Qfalse;

    rb_scan_args(argc, argv, "0:", &opts);

    if (RTEST(opts)) {
	mode = rb_hash_aref(opts, sym_mode);
	interval = rb_hash_aref(opts, sym_interval);
	out = rb_hash_aref(opts, sym_out);

	if (RTEST(rb_hash_aref(opts, sym_raw)))
	    raw = 1;
	if (rb_hash_lookup2(opts, sym_aggregate, Qundef) == Qfalse)
	    aggregate = 0;
    }
    if (!RTEST(mode)) mode = sym_wall;

    if (!_stackprof.frames) {
	_stackprof.frames = st_init_numtable();
	_stackprof.overall_signals = 0;
	_stackprof.overall_samples = 0;
	_stackprof.during_gc = 0;
    }

    if (mode == sym_object) {
	if (!RTEST(interval)) interval = INT2FIX(1);

	objtracer = rb_tracepoint_new(Qnil, RUBY_INTERNAL_EVENT_NEWOBJ, stackprof_newobj_handler, 0);
	rb_tracepoint_enable(objtracer);
    } else if (mode == sym_wall || mode == sym_cpu) {
	if (!RTEST(interval)) interval = INT2FIX(1000);

	sa.sa_sigaction = stackprof_signal_handler;
	sa.sa_flags = SA_RESTART | SA_SIGINFO;
	sigemptyset(&sa.sa_mask);
	sigaction(mode == sym_wall ? SIGALRM : SIGPROF, &sa, NULL);

	timer.it_interval.tv_sec = 0;
	timer.it_interval.tv_usec = NUM2LONG(interval);
	timer.it_value = timer.it_interval;
	setitimer(mode == sym_wall ? ITIMER_REAL : ITIMER_PROF, &timer, 0);
    } else if (mode == sym_custom) {
	/* sampled manually */
	interval = Qnil;
    } else {
	rb_raise(rb_eArgError, "unknown profiler mode");
    }

    _stackprof.running = 1;
    _stackprof.raw = raw;
    _stackprof.aggregate = aggregate;
    _stackprof.mode = mode;
    _stackprof.interval = interval;
    _stackprof.out = out;

    return Qtrue;
}
Exemplo n.º 23
0
static inline void event_callback (struct em_event* e)
{
	const unsigned long signature = e->signature;
	int event = e->event;
	const char *data_str = e->data_str;
	const unsigned long data_num = e->data_num;

	switch (event) {
		case EM_CONNECTION_READ:
		{
			VALUE conn = rb_hash_aref (EmConnsHash, ULONG2NUM (signature));
			if (conn == Qnil)
				rb_raise (EM_eConnectionNotBound, "received %lu bytes of data for unknown signature: %lu", data_num, signature);
			rb_funcall (conn, Intern_receive_data, 1, rb_str_new (data_str, data_num));
			return;
		}
		case EM_CONNECTION_ACCEPTED:
		case EM_CONNECTION_UNBOUND:
		{
			rb_funcall (EmModule, Intern_event_callback, 3, ULONG2NUM(signature), INT2FIX(event), data_str ? rb_str_new(data_str,data_num) : ULONG2NUM(data_num));
			return;
		}
		case EM_CONNECTION_COMPLETED:
		{
			VALUE conn = ensure_conn(signature);
			rb_funcall (conn, Intern_connection_completed, 0);
			return;
		}
		case EM_CONNECTION_NOTIFY_READABLE:
		{
			VALUE conn = ensure_conn(signature);
			rb_funcall (conn, Intern_notify_readable, 0);
			return;
		}
		case EM_CONNECTION_NOTIFY_WRITABLE:
		{
			VALUE conn = ensure_conn(signature);
			rb_funcall (conn, Intern_notify_readable, 0);
			return;
		}
		case EM_LOOPBREAK_SIGNAL:
		{
			rb_funcall (EmModule, Intern_run_deferred_callbacks, 0);
			return;
		}
		case EM_TIMER_FIRED:
		{
			VALUE timer = rb_funcall (EmTimersHash, Intern_delete, 1, ULONG2NUM (data_num));
			if (timer == Qnil) {
				rb_raise (EM_eUnknownTimerFired, "no such timer: %lu", data_num);
			} else if (timer == Qfalse) {
				/* Timer Canceled */
			} else {
				rb_funcall (timer, Intern_call, 0);
			}
			return;
		}
		#ifdef WITH_SSL
		case EM_SSL_HANDSHAKE_COMPLETED:
		{
			VALUE conn = ensure_conn(signature);
			rb_funcall (conn, Intern_ssl_handshake_completed, 0);
			return;
		}
		case EM_SSL_VERIFY:
		{
			VALUE conn = ensure_conn(signature);
			VALUE should_accept = rb_funcall (conn, Intern_ssl_verify_peer, 1, rb_str_new(data_str, data_num));
			if (RTEST(should_accept))
				evma_accept_ssl_peer (signature);
			return;
		}
		#endif
		case EM_PROXY_TARGET_UNBOUND:
		{
			VALUE conn = ensure_conn(signature);
			rb_funcall (conn, Intern_proxy_target_unbound, 0);
			return;
		}
	}
}
Exemplo n.º 24
0
static VALUE rb_mysql_client_query(int argc, VALUE * argv, VALUE self) {
    struct nogvl_send_query_args args;
    fd_set fdset;
    int fd, retval;
    int async = 0;
    VALUE opts, defaults, read_timeout;
#ifdef HAVE_RUBY_ENCODING_H
    rb_encoding *conn_enc;
#endif
    struct timeval tv;
    struct timeval* tvp;
    long int sec;
    VALUE result;
    GET_CLIENT(self);

    REQUIRE_OPEN_DB(wrapper);
    args.mysql = wrapper->client;

    // see if this connection is still waiting on a result from a previous query
    if (wrapper->active == 0) {
        // mark this connection active
        wrapper->active = 1;
    } else {
        rb_raise(cMysql2Error, "This connection is still waiting for a result, try again once you have the result");
    }

    defaults = rb_iv_get(self, "@query_options");
    if (rb_scan_args(argc, argv, "11", &args.sql, &opts) == 2) {
        opts = rb_funcall(defaults, intern_merge, 1, opts);
        rb_iv_set(self, "@query_options", opts);

        if (rb_hash_aref(opts, sym_async) == Qtrue) {
            async = 1;
        }
    } else {
        opts = defaults;
    }

    Check_Type(args.sql, T_STRING);
#ifdef HAVE_RUBY_ENCODING_H
    conn_enc = rb_to_encoding(wrapper->encoding);
    // ensure the string is in the encoding the connection is expecting
    args.sql = rb_str_export_to_enc(args.sql, conn_enc);
#endif

    if (rb_thread_blocking_region(nogvl_send_query, &args, RUBY_UBF_IO, 0) == Qfalse) {
        // an error occurred, we're not active anymore
        MARK_CONN_INACTIVE(self);
        return rb_raise_mysql2_error(wrapper);
    }

    read_timeout = rb_iv_get(self, "@read_timeout");

    tvp = NULL;
    if (!NIL_P(read_timeout)) {
        Check_Type(read_timeout, T_FIXNUM);
        tvp = &tv;
        sec = FIX2INT(read_timeout);
        // TODO: support partial seconds?
        // also, this check is here for sanity, we also check up in Ruby
        if (sec >= 0) {
            tvp->tv_sec = sec;
        } else {
            rb_raise(cMysql2Error, "read_timeout must be a positive integer, you passed %ld", sec);
        }
        tvp->tv_usec = 0;
    }

    if (!async) {
        // the below code is largely from do_mysql
        // http://github.com/datamapper/do
        fd = wrapper->client->net.fd;
        for(;;) {
            int fd_set_fd = fd;

#if defined(_WIN32) && !defined(HAVE_RB_THREAD_BLOCKING_REGION)
            WSAPROTOCOL_INFO wsa_pi;
            // dupicate the SOCKET from libmysql
            int r = WSADuplicateSocket(fd, GetCurrentProcessId(), &wsa_pi);
            SOCKET s = WSASocket(wsa_pi.iAddressFamily, wsa_pi.iSocketType, wsa_pi.iProtocol, &wsa_pi, 0, 0);
            // create the CRT fd so ruby can get back to the SOCKET
            fd_set_fd = _open_osfhandle(s, O_RDWR|O_BINARY);
#endif

            FD_ZERO(&fdset);
            FD_SET(fd_set_fd, &fdset);

            retval = rb_thread_select(fd_set_fd + 1, &fdset, NULL, NULL, tvp);

#if defined(_WIN32) && !defined(HAVE_RB_THREAD_BLOCKING_REGION)
            // cleanup the CRT fd
            _close(fd_set_fd);
            // cleanup the duplicated SOCKET
            closesocket(s);
#endif

            if (retval == 0) {
                rb_raise(cMysql2Error, "Timeout waiting for a response from the last query. (waited %d seconds)", FIX2INT(read_timeout));
            }

            if (retval < 0) {
                rb_sys_fail(0);
            }

            if (retval > 0) {
                break;
            }
        }

        result = rb_mysql_client_async_result(self);

        return result;
    } else {
        return Qnil;
    }
}
Exemplo n.º 25
0
static VALUE rb_tinytds_result_each(int argc, VALUE * argv, VALUE self) {
  /* Local Vars */
  VALUE qopts, opts, block;
  ID timezone;
  int symbolize_keys = 0, as_array = 0, cache_rows = 0, first = 0, empty_sets = 0;
  tinytds_client_userdata *userdata;
  GET_RESULT_WRAPPER(self);
  userdata = (tinytds_client_userdata *)dbgetuserdata(rwrap->client);
  /* Merge Options Hash To Query Options. Populate Opts & Block Var. */
  qopts = rb_iv_get(self, "@query_options");
  if (rb_scan_args(argc, argv, "01&", &opts, &block) == 1)
    qopts = rb_funcall(qopts, intern_merge, 1, opts);
  rb_iv_set(self, "@query_options", qopts);
  /* Locals From Options */
  if (rb_hash_aref(qopts, sym_first) == Qtrue)
    first = 1;
  if (rb_hash_aref(qopts, sym_symbolize_keys) == Qtrue)
    symbolize_keys = 1;
  if (rb_hash_aref(qopts, sym_as) == sym_array)
    as_array = 1;
  if (rb_hash_aref(qopts, sym_cache_rows) == Qtrue)
    cache_rows = 1;
  if (rb_hash_aref(qopts, sym_timezone) == sym_local) {
    timezone = intern_local;
  } else if (rb_hash_aref(qopts, sym_timezone) == sym_utc) {
    timezone = intern_utc;
  } else {
    rb_warn(":timezone option must be :utc or :local - defaulting to :local");
    timezone = intern_local;
  }
  if (rb_hash_aref(qopts, sym_empty_sets) == Qtrue)
    empty_sets = 1;
  /* Make The Results Or Yield Existing */
  if (NIL_P(rwrap->results)) {
    RETCODE dbsqlok_rc, dbresults_rc;
    rwrap->results = rb_ary_new();
    dbsqlok_rc = rb_tinytds_result_ok_helper(rwrap->client);
    dbresults_rc = rb_tinytds_result_dbresults_retcode(self);
    while ((dbsqlok_rc == SUCCEED) && (dbresults_rc == SUCCEED)) {
      int has_rows = (DBROWS(rwrap->client) == SUCCEED) ? 1 : 0;
      if (has_rows || empty_sets || (rwrap->number_of_results == 0))
        rb_tinytds_result_fields(self);
      if ((has_rows || empty_sets) && rwrap->number_of_fields > 0) {
        /* Create rows for this result set. */
        unsigned long rowi = 0;
        VALUE result = rb_ary_new();
        while (nogvl_dbnextrow(rwrap->client) != NO_MORE_ROWS) {
          VALUE row = rb_tinytds_result_fetch_row(self, timezone, symbolize_keys, as_array);
          if (cache_rows)
            rb_ary_store(result, rowi, row);
          if (!NIL_P(block))
            rb_yield(row);
          if (first) {
            dbcanquery(rwrap->client);
            userdata->dbcancel_sent = 1;
          }
          rowi++;
        }
        rwrap->number_of_rows = rowi;
        /* Store the result. */
        if (cache_rows) {
          if (rwrap->number_of_results == 0) {
            rwrap->results = result;
          } else if (rwrap->number_of_results == 1) {
            VALUE multi_resultsets = rb_ary_new();
            rb_ary_store(multi_resultsets, 0, rwrap->results);
            rb_ary_store(multi_resultsets, 1, result);
            rwrap->results = multi_resultsets;
          } else {
            rb_ary_store(rwrap->results, rwrap->number_of_results, result);
          }
        }
        // If we find results increment the counter that helpers use and setup the next loop.
        rwrap->number_of_results = rwrap->number_of_results + 1;
        dbresults_rc = rb_tinytds_result_dbresults_retcode(self);
        rb_ary_store(rwrap->fields_processed, rwrap->number_of_results, Qnil);
      } else {
        // If we do not find results, side step the rb_tinytds_result_dbresults_retcode helper and
        // manually populate its memoized array while nullifing any memoized fields too before loop.
        dbresults_rc = nogvl_dbresults(rwrap->client);
        rb_ary_store(rwrap->dbresults_retcodes, rwrap->number_of_results, INT2FIX(dbresults_rc));
        rb_ary_store(rwrap->fields_processed, rwrap->number_of_results, Qnil);
      }
    }
    if (dbresults_rc == FAIL)
      rb_warn("TinyTDS: Something in the dbresults() while loop set the return code to FAIL.\n");
    userdata->dbsql_sent = 0;
  } else if (!NIL_P(block)) {
    unsigned long i;
    for (i = 0; i < rwrap->number_of_rows; i++) {
      rb_yield(rb_ary_entry(rwrap->results, i));
    }
  }
  return rwrap->results;
}
Exemplo n.º 26
0
static VALUE rb_mysql_client_query(int argc, VALUE * argv, VALUE self) {
#ifndef _WIN32
  struct async_query_args async_args;
#endif
  struct nogvl_send_query_args args;
  int async = 0;
  VALUE opts, defaults;
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *conn_enc;
#endif
  GET_CLIENT(self);

  REQUIRE_OPEN_DB(wrapper);
  args.mysql = wrapper->client;


  defaults = rb_iv_get(self, "@query_options");
  if (rb_scan_args(argc, argv, "11", &args.sql, &opts) == 2) {
    opts = rb_funcall(defaults, intern_merge, 1, opts);
    rb_iv_set(self, "@query_options", opts);

    if (rb_hash_aref(opts, sym_async) == Qtrue) {
      async = 1;
    }
  } else {
    opts = defaults;
  }

  Check_Type(args.sql, T_STRING);
#ifdef HAVE_RUBY_ENCODING_H
  conn_enc = rb_to_encoding(wrapper->encoding);
  // ensure the string is in the encoding the connection is expecting
  args.sql = rb_str_export_to_enc(args.sql, conn_enc);
#endif
  args.sql_ptr = StringValuePtr(args.sql);
  args.sql_len = RSTRING_LEN(args.sql);

  // see if this connection is still waiting on a result from a previous query
  if (wrapper->active == 0) {
    // mark this connection active
    wrapper->active = 1;
  } else {
    rb_raise(cMysql2Error, "This connection is still waiting for a result, try again once you have the result");
  }

  args.wrapper = wrapper;

#ifndef _WIN32
  rb_rescue2(do_send_query, (VALUE)&args, disconnect_and_raise, self, rb_eException, (VALUE)0);

  if (!async) {
    async_args.fd = wrapper->client->net.fd;
    async_args.self = self;

    rb_rescue2(do_query, (VALUE)&async_args, disconnect_and_raise, self, rb_eException, (VALUE)0);

    return rb_mysql_client_async_result(self);
  } else {
    return Qnil;
  }
#else
  do_send_query(&args);

  // this will just block until the result is ready
  return rb_ensure(rb_mysql_client_async_result, self, finish_and_mark_inactive, self);
#endif
}
Exemplo n.º 27
0
// prereq: len > 0
static void _nested_aset(VALUE output, volatile VALUE keys, VALUE value) {
  volatile VALUE klass = rb_obj_class(output);
  VALUE* arr = RARRAY_PTR(keys);
  long len = RARRAY_LEN(keys);

  // first key seg
  if (!RSTRING_LEN(arr[0])) {
    rb_raise(rb_eRuntimeError, "array key at:0 conflicts with hash");
  }
  bool is_hash_key = true;

# define NEW_CHILD(child) \
    volatile VALUE child = (next_is_hash_key ? rb_class_new_instance(0, NULL, klass) : rb_ary_new());
# define ASSERT_HASH \
    if (TYPE(output) != T_HASH) {\
      rb_raise(rb_eTypeError, "hash key at:%ld conflicts with array", i + 1);\
    }
# define ASSERT_ARRAY \
    if (TYPE(output) != T_ARRAY) {\
      rb_raise(rb_eTypeError, "array key at:%ld conflicts with hash", i + 1);\
    }
# define CHECK_NEXT \
    if (next_is_hash_key) {\
      ASSERT_HASH;\
    } else {\
      ASSERT_ARRAY;\
    }

  // special treatment to array keys according to last 2 segments:
  // *[][foo] append new hash if already exists
  //
  // normal cases:
  // *[]      just push
  // *[foo]   find last elem first
  // *[]*     find last elem first

  // middle key segs
  for (long i = 0; i < len - 1; i++) {
    bool next_is_hash_key = RSTRING_LEN(arr[i + 1]);
    if (is_hash_key) {
      if (nyara_rb_hash_has_key(output, arr[i])) {
        output = rb_hash_aref(output, arr[i]);
        CHECK_NEXT;
      } else {
        NEW_CHILD(child);
        rb_hash_aset(output, arr[i], child);
        output = child;
      }
    } else {
      // array key, try to use the last elem
      long output_len = RARRAY_LEN(output);
      if (output_len) {
        bool append = false;
        if (i == len - 2 && next_is_hash_key) {
          volatile VALUE next_hash = RARRAY_PTR(output)[output_len - 1];
          if (nyara_rb_hash_has_key(next_hash, arr[i + 1])) {
            append = true;
          }
        }
        if (append) {
          volatile VALUE child = rb_class_new_instance(0, NULL, klass);
          rb_ary_push(output, child);
          output = child;
        } else {
          output = RARRAY_PTR(output)[output_len - 1];
          CHECK_NEXT;
        }
      } else {
        NEW_CHILD(child);
        rb_ary_push(output, child);
        output = child;
      }
    }
    is_hash_key = next_is_hash_key;
  }

# undef CHECK_NEXT
# undef ASSERT_ARRAY
# undef ASSERT_HASH
# undef NEW_CHILD

  // terminate seg
  if (is_hash_key) {
    rb_hash_aset(output, arr[len - 1], value);
  } else {
    rb_ary_push(output, value);
  }
}
Exemplo n.º 28
0
/* CHANGED */
void
wsf_util_create_op_and_add_to_svc (
    wsf_svc_info_t * svc_info,
    char *action,
    axutil_env_t * env,
    char *op_name,
    VALUE ht_mep)
{
    axis2_svc_t *svc = NULL;
    axis2_op_t *op = NULL;
    axutil_qname_t *op_qname = NULL;
    op_qname = axutil_qname_create (env, op_name, NULL, NULL);
    svc = svc_info->svc;

    if (NULL != svc && NULL != op_name) {
        op = axis2_svc_get_op_with_name (svc_info->svc, env, op_name);
        if (!op) {
            axis2_conf_t *conf = NULL;
            axis2_conf_ctx_t *conf_ctx = NULL;
            axis2_phases_info_t *info = NULL;

            op_qname = axutil_qname_create (env, op_name, NULL, NULL);

            op = axis2_op_create_with_qname (env, op_qname);

            axis2_op_set_msg_recv (op, env, svc_info->msg_recv);

            conf_ctx = wsf_worker_get_conf_ctx (svc_info->ruby_worker, env);

            conf = axis2_conf_ctx_get_conf (conf_ctx, env);

            info = axis2_conf_get_phases_info (conf, env);
            axis2_phases_info_set_op_phases (info, env, op);
            axis2_svc_add_op (svc_info->svc, env, op);

            if (ht_mep) {
                char operation[300];
                VALUE mep_value;
                char *mep;

                AXIS2_LOG_DEBUG (env->log, AXIS2_LOG_SI,
                                 "[wsf_service] ht mep not null, %s", op_name);
                snprintf (operation, sizeof(operation), "%s", op_name);
                if(TYPE(ht_mep) == T_HASH)
                {
                    mep_value = rb_hash_aref(ht_mep, ID2SYM(rb_intern(operation)));
                }
                if(mep_value != Qnil)
                {
                    mep = RSTRING(mep_value)->ptr;
                    if (mep) {
                        AXIS2_LOG_DEBUG (env->log, AXIS2_LOG_SI,
                                         "[wsf_service] op mep %s", mep);
                        if (strcmp (mep, "IN_ONLY") == 0) {
                            axis2_op_set_msg_exchange_pattern (op, env,
                                                               AXIS2_MEP_URI_IN_ONLY);
                            AXIS2_LOG_DEBUG (env->log, AXIS2_LOG_SI,
                                             "[wsf_service] AXIS2_MEP_URI_IN_ONLY");

                        } else if (strcmp (mep, "IN_OUT") == 0) {
                            axis2_op_set_msg_exchange_pattern (op, env,
                                                               AXIS2_MEP_URI_IN_OUT);
                            AXIS2_LOG_DEBUG (env->log, AXIS2_LOG_SI,
                                             "[wsf_service] AXIS2_MEP_URI_IN_OUT");
                        }
                    }
                }
                else {
                    AXIS2_LOG_DEBUG (env->log, AXIS2_LOG_SI,
                                     "[wsf service] message exchange pattern for %s not found",
                                     op_name);
                }
            }
            if (action) {
                axis2_svc_add_mapping (svc_info->svc, env, action, op);
            }
        }
    }
    if(op_qname) {
        axutil_qname_free(op_qname, env);
    }

    return;
}
Exemplo n.º 29
0
static VALUE header_hash_aref(VALUE self, VALUE key) {
  return rb_hash_aref(self, header_hash_tidy_key(key));
}
Exemplo n.º 30
0
/*
 * Initialize new CouchRequest
 *
 * @since 1.2.0
 *
 * @return [Bucket::CouchRequest]
 */
VALUE
cb_http_request_init(int argc, VALUE *argv, VALUE self)
{
    struct cb_http_request_st *request = DATA_PTR(self);
    VALUE bucket, path, opts, on_body, pp, arg;
    rb_scan_args(argc, argv, "22", &bucket, &pp, &opts, &on_body);

    if (NIL_P(on_body) && rb_block_given_p()) {
        on_body = rb_block_proc();
    }
    if (CLASS_OF(bucket) != cb_cBucket) {
        rb_raise(rb_eTypeError, "wrong argument type (expected Couchbase::Bucket)");
    }
    memset(&request->cmd, 0, sizeof(lcb_http_cmd_t));
    request->type = LCB_HTTP_TYPE_VIEW;
    request->on_body_callback = on_body;
    request->bucket = DATA_PTR(bucket);
    request->bucket_obj = bucket;
    request->extended = Qfalse;
    path = StringValue(pp);	/* convert path to string */
    request->cmd.v.v0.path = strdup(RSTRING_PTR(path));
    request->cmd.v.v0.npath = RSTRING_LEN(path);
    request->cmd.v.v0.method = LCB_HTTP_METHOD_GET;
    request->cmd.v.v0.content_type = strdup("application/json");

    if (opts != Qnil) {
        Check_Type(opts, T_HASH);
        request->extended = RTEST(rb_hash_aref(opts, cb_sym_extended));
        request->cmd.v.v0.chunked = RTEST(rb_hash_aref(opts, cb_sym_chunked));
        if ((arg = rb_hash_aref(opts, cb_sym_type)) != Qnil) {
            if (arg == cb_sym_view) {
                request->type = LCB_HTTP_TYPE_VIEW;
            } else if (arg == cb_sym_management) {
                request->type = LCB_HTTP_TYPE_MANAGEMENT;
            } else {
                rb_raise(rb_eArgError, "unsupported request type");
            }
        }
        if ((arg = rb_hash_aref(opts, cb_sym_method)) != Qnil) {
            if (arg == cb_sym_get) {
                request->cmd.v.v0.method = LCB_HTTP_METHOD_GET;
            } else if (arg == cb_sym_post) {
                request->cmd.v.v0.method = LCB_HTTP_METHOD_POST;
            } else if (arg == cb_sym_put) {
                request->cmd.v.v0.method = LCB_HTTP_METHOD_PUT;
            } else if (arg == cb_sym_delete) {
                request->cmd.v.v0.method = LCB_HTTP_METHOD_DELETE;
            } else {
                rb_raise(rb_eArgError, "unsupported HTTP method");
            }
        }
        if ((arg = rb_hash_aref(opts, cb_sym_body)) != Qnil) {
            Check_Type(arg, T_STRING);
            request->cmd.v.v0.body = strdup(RSTRING_PTR(arg));
            request->cmd.v.v0.nbody = RSTRING_LEN(arg);
        }
        if ((arg = rb_hash_aref(opts, cb_sym_content_type)) != Qnil) {
            Check_Type(arg, T_STRING);
            free((char *)request->cmd.v.v0.content_type);
            request->cmd.v.v0.content_type = strdup(RSTRING_PTR(arg));
        }
    }

    return self;
}