Ejemplo n.º 1
0
/**
 * @function net.listen
 * 
 * ### Synopsis
 * 
 * var sock = net.listen(port);
 * var sock = net.listen(port, backlog);
 * var sock = net.listen(port, backlog, ip);
 * 
 * This function creates a TCP SOCK_STREAM socket, binds it to the specified port, and does a listen(2) on the socket.
 * 
 * Connections to the socket from the outside world can be accepted via net.accept().
 * 
 * The backlog argument specifies the maximum length for the queue of pending connections.  If the queue fills and another connection attempt is made, the client will likely receive a "connection refused" error.
 * 
 * The ip argument specifies what IP address to listen on.  By default, it will be 0.0.0.0 for "listen on any IP."  If you set this to a different value, only that IP will be listened on, and the socket will not be reachable via localhost (for example).
 * 
 * @param {int} port - port number to listen on
 * @param {int} backlog - length of pending connection queue
 * @param {string} ip - ip address to listen on
 * @return {int} sock - file descriptor of socket in listen mode
 * 
 * ### Exceptions
 * This function throws an exception of the socket(), bind(), or listen() OS calls fail.
 */
static JSVAL net_listen (JSARGS args) {
    HandleScope scope;
    int port = args[0]->IntegerValue();
    int backlog = 30;
    if (args.Length() > 1) {
        backlog = args[1]->IntegerValue();
    }
    int listenAddress = INADDR_ANY;
#ifdef WIN32
	char *listenAddressString = (char *)"0.0.0.0";
	WSADATA wsaData = {0};
    int iResult = 0;

	int sock = INVALID_SOCKET;
    int iFamily = AF_UNSPEC;
    int iType = 0;
    int iProtocol = 0;

	iFamily = AF_INET;
    iType = SOCK_STREAM;
    iProtocol = 0;
    
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
		char str_ret[128];
        scanf(str_ret, L"%d\n", iResult);
		return ThrowException(String::Concat(String::New("socket() Error: "), String::New(str_ret)));
    }

#else
    char *listenAddressString = (char *)'0.0.0.0';
#endif

    if (args.Length() > 2) {
        String::AsciiValue addr(args[2]);
        listenAddressString = *addr;
        listenAddress = inet_addr(*addr);
    }

#ifdef WIN32
    sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == INVALID_SOCKET) {
		char str_int[128];

		scanf(str_int, "%d", 0);
        return ThrowException(String::Concat(String::New("socket() Error: "), String::New(str_int)));
    }
#else
    int sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock < 0) {
        return ThrowException(String::Concat(String::New("socket() Error: "), String::New(strerror(errno))));
    }
#endif

    {
        int on = 1;
        setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof (on));
    }

    struct sockaddr_in my_addr;
#ifdef WIN32
	memset(&my_addr, 0, sizeof(my_addr));
#else
    bzero(&my_addr, sizeof (my_addr));
#endif
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(port);
//    printf("listenAddress: '%s' %08x\n", listenAddressString, listenAddress);

    my_addr.sin_addr.s_addr = listenAddress; // htonl(listenAddress);

    if (bind(sock, (struct sockaddr *) &my_addr, sizeof (my_addr))) {
        return ThrowException(String::Concat(String::New("bind()Error: "), String::New(strerror(errno))));
    }

    if (listen(sock, backlog)) {
        return ThrowException(String::Concat(String::New("listen() Error: "), String::New(strerror(errno))));
    }
    return scope.Close(Integer::New(sock));
}
Ejemplo n.º 2
0
Archivo: js.cpp Proyecto: sol/v8
Local<Value> c_runScript(const char* input) {
  HandleScope scope;
  Local<Value> value = Script::Compile(String::New(input))->Run();
  return scope.Close(value);
}
Ejemplo n.º 3
0
static JSVAL sqlite_extended_errcode(JSARGS args) {
    HandleScope scope;
    Local<External>wrap = Local<External>::Cast(args[0]);
    sqlite3 *db = (sqlite3 *)wrap->Value();
    return scope.Close(Integer::New(sqlite3_extended_errcode(db)));
}
Ejemplo n.º 4
0
Handle<Value>
Session::subscribe(const Arguments& args, bool resubscribe)
{
    HandleScope scope;

    if (args.Length() < 1 || !args[0]->IsArray()) {
        return ThrowException(Exception::Error(String::New(
                "Array of subscription information must be provided.")));
    }
    if (args.Length() >= 2 && !args[1]->IsUndefined() && !args[1]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Optional subscription label must be a string.")));
    }
    if (args.Length() > 2) {
        return ThrowException(Exception::Error(String::New(
                "Function expects at most two arguments.")));
    }

    blpapi::SubscriptionList sl;

    Local<Object> o = args[0]->ToObject();
    for (std::size_t i = 0; i < Array::Cast(*(args[0]))->Length(); ++i) {
        Local<Value> v = o->Get(i);
        if (!v->IsObject()) {
            return ThrowException(Exception::Error(String::New(
                        "Array elements must be objects "
                        "containing subscription information.")));
        }
        Local<Object> io = v->ToObject();

        // Process 'security' string
        Local<Value> iv = io->Get(String::New("security"));
        if (!iv->IsString()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'security' must be a string.")));
        }
        String::Utf8Value secv(iv);
        if (0 == secv.length()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'security' must be a string.")));
        }

        // Process 'fields' array
        iv = io->Get(String::New("fields"));
        if (!iv->IsArray()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'fields' must be an array of strings.")));
        }
        std::string fields;
        formFields(&fields, iv->ToObject());

        // Process 'options' array
        iv = io->Get(String::New("options"));
        if (!iv->IsUndefined() && !iv->IsNull() && !iv->IsObject()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'options' must be an object containing "
                        "whose keys and key values will be configured as "
                        "options.")));
        }
        std::string options;
        formOptions(&options, iv);

        // Process 'correlation' int or string
        iv = io->Get(String::New("correlation"));
        if (!iv->IsInt32()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'correlation' must be an integer.")));
        }
        int correlation = iv->Int32Value();

        sl.add(*secv, fields.c_str(), options.c_str(),
               blpapi::CorrelationId(correlation));
    }

    Session* session = ObjectWrap::Unwrap<Session>(args.This());

    BLPAPI_EXCEPTION_TRY
    if (args.Length() == 2) {
        Local<String> s = args[1]->ToString();
        String::Utf8Value labelv(s);
        if (resubscribe)
            session->d_session->resubscribe(sl, *labelv, labelv.length());
        else
            session->d_session->subscribe(sl, *labelv, labelv.length());
    } else {
        if (resubscribe)
            session->d_session->resubscribe(sl);
        else
            session->d_session->subscribe(sl);
    }
    BLPAPI_EXCEPTION_CATCH_RETURN

    return scope.Close(args.This());
}
Ejemplo n.º 5
0
Handle<Value> rs::Fetch(const v8::Arguments& args){
    HandleScope scope;
    rs* _this = node::ObjectWrap::Unwrap<rs>(args.This());

    std::vector<MetaData> metaData = _this->_rs->getColumnListMetaData();

    int columnCount = metaData.size();

    if ( columnCount > 0 ){

    	int32_t arrayIndex = 0;

    	if ( _this->_rs->next() ){
    		Local<Object> js_field_obj = Object::New();

	    	Local<String> pName;

	    	for ( int i = 0; i < columnCount; i++ ) {
	    		pName = V8STR(metaData[i].getString(MetaData::ATTR_NAME).c_str());

	    		int pNum = i+1;
    	    	switch ( metaData[i].getInt(MetaData::ATTR_DATA_TYPE) ){
    	    		case OCCI_SQLT_AFC :
    	    		case OCCI_SQLT_VCS :
    	    		case OCCI_SQLT_STR :
    	    		case OCCI_SQLT_CHR : {
    	    				std::string pVal = _this->_rs->getString(pNum);
    	    	    	    js_field_obj->Set(
    	    					pName,
    	    					V8STR(pVal.c_str())
    	    				);
    	    			}
    	    	        break;
    	    		case OCCIFLOAT :
    	    		case OCCI_SQLT_NUM : {
    	    				double pVal = _this->_rs->getDouble(pNum);
    	    	    	    js_field_obj->Set(
    	    					pName,
    	    					v8::Number::New(pVal)
    	    				);
    	    			}
    	    	        break;
    	    		case OCCIINT : {
    	    				int32_t pVal = _this->_rs->getInt(pNum);
    	    				js_field_obj->Set(
    	    					pName,
    	    					v8::Integer::NewFromUnsigned(pVal)
    	    	    		);
    	    			}
    	    			break;
    	    		case OCCI_SQLT_CLOB: {
							Clob lClob = _this->_rs->getClob(pNum);
							lClob.setCharSetForm(OCCI_SQLCS_NCHAR);
							if (lClob.isNull() ){
								js_field_obj->Set(
	    	    					pName,
	    	    					String::New("")
	    	    	    		);
							}
							else {
								lClob.open(OCCI_LOB_READONLY);

								const unsigned int BUFSIZE = 100000;
								unsigned char buffer[BUFSIZE];
								unsigned int readAmt=BUFSIZE;
								unsigned int offset=1;

								memset(buffer,0,sizeof(buffer));
								lClob.read(readAmt,buffer,BUFSIZE,offset);

								lClob.close();

								js_field_obj->Set(
	    	    					pName,
	    	    					String::New((const char*)buffer)
	    	    	    		);
							}
    	    			}
    	    	        break;
    	    	}
    	    }

	    	return scope.Close(js_field_obj);
    	}
    }

    return scope.Close(False());
}
Ejemplo n.º 6
0
v8::Handle<v8::Value> DocumentCopyingContextDriver::CreateFormXObjectFromPDFPage(const v8::Arguments& args)
{
    HandleScope scope;
    
    DocumentCopyingContextDriver* copyingContextDriver = ObjectWrap::Unwrap<DocumentCopyingContextDriver>(args.This());
    
    if(!copyingContextDriver->CopyingContext)
    {
		ThrowException(Exception::TypeError(String::New("copying context object not initialized, create using pdfWriter.createPDFCopyingContext")));
        return scope.Close(Undefined());
    }
    
    if(args.Length() < 2 ||
       args.Length() > 3 ||
       !args[0]->IsNumber() ||
       (!args[1]->IsNumber() && !args[1]->IsArray()) ||
       (args.Length() == 3 && !args[2]->IsArray()))
    {
		ThrowException(Exception::TypeError(String::New("Wrong arguments. provide 2 or 3 arugments, where the first is a 0 based page index, and the second is a EPDFPageBox enumeration value or a 4 numbers array defining an box. a 3rd parameter may be provided to deisgnate the result form matrix")));
        return scope.Close(Undefined());
    }
 
    double matrixBuffer[6];
    double* transformationMatrix = NULL;
    
    if(args.Length() == 3)
    {
        Handle<Object> matrixArray = args[2]->ToObject();
        if(matrixArray->Get(v8::String::New("length"))->ToObject()->Uint32Value() != 6)
        {
            ThrowException(Exception::TypeError(String::New("matrix array should be 6 numbers long")));
            return scope.Close(Undefined());
        }
        
        for(int i=0;i<6;++i)
            matrixBuffer[i] = matrixArray->Get(i)->ToNumber()->Value();
        transformationMatrix = matrixBuffer;
    }
    
    
    EStatusCodeAndObjectIDType result;
    
    if(args[0]->IsNumber())
    {
        result = copyingContextDriver->CopyingContext->CreateFormXObjectFromPDFPage(args[0]->ToNumber()->Uint32Value(),
                                                                       (EPDFPageBox)args[1]->ToNumber()->Uint32Value(),
                                                                                    transformationMatrix);
    }
    else
    {
        Handle<Object> boxArray = args[1]->ToObject();
        if(boxArray->Get(v8::String::New("length"))->ToObject()->Uint32Value() != 4)
        {
            ThrowException(Exception::TypeError(String::New("box dimensions array should be 4 numbers long")));
            return scope.Close(Undefined());
        }
        
        PDFRectangle box(boxArray->Get(0)->ToNumber()->Value(),
                         boxArray->Get(1)->ToNumber()->Value(),
                         boxArray->Get(2)->ToNumber()->Value(),
                         boxArray->Get(3)->ToNumber()->Value());
        
        result = copyingContextDriver->CopyingContext->CreateFormXObjectFromPDFPage(args[0]->ToNumber()->Uint32Value(),
                                                                                    box,
                                                                                    transformationMatrix);

    }
        
    
    if(result.first != eSuccess)
    {
		ThrowException(Exception::Error(String::New("Unable to create form xobject from PDF page, parhaps the page index does not fit the total pages count")));
        return scope.Close(Undefined());
    }
    
    Local<Number> idValue = Number::New(result.second);
    
    return scope.Close(idValue);
}
Handle<Value> CreateEngine(const Arguments& args) {
	HandleScope scope;
	return scope.Close( Audio::AudioEngine::NewInstance(args) );
} // end CreateEngine()
Ejemplo n.º 8
0
Handle<Object> GetTableCall::buildDBColumn(const NdbDictionary::Column *col) {
  HandleScope scope;
  
  Local<Object> obj = NdbDictColumnEnv.newWrapper();
  wrapPointerInObject(col, NdbDictColumnEnv, obj);  
  
  NdbDictionary::Column::Type col_type = col->getType();
  bool is_int = (col_type <= NDB_TYPE_BIGUNSIGNED);
  bool is_dec = ((col_type == NDB_TYPE_DECIMAL) || (col_type == NDB_TYPE_DECIMALUNSIGNED));
  bool is_binary = ((col_type == NDB_TYPE_BLOB) || (col_type == NDB_TYPE_BINARY) 
                   || (col_type == NDB_TYPE_VARBINARY) || (col_type == NDB_TYPE_LONGVARBINARY));
  bool is_char = ((col_type == NDB_TYPE_CHAR) || (col_type == NDB_TYPE_TEXT)
                   || (col_type == NDB_TYPE_VARCHAR) || (col_type == NDB_TYPE_LONGVARCHAR));

  /* Required Properties */

  obj->Set(String::NewSymbol("name"),
           String::New(col->getName()),
           ReadOnly);
  
  obj->Set(String::NewSymbol("columnNumber"),
           v8::Int32::New(col->getColumnNo()),
           ReadOnly);
  
  obj->Set(String::NewSymbol("columnType"), 
           getColumnType(col), 
           ReadOnly);

  obj->Set(String::NewSymbol("isIntegral"),
           Boolean::New(is_int),
           ReadOnly);

  obj->Set(String::NewSymbol("isNullable"),
           Boolean::New(col->getNullable()),
           ReadOnly);

  obj->Set(String::NewSymbol("isInPrimaryKey"),
           Boolean::New(col->getPrimaryKey()),
           ReadOnly);

  obj->Set(String::NewSymbol("columnSpace"),
           v8::Int32::New(col->getSizeInBytes()),
           ReadOnly);           

  /* Implementation-specific properties */
  
  obj->Set(String::NewSymbol("ndbTypeId"),
           v8::Int32::New(static_cast<int>(col->getType())),
           ReadOnly);

  obj->Set(String::NewSymbol("ndbRawDefaultValue"),
           getDefaultValue(col), 
           ReadOnly);
  
  /* Optional Properties, depending on columnType */
  /* Group A: Numeric */
  if(is_int || is_dec) {
    obj->Set(String::NewSymbol("isUnsigned"),
             getIntColumnUnsigned(col),
             ReadOnly);
  }
  
  if(is_int) {    
    obj->Set(String::NewSymbol("intSize"),
             v8::Int32::New(col->getSizeInBytes()),
             ReadOnly);
  }
  
  if(is_dec) {
    obj->Set(String::NewSymbol("scale"),
             v8::Int32::New(col->getScale()),
             ReadOnly);
    
    obj->Set(String::NewSymbol("precision"),
             v8::Int32::New(col->getPrecision()),
             ReadOnly);
  }
  
  /* Group B: Non-numeric */
  if(is_binary || is_char) {  
    obj->Set(String::NewSymbol("length"),
             v8::Int32::New(col->getLength()),
             ReadOnly);

    obj->Set(String::NewSymbol("isBinary"),
             Boolean::New(is_binary),
             ReadOnly);
  
    if(is_char) {
      obj->Set(String::NewSymbol("charsetNumber"),
               Number::New(col->getCharsetNumber()),
               ReadOnly);
      // todo: charsetName
    }
  }
    
  return scope.Close(obj);
} 
Ejemplo n.º 9
0
Handle<Value> GeometryFactory::GetSRID(const Arguments& args) {
    HandleScope scope;
    GeometryFactory *factory = ObjectWrap::Unwrap<GeometryFactory>(args.This());
    return scope.Close(Integer::New(factory->_factory->getSRID()));
}
Ejemplo n.º 10
0
Handle<Value> Hello(const Arguments& args) {
    HandleScope scope;
    std::string hellostring("hello");
    return scope.Close(String::New(hellostring.c_str()));
}
Ejemplo n.º 11
0
Handle<Value> Method(const Arguments& args) {
  HandleScope scope;
  return scope.Close(String::New("world"));
}
Ejemplo n.º 12
0
int Database::EIO_AfterQuery(eio_req *req) {
  //printf("Database::EIO_AfterQuery\n");
  ev_unref(EV_DEFAULT_UC);

  struct query_request *prep_req = (struct query_request *)(req->data);
  
  HandleScope scope;
  
  Database *self = prep_req->dbo->self(); //an easy reference to the Database object
  Local<Object> objError = Object::New(); //our error object which we will use if we discover errors while processing the result set
  
  short colCount = 0; //used to keep track of the number of columns received in a result set
  short emitCount = 0; //used to keep track of the number of event emittions that have occurred
  short errorCount = 0; //used to keep track of the number of errors that have been found
  
  SQLSMALLINT buflen; //used as a place holder for the length of column names
  SQLRETURN ret; //used to capture the return value from various SQL function calls
  
  char *buf = (char *) malloc(MAX_VALUE_SIZE); //allocate a buffer for incoming column values
  
  //check to make sure malloc succeeded
  if (buf == NULL) {
    //malloc failed, set an error message
    objError->Set(String::New("error"), String::New("[node-odbc] Failed Malloc"));
    objError->Set(String::New("message"), String::New("An attempt to allocate memory failed. This allocation was for a value buffer of incoming recordset values."));
    
    //emit an error event immidiately.
    Local<Value> args[3];
    args[0] = objError;
    args[1] = Local<Value>::New(Null());
    args[2] = Local<Boolean>::New(False());
    
    //emit an error event
    self->Emit(String::New("error"), 3, args);
    
    //emit a result event
    self->Emit(String::New("result"), 3, args);
  }
  else {
    //malloc succeeded so let's continue -- I'm not too fond of having all this code in the else statement, but I don't know what else to do...
    
    memset(buf,0,MAX_VALUE_SIZE); //set all of the bytes of the buffer to 0; I tried doing this inside the loop, but it increased processing time dramatically
    struct tm timeInfo = { 0 }; //used for processing date/time datatypes 
    
    //First thing, let's check if the execution of the query returned any errors (in EIO_Query)
    if(req->result == SQL_ERROR)
    {
      errorCount++;
      
      char errorMessage[512];
      char errorSQLState[128];
      SQLError(self->m_hEnv, self->m_hDBC, self->m_hStmt,(SQLCHAR *)errorSQLState,NULL,(SQLCHAR *)errorMessage, sizeof(errorMessage), NULL);
      objError->Set(String::New("state"), String::New(errorSQLState));
      objError->Set(String::New("error"), String::New("[node-odbc] SQL_ERROR"));
      objError->Set(String::New("message"), String::New(errorMessage));
      
      //only set the query value of the object if we actually have a query
      if (prep_req->sql != NULL) {
        objError->Set(String::New("query"), String::New(prep_req->sql));
      }
      
      //emit an error event immidiately.
      Local<Value> args[1];
      args[0] = objError;
      self->Emit(String::New("error"), 1, args);
    }
    
    //loop through all result sets
    do {
      colCount = 0; //always reset colCount for the current result set to 0;
      
      SQLNumResultCols(self->m_hStmt, &colCount);
      Column *columns = new Column[colCount];
      
      Local<Array> rows = Array::New();
      
      if (colCount > 0) {
        // retrieve and store column attributes to build the row object
        for(int i = 0; i < colCount; i++)
        {
          columns[i].name = new unsigned char[MAX_FIELD_SIZE];
          
          //zero out the space where the column name will be stored
          memset(columns[i].name, 0, MAX_FIELD_SIZE);
          
          //get the column name
          ret = SQLColAttribute(self->m_hStmt, (SQLUSMALLINT)i+1, SQL_DESC_LABEL, columns[i].name, (SQLSMALLINT)MAX_FIELD_SIZE, (SQLSMALLINT *)&buflen, NULL);
          
          //store the len attribute
          columns[i].len = buflen;
          
          //get the column type and store it directly in column[i].type
          ret = SQLColAttribute( self->m_hStmt, (SQLUSMALLINT)i+1, SQL_COLUMN_TYPE, NULL, NULL, NULL, &columns[i].type );
        }
        
        int count = 0;
        
        // i dont think odbc will tell how many rows are returned, loop until out...
        while(true)
        {
          Local<Object> tuple = Object::New();
          ret = SQLFetch(self->m_hStmt);
          
          //TODO: Do something to enable/disable dumping these info messages to the console.
          if (ret == SQL_SUCCESS_WITH_INFO ) {
            char errorMessage[512];
            char errorSQLState[128];
            SQLError(self->m_hEnv, self->m_hDBC, self->m_hStmt,(SQLCHAR *)errorSQLState,NULL,(SQLCHAR *)errorMessage, sizeof(errorMessage), NULL);
            
            //printf("EIO_Query ret => %i\n", ret);
            printf("EIO_Query => %s\n", errorMessage);
            printf("EIO_Query => %s\n", errorSQLState);
            //printf("EIO_Query sql => %s\n", prep_req->sql);
          }
          
          if (ret == SQL_ERROR)  {
            char errorMessage[512];
            char errorSQLState[128];
            SQLError(self->m_hEnv, self->m_hDBC, self->m_hStmt,(SQLCHAR *)errorSQLState,NULL,(SQLCHAR *)errorMessage, sizeof(errorMessage), NULL);
            
            errorCount++;
            objError->Set(String::New("state"), String::New(errorSQLState));
	    objError->Set(String::New("error"), String::New("[node-odbc] SQL_ERROR"));
            objError->Set(String::New("message"), String::New(errorMessage));
            objError->Set(String::New("query"), String::New(prep_req->sql));
            
            //emit an error event immidiately.
            Local<Value> args[1];
            args[0] = objError;
            self->Emit(String::New("error"), 1, args);
            
            break;
          }
          
          if (ret == SQL_NO_DATA) {
            break;
          }
          
          for(int i = 0; i < colCount; i++)
          {
            SQLLEN len;
            
            // SQLGetData can supposedly return multiple chunks, need to do this to retrieve large fields
            int ret = SQLGetData(self->m_hStmt, i+1, SQL_CHAR, (char *) buf, MAX_VALUE_SIZE-1, (SQLLEN *) &len);
            
            //printf("%s %i\n", columns[i].name, columns[i].type);
            
            if(ret == SQL_NULL_DATA || len < 0)
            {
              tuple->Set(String::New((const char *)columns[i].name), Null());
            }
            else
            { 
              switch (columns[i].type) {
                case SQL_NUMERIC :
                  tuple->Set(String::New((const char *)columns[i].name), Number::New(atof(buf)));
                  break;
                case SQL_DECIMAL :
                  tuple->Set(String::New((const char *)columns[i].name), Number::New(atof(buf)));
                  break;
                case SQL_INTEGER :
                  tuple->Set(String::New((const char *)columns[i].name), Number::New(atof(buf)));
                  break;
                case SQL_SMALLINT :
                  tuple->Set(String::New((const char *)columns[i].name), Number::New(atof(buf)));
                  break;
                case SQL_FLOAT :
                  tuple->Set(String::New((const char *)columns[i].name), Number::New(atof(buf)));
                  break;
                case SQL_REAL :
                  tuple->Set(String::New((const char *)columns[i].name), Number::New(atof(buf)));
                  break;
                case SQL_DOUBLE :
                  tuple->Set(String::New((const char *)columns[i].name), Number::New(atof(buf)));
                  break;
                case SQL_DATETIME :
                case SQL_TIMESTAMP :
                  //I am not sure if this is locale-safe or cross database safe, but it works for me on MSSQL
                  strptime(buf, "%Y-%m-%d %H:%M:%S", &timeInfo);
                  timeInfo.tm_isdst = -1; //a negative value means that mktime() should (use timezone information and system 
                        //databases to) attempt to determine whether DST is in effect at the specified time.
                  
                  tuple->Set(String::New((const char *)columns[i].name), Date::New(mktime(&timeInfo) * 1000));
                  
                  break;
                case SQL_BIT :
                  //again, i'm not sure if this is cross database safe, but it works for MSSQL
                  tuple->Set(String::New((const char *)columns[i].name), Boolean::New( ( *buf == '0') ? false : true ));
                  break;
                default :
                  tuple->Set(String::New((const char *)columns[i].name), String::New(buf));
                  break;
              }
            }
          }
          
          rows->Set(Integer::New(count), tuple);
          count++;
        }
        
        for(int i = 0; i < colCount; i++)
        {
          delete [] columns[i].name;
        }

        delete [] columns;
      }
      
      //move to the next result set
      ret = SQLMoreResults( self->m_hStmt );
      
      if ( ret != SQL_SUCCESS ) {
        //there are no more recordsets so free the statement now before we emit
        //because as soon as we emit the last recordest, we are clear to submit another query
        //which could cause a race condition with freeing and allocating handles.
        SQLFreeStmt( self->m_hStmt, NULL );
        SQLAllocHandle( SQL_HANDLE_STMT, self->m_hDBC, &self->m_hStmt );
      }
      
      //Only trigger an emit if there are columns OR if this is the last result and none others have been emitted
      //odbc will process individual statments like select @something = 1 as a recordset even though it doesn't have
      //any columns. We don't want to emit those unless there are actually columns
      if (colCount > 0 || ( ret != SQL_SUCCESS && emitCount == 0 )) {
        emitCount++;
        
        Local<Value> args[3];
        
        if (errorCount) {
          args[0] = objError;
        }
        else {
          args[0] = Local<Value>::New(Null());
        }
        
        args[1] = rows;
        args[2] = Local<Boolean>::New(( ret == SQL_SUCCESS ) ? True() : False() ); //true or false, are there more result sets to follow this emit?
        
        self->Emit(String::New("result"), 3, args);
      }
    }
    while ( self->canHaveMoreResults && ret == SQL_SUCCESS );
  } //end of malloc check
  
  TryCatch try_catch;
  
  self->Unref();
  
  if (try_catch.HasCaught()) {
    FatalException(try_catch);
  }
  
  free(buf);
  free(prep_req->sql);
  free(prep_req->catalog);
  free(prep_req->schema);
  free(prep_req->table);
  free(prep_req->type);
  free(prep_req);
  scope.Close(Undefined());
  
  return 0;
}
Ejemplo n.º 13
0
/**
 * @function net.remote_addr
 * 
 * ### Synopsis
 * 
 * var remote_ip = net.remote_addr();
 * 
 * This function returns the IP address of the last client to connect via net.accept().
 * 
 * @return {string} remote_ip - ip address of client
 */
static JSVAL net_remote_addr (JSARGS args) {
    HandleScope scope;
    return scope.Close(String::New(remote_addr));
}
Ejemplo n.º 14
0
/**
 * @function net.accept
 * 
 * ### Synopsis
 * 
 * var sock = net.accept(listen_socket);
 * 
 * This function waits until there is an incoming connection to the listen_socket and returns a new socket directly connected to the client.
 * 
 * The IP address of the connecting client is stored by this function.  It may be retrieved by calling net.remote_addr().
 * 
 * @param {int} listen_socket - socket already in listen mode
 * @return {int} client_socket - socket connected to a client
 * 
 * ### Notes
 * There is an old and well-known issue known as the "thundering herd problem" involving the OS accept() call.  The problem may occur if there are a large number of processes calling accept() on the same listen_socket. 
 * 
 * The solution is to use some sort of semaphore such as fs.flock() or fs.lockf() around net.accept().
 * 
 * See http://en.wikipedia.org/wiki/Thundering_herd_problem for a brief description of the problem.
 */
static JSVAL net_accept (JSARGS args) {
    HandleScope scope;
    struct sockaddr_in their_addr;

    int sock = args[0]->IntegerValue();

    socklen_t sock_size = sizeof (struct sockaddr_in);
	//{ FILE* fp=fopen("c:\\accept.txt", "a+b"); fprintf(fp, "%d\r\n", __LINE__); fclose(fp); }
#ifdef WIN32
	int accpt_sock;
	memset(&their_addr, 0, sizeof(their_addr));
#else
    bzero(&their_addr, sizeof (their_addr));
#endif
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(sock, &fds);
    //	struct timeval timeout;
    //	timeout.tv_sec = 5;
    //	timeout.tv_usec = 0;
	while(1)
	{
		switch (select(sock + 1, &fds, NULL, NULL, NULL)) {
			case -1:
				{ FILE* fp=fopen("c:\\error.txt", "a+b"); fprintf(fp, "%d", __LINE__); fclose(fp); }
				perror("select");
				return ThrowException(String::Concat(String::New("Read Error: "), String::New(strerror(errno))));
			case 0:
				{ FILE* fp=fopen("c:\\error.txt", "a+b"); fprintf(fp, "%d", __LINE__); fclose(fp); }
				printf("select timed out\n");
				return Null();
		}
		if (FD_ISSET(sock, &fds)) break;
	}

    while (1) 
	{
        accpt_sock = accept(sock, (struct sockaddr *) &their_addr, &sock_size);

#ifdef WIN32
		if (accpt_sock == INVALID_SOCKET) {
			perror("accept failed with error: ");
			printf("%ld\r\n", WSAGetLastError());
			{ FILE* fp=fopen("c:\\error.txt", "a+b"); fprintf(fp, "%d", __LINE__); fclose(fp); }
			//closesocket(sock);
			//WSACleanup();
		} 
		else 
		{
			ULONG NonBlock = 1;
			ioctlsocket(accpt_sock, FIONBIO, &NonBlock);
			break;
		}
#else
        if (accpt_sock > 0) {
            break;
        }
        else {
            perror("accept");
        }
#endif
    }

    //	int yes = 1;
    //#ifdef USE_CORK
    //	setsockopt( sock, IPPROTO_TCP, TCP_CORK, (char *)&yes, sizeof(yes) );
    //#else
    //	setsockopt( sock, IPPROTO_TCP, TCP_NODELAY, (char *)&yes, sizeof(yes) );
    //#endif
    //	{
    //		int x;
    //		x = fcntl(sock, F_GETFL, 0);
    //		fcntl(sock, F_SETFL, x | O_NONBLOCK);
    //	}
    strcpy(remote_addr, inet_ntoa(their_addr.sin_addr));
    return scope.Close(Integer::New(accpt_sock));
}
Ejemplo n.º 15
0
Handle<Value> getValueObjectWriteCount(const Arguments &args) {
  HandleScope scope;
  NdbRecordObject * nro = unwrapPointer<NdbRecordObject *>(args[0]->ToObject());
  return scope.Close(Number::New(nro->getWriteCount()));
}
Ejemplo n.º 16
0
Handle<Value> GeometryFactory::GetPrecisionModel(const Arguments& args) {
    HandleScope scope;
    GeometryFactory *factory = ObjectWrap::Unwrap<GeometryFactory>(args.This());
    return scope.Close(PrecisionModel::New(factory->_factory->getPrecisionModel()));
}
Ejemplo n.º 17
0
Handle<Value> prepareForUpdate(const Arguments &args) {
  HandleScope scope;
  NdbRecordObject * nro = unwrapPointer<NdbRecordObject *>(args[0]->ToObject());
  return scope.Close(nro->prepare());
}
Ejemplo n.º 18
0
Handle<Value> CharsetMap_recode_in(const Arguments &args) {
  HandleScope scope;
  DEBUG_MARKER(UDEB_DEBUG);
  
  REQUIRE_ARGS_LENGTH(5);

  JsValueConverter<CharsetMap *> converter(args.Holder());
  CharsetMap * csmap = converter.toC();
  
  int32_t lengths[2]; 
  enum { SOURCE = 0 , DEST = 1 };  // for lengths[]
  int status = CharsetMap::RECODE_OK;
  int copyLen;
  
  Local<Object> NodeBuffer = args[2]->ToObject();
  Local<String> sourceStr  = args[0]->ToString();
  int32_t cs_to            = args[1]->Int32Value();
  char * buffer            = node::Buffer::Data(NodeBuffer);
  uint32_t offset          = args[3]->Uint32Value();
  lengths[DEST]            = args[4]->Int32Value();

  /* Source string length and charset */
  int32_t cs_from          = csmap->getUTF16CharsetNumber();
  lengths[SOURCE]          = sourceStr->Length();

  /* Special case: if the destination is 2-byte unicode, just copy directly. 
     sourceStr->Write(uint16_t * ...) might face alignment issues, so we use
     memcpy().
  */
  if(cs_to == cs_from) {
    if(lengths[DEST] >= lengths[SOURCE]) {
      copyLen = lengths[SOURCE];
    }
    else {
      copyLen = lengths[DEST];
      status = csmap->RECODE_BUFF_TOO_SMALL;
    }
    DEBUG_PRINT("recodeIn() optimized path UTF16 -> UTF16 using memcpy");
    String::Value source(sourceStr);
    memcpy(buffer + offset, *source, copyLen);
    lengths[DEST] = copyLen;
  }
  
  /* Special case: if the destination is UTF-8, let V8 do the copying. 
     copyLen will receive the length written in characters.
     The return value is the length written in bytes.
  */
  else if(cs_to == csmap->getUTF8CharsetNumber()) {
    lengths[DEST] = sourceStr->WriteUtf8(buffer + offset, lengths[DEST], 
                                         &copyLen, 1);
    if(copyLen < sourceStr->Length()) {
      status = CharsetMap::RECODE_BUFF_TOO_SMALL;
    }                                         
    DEBUG_PRINT("recodeIn() UTF16 -> UTF8 using v8 WriteUtf8(): %s",
                buffer + offset);
  }
  
  /* General case: use CharsetMap::recode() */
  else {
    String::Value source(sourceStr);
    status = csmap->recode(lengths, cs_from, cs_to, *source, buffer + offset);
    DEBUG_PRINT("recodeIn() UTF16 -> X using recode(%c%c%c%c...): %s", 
                (*source)[1], (*source)[3], (*source)[5], (*source)[7],
                buffer + offset);
  }

  /* Build the return value */
  Local<Object> returnVal = Object::New();
  returnVal->Set(String::NewSymbol("status"), Integer::New(status));
  returnVal->Set(String::NewSymbol("lengthIn"), Integer::New(lengths[SOURCE]));
  returnVal->Set(String::NewSymbol("lengthOut"), Integer::New(lengths[DEST]));
  returnVal->Set(String::NewSymbol("charset"), args[1]);
  returnVal->Set(String::NewSymbol("offset"), Integer::New(offset));
  
  return scope.Close(returnVal);
}
Ejemplo n.º 19
0
Handle<Value> MSMap::PropertyGetter (Local<String> property, const AccessorInfo& info) {
  MSMap *map = ObjectWrap::Unwrap<MSMap>(info.This());
  v8::String::AsciiValue n(property);
  if (strcmp(*n, "width") == 0) {
    RETURN_NUMBER(map->this_->width);
  } else if (strcmp(*n, "height") == 0) {
    RETURN_NUMBER(map->this_->height);
  } else if (strcmp(*n, "status") == 0) {
    RETURN_NUMBER(map->this_->status);
  } else if (strcmp(*n, "maxsize") == 0) {
    RETURN_NUMBER(map->this_->maxsize);
  } else if (strcmp(*n, "cellsize") == 0) {
    RETURN_NUMBER(map->this_->cellsize);
  } else if (strcmp(*n, "units") == 0) {
    RETURN_NUMBER(map->this_->units);
  } else if (strcmp(*n, "scaledenom") == 0) {
    RETURN_NUMBER(map->this_->scaledenom);
  } else if (strcmp(*n, "resolution") == 0) {
    RETURN_NUMBER(map->this_->resolution);
  } else if (strcmp(*n, "defresolution") == 0) {
    RETURN_NUMBER(map->this_->defresolution);
  } else if (strcmp(*n, "imagetype") == 0) {
    RETURN_STRING(map->this_->imagetype);
  } else if (strcmp(*n, "mimetype") == 0) {
    RETURN_STRING(map->this_->outputformat->mimetype);
  } else if (strcmp(*n, "shapepath") == 0) {
    RETURN_STRING(map->this_->shapepath);
  } else if (strcmp(*n, "mappath") == 0) {
    RETURN_STRING(map->this_->mappath);
  } else if (strcmp(*n, "name") == 0) {
    RETURN_STRING(map->this_->name);
  } else if (strcmp(*n, "outputformat") == 0) {
    HandleScope scope;
    return scope.Close(MSOutputFormat::New(map->this_->outputformat));
  } else if (strcmp(*n, "projection") == 0) {
    HandleScope scope;
    return scope.Close(MSProjection::New(&map->this_->projection));
  } else if (strcmp(*n, "layers") == 0) {
    HandleScope scope;
    return scope.Close(MSLayers::New(map->this_));
  } else if (strcmp(*n, "metadata") == 0) {
    HandleScope scope;
#if MS_VERSION_NUM < 60400
    Handle<ObjectTemplate> objTempl = ObjectTemplate::New();
    Local<Object> result = objTempl->NewInstance();
    return scope.Close(result);
#else
    return scope.Close(MSHashTable::New(&(map->this_->web.metadata)));
#endif
  } else if (strcmp(*n, "extent") == 0) {
    HandleScope scope;
    return scope.Close(MSRect::New(&map->this_->extent));
  }
  return Undefined();
}
Ejemplo n.º 20
0
Handle<Value> WrappedScript::EvalMachine(const Arguments& args)
{
	HandleScope scope;

	if (input_flag == compileCode && args.Length() < 1) {
		return ThrowException(Exception::TypeError(String::New("needs at least 'code' argument.")));
	}

	const int sandbox_index = input_flag == compileCode ? 1 : 0;
	if (context_flag == userContext && args.Length() < (sandbox_index + 1)) {
		return ThrowException(Exception::TypeError(String::New("needs a 'context' argument.")));
	}

	Local<String> code;
	if (input_flag == compileCode) code = args[0]->ToString();

	Local<Object> sandbox;
	if (context_flag == newContext) {
		sandbox = args[sandbox_index]->IsObject() ? args[sandbox_index]->ToObject() : Object::New();
	} else if (context_flag == userContext) {
		sandbox = args[sandbox_index]->ToObject();
	}

	const int filename_index = sandbox_index + (context_flag == newContext ? 1 : 0);
	Local<String> filename =
			args.Length() > filename_index ? args[filename_index]->ToString() : String::New("evalmachine.<anonymous>");

	const int display_error_index = args.Length() - 1;
	bool display_error = false;
	if (args.Length() > display_error_index && args[display_error_index]->IsBoolean()
		&& args[display_error_index]->BooleanValue() == true) {
		display_error = true;
	}

	Persistent<Context> context;

	Local<Array> keys;
	unsigned int i;
	WrappedContext *nContext = NULL;
	Local<Object> contextArg;

	if (context_flag == newContext) {
		// Create the new context
		context = Context::New();

	} else if (context_flag == userContext) {
		// Use the passed in context
		contextArg = args[sandbox_index]->ToObject();
		nContext = NativeObject::Unwrap<WrappedContext>(contextArg);
		context = nContext->GetV8Context();
	}

	// New and user context share code. DRY it up.
	if (context_flag == userContext || context_flag == newContext) {
		// Enter the context
		context->Enter();

		// Call the initCallback, if it exists
		if (nContext) {
			Persistent<Function> initCallback = nContext->GetInitCallback();

			if (!initCallback.IsEmpty()) {
				Handle<Value> callbackArgs[] = { contextArg, context->Global() };
				initCallback->Call(contextArg, 2, callbackArgs);
			}
		}

		// Copy everything from the passed in sandbox (either the persistent
		// context for runInContext(), or the sandbox arg to runInNewContext()).
		keys = sandbox->GetPropertyNames();

		for (i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = sandbox->Get(key);
			if (value == sandbox) {
				value = context->Global();
			}
			context->Global()->Set(key, value);
		}
	}

	Handle<Value> result;
	Handle<Script> script;

	if (input_flag == compileCode) {
		// well, here WrappedScript::New would suffice in all cases, but maybe
		// Compile has a little better performance where possible
		script = output_flag == returnResult ? Script::Compile(code, filename) : Script::New(code, filename);
		if (script.IsEmpty()) {
			// Hack because I can't get a proper stacktrace on SyntaxError
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		} else if (n_script->script_.IsEmpty()) {
			return ThrowException(Exception::Error(String::New("'this' must be a result of previous "
				"new Script(code) call.")));
		}

		script = n_script->script_;
	}

	if (output_flag == returnResult) {
		result = script->Run();
		if (result.IsEmpty()) {
			if (context_flag == newContext) {
				context->DetachGlobal();
				context->Exit();
				context.Dispose();
			}
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		}
		n_script->script_ = Persistent<Script>::New(script);
		result = args.This();
	}

	if (context_flag == userContext || context_flag == newContext) {
		// success! copy changes back onto the sandbox object.
		keys = context->Global()->GetPropertyNames();
		for (i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = context->Global()->Get(key);
			if (value == context->Global()) {
				value = sandbox;
			}
			sandbox->Set(key, value);
		}
	}

	if (context_flag == newContext) {
		// Clean up, clean up, everybody everywhere!
		context->DetachGlobal();
		context->Exit();
		context.Dispose();
	} else if (context_flag == userContext) {
		// Exit the passed in context.
		context->Exit();
	}

	if (result->IsObject()) {
		Local<Context> creation = result->ToObject()->CreationContext();
	}

	return result == args.This() ? result : scope.Close(result);
}
Ejemplo n.º 21
0
Handle<Value>
Session::Authorize(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 1 || !args[0]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Service URI string must be provided as first parameter.")));
    }
    if (args.Length() < 2 || !args[1]->IsInt32()) {
        return ThrowException(Exception::Error(String::New(
                "Integer correlation identifier must be provided "
                "as second parameter.")));
    }
    if (args.Length() > 2) {
        return ThrowException(Exception::Error(String::New(
                "Function expects at most two arguments.")));
    }

    Local<String> s = args[0]->ToString();
    String::Utf8Value uriv(s);

    int cidi = args[1]->Int32Value();

    Session* session = ObjectWrap::Unwrap<Session>(args.This());

    BLPAPI_EXCEPTION_TRY

    blpapi::EventQueue tokenEventQueue;
    blpapi::CorrelationId tokenCid(static_cast<void*>(&tokenEventQueue));
    session->d_session->generateToken(tokenCid, &tokenEventQueue);

    std::string token;
    blpapi::Event ev = tokenEventQueue.nextEvent();
    if (blpapi::Event::TOKEN_STATUS == ev.eventType() ||
        blpapi::Event::REQUEST_STATUS == ev.eventType()) {
        blpapi::MessageIterator msgIter(ev);
        while (msgIter.next()) {
            blpapi::Message msg = msgIter.message();
            if ("TokenGenerationSuccess" == msg.messageType()) {
                token = msg.getElementAsString("token");
            } else {
                std::stringstream ss;
                ss << "Failed to generate token: " << msg.getElement("reason");
                std::string s = ss.str();
                return ThrowException(Exception::Error(String::New(
                        s.c_str())));
            }
        }
    }
    if (0 == token.length()) {
        return ThrowException(Exception::Error(String::New(
                        "Failed to get token.")));
    }

    blpapi::Service authService = session->d_session->getService(*uriv);
    blpapi::Request authRequest = authService.createAuthorizationRequest();
    authRequest.set("token", token.c_str());

    session->d_identity = session->d_session->createIdentity();

    blpapi::CorrelationId cid(cidi);
    session->d_session->sendAuthorizationRequest(authRequest,
                                                 &session->d_identity, cid);

    BLPAPI_EXCEPTION_CATCH_RETURN

    return scope.Close(Integer::New(cidi));
}
Ejemplo n.º 22
0
 Handle<Value> JSHandler::on(const Arguments& args) {
     HandleScope scope;
     if (args.Length() != 2 || !args[0]->IsString() || !args[1]->IsFunction()) {
         return ThrowException(Exception::TypeError(String::New("please provide an event name and callback function")));
     }
     std::string callback_name = *String::Utf8Value(args[0]->ToString());
     Local<Function> callback = Local<Function>::Cast(args[1]);
     if (callback->IsNull() || callback->IsUndefined()) {
         return ThrowException(Exception::TypeError(String::New("please provide a valid callback function for second arg")));
     }
     JSHandler* handler = node::ObjectWrap::Unwrap<JSHandler>(args.This());
     if (callback_name == "node") {
         if (!handler->node_cb.IsEmpty()) {
             handler->node_cb.Dispose();
         }
         handler->node_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "way") {
         if (!handler->way_cb.IsEmpty()) {
             handler->way_cb.Dispose();
         }
         handler->way_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "relation") {
         if (!handler->relation_cb.IsEmpty()) {
             handler->relation_cb.Dispose();
         }
         handler->relation_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "init") {
         if (!handler->init_cb.IsEmpty()) {
             handler->init_cb.Dispose();
         }
         handler->init_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "before_nodes") {
         if (!handler->before_nodes_cb.IsEmpty()) {
             handler->before_nodes_cb.Dispose();
         }
         handler->before_nodes_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "after_nodes") {
         if (!handler->after_nodes_cb.IsEmpty()) {
             handler->after_nodes_cb.Dispose();
         }
         handler->after_nodes_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "before_ways") {
         if (!handler->before_ways_cb.IsEmpty()) {
             handler->before_ways_cb.Dispose();
         }
         handler->before_ways_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "after_ways") {
         if (!handler->after_ways_cb.IsEmpty()) {
             handler->after_ways_cb.Dispose();
         }
         handler->after_ways_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "before_relations") {
         if (!handler->before_relations_cb.IsEmpty()) {
             handler->before_relations_cb.Dispose();
         }
         handler->before_relations_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "after_relations") {
         if (!handler->after_relations_cb.IsEmpty()) {
             handler->after_relations_cb.Dispose();
         }
         handler->after_relations_cb = Persistent<Function>::New(callback);
     } else if (callback_name == "done") {
         if (!handler->done_cb.IsEmpty()) {
             handler->done_cb.Dispose();
         }
         handler->done_cb = Persistent<Function>::New(callback);
     }
     return scope.Close(Undefined());
 }
Ejemplo n.º 23
0
Handle<Value>
Session::Request(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 1 || !args[0]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Service URI string must be provided as first parameter.")));
    }
    if (args.Length() < 2 || !args[1]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "String request name must be provided as second parameter.")));
    }
    if (args.Length() < 3 || !args[2]->IsObject()) {
        return ThrowException(Exception::Error(String::New(
                "Object containing request parameters must be provided "
                "as third parameter.")));
    }
    if (args.Length() < 4 || !args[3]->IsInt32()) {
        return ThrowException(Exception::Error(String::New(
                "Integer correlation identifier must be provided "
                "as fourth parameter.")));
    }
    if (args.Length() >= 5 && !args[4]->IsUndefined() && !args[4]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Optional request label must be a string.")));
    }
    if (args.Length() > 5) {
        return ThrowException(Exception::Error(String::New(
                "Function expects at most five arguments.")));
    }

    int cidi = args[3]->Int32Value();

    Session* session = ObjectWrap::Unwrap<Session>(args.This());

    BLPAPI_EXCEPTION_TRY

    Local<String> uri = args[0]->ToString();
    String::AsciiValue uriv(uri);

    blpapi::Service service = session->d_session->getService(*uriv);

    Local<String> name = args[1]->ToString();
    String::Utf8Value namev(name);

    blpapi::Request request = service.createRequest(*namev);

    // Loop over object properties, appending/setting into the request.
    Local<Object> obj = args[2]->ToObject();
    Local<Array> props = obj->GetPropertyNames();

    for (std::size_t i = 0; i < props->Length(); ++i) {
        // Process the key.
        Local<Value> keyval = props->Get(i);
        Local<String> key = keyval->ToString();
        String::Utf8Value keyv(key);

        // Process the value.
        //
        // The values present on the outer object are marshalled into the
        // blpapi::Request by setting values using 'set'.  Arrays indicate
        // values which should be marshalled using 'append'.
        Local<Value> val = obj->Get(keyval);
        if (val->IsString()) {
            Local<String> s = val->ToString();
            String::Utf8Value valv(s);
            request.set(*keyv, *valv);
        } else if (val->IsBoolean()) {
            request.set(*keyv, val->BooleanValue());
        } else if (val->IsNumber()) {
            request.set(*keyv, val->NumberValue());
        } else if (val->IsInt32()) {
            request.set(*keyv, val->Int32Value());
        } else if (val->IsUint32()) {
            request.set(*keyv,
                static_cast<blpapi::Int64>(val->Uint32Value()));
        } else if (val->IsDate()) {
            blpapi::Datetime dt;
            mkdatetime(&dt, val);
            request.set(*keyv, dt);
        } else if (val->IsArray()) {
            // Arrays are marshalled into the blpapi::Request by appending
            // value types using the key of the array in the outer object.
            Local<Object> subarray = val->ToObject();
            int jmax = Array::Cast(*val)->Length();
            for (int j = 0; j < jmax; ++j) {
                Local<Value> subval = subarray->Get(j);
                // Only strings, booleans, and numbers are marshalled.
                if (subval->IsString()) {
                    Local<String> s = subval->ToString();
                    String::Utf8Value subvalv(s);
                    request.append(*keyv, *subvalv);
                } else if (subval->IsBoolean()) {
                    request.append(*keyv, subval->BooleanValue());
                } else if (subval->IsNumber()) {
                    request.append(*keyv, subval->NumberValue());
                } else if (subval->IsInt32()) {
                    request.append(*keyv, subval->Int32Value());
                } else if (subval->IsUint32()) {
                    request.append(*keyv,
                        static_cast<blpapi::Int64>(subval->Uint32Value()));
                } else if (subval->IsDate()) {
                    blpapi::Datetime dt;
                    mkdatetime(&dt, subval);
                    request.append(*keyv, dt);
                } else {
                    return ThrowException(Exception::Error(String::New(
                                "Array contains invalid value type.")));
                }
            }
        } else {
            return ThrowException(Exception::Error(String::New(
                        "Object contains invalid value type.")));
        }
    }

    blpapi::CorrelationId cid(cidi);

    if (args.Length() == 5) {
        String::Utf8Value labelv(args[4]->ToString());
        session->d_session->sendRequest(request, session->d_identity,
                                        cid, 0, *labelv, labelv.length());
    } else {
        session->d_session->sendRequest(request, session->d_identity, cid);
    }

    BLPAPI_EXCEPTION_CATCH_RETURN

    return scope.Close(Integer::New(cidi));
}
Ejemplo n.º 24
0
Handle<Value> NovaNode::GetSupportedEngines(const Arguments &)
{
	HandleScope scope;

	return scope.Close(cvv8::CastToJS(Nova::Config::Inst()->GetSupportedEngines()));
}
Ejemplo n.º 25
0
v8::Handle<v8::Value> Input_v8::Poll(const v8::Arguments &args) {
	HandleScope scope;

	Handle<Object> holder = args.Holder();
	Input_v8 *input_v8 = ObjectWrap::Unwrap<Input_v8>(holder);

	if (NULL == input_v8) {
		return ThrowException(v8::Exception::ReferenceError(String::NewSymbol(
			"Input::poll(): NULL Holder."
		)));
	}

	bool anyResults = input_v8->input->poll();
	if (anyResults) {
		Input::PollResults &results = input_v8->input->results;

		Handle<Function> emitFunction = args.Holder()->Get(
			String::New("emit")
		).As<Function>();

		Handle<Value> argv[2];

		if (results.keyDown.size() > 0) {
			argv[0] = String::New("keyDown");
			for (unsigned int i = 0; i < results.keyDown.size(); i++) {

				argv[1] = Integer::New(results.keyDown[i].code);
				emitFunction->Call(holder, 2, argv);
			}
		}

		if (results.keyUp.size() > 0) {
			argv[0] = String::New("keyUp");
			for (unsigned int i = 0; i < results.keyUp.size(); i++) {

				argv[1] = Integer::New(results.keyUp[i].code);
				emitFunction->Call(holder, 2, argv);
			}
		}

		// TODO: Joystick

		if (results.resize.width && results.resize.height) {
			argv[0] = String::New("resize");

			Handle<Array> resize = Array::New(2);
			resize->Set(0, Integer::New(results.resize.width));
			resize->Set(1, Integer::New(results.resize.height));

			argv[1] = resize;
			emitFunction->Call(holder, 2, argv);
		}

		if (results.quit) {
			argv[0] = String::New("quit");

			argv[1] = Boolean::New(true);
			emitFunction->Call(holder, 2, argv);
		}
	}

	return scope.Close(Boolean::New(anyResults));
}
Ejemplo n.º 26
0
Handle<Value> NovaNode::GetDIM(const Arguments &)
{
	HandleScope scope;

	return scope.Close(cvv8::CastToJS(DIM));
}
Ejemplo n.º 27
0
static JSVAL sqlite_data_count(JSARGS args) {
    HandleScope scope;
    Local<External>wrap = Local<External>::Cast(args[0]);
    sqlite3_stmt *stmt = (sqlite3_stmt *)wrap->Value();
    return scope.Close(Integer::New(sqlite3_data_count(stmt)));
}
Ejemplo n.º 28
0
Handle<Value> Image::encodeSync(const Arguments& args)
{
    HandleScope scope;

    Image* im = ObjectWrap::Unwrap<Image>(args.This());

    std::string format = "png";
    palette_ptr palette;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }


    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

        Local<Object> options = args[1]->ToObject();

        if (options->Has(String::New("palette")))
        {
            Local<Value> format_opt = options->Get(String::New("palette"));
            if (!format_opt->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("'palette' must be an object")));

            Local<Object> obj = format_opt->ToObject();
            if (obj->IsNull() || obj->IsUndefined() || !Palette::constructor->HasInstance(obj))
                return ThrowException(Exception::TypeError(String::New("mapnik.Palette expected as second arg")));

            palette = ObjectWrap::Unwrap<Palette>(obj)->palette();
        }
    }

    try {
        std::string s;
        if (palette.get())
        {
            s = save_to_string(*(im->this_), format, *palette);
        }
        else {
            s = save_to_string(*(im->this_), format);
        }

        node::Buffer *retbuf = Buffer::New((char*)s.data(),s.size());
        return scope.Close(retbuf->handle_);
    }
    catch (std::exception & ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
    catch (...)
    {
        return ThrowException(Exception::Error(
                                  String::New("unknown exception happened when encoding image: please file bug report")));
    }
}
Ejemplo n.º 29
0
static JSVAL sqlite_errmsg16(JSARGS args) {
    HandleScope scope;
    Local<External>wrap = Local<External>::Cast(args[0]);
    sqlite3 *db = (sqlite3 *)wrap->Value();
    return scope.Close(String::New((char *)sqlite3_errmsg16(db)));
}
Ejemplo n.º 30
0
 Handle<v8::Value> Function::New(const Arguments& args)
 {
   HandleScope scope;
   return scope.Close(args.This());
 }