コード例 #1
0
void HoneydProfileBinding::Init(v8::Handle<Object> target)
{
	// Prepare constructor template
	Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
	tpl->SetClassName(String::NewSymbol("HoneydProfileBinding"));
	tpl->InstanceTemplate()->SetInternalFieldCount(1);
	// Prototype
	Local<Template> proto = tpl->PrototypeTemplate();

	proto->Set("SetName",           FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetName>));
	proto->Set("SetTcpAction",      FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetTcpAction>));
	proto->Set("SetUdpAction",      FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetUdpAction>));
	proto->Set("SetIcmpAction",     FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetIcmpAction>));
	proto->Set("SetPersonality",    FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetPersonality>));
	proto->Set("SetEthernet",       FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetEthernet>));
	proto->Set("SetUptimeMin",      FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetUptimeMin>));
	proto->Set("SetUptimeMax",      FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetUptimeMax>));
	proto->Set("SetDropRate",       FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetDropRate>));
	proto->Set("SetParentProfile",  FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetParentProfile>));
	proto->Set(String::NewSymbol("SetVendors"),FunctionTemplate::New(SetVendors)->GetFunction());
	
	proto->Set("setTcpActionInherited",  FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setTcpActionInherited>));
	proto->Set("setUdpActionInherited",  FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setUdpActionInherited>));
	proto->Set("setIcmpActionInherited", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setIcmpActionInherited>));
	proto->Set("setPersonalityInherited",FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setPersonalityInherited>));
	proto->Set("setEthernetInherited",   FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setEthernetInherited>));
	proto->Set("setUptimeInherited",     FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setUptimeInherited>));
	proto->Set("setDropRateInherited",   FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setDropRateInherited>));

    proto->Set(String::NewSymbol("Save"),FunctionTemplate::New(Save)->GetFunction()); 
    proto->Set(String::NewSymbol("AddPort"),FunctionTemplate::New(AddPort)->GetFunction()); 


	Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
	target->Set(String::NewSymbol("HoneydProfileBinding"), constructor);
}
コード例 #2
0
ファイル: Database.cpp プロジェクト: gurzgri/node-odbc
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, 0, 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, SQL_CLOSE );
        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;
}
コード例 #3
0
Local<Function> MetadataNode::SetMembersFromStaticMetadata(Isolate *isolate, Local<FunctionTemplate>& ctorFuncTemplate, Local<ObjectTemplate>& prototypeTemplate, vector<MethodCallbackData*>& instanceMethodsCallbackData, const vector<MethodCallbackData*>& baseInstanceMethodsCallbackData, MetadataTreeNode *treeNode)
{
	SET_PROFILER_FRAME();

	Local<Function> ctorFunction;

	uint8_t *curPtr = s_metadataReader.GetValueData() + treeNode->offsetValue + 1;

	auto nodeType = s_metadataReader.GetNodeType(treeNode);

	auto curType = s_metadataReader.ReadTypeName(treeNode);

	curPtr += sizeof(uint16_t /* baseClassId */);

	if (s_metadataReader.IsNodeTypeInterface(nodeType))
	{
		curPtr += sizeof(uint8_t) + sizeof(uint32_t);
	}

	//get candidates from instance methods metadata
	auto instanceMethodCout = *reinterpret_cast<uint16_t*>(curPtr);
	curPtr += sizeof(uint16_t);
	string lastMethodName;
	MethodCallbackData *callbackData = nullptr;
	for (auto i = 0; i < instanceMethodCout; i++)
	{
		auto entry = s_metadataReader.ReadInstanceMethodEntry(&curPtr);
		if (entry.name != lastMethodName)
		{
			callbackData = new MethodCallbackData(this);

			instanceMethodsCallbackData.push_back(callbackData);
			auto itBegin = baseInstanceMethodsCallbackData.begin();
			auto itEnd = baseInstanceMethodsCallbackData.end();
			auto itFound = find_if(itBegin, itEnd, [&entry] (MethodCallbackData *x)
			{	return x->candidates.front().name == entry.name;});
			if (itFound != itEnd)
			{
				callbackData->parent = *itFound;
			}

			auto funcData = External::New(isolate, callbackData);
			auto funcTemplate = FunctionTemplate::New(isolate, MethodCallback, funcData);
			auto funcName = ConvertToV8String(entry.name);
			prototypeTemplate->Set(funcName, funcTemplate->GetFunction());
			lastMethodName = entry.name;
		}
		callbackData->candidates.push_back(entry);
	}

	//get candidates from instance fields metadata
	auto instanceFieldCout = *reinterpret_cast<uint16_t*>(curPtr);
	curPtr += sizeof(uint16_t);
	for (auto i = 0; i < instanceFieldCout; i++)
	{
		auto entry = s_metadataReader.ReadInstanceFieldEntry(&curPtr);

		auto fieldName = ConvertToV8String(entry.name);
		auto fieldInfo = new FieldCallbackData(entry);
		fieldInfo->declaringType = curType;
		auto fieldData = External::New(isolate, fieldInfo);
		prototypeTemplate->SetAccessor(fieldName, FieldAccessorGetterCallback, FieldAccessorSetterCallback, fieldData, AccessControl::DEFAULT, PropertyAttribute::DontDelete);
	}

	ctorFunction = ctorFuncTemplate->GetFunction();

	//get candidates from static methods metadata
	callbackData = nullptr;
	lastMethodName.clear();
	auto staticMethodCout = *reinterpret_cast<uint16_t*>(curPtr);
	curPtr += sizeof(uint16_t);
	for (auto i = 0; i < staticMethodCout; i++)
	{
		auto entry = s_metadataReader.ReadStaticMethodEntry(&curPtr);
		if (entry.name != lastMethodName)
		{
			callbackData = new MethodCallbackData(this);
			auto funcData = External::New(isolate, callbackData);
			auto funcTemplate = FunctionTemplate::New(isolate, MethodCallback, funcData);
			auto funcName = ConvertToV8String(entry.name);
			ctorFunction->Set(funcName, funcTemplate->GetFunction());
			lastMethodName = entry.name;
		}
		callbackData->candidates.push_back(entry);
	}

	auto extendFuncName = V8StringConstants::GetExtend();
	auto extendFuncTemplate = FunctionTemplate::New(isolate, ExtendCallMethodCallback, External::New(isolate, this));
	ctorFunction->Set(extendFuncName, extendFuncTemplate->GetFunction());

	//get candidates from static fields metadata
	auto staticFieldCout = *reinterpret_cast<uint16_t*>(curPtr);
	curPtr += sizeof(uint16_t);
	for (auto i = 0; i < staticFieldCout; i++)
	{
		auto entry = s_metadataReader.ReadStaticFieldEntry(&curPtr);

		auto fieldName = ConvertToV8String(entry.name);
		auto fieldData = External::New(isolate, new FieldCallbackData(entry));
		ctorFunction->SetAccessor(fieldName, FieldAccessorGetterCallback, FieldAccessorSetterCallback, fieldData, AccessControl::DEFAULT, PropertyAttribute::DontDelete);
	}

	SetClassAccessor(ctorFunction);

	return ctorFunction;
}
コード例 #4
0
/*
 * Prototype:
 * TBW
 *
 * Docs:
 * TBW
 *
 * Example:
 * TBW
 */
static void
gum_script_thread_on_backtrace (const FunctionCallbackInfo<Value> & info)
{
  GumScriptThread * self = static_cast<GumScriptThread *> (
      info.Data ().As<External> ()->Value ());
  Isolate * isolate = info.GetIsolate ();

  int num_args = info.Length ();

  GumCpuContext * cpu_context = NULL;
  if (num_args >= 1)
  {
    Local<Value> value = info[0];
    if (!value->IsNull ())
    {
      if (!_gum_script_cpu_context_get (value, &cpu_context, self->core))
        return;
    }
  }

  bool accurate = true;
  if (num_args >= 2)
  {
    Local<Value> selector = info[1];
    if (!selector->IsNull ())
    {
      if ((*self->fuzzy_enum_value) == selector)
      {
        accurate = false;
      }
      else if ((*self->accurate_enum_value) != selector)
      {
        isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (
            isolate, "Thread.backtrace: invalid backtracer enum value")));
        return;
      }
    }
  }

  GumBacktracer * backtracer;
  if (accurate)
  {
    if (self->accurate_backtracer == NULL)
      self->accurate_backtracer = gum_backtracer_make_accurate ();
    backtracer = self->accurate_backtracer;
  }
  else
  {
    if (self->fuzzy_backtracer == NULL)
      self->fuzzy_backtracer = gum_backtracer_make_fuzzy ();
    backtracer = self->fuzzy_backtracer;
  }
  if (backtracer == NULL)
  {
    isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (
        isolate, accurate
        ? "Thread.backtrace: backtracer not yet available for this "
        "platform; please try Thread.backtrace(context, Backtracer.FUZZY)"
        : "Thread.backtrace: backtracer not yet available for this "
        "platform; please try Thread.backtrace(context, Backtracer.ACCURATE)"
        )));
    return;
  }

  GumReturnAddressArray ret_addrs;
  gum_backtracer_generate (backtracer, cpu_context, &ret_addrs);

  Local<Array> result = Array::New (isolate, ret_addrs.len);
  for (guint i = 0; i != ret_addrs.len; i++)
    result->Set (i, _gum_script_pointer_new (ret_addrs.items[i], self->core));
  info.GetReturnValue ().Set (result);
}
コード例 #5
0
ファイル: v8_wrapper.cpp プロジェクト: IlyaM/mongo
    Local<v8::Object> mongoToV8( const BSONObj& m , bool array, bool readOnly ){

        // handle DBRef. needs to come first. isn't it? (metagoto)
        static string ref = "$ref";
        if ( ref == m.firstElement().fieldName() ) {
            const BSONElement& id = m["$id"];
            if (!id.eoo()) { // there's no check on $id exitence in sm implementation. risky ?
                v8::Function* dbRef = getNamedCons( "DBRef" );
                v8::Handle<v8::Value> argv[2];
                argv[0] = mongoToV8Element(m.firstElement());
                argv[1] = mongoToV8Element(m["$id"]);
                return dbRef->NewInstance(2, argv);
            }
        }

        Local< v8::ObjectTemplate > readOnlyObjects;
        // Hoping template construction is fast...
        Local< v8::ObjectTemplate > internalFieldObjects = v8::ObjectTemplate::New();
        internalFieldObjects->SetInternalFieldCount( 1 );

        Local<v8::Object> o;
        if ( array ) {
            // NOTE Looks like it's impossible to add interceptors to non array objects in v8.
            o = v8::Array::New();
        } else if ( !readOnly ) {
            o = v8::Object::New();
        } else {
            // NOTE Our readOnly implemention relies on undocumented ObjectTemplate
            // functionality that may be fragile, but it still seems like the best option
            // for now -- fwiw, the v8 docs are pretty sparse.  I've determined experimentally
            // that when property handlers are set for an object template, they will attach
            // to objects previously created by that template.  To get this to work, though,
            // it is necessary to initialize the template's property handlers before
            // creating objects from the template (as I have in the following few lines
            // of code).
            // NOTE In my first attempt, I configured the permanent property handlers before
            // constructiong the object and replaced the Set() calls below with ForceSet().
            // However, it turns out that ForceSet() only bypasses handlers for named
            // properties and not for indexed properties.
            readOnlyObjects = v8::ObjectTemplate::New();
            // NOTE This internal field will store type info for special db types.  For
            // regular objects the field is unnecessary - for simplicity I'm creating just
            // one readOnlyObjects template for objects where the field is & isn't necessary,
            // assuming that the overhead of an internal field is slight.
            readOnlyObjects->SetInternalFieldCount( 1 );
            readOnlyObjects->SetNamedPropertyHandler( 0 );
            readOnlyObjects->SetIndexedPropertyHandler( 0 );
            o = readOnlyObjects->NewInstance();
        }
        
        mongo::BSONObj sub;

        for ( BSONObjIterator i(m); i.more(); ) {
            const BSONElement& f = i.next();
        
            Local<Value> v;
        
            switch ( f.type() ){

            case mongo::Code:
                o->Set( v8::String::New( f.fieldName() ), newFunction( f.valuestr() ) );
                break;

            case CodeWScope:
                if ( f.codeWScopeObject().isEmpty() )
                    log() << "warning: CodeWScope doesn't transfer to db.eval" << endl;
                o->Set( v8::String::New( f.fieldName() ), newFunction( f.codeWScopeCode() ) );
                break;
            
            case mongo::String: 
                o->Set( v8::String::New( f.fieldName() ) , v8::String::New( f.valuestr() ) );
                break;
            
            case mongo::jstOID: {
                v8::Function * idCons = getObjectIdCons();
                v8::Handle<v8::Value> argv[1];
                argv[0] = v8::String::New( f.__oid().str().c_str() );
                o->Set( v8::String::New( f.fieldName() ) , 
                            idCons->NewInstance( 1 , argv ) );
                break;
            }
            
            case mongo::NumberDouble:
            case mongo::NumberInt:
                o->Set( v8::String::New( f.fieldName() ) , v8::Number::New( f.number() ) );
                break;
            
            case mongo::Array:
            case mongo::Object:
                sub = f.embeddedObject();
                o->Set( v8::String::New( f.fieldName() ) , mongoToV8( sub , f.type() == mongo::Array, readOnly ) );
                break;
            
            case mongo::Date:
                o->Set( v8::String::New( f.fieldName() ) , v8::Date::New( f.date() ) );
                break;

            case mongo::Bool:
                o->Set( v8::String::New( f.fieldName() ) , v8::Boolean::New( f.boolean() ) );
                break;
            
            case mongo::jstNULL:
            case mongo::Undefined: // duplicate sm behavior
                o->Set( v8::String::New( f.fieldName() ) , v8::Null() );
                break;
            
            case mongo::RegEx: {
                v8::Function * regex = getNamedCons( "RegExp" );
            
                v8::Handle<v8::Value> argv[2];
                argv[0] = v8::String::New( f.regex() );
                argv[1] = v8::String::New( f.regexFlags() );
            
                o->Set( v8::String::New( f.fieldName() ) , regex->NewInstance( 2 , argv ) );
                break;
            }
            
            case mongo::BinData: {
                Local<v8::Object> b = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();

                int len;
                const char *data = f.binData( len );
            
                v8::Function* binData = getNamedCons( "BinData" );
                v8::Handle<v8::Value> argv[3];
                argv[0] = v8::Number::New( len );
                argv[1] = v8::Number::New( f.binDataType() );
                argv[2] = v8::String::New( data, len );
                o->Set( v8::String::New( f.fieldName() ), binData->NewInstance(3, argv) );
                break;
            }
            
            case mongo::Timestamp: {
                Local<v8::Object> sub = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();
                
                sub->Set( v8::String::New( "time" ) , v8::Date::New( f.timestampTime() ) );
                sub->Set( v8::String::New( "i" ) , v8::Number::New( f.timestampInc() ) );
                sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
                
                o->Set( v8::String::New( f.fieldName() ) , sub );
                break;
            }
            
            case mongo::NumberLong: {
                Local<v8::Object> sub = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();
                unsigned long long val = f.numberLong();
                v8::Function* numberLong = getNamedCons( "NumberLong" );
                v8::Handle<v8::Value> argv[2];
                argv[0] = v8::Integer::New( val >> 32 );
                argv[1] = v8::Integer::New( (unsigned long)(val & 0x00000000ffffffff) );
                o->Set( v8::String::New( f.fieldName() ), numberLong->NewInstance(2, argv) );
                break;                
            }
                    
            case mongo::MinKey: {
                Local<v8::Object> sub = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();
                sub->Set( v8::String::New( "$MinKey" ), v8::Boolean::New( true ) );
                sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
                o->Set( v8::String::New( f.fieldName() ) , sub );
                break;
            }
                    
            case mongo::MaxKey: {
                Local<v8::Object> sub = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();
                sub->Set( v8::String::New( "$MaxKey" ), v8::Boolean::New( true ) );
                sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
                o->Set( v8::String::New( f.fieldName() ) , sub );
                break;
            }

            case mongo::DBRef: {
                v8::Function* dbPointer = getNamedCons( "DBPointer" );
                v8::Handle<v8::Value> argv[2];
                argv[0] = v8::String::New( f.dbrefNS() );
                argv[1] = newId( f.dbrefOID() );
                o->Set( v8::String::New( f.fieldName() ), dbPointer->NewInstance(2, argv) );
                break;
            }
                    
            default:
                cout << "can't handle type: ";
                cout  << f.type() << " ";
                cout  << f.toString();
                cout  << endl;
                break;
            }
        
        }

        if ( !array && readOnly ) {
            readOnlyObjects->SetNamedPropertyHandler( 0, NamedReadOnlySet, 0, NamedReadOnlyDelete );
            readOnlyObjects->SetIndexedPropertyHandler( 0, IndexedReadOnlySet, 0, IndexedReadOnlyDelete );            
        }
        
        return o;
    }
コード例 #6
0
void ODBCResult::UV_AfterFetchAll(uv_work_t* work_req, int status) {
  DEBUG_PRINTF("ODBCResult::UV_AfterFetchAll\n");
  NanScope();
  
  fetch_work_data* data = (fetch_work_data *)(work_req->data);
  
  ODBCResult* self = data->objResult->self();
  
  bool doMoreWork = true;
  
  if (self->colCount == 0) {
    self->columns = ODBC::GetColumns(self->m_hSTMT, &self->colCount);
  }
  
  //check to see if the result set has columns
  if (self->colCount == 0) {
    //this most likely means that the query was something like
    //'insert into ....'
    doMoreWork = false;
  }
  //check to see if there was an error
  else if (data->result == SQL_ERROR)  {
    data->errorCount++;
    
    NanAssignPersistent(data->objError, ODBC::GetSQLError(
      SQL_HANDLE_STMT, 
      self->m_hSTMT,
      (char *) "[node-odbc] Error in ODBCResult::UV_AfterFetchAll"
    ));
    
    doMoreWork = false;
  }
  //check to see if we are at the end of the recordset
  else if (data->result == SQL_NO_DATA) {
    doMoreWork = false;
  }
  else {
    //TODO: !important: persistent forces us to set this to a local handle, but do we need to recopy it back to persistent handle?
    Local<Array> rows = NanNew(data->rows);
    if (data->fetchMode == FETCH_ARRAY) {
      rows->Set(
        NanNew(data->count), 
        ODBC::GetRecordArray(
          self->m_hSTMT,
          self->columns,
          &self->colCount,
          self->buffer,
          self->bufferLength)
      );
    }
    else {
      rows->Set(
        NanNew(data->count), 
        ODBC::GetRecordTuple(
          self->m_hSTMT,
          self->columns,
          &self->colCount,
          self->buffer,
          self->bufferLength)
      );
    }
    data->count++;
  }
  
  if (doMoreWork) {
    //Go back to the thread pool and fetch more data!
    uv_queue_work(
      uv_default_loop(),
      work_req, 
      UV_FetchAll, 
      (uv_after_work_cb)UV_AfterFetchAll);
  }
  else {
    ODBC::FreeColumns(self->columns, &self->colCount);
    
    Handle<Value> args[2];
    
    if (data->errorCount > 0) {
      args[0] = NanNew(data->objError);
    }
    else {
      args[0] = NanNull();
    }
    
    args[1] = NanNew(data->rows);

    TryCatch try_catch;

    data->cb->Call(2, args);
    delete data->cb;
    NanDisposePersistent(data->rows);
    NanDisposePersistent(data->objError);

    if (try_catch.HasCaught()) {
      FatalException(try_catch);
    }

    //TODO: Do we need to free self->rows somehow?
    free(data);
    free(work_req);

    self->Unref(); 
  }
}
コード例 #7
0
ファイル: MySQL.cpp プロジェクト: steilman/samp.js
void MySQL::QueryAsync(int id, string query, Persistent<Function, CopyablePersistentTraits<Function>> callback){
	

	// We need to do this or for some reason it loses its persistence and goes out of scope :(
	Persistent<Function, CopyablePersistentTraits<Function>> cb;
	cb.Reset(isolate, callback);

	thread( [this, id, cb, query](){
		mysql_thread_init();
		std::lock_guard<std::mutex> lock{ connections[id]->lock };
		MYSQL* msql = connections[id]->mysql;
		if (!isConnected(msql)){
			sjs::logger::error("MYSQL Error: Not connected");
		} else {
			mysql_query(msql, query.c_str());

			unsigned int err_no = mysql_errno(msql);
			if (err_no){
				sjs::logger::error("MYSQL Query Error: %s", mysql_error(msql));
				V8PCONTEXT(isolate, context);

				TryCatch try_catch;

				Local<String> err = String::NewFromUtf8(isolate, mysql_error(msql));
				Local<Value> argv[1] = { err };
				Local<Function> func = Local<Function>::New(isolate, cb);
				func->Call(func, 1, argv);
				if (try_catch.HasCaught()){
					Utils::PrintException(&try_catch);
				}
				mysql_thread_end();
				return;
			}

			MYSQL_RES *result = mysql_store_result(msql);

			if (result == NULL){

				// No error and result was null meaning it wasn't a SELECT type statement
				my_ulonglong affected = mysql_affected_rows(msql);
				my_ulonglong insert_id = mysql_insert_id(msql);


				V8PCONTEXT(isolate, context);
				TryCatch try_catch;
				JS_Object jsresult(isolate);

				jsresult.Set("insertId", insert_id);
				jsresult.Set("affectedRows", affected);

				Local<Value> empty = Undefined(isolate);
				Local<Value> argv[2] = { empty, jsresult.get() };

				Local<Function> func = Local<Function>::New(isolate, cb);


				func->Call(func, 2, argv);
				if (try_catch.HasCaught()){
					Utils::PrintException(&try_catch);
				}


			}
			else {
				int num_fields = mysql_num_fields(result);

				MYSQL_ROW row;
				MYSQL_FIELD *field;

				vector<string> fields;


				V8PCONTEXT(isolate, context);
				TryCatch try_catch;
				Local<Array> jsrows = Array::New(isolate, 0);
				Local<Array> jsfields = Array::New(isolate, num_fields);

				for (int j = 0; j < num_fields; j++){
					field = mysql_fetch_field_direct(result, j);
					fields.push_back(field->name);
					jsfields->Set(j, String::NewFromUtf8(isolate, field->name));
				}

				int row_count = 0;
				while ((row = mysql_fetch_row(result))){
					JS_Object jsrow(isolate);
					for (int i = 0; i < num_fields; i++){

						if (row[i] == NULL) jsrow.SetNull(fields[i]);
						else jsrow.Set(fields[i], string(row[i]));

					}

					jsrows->Set(row_count++, jsrow.get());
				}

				Local<Value> empty = Undefined(isolate);
				Local<Value> argv[3] = { empty, jsrows, jsfields };

				Local<Function> func = Local<Function>::New(isolate, cb);

				func->Call(func, 3, argv);
				if (try_catch.HasCaught()){
					Utils::PrintException(&try_catch);
				}

				mysql_free_result(result);

			}
		}
		mysql_thread_end();
	}).detach();
}
コード例 #8
0
void SimpleProfiler::Init(Isolate *isolate, Local<ObjectTemplate>& globalTemplate)
{
	s_frames.reserve(10000);
	auto funcName = String::NewFromUtf8(isolate, "__printProfilerData");
	globalTemplate->Set(funcName, FunctionTemplate::New(isolate, PrintProfilerDataCallback));
}
コード例 #9
0
ファイル: odbc.cpp プロジェクト: jstopchick/node-odbc
Local<Object> ODBC::GetSQLError (SQLSMALLINT handleType, SQLHANDLE handle, char* message) {
    Nan::EscapableHandleScope scope;

    DEBUG_PRINTF("ODBC::GetSQLError : handleType=%i, handle=%p\n", handleType, handle);

    Local<Object> objError = Nan::New<Object>();

    SQLINTEGER i = 0;
    SQLINTEGER native;

    SQLSMALLINT len;
    SQLINTEGER statusRecCount;
    SQLRETURN ret;
    char errorSQLState[14];
    char errorMessage[ERROR_MESSAGE_BUFFER_BYTES];

    ret = SQLGetDiagField(
              handleType,
              handle,
              0,
              SQL_DIAG_NUMBER,
              &statusRecCount,
              SQL_IS_INTEGER,
              &len);

    // Windows seems to define SQLINTEGER as long int, unixodbc as just int... %i should cover both
    DEBUG_PRINTF("ODBC::GetSQLError : called SQLGetDiagField; ret=%i, statusRecCount=%i\n", ret, statusRecCount);

    Local<Array> errors = Nan::New<Array>();
    objError->Set(Nan::New("errors").ToLocalChecked(), errors);

    for (i = 0; i < statusRecCount; i++) {
        DEBUG_PRINTF("ODBC::GetSQLError : calling SQLGetDiagRec; i=%i, statusRecCount=%i\n", i, statusRecCount);

        ret = SQLGetDiagRec(
                  handleType,
                  handle,
                  (SQLSMALLINT)(i + 1),
                  (SQLTCHAR *) errorSQLState,
                  &native,
                  (SQLTCHAR *) errorMessage,
                  ERROR_MESSAGE_BUFFER_CHARS,
                  &len);

        DEBUG_PRINTF("ODBC::GetSQLError : after SQLGetDiagRec; i=%i\n", i);

        if (SQL_SUCCEEDED(ret)) {
            DEBUG_PRINTF("ODBC::GetSQLError : errorMessage=%s, errorSQLState=%s\n", errorMessage, errorSQLState);

            if (i == 0) {
                // First error is assumed the primary error
                objError->Set(Nan::New("error").ToLocalChecked(), Nan::New(message).ToLocalChecked());
#ifdef UNICODE
                objError->SetPrototype(Exception::Error(Nan::New((uint16_t *)errorMessage).ToLocalChecked()));
                objError->Set(Nan::New("message").ToLocalChecked(), Nan::New((uint16_t *)errorMessage).ToLocalChecked());
                objError->Set(Nan::New("state").ToLocalChecked(), Nan::New((uint16_t *)errorSQLState).ToLocalChecked());
#else
                objError->SetPrototype(Exception::Error(Nan::New(errorMessage).ToLocalChecked()));
                objError->Set(Nan::New("message").ToLocalChecked(), Nan::New(errorMessage).ToLocalChecked());
                objError->Set(Nan::New("state").ToLocalChecked(), Nan::New(errorSQLState).ToLocalChecked());
#endif
            }

            Local<Object> subError = Nan::New<Object>();

#ifdef UNICODE
            subError->Set(Nan::New("message").ToLocalChecked(), Nan::New((uint16_t *)errorMessage).ToLocalChecked());
            subError->Set(Nan::New("state").ToLocalChecked(), Nan::New((uint16_t *)errorSQLState).ToLocalChecked());
#else
            subError->Set(Nan::New("message").ToLocalChecked(), Nan::New(errorMessage).ToLocalChecked());
            subError->Set(Nan::New("state").ToLocalChecked(), Nan::New(errorSQLState).ToLocalChecked());
#endif
            errors->Set(Nan::New(i), subError);

        } else if (ret == SQL_NO_DATA) {
            break;
        }
    }

    if (statusRecCount == 0) {
        //Create a default error object if there were no diag records
        objError->Set(Nan::New("error").ToLocalChecked(), Nan::New(message).ToLocalChecked());
        objError->SetPrototype(Exception::Error(Nan::New(message).ToLocalChecked()));
        objError->Set(Nan::New("message").ToLocalChecked(), Nan::New(
                          (const char *) "[node-odbc] An error occurred but no diagnostic information was available.").ToLocalChecked());
    }

    return scope.Escape(objError);
}
コード例 #10
0
ファイル: Server.cpp プロジェクト: steilman/samp.js
void Server::JS_CallNative(const FunctionCallbackInfo<Value> & args){
	typedef int(*amx_Function_t)(AMX * amx, cell * params);
	TryCatch try_catch;

	if (args.Length() < 1){
		sjs::logger::error("Function CallNative requires at least 1 argument CallNative(nativeName, params, args);");
		args.GetReturnValue().SetNull();
		return;
	}

	std::string func_name = JS2STRING(args[0]);

	int func_idx;
	AMX_HEADER *amx_hdr = (AMX_HEADER *)SAMPJS::amx->base;

	auto iter = _native_func_cache.find(func_name);
	if (iter != _native_func_cache.end()) func_idx = iter->second;
	else {
		if (amx_FindNative(SAMPJS::amx, func_name.c_str(), &func_idx)){
			sjs::logger::error("Cannot find native function %s", func_name.c_str());
			return;
		}
		_native_func_cache[func_name] = func_idx;
	}

	unsigned int amx_addr = (unsigned int)((AMX_FUNCSTUB *)((char *)amx_hdr + amx_hdr->natives + amx_hdr->defsize * func_idx))->address;

	if (args.Length() > 1){
		if (!args[1]->IsString()){
			sjs::logger::error("CallNative %s, 2nd argument must be a string", func_name.c_str());
			return;
		}


		std::string param = JS2STRING(args[1]);
		size_t S_oc = std::count(param.begin(), param.end(), 'S');
		size_t I_oc = std::count(param.begin(), param.end(), 'I');
		size_t F_oc = std::count(param.begin(), param.end(), 'F');
		

		bool multi = false;
		if ((S_oc + I_oc + F_oc) > 1) multi = true;
		if (!args[args.Length() - 1]->IsArray() && multi){
			sjs::logger::error("CallNative %s, you must supply an array of strings for functions with multiple references", func_name.c_str());
			return;
		}

		unsigned int count = (param.length()), variables = 0;

		cell *physAddr[6];
		cell *params = new cell[count + 1];
		params[0] = count * sizeof(cell);
		unsigned int strVars = 0;
		unsigned int k = 2, j = 1;
		for (unsigned int i = 0; i < param.length(); i++){
			switch (param[i]){
			case 'd':
			case 'i':
			{
				int val = 0;
				if (!args[k]->IsUndefined()) val = args[k]->Int32Value();
				params[j++] = val;

				k++;
				break;
			}
			case 'f':
			{
				float val = 0.0;
				if (!args[k]->IsUndefined()) val = (float)args[k]->NumberValue();
				params[j++] = amx_ftoc(val);

				k++;
				break;
			}
			case 's':
			{
				std::string str = "";
				if (!args[k]->IsUndefined()) str = JS2STRING(args[k]);
				const char* val = str.c_str();
				amx_Allot(SAMPJS::amx, strlen(val) + 1, &params[j++], &physAddr[variables++]);
				amx_SetString(physAddr[variables - 1], val, 0, 0, strlen(val) + 1);
				k++;
				break;
			}

			case 'F':
			case 'I':
			{
				amx_Allot(SAMPJS::amx, 1, &params[j++], &physAddr[variables++]);
				break;
			}

			case 'S':
			{
				int strlen = args[k++]->Int32Value();
				amx_Allot(SAMPJS::amx, strlen, &params[j++], &physAddr[variables++]);
				params[j++] = strlen;
				i++;
				break;
			}
			}
		}




		amx_Function_t amx_Function = (amx_Function_t)amx_addr;
		int value = amx_Function(SAMPJS::amx, params);

	

		if (variables){
			Local<Object> retobj;
			Local<Value> retval;
			Local<Array> arr;
			if (multi){
				arr = Local<Array>::Cast(args[args.Length() - 1]);
				retobj = Object::New(args.GetIsolate());
			}

			unsigned int k = 1;
			unsigned int j = 0;
			variables = 0;
			strVars = 0;
			for (unsigned int i = 0; i < param.length(); i++){
				switch (param[i]){
				default: k++;
					break;

				case 's':{
					strVars++;
					variables++;
					//amx_Release(sampjs.GetAMX(), params[i]);
					break;
				}

				case 'S':{
					char* text;
					text = new char[params[k++]];
					amx_GetString(text, physAddr[variables++], 0, params[k++]);
					i++;
					k++;

					if (multi) retobj->Set(arr->Get(j++), STRING2JS(args.GetIsolate(), text));
					else retval = STRING2JS(args.GetIsolate(), text);
					delete text;
					//amx_Release(sampjs.GetAMX(), params[i]);
					break;
				}

				case 'F':{
					cell* returnValue = (cell*)physAddr[variables++];
					float fl = amx_ctof(*returnValue);

					if (multi) retobj->Set(arr->Get(j++), Number::New(args.GetIsolate(), fl));
					else retval = Number::New(args.GetIsolate(), fl);
					//amx_Release(sampjs.GetAMX(), params[i]);
					break;
				}
				case 'I':{
					cell* returnValue = (cell*)physAddr[variables++];
					int value = *returnValue;
					if (multi) retobj->Set(arr->Get(j++), Integer::New(args.GetIsolate(), value));
					else retval = Integer::New(args.GetIsolate(), value);
					//amx_Release(sampjs.GetAMX(), params[i]);
					break;
				}

				}
			}

			for (int i = param.length() - 1; i >= 0; i--){
				if (param[i] == 'F' || param[i] == 'I' || param[i] == 'S' || param[i] == 's'){
					amx_Release(SAMPJS::amx, params[i + 1]);
				}
			}

			if (try_catch.HasCaught()){
				args.GetIsolate()->CancelTerminateExecution();
				Utils::PrintException(&try_catch);
				delete[] params;
				return;
			}
			if (multi){
				args.GetReturnValue().Set(retobj);
				delete[] params;
				return;
			}
			else if (!retval.IsEmpty()){
				args.GetReturnValue().Set(Local<Value>::Cast(retval));
				delete[] params;
				return;
			}

		}

		args.GetReturnValue().Set(value);
		delete[] params;
		return;
	}
	else {
		if (try_catch.HasCaught()){
			args.GetIsolate()->CancelTerminateExecution();
			Utils::PrintException(&try_catch);
			return;
		}
		amx_Function_t amx_Function = (amx_Function_t)amx_addr;
		int value = amx_Function(SAMPJS::amx, NULL);
		args.GetReturnValue().Set(value);
		return;
	}
}
コード例 #11
0
// Implementation of the schema handler for appjs:// requests.
void AppjsSchemeHandler::Execute(CefThreadId threadId) {

  REQUIRE_UI_THREAD();

  HandleScope scope;

  Local<Object>  global = Context::GetCurrent()->Global();
  Local<Object> emitter = global->Get(String::NewSymbol("process"))->ToObject();

  const int argc = 3;

  Handle<Value>    self = WrapObject(this);
  Local<Function>    cb = FunctionTemplate::New(NodeCallback,self)->GetFunction();
  Local<Object>     req = Object::New();
  Local<String>    post = String::New("");
  Local<Object> headers = Object::New();
  Local<String>   files = String::New("");

  CefRequest::HeaderMap headerMap;
  request_->GetHeaderMap(headerMap);

  if (headerMap.size() > 0) {
    CefRequest::HeaderMap::const_iterator it = headerMap.begin();
    for ( ; it != headerMap.end(); ++it) {
      headers->Set(String::New((uint16_t*)(*it).first.c_str()),String::New((uint16_t*)(*it).second.c_str()));
    }
  }

  CefRefPtr<CefPostData> postData = request_->GetPostData();

  if(postData.get()){

    CefPostData::ElementVector elements;

    postData->GetElements(elements);

    if (elements.size() > 0) {
      CefRefPtr<CefPostDataElement> element;
      CefPostData::ElementVector::const_iterator it = elements.begin();

      for ( ; it != elements.end(); ++it) {
        element = (*it);
        if (element->GetType() == PDE_TYPE_BYTES && element->GetBytesCount()) {

          // retrieve the data.
          size_t size = element->GetBytesCount();
          char* bytes = new char[size];
          element->GetBytes(size, bytes);
          post = String::New(bytes,size);
          delete [] bytes;

        } else if (element->GetType() == PDE_TYPE_FILE) {
          //TODO Needs testing
          files = String::New((uint16_t*)element->GetFile().c_str());
        }
      }

    }
  }

  Handle<Value> method = String::New((uint16_t*)request_->GetMethod().c_str());
  Handle<Value> url = String::New((uint16_t*)request_->GetURL().c_str());

  req->Set(String::NewSymbol("method"),method);
  req->Set(String::NewSymbol("url"),url);
  req->Set(String::NewSymbol("post"),post);
  req->Set(String::NewSymbol("headers"),headers);
  req->Set(String::NewSymbol("files"),files);

  Handle<Value> argv[argc] = {String::New("appjs-request"),req,cb};
  node::MakeCallback(emitter,"emit",argc,argv);

}
コード例 #12
0
ファイル: glescustom.cpp プロジェクト: Ryanaxp/v8-gl
//GetBooleanv, GetIntegerv, GetString, GetFloatv, GetDoublev should map here.
Handle<Value> GLESglGetParameterCallback(const Arguments& args) {
  //if less that nbr of formal parameters then do nothing
  if (args.Length() < 1) return v8::Undefined();
  //define handle scope
  HandleScope handle_scope;
  //get arguments
  unsigned pname = args[0]->Uint32Value();


  switch(pname) {
  //return 1 int value
  case GL_ALPHA_TEST_FUNC:
  case GL_ACCUM_ALPHA_BITS:
  case GL_ACCUM_BLUE_BITS:
  case GL_ACCUM_GREEN_BITS:
  case GL_ACCUM_RED_BITS:
  case GL_ALPHA_BITS:
  case GL_ATTRIB_STACK_DEPTH:
  case GL_AUX_BUFFERS:
  case GL_BLEND_DST:
  case GL_BLEND_EQUATION_EXT:
  case GL_BLEND_SRC:
  case GL_BLUE_BITS:
  case GL_SUBPIXEL_BITS:
  case GL_CLIENT_ATTRIB_STACK_DEPTH:
  case GL_COLOR_ARRAY_SIZE:
  case GL_COLOR_ARRAY_STRIDE:
  case GL_COLOR_ARRAY_TYPE:
  case GL_COLOR_MATERIAL_FACE:
  case GL_COLOR_MATERIAL_PARAMETER:
  case GL_CULL_FACE_MODE:
  case GL_DEPTH_BITS:
  case GL_DEPTH_FUNC:
  case GL_DRAW_BUFFER:
  case GL_EDGE_FLAG_ARRAY_STRIDE:
  case GL_FOG_HINT:
  case GL_FOG_MODE:
  case GL_FRONT_FACE:
  case GL_GREEN_BITS:
  case GL_INDEX_ARRAY_STRIDE:
  case GL_INDEX_ARRAY_TYPE:
  case GL_INDEX_BITS:
  case GL_INDEX_WRITEMASK:
  case GL_LINE_SMOOTH_HINT:
  case GL_LINE_STIPPLE_PATTERN:
  case GL_LINE_STIPPLE_REPEAT:
  case GL_LIST_BASE:
  case GL_LIST_INDEX: //name of the display list
  case GL_LIST_MODE:
  case GL_LOGIC_OP_MODE:
  case GL_MAP1_GRID_SEGMENTS:
  case GL_MATRIX_MODE:
  case GL_MAX_CLIENT_ATTRIB_STACK_DEPTH:
  case GL_MAX_ATTRIB_STACK_DEPTH:
  case GL_MAX_CLIP_PLANES:
  case GL_MAX_EVAL_ORDER:
  case GL_MAX_LIGHTS:
  case GL_MAX_LIST_NESTING:
  case GL_MAX_MODELVIEW_STACK_DEPTH:
  case GL_MAX_NAME_STACK_DEPTH:
  case GL_MAX_PIXEL_MAP_TABLE:
  case GL_MAX_PROJECTION_STACK_DEPTH:
  case GL_MAX_TEXTURE_SIZE:
  case GL_MAX_TEXTURE_STACK_DEPTH:
  case GL_MODELVIEW_STACK_DEPTH:
  case GL_NAME_STACK_DEPTH:
  case GL_NORMAL_ARRAY_STRIDE:
  case GL_NORMAL_ARRAY_TYPE:
  case GL_PACK_ALIGNMENT:
  case GL_PACK_ROW_LENGTH:
  case GL_PACK_SKIP_PIXELS:
  case GL_PACK_SKIP_ROWS:
  case GL_PERSPECTIVE_CORRECTION_HINT:
  case GL_PIXEL_MAP_A_TO_A_SIZE:
  case GL_PIXEL_MAP_B_TO_B_SIZE:
  case GL_PIXEL_MAP_G_TO_G_SIZE:
  case GL_PIXEL_MAP_I_TO_A_SIZE:
  case GL_PIXEL_MAP_I_TO_B_SIZE:
  case GL_PIXEL_MAP_I_TO_G_SIZE:
  case GL_PIXEL_MAP_I_TO_I_SIZE:
  case GL_PIXEL_MAP_I_TO_R_SIZE:
  case GL_PIXEL_MAP_R_TO_R_SIZE:
  case GL_PIXEL_MAP_S_TO_S_SIZE:
  case GL_POINT_SMOOTH_HINT:
  case GL_POLYGON_SMOOTH_HINT:
  case GL_PROJECTION_STACK_DEPTH:
  case GL_RED_BITS:
  case GL_RENDER_MODE:
  case GL_SHADE_MODEL:
  case GL_STENCIL_BITS:
  case GL_STENCIL_CLEAR_VALUE:
  case GL_STENCIL_FAIL:
  case GL_STENCIL_FUNC:
  case GL_STENCIL_PASS_DEPTH_FAIL:
  case GL_STENCIL_PASS_DEPTH_PASS:
  case GL_STENCIL_REF:
  case GL_STENCIL_VALUE_MASK:
  case GL_STENCIL_WRITEMASK:
//  case GL_TEXTURE_1D_BINDING:
//  case GL_TEXTURE_2D_BINDING:
  case GL_TEXTURE_COORD_ARRAY_SIZE:
  case GL_TEXTURE_COORD_ARRAY_STRIDE:
  case GL_TEXTURE_COORD_ARRAY_TYPE:
  case GL_TEXTURE_STACK_DEPTH:
  case GL_UNPACK_ALIGNMENT:
  case GL_UNPACK_ROW_LENGTH:
  case GL_UNPACK_SKIP_PIXELS:
  case GL_UNPACK_SKIP_ROWS:
  case GL_VERTEX_ARRAY_SIZE:
  case GL_VERTEX_ARRAY_STRIDE:
  case GL_VERTEX_ARRAY_TYPE:
  {
	  int ans = 0;
	  glGetIntegerv((GLenum)pname, (GLint*)&ans);
	  return handle_scope.Close(Integer::New(ans));
  }
  //2 values int
  case GL_LINE_WIDTH_RANGE:
  case GL_MAP2_GRID_SEGMENTS:
  case GL_MAX_VIEWPORT_DIMS:
  case GL_POLYGON_MODE:
  {
	  int* ans = new int[2];
	  glGetIntegerv((GLenum)pname, ans);

	  Local<Array> res = Array::New(2);
	  for (int i = 0; i < 2; ++i) {
	    res->Set(Integer::New(i), Integer::New(ans[i]));
	  }

	  delete[] ans;

	  return handle_scope.Close(res);
  }
  //4 values int
  case GL_SCISSOR_BOX:
  case GL_VIEWPORT:
  {
	  int* ans = new int[4];
	  glGetIntegerv((GLenum)pname, ans);

	  Local<Array> res = Array::New(4);
	  for (int i = 0; i < 4; ++i) {
	    res->Set(Integer::New(i), Integer::New(ans[i]));
	  }

	  delete[] ans;

	  return handle_scope.Close(res);
  }

  //1 value boolean
  case GL_ALPHA_TEST:
  case GL_AUTO_NORMAL:
  case GL_BLEND:
  case GL_DEPTH_TEST:
//  case GL_CLIP_PLANEi:
  case GL_COLOR_ARRAY:
  case GL_COLOR_LOGIC_OP:
  case GL_COLOR_MATERIAL:
  case GL_CULL_FACE:
  case GL_CURRENT_RASTER_POSITION_VALID:
  case GL_DEPTH_WRITEMASK:
  case GL_DITHER:
  case GL_DOUBLEBUFFER:
  case GL_EDGE_FLAG:
  case GL_EDGE_FLAG_ARRAY:
  case GL_FOG:
  case GL_INDEX_ARRAY:
  case GL_INDEX_LOGIC_OP:
  case GL_INDEX_MODE:
//  case GL_LIGHTi:
  case GL_LIGHTING:
  case GL_LIGHT_MODEL_LOCAL_VIEWER:
  case GL_LIGHT_MODEL_TWO_SIDE:
  case GL_LINE_SMOOTH:
  case GL_LINE_STIPPLE:
  case GL_MAP1_COLOR_4:
  case GL_MAP1_INDEX:
  case GL_MAP1_NORMAL:
  case GL_MAP1_TEXTURE_COORD_1:
  case GL_MAP1_TEXTURE_COORD_2:
  case GL_MAP1_TEXTURE_COORD_3:
  case GL_MAP1_TEXTURE_COORD_4:
  case GL_MAP1_VERTEX_3:
  case GL_MAP1_VERTEX_4:
  case GL_MAP2_COLOR_4:
  case GL_MAP2_INDEX:
  case GL_MAP2_NORMAL:
  case GL_MAP2_TEXTURE_COORD_1:
  case GL_MAP2_TEXTURE_COORD_2:
  case GL_MAP2_TEXTURE_COORD_3:
  case GL_MAP2_TEXTURE_COORD_4:
  case GL_MAP2_VERTEX_3:
  case GL_MAP2_VERTEX_4:
  case GL_MAP_COLOR:
  case GL_MAP_STENCIL:
  case GL_NORMAL_ARRAY:
  case GL_NORMALIZE:
  case GL_PACK_LSB_FIRST:
  case GL_PACK_SWAP_BYTES:
  case GL_POINT_SMOOTH:
  case GL_POLYGON_OFFSET_FILL:
  case GL_POLYGON_OFFSET_LINE:
  case GL_POLYGON_OFFSET_POINT:
  case GL_POLYGON_SMOOTH:
  case GL_POLYGON_STIPPLE:
  case GL_READ_BUFFER:
  case GL_RGBA_MODE:
  case GL_SCISSOR_TEST:
  case GL_STENCIL_TEST:
  case GL_STEREO:
  case GL_TEXTURE_1D:
  case GL_TEXTURE_2D:
  case GL_TEXTURE_COORD_ARRAY:
  case GL_TEXTURE_GEN_Q:
  case GL_TEXTURE_GEN_R:
  case GL_TEXTURE_GEN_S:
  case GL_TEXTURE_GEN_T:
  case GL_UNPACK_LSB_FIRST:
  case GL_VERTEX_ARRAY:
  case GL_UNPACK_SWAP_BYTES:
  {
	  GLboolean ans = 0;
	  glGetBooleanv((GLenum)pname, &ans);
	  return handle_scope.Close(Boolean::New(ans != GL_FALSE));
  }

  //1 value float
  case GL_ALPHA_BIAS:
  case GL_ALPHA_SCALE:
  case GL_BLUE_BIAS:
  case GL_BLUE_SCALE:
  case GL_RED_BIAS:
  case GL_RED_SCALE:
  case GL_GREEN_BIAS:
  case GL_GREEN_SCALE:
  case GL_DEPTH_BIAS:
  case GL_DEPTH_SCALE:
  case GL_ALPHA_TEST_REF:
  case GL_ZOOM_X:
  case GL_ZOOM_Y:
  case GL_CURRENT_INDEX:
  case GL_CURRENT_RASTER_DISTANCE:
  case GL_CURRENT_RASTER_INDEX:
  case GL_DEPTH_CLEAR_VALUE:
  case GL_FOG_DENSITY:
  case GL_FOG_END:
  case GL_FOG_INDEX:
  case GL_FOG_START:
  case GL_INDEX_CLEAR_VALUE:
  case GL_INDEX_OFFSET:
  case GL_INDEX_SHIFT:
  case GL_LINE_WIDTH:
  case GL_LINE_WIDTH_GRANULARITY:
  case GL_POINT_SIZE:
  case GL_POINT_SIZE_GRANULARITY:
  {
	  float ans = 0.0f;
	  glGetFloatv((GLenum)pname, &ans);
	  return handle_scope.Close(Number::New(ans));
  }

  //4 values float
  case GL_BLEND_COLOR_EXT:
  case GL_ACCUM_CLEAR_VALUE:
  case GL_COLOR_CLEAR_VALUE:
  case GL_CURRENT_COLOR:
  case GL_CURRENT_RASTER_COLOR:
  case GL_CURRENT_RASTER_POSITION:
  case GL_CURRENT_RASTER_TEXTURE_COORDS:
  case GL_CURRENT_TEXTURE_COORDS:
  case GL_FOG_COLOR:
  case GL_LIGHT_MODEL_AMBIENT:
  case GL_MAP2_GRID_DOMAIN:
  case GL_POLYGON_OFFSET_FACTOR:
  case GL_POLYGON_OFFSET_UNITS:
  {
	  float* ans = new float[4];
	  glGetFloatv((GLenum)pname, ans);

	  Local<Array> res = Array::New(4);
	  for (int i = 0; i < 4; ++i) {
	    res->Set(Integer::New(i), Number::New(ans[i]));
	  }

	  delete[] ans;

	  return handle_scope.Close(res);
  }

   //3 values float
  case GL_CURRENT_NORMAL:
  {
	  float* ans = new float[3];
	  glGetFloatv((GLenum)pname, ans);

	  Local<Array> res = Array::New(3);
	  for (int i = 0; i < 3; ++i) {
	    res->Set(Integer::New(i), Number::New(ans[i]));
	  }

	  delete[] ans;

	  return handle_scope.Close(res);
  }

  //2 values float
  case GL_DEPTH_RANGE:
  case GL_MAP1_GRID_DOMAIN:
  case GL_POINT_SIZE_RANGE:
  {
	  float* ans = new float[2];
	  glGetFloatv((GLenum)pname, ans);

	  Local<Array> res = Array::New(2);
	  for (int i = 0; i < 2; ++i) {
	    res->Set(Integer::New(i), Number::New(ans[i]));
	  }

	  delete[] ans;

	  return handle_scope.Close(res);
  }

  //16 values float
  case GL_MODELVIEW_MATRIX:
  case GL_PROJECTION_MATRIX:
  case GL_TEXTURE_MATRIX:
  {
	  float* ans = new float[16];
	  glGetFloatv((GLenum)pname, ans);

	  Local<Array> res = Array::New(16);
	  for (int i = 0; i < 16; ++i) {
	    res->Set(Integer::New(i), Number::New(ans[i]));
	  }

	  delete[] ans;

	  return handle_scope.Close(res);
  }

  //4 values boolean
  case GL_COLOR_WRITEMASK:
  {
	  GLboolean* ans = new GLboolean[4];
	  glGetBooleanv((GLenum)pname, ans);

	  Local<Array> res = Array::New(4);
	  for (int i = 0; i < 4; ++i) {
	    res->Set(Integer::New(i), Boolean::New(ans[i] != GL_FALSE));
	  }

	  delete[] ans;

	  return handle_scope.Close(res);
  }

  }
  return v8::Undefined();
}
コード例 #13
0
JNIEXPORT jboolean JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeFireEvent
	(JNIEnv *env, jobject jEmitter, jlong ptr, jobject jsource, jlong sourcePtr, jstring event, jobject data, jboolean bubble, jboolean reportSuccess, jint code, jstring errorMessage)
{
	HandleScope scope(V8Runtime::v8_isolate);
	JNIScope jniScope(env);

	Local<Value> jsEvent = TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, event);

#ifdef TI_DEBUG
	titanium::Utf8Value eventName(jsEvent);
	LOGV(TAG, "firing event \"%s\"", *eventName);
#endif

	Local<Object> emitter;
	if (ptr != 0) {
		titanium::Proxy* proxy = (titanium::Proxy*) ptr;
		emitter = proxy->handle(V8Runtime::v8_isolate);
	} else {
		emitter = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, jEmitter).As<Object>();
	}

	Local<Value> fireEventValue = emitter->Get(EventEmitter::emitSymbol.Get(V8Runtime::v8_isolate));
	if (!fireEventValue->IsFunction()) {
		return JNI_FALSE;
	}

	Local<Object> source;
	if ((jsource == NULL) || (jsource == jEmitter)) {
		source = emitter;
	} else if (sourcePtr != 0) {
		titanium::Proxy* proxy = (titanium::Proxy*) sourcePtr;
		source = proxy->handle(V8Runtime::v8_isolate);
	} else {
		source = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, jsource).As<Object>();
	}

	Local<Function> fireEvent = fireEventValue.As<Function>();

	Local<Object> jsData = TypeConverter::javaHashMapToJsValue(V8Runtime::v8_isolate, env, data);

	jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "bubbles"), TypeConverter::javaBooleanToJsBoolean(V8Runtime::v8_isolate, bubble));

	jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "source"), source);

	if (reportSuccess || code != 0) {
		jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "success"), TypeConverter::javaBooleanToJsBoolean(V8Runtime::v8_isolate, code == 0));
		jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "code"), TypeConverter::javaIntToJsNumber(V8Runtime::v8_isolate, code));
	}

	if (errorMessage != NULL) {
		jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "error"), TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, errorMessage));
	}

	TryCatch tryCatch(V8Runtime::v8_isolate);
	Local<Value> args[] = { jsEvent, jsData };
	MaybeLocal<Value> result = fireEvent->Call(V8Runtime::v8_isolate->GetCurrentContext(), emitter, 2, args);

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(V8Runtime::v8_isolate, tryCatch);
		V8Util::reportException(V8Runtime::v8_isolate, tryCatch);
	} else if (result.IsEmpty()) {
		return JNI_FALSE;
	} else if (result.ToLocalChecked()->IsTrue()) {
		return JNI_TRUE;
	}
	return JNI_FALSE;
}
コード例 #14
0
ファイル: odbc.cpp プロジェクト: impy88/node-odbc
Local<Object> ODBC::GetSQLError (SQLSMALLINT handleType, SQLHANDLE handle, char* message) {
  HandleScope scope;
  
  DEBUG_PRINTF("ODBC::GetSQLError : handleType=%i, handle=%p\n", handleType, handle);
  
  Local<Object> objError = Object::New();
  Local<String> str = String::New("");

  SQLINTEGER i = 0;
  SQLINTEGER native;
  
  SQLSMALLINT len;
  SQLINTEGER statusRecCount;
  SQLRETURN ret;
  char errorSQLState[14];
  char errorMessage[ERROR_MESSAGE_BUFFER_BYTES];

  ret = SQLGetDiagField(
    handleType,
    handle,
    0,
    SQL_DIAG_NUMBER,
    &statusRecCount,
    SQL_IS_INTEGER,
    &len);

  // Windows seems to define SQLINTEGER as long int, unixodbc as just int... %i should cover both
  DEBUG_PRINTF("ODBC::GetSQLError : called SQLGetDiagField; ret=%i, statusRecCount=%i\n", ret, statusRecCount);

  for (i = 0; i < statusRecCount; i++){
    DEBUG_PRINTF("ODBC::GetSQLError : calling SQLGetDiagRec; i=%i, statusRecCount=%i\n", i, statusRecCount);
    
    ret = SQLGetDiagRec(
      handleType, 
      handle,
      i + 1, 
      (SQLTCHAR *) errorSQLState,
      &native,
      (SQLTCHAR *) errorMessage,
      ERROR_MESSAGE_BUFFER_CHARS,
      &len);
    
    DEBUG_PRINTF("ODBC::GetSQLError : after SQLGetDiagRec; i=%i\n", i);

    if (SQL_SUCCEEDED(ret)) {
      DEBUG_PRINTF("ODBC::GetSQLError : errorMessage=%s, errorSQLState=%s\n", errorMessage, errorSQLState);

      objError->Set(String::New("error"), String::New(message));
#ifdef UNICODE
      str = String::Concat(str, String::New((uint16_t *) errorMessage));

      objError->SetPrototype(Exception::Error(String::New((uint16_t *) errorMessage)));
      objError->Set(String::New("message"), str);
      objError->Set(String::New("state"), String::New((uint16_t *) errorSQLState));
#else
      str = String::Concat(str, String::New(errorMessage));

      objError->SetPrototype(Exception::Error(String::New(errorMessage)));
      objError->Set(String::New("message"), str);
      objError->Set(String::New("state"), String::New(errorSQLState));
#endif
    } else if (ret == SQL_NO_DATA) {
      break;
    }
  }

  if (statusRecCount == 0) {
    //Create a default error object if there were no diag records
    objError->Set(String::New("error"), String::New(message));
    objError->SetPrototype(Exception::Error(String::New(message)));
    objError->Set(String::New("message"), String::New(
      (const char *) "[node-odbc] An error occurred but no diagnostic information was available."));
  }

  return scope.Close(objError);
}
コード例 #15
0
Handle<Value> ProjTransform::forward(const Arguments& args)
{
    HandleScope scope;
    ProjTransform* p = ObjectWrap::Unwrap<ProjTransform>(args.This());

    if (!args.Length() == 1)
        return ThrowException(Exception::Error(
                                  String::New("Must provide an array of either [x,y] or [minx,miny,maxx,maxy]")));
    else
    {
        if (!args[0]->IsArray())
            return ThrowException(Exception::Error(
                                      String::New("Must provide an array of either [x,y] or [minx,miny,maxx,maxy]")));

        Local<Array> a = Local<Array>::Cast(args[0]);
        uint32_t array_length = a->Length();
        if (array_length == 2)
        {
            double x = a->Get(0)->NumberValue();
            double y = a->Get(1)->NumberValue();
            double z = 0;
            if (!p->this_->forward(x,y,z))
            {
                std::ostringstream s;
                s << "Failed to forward project "
                  << a->Get(0)->NumberValue() << "," << a->Get(1)->NumberValue() << " from " << p->this_->source().params() << " to " << p->this_->dest().params();
                return ThrowException(Exception::Error(
                                      String::New(s.str().c_str())));
                
            }
            Local<Array> a = Array::New(2);
            a->Set(0, Number::New(x));
            a->Set(1, Number::New(y));
            return scope.Close(a);
        }
        else if (array_length == 4)
        {
            mapnik::box2d<double> box(a->Get(0)->NumberValue(),
                                      a->Get(1)->NumberValue(),
                                      a->Get(2)->NumberValue(),
                                      a->Get(3)->NumberValue());
            if (!p->this_->forward(box))
            {
                std::ostringstream s;
                s << "Failed to forward project "
                  << box << " from " << p->this_->source().params() << " to " << p->this_->dest().params();
                return ThrowException(Exception::Error(
                                      String::New(s.str().c_str())));
            
            }
            Local<Array> a = Array::New(4);
            a->Set(0, Number::New(box.minx()));
            a->Set(1, Number::New(box.miny()));
            a->Set(2, Number::New(box.maxx()));
            a->Set(3, Number::New(box.maxy()));
            return scope.Close(a);
        }
        else
            return ThrowException(Exception::Error(
                                      String::New("Must provide an array of either [x,y] or [minx,miny,maxx,maxy]")));

    }
}
コード例 #16
0
ファイル: odbc.cpp プロジェクト: jstopchick/node-odbc
Local<Array> ODBC::GetAllRecordsSync (HENV hENV,
                                      HDBC hDBC,
                                      HSTMT hSTMT,
                                      uint16_t* buffer,
                                      int bufferLength) {
    DEBUG_PRINTF("ODBC::GetAllRecordsSync\n");

    Nan::EscapableHandleScope scope;

    Local<Object> objError = Nan::New<Object>();

    int count = 0;
    int errorCount = 0;
    short colCount = 0;

    Column* columns = GetColumns(hSTMT, &colCount);

    Local<Array> rows = Nan::New<Array>();

    //loop through all records
    while (true) {
        SQLRETURN ret = SQLFetch(hSTMT);

        //check to see if there was an error
        if (ret == SQL_ERROR)  {
            //TODO: what do we do when we actually get an error here...
            //should we throw??

            errorCount++;

            objError = ODBC::GetSQLError(
                           SQL_HANDLE_STMT,
                           hSTMT,
                           (char *) "[node-odbc] Error in ODBC::GetAllRecordsSync"
                       );

            break;
        }

        //check to see if we are at the end of the recordset
        if (ret == SQL_NO_DATA) {
            ODBC::FreeColumns(columns, &colCount);

            break;
        }

        rows->Set(
            Nan::New(count),
            ODBC::GetRecordTuple(
                hSTMT,
                columns,
                &colCount,
                buffer,
                bufferLength)
        );

        count++;
    }
    //TODO: what do we do about errors!?!
    //we throw them
    return scope.Escape(rows);
}
コード例 #17
0
VALUE_MODIFY TiRootObject::onChildValueChange(TiObject* childObject, Handle<Value>, Handle<Value> newValue)
{
    Local<Object> obj = getValue()->ToObject();
    obj->Set(String::New(childObject->getName()), newValue);
    return VALUE_MODIFY_ALLOW;
}
コード例 #18
0
ファイル: node_mapnik.cpp プロジェクト: mojodna/node-mapnik
    static void InitMapnik (Handle<Object> target)
    {
        HandleScope scope;
        GOOGLE_PROTOBUF_VERIFY_VERSION;

        // module level functions
        NODE_SET_METHOD(target, "register_datasources", node_mapnik::register_datasources);
        NODE_SET_METHOD(target, "datasources", node_mapnik::available_input_plugins);
        NODE_SET_METHOD(target, "register_fonts", node_mapnik::register_fonts);
        NODE_SET_METHOD(target, "fonts", node_mapnik::available_font_faces);
        NODE_SET_METHOD(target, "fontFiles", node_mapnik::available_font_files);
        NODE_SET_METHOD(target, "clearCache", clearCache);
        NODE_SET_METHOD(target, "gc", gc);
        NODE_SET_METHOD(target, "shutdown",shutdown);

        // Classes
        VectorTile::Initialize(target);
        Map::Initialize(target);
        Color::Initialize(target);
        Geometry::Initialize(target);
        Feature::Initialize(target);
        Image::Initialize(target);
        ImageView::Initialize(target);
        Palette::Initialize(target);
        Projection::Initialize(target);
        ProjTransform::Initialize(target);
        Layer::Initialize(target);
        Grid::Initialize(target);
        GridView::Initialize(target);
        Datasource::Initialize(target);
        Featureset::Initialize(target);
        // Not production safe, so disabling indefinitely
        //JSDatasource::Initialize(target);
        MemoryDatasource::Initialize(target);
        Expression::Initialize(target);
        CairoSurface::Initialize(target);

        // versions of deps
        Local<Object> versions = Object::New();
        versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
        versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
        versions->Set(String::NewSymbol("boost"), String::New(format_version(BOOST_VERSION).c_str()));
        versions->Set(String::NewSymbol("boost_number"), Integer::New(BOOST_VERSION));
        versions->Set(String::NewSymbol("mapnik"), String::New(format_version(MAPNIK_VERSION).c_str()));
        versions->Set(String::NewSymbol("mapnik_number"), Integer::New(MAPNIK_VERSION));
#if defined(HAVE_CAIRO)
        versions->Set(String::NewSymbol("cairo"), String::New(CAIRO_VERSION_STRING));
#endif
        target->Set(String::NewSymbol("versions"), versions);

        Local<Object> supports = Object::New();
#if MAPNIK_VERSION >= 200300
        #ifdef GRID_RENDERER
        supports->Set(String::NewSymbol("grid"), True());
        #else
        supports->Set(String::NewSymbol("grid"), False());
        #endif
#else
        supports->Set(String::NewSymbol("grid"), True());
#endif

#ifdef SVG_RENDERER
        supports->Set(String::NewSymbol("svg"), True());
#else
        supports->Set(String::NewSymbol("svg"), False());
#endif

#if defined(HAVE_CAIRO)
        supports->Set(String::NewSymbol("cairo"), True());
        #ifdef CAIRO_HAS_PDF_SURFACE
        supports->Set(String::NewSymbol("cairo_pdf"), True());
        #else
        supports->Set(String::NewSymbol("cairo_pdf"), False());
        #endif
        #ifdef CAIRO_HAS_SVG_SURFACE
        supports->Set(String::NewSymbol("cairo_svg"), True());
        #else
        supports->Set(String::NewSymbol("cairo_svg"), False());
        #endif
#else
        supports->Set(String::NewSymbol("cairo"), False());
#endif

#if defined(HAVE_PNG)
        supports->Set(String::NewSymbol("png"), True());
#else
        supports->Set(String::NewSymbol("png"), False());
#endif

#if defined(HAVE_JPEG)
        supports->Set(String::NewSymbol("jpeg"), True());
#else
        supports->Set(String::NewSymbol("jpeg"), False());
#endif

#if defined(HAVE_TIFF)
        supports->Set(String::NewSymbol("tiff"), True());
#else
        supports->Set(String::NewSymbol("tiff"), False());
#endif

#if defined(HAVE_WEBP)
        supports->Set(String::NewSymbol("webp"), True());
#else
        supports->Set(String::NewSymbol("webp"), False());
#endif

#if defined(MAPNIK_USE_PROJ4)
        supports->Set(String::NewSymbol("proj4"), True());
#else
        supports->Set(String::NewSymbol("proj4"), False());
#endif

#if defined(MAPNIK_THREADSAFE)
        supports->Set(String::NewSymbol("threadsafe"), True());
#else
        supports->Set(String::NewSymbol("threadsafe"), False());
#endif

        target->Set(String::NewSymbol("supports"), supports);

#if MAPNIK_VERSION >= 200100
        Local<Object> composite_ops = Object::New();
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "clear", mapnik::clear)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src", mapnik::src)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst", mapnik::dst)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_over", mapnik::src_over)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_over", mapnik::dst_over)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_in", mapnik::src_in)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_in", mapnik::dst_in)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_out", mapnik::src_out)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_out", mapnik::dst_out)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_atop", mapnik::src_atop)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_atop", mapnik::dst_atop)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "xor", mapnik::_xor)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "plus", mapnik::plus)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "minus", mapnik::minus)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "multiply", mapnik::multiply)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "screen", mapnik::screen)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "overlay", mapnik::overlay)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "darken", mapnik::darken)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "lighten", mapnik::lighten)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color_dodge", mapnik::color_dodge)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color_burn", mapnik::color_burn)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "hard_light", mapnik::hard_light)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "soft_light", mapnik::soft_light)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "difference", mapnik::difference)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "exclusion", mapnik::exclusion)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "contrast", mapnik::contrast)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "invert", mapnik::invert)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "grain_merge", mapnik::grain_merge)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "grain_extract", mapnik::grain_extract)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "hue", mapnik::hue)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "saturation", mapnik::saturation)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color", mapnik::_color)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "value", mapnik::_value)

        target->Set(String::NewSymbol("compositeOp"), composite_ops);
#endif
    }
コード例 #19
0
ファイル: odbc_result.cpp プロジェクト: hcsoft/nodewebhis
Handle<Value> ODBCResult::FetchAllSync(const Arguments& args) {
  DEBUG_PRINTF("ODBCResult::FetchAllSync\n");

  HandleScope scope;
  
  ODBCResult* self = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
  
  Local<Object> objError = Object::New();
  
  SQLRETURN ret;
  int count = 0;
  int errorCount = 0;
  int fetchMode = self->m_fetchMode;

  if (args.Length() == 1 && args[0]->IsObject()) {
    Local<Object> obj = args[0]->ToObject();
    
    if (obj->Has(OPTION_FETCH_MODE) && obj->Get(OPTION_FETCH_MODE)->IsInt32()) {
      fetchMode = obj->Get(OPTION_FETCH_MODE)->ToInt32()->Value();
    }
  }
  
  if (self->colCount == 0) {
    self->columns = ODBC::GetColumns(self->m_hSTMT, &self->colCount);
  }
  
  Local<Array> rows = Array::New();
  
  //Only loop through the recordset if there are columns
  if (self->colCount > 0) {
    //loop through all records
    while (true) {
      ret = SQLFetch(self->m_hSTMT);
      
      //check to see if there was an error
      if (ret == SQL_ERROR)  {
        errorCount++;
        
        objError = ODBC::GetSQLError(
          SQL_HANDLE_STMT, 
          self->m_hSTMT,
          (char *) "[node-odbc] Error in ODBCResult::UV_AfterFetchAll; probably"
            " your query did not have a result set."
        );
        
        break;
      }
      
      //check to see if we are at the end of the recordset
      if (ret == SQL_NO_DATA) {
        ODBC::FreeColumns(self->columns, &self->colCount);
        
        break;
      }

      if (fetchMode == FETCH_ARRAY) {
        rows->Set(
          Integer::New(count), 
          ODBC::GetRecordArray(
            self->m_hSTMT,
            self->columns,
            &self->colCount,
            self->buffer,
            self->bufferLength)
        );
      }
      else {
        rows->Set(
          Integer::New(count), 
          ODBC::GetRecordTuple(
            self->m_hSTMT,
            self->columns,
            &self->colCount,
            self->buffer,
            self->bufferLength)
        );
      }
      count++;
    }
  }
  else {
    ODBC::FreeColumns(self->columns, &self->colCount);
  }
  
  //throw the error object if there were errors
  if (errorCount > 0) {
    ThrowException(objError);
  }
  
  return scope.Close(rows);
}
コード例 #20
0
static void Initialize(Local<Object> exports) {
  Local<FunctionTemplate> initializeTemplate(NanNew<FunctionTemplate>(node_gemfire::Initialize));
  exports->Set(NanNew("initialize"), initializeTemplate->GetFunction());
}
コード例 #21
0
ファイル: WeakRef.cpp プロジェクト: Emat12/android-runtime
void WeakRef::Init(v8::Isolate *isolate, Local<ObjectTemplate>& globalObjectTemplate, ObjectManager *objectManager)
{
	m_objectManager = objectManager;
	auto extData = External::New(isolate, this);
	globalObjectTemplate->Set(ConvertToV8String("WeakRef"), FunctionTemplate::New(isolate, ConstructorCallback, extData));
}
コード例 #22
0
ファイル: connection.cpp プロジェクト: NCJ1979/NodeJS
Local<Object> Connection::CreateV8ObjectFromRow(std::vector<column_t*> columns, row_t* currentRow) {
  Local<Object> obj = Object::New();
  uint32_t colIndex = 0;
  for (std::vector<column_t*>::iterator iterator = columns.begin(), end = columns.end(); iterator != end; ++iterator, colIndex++) {
    column_t* col = *iterator;
    // printf("Column: %s\n", col->name.c_str());
    void* val = currentRow->values[colIndex];
    if(val == NULL) {
      obj->Set(String::New(col->name.c_str()), Null());
    } else {
      switch(col->type) {
        case VALUE_TYPE_STRING:
          {
            std::string* v = (std::string*)val;
            obj->Set(String::New(col->name.c_str()), String::New(v->c_str()));
            delete v;
          }
          break;
        case VALUE_TYPE_NUMBER:
          {
            oracle::occi::Number* v = (oracle::occi::Number*)val;
            obj->Set(String::New(col->name.c_str()), Number::New((double)(*v)));
            delete v;
          }
          break;
        case VALUE_TYPE_DATE:
          {
            oracle::occi::Date* v = (oracle::occi::Date*)val;
            obj->Set(String::New(col->name.c_str()), OracleDateToV8Date(v));
          }
          break;
        case VALUE_TYPE_TIMESTAMP:
          {
            oracle::occi::Timestamp* v = (oracle::occi::Timestamp*)val;
            obj->Set(String::New(col->name.c_str()), OracleTimestampToV8Date(v));
          }
          break;
        case VALUE_TYPE_CLOB:
          {
            oracle::occi::Clob* v = (oracle::occi::Clob*)val;
            v->open(oracle::occi::OCCI_LOB_READONLY);

            switch(col->charForm) {
            case SQLCS_IMPLICIT:
            	v->setCharSetForm(oracle::occi::OCCI_SQLCS_IMPLICIT);
                break;
            case SQLCS_NCHAR:
            	v->setCharSetForm(oracle::occi::OCCI_SQLCS_NCHAR);
                break;
            case SQLCS_EXPLICIT:
            	v->setCharSetForm(oracle::occi::OCCI_SQLCS_EXPLICIT);
                break;
            case SQLCS_FLEXIBLE:
            	v->setCharSetForm(oracle::occi::OCCI_SQLCS_FLEXIBLE);
                break;
            }

            int clobLength = v->length();
            oracle::occi::Stream *instream = v->getStream(1,0);
            char *buffer = new char[clobLength];
            memset(buffer, 0, clobLength);
            instream->readBuffer(buffer, clobLength);
            v->closeStream(instream);
            v->close();
            obj->Set(String::New(col->name.c_str()), String::New(buffer, clobLength));
            delete buffer;
          }
          break;
        case VALUE_TYPE_BLOB:
          {
            oracle::occi::Blob* v = (oracle::occi::Blob*)val;
            v->open(oracle::occi::OCCI_LOB_READONLY);
            int blobLength = v->length();
            oracle::occi::Stream *instream = v->getStream(1,0);
            char *buffer = new char[blobLength];
            memset(buffer, 0, blobLength);
            instream->readBuffer(buffer, blobLength);
            v->closeStream(instream);
            v->close();

            // convert to V8 buffer
            node::Buffer *nodeBuff = node::Buffer::New(buffer, blobLength, RandomBytesFree, NULL);
            v8::Local<v8::Object> globalObj = v8::Context::GetCurrent()->Global();
            v8::Local<v8::Function> bufferConstructor = v8::Local<v8::Function>::Cast(globalObj->Get(v8::String::New("Buffer")));
            v8::Handle<v8::Value> constructorArgs[3] = { nodeBuff->handle_, v8::Integer::New(blobLength), v8::Integer::New(0) };
            v8::Local<v8::Object> v8Buffer = bufferConstructor->NewInstance(3, constructorArgs);
            obj->Set(String::New(col->name.c_str()), v8Buffer);
            delete buffer;            
            break;
          }
          break;
        default:
          std::ostringstream message;
          message << "CreateV8ObjectFromRow: Unhandled type: " << col->type;
          throw NodeOracleException(message.str());
          break;
      }
    }
  }
  return obj;
}
コード例 #23
0
ファイル: v8_wrapper.cpp プロジェクト: IlyaM/mongo
    Handle<v8::Value> mongoToV8Element( const BSONElement &f ) {
        Local< v8::ObjectTemplate > internalFieldObjects = v8::ObjectTemplate::New();
        internalFieldObjects->SetInternalFieldCount( 1 );

        switch ( f.type() ){

        case mongo::Code:
            return newFunction( f.valuestr() );
                
        case CodeWScope:
            if ( f.codeWScopeObject().isEmpty() )
                log() << "warning: CodeWScope doesn't transfer to db.eval" << endl;
            return newFunction( f.codeWScopeCode() );
                
        case mongo::String: 
            return v8::String::New( f.valuestr() );
            
        case mongo::jstOID:
            return newId( f.__oid() );
            
        case mongo::NumberDouble:
        case mongo::NumberInt:
            return v8::Number::New( f.number() );
            
        case mongo::Array:
        case mongo::Object:
            return mongoToV8( f.embeddedObject() , f.type() == mongo::Array );
            
        case mongo::Date:
            return v8::Date::New( f.date() );
            
        case mongo::Bool:
            return v8::Boolean::New( f.boolean() );

        case mongo::EOO:            
        case mongo::jstNULL:
        case mongo::Undefined: // duplicate sm behavior
            return v8::Null();
            
        case mongo::RegEx: {
            v8::Function * regex = getNamedCons( "RegExp" );
            
            v8::Handle<v8::Value> argv[2];
            argv[0] = v8::String::New( f.regex() );
            argv[1] = v8::String::New( f.regexFlags() );
            
            return regex->NewInstance( 2 , argv );
            break;
        }
            
        case mongo::BinData: {
            int len;
            const char *data = f.binData( len );
            
            v8::Function* binData = getNamedCons( "BinData" );
            v8::Handle<v8::Value> argv[3];
            argv[0] = v8::Number::New( len );
            argv[1] = v8::Number::New( f.binDataType() );
            argv[2] = v8::String::New( data, len );
            return binData->NewInstance( 3, argv );
        };
            
        case mongo::Timestamp: {
            Local<v8::Object> sub = internalFieldObjects->NewInstance();
            
            sub->Set( v8::String::New( "time" ) , v8::Date::New( f.timestampTime() ) );
            sub->Set( v8::String::New( "i" ) , v8::Number::New( f.timestampInc() ) );
            sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );

            return sub;
        }
                
        case mongo::NumberLong: {
            Local<v8::Object> sub = internalFieldObjects->NewInstance();
            unsigned long long val = f.numberLong();
            v8::Function* numberLong = getNamedCons( "NumberLong" );
            v8::Handle<v8::Value> argv[2];
            argv[0] = v8::Integer::New( val >> 32 );
            argv[1] = v8::Integer::New( (unsigned long)(val & 0x00000000ffffffff) );
            return numberLong->NewInstance( 2, argv );
        }
            
        case mongo::MinKey: {
            Local<v8::Object> sub = internalFieldObjects->NewInstance();
            sub->Set( v8::String::New( "$MinKey" ), v8::Boolean::New( true ) );
            sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
            return sub;
        }
            
        case mongo::MaxKey: {
            Local<v8::Object> sub = internalFieldObjects->NewInstance();
            sub->Set( v8::String::New( "$MaxKey" ), v8::Boolean::New( true ) );
            sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
            return sub;
        }
                
        case mongo::DBRef: {
            v8::Function* dbPointer = getNamedCons( "DBPointer" );
            v8::Handle<v8::Value> argv[2];
            argv[0] = v8::String::New( f.dbrefNS() );
            argv[1] = newId( f.dbrefOID() );
            return dbPointer->NewInstance(2, argv);
        }
                       
        default:
            cout << "can't handle type: ";
			cout  << f.type() << " ";
			cout  << f.toString();
			cout  << endl;
            break;
        }    
        
        return v8::Undefined();
    }
コード例 #24
0
ファイル: connection.cpp プロジェクト: NCJ1979/NodeJS
void Connection::EIO_AfterExecute(uv_work_t* req, int status) {
  ExecuteBaton* baton = static_cast<ExecuteBaton*>(req->data);

  baton->connection->Unref();
  try {
    Handle<Value> argv[2];
    if(baton->error) {
      argv[0] = Exception::Error(String::New(baton->error->c_str()));
      argv[1] = Undefined();
    } else {
      argv[0] = Undefined();
      if(baton->rows) {
        argv[1] = CreateV8ArrayFromRows(baton->columns, baton->rows);
      } else {
        Local<Object> obj = Object::New();
        obj->Set(String::New("updateCount"), Integer::New(baton->updateCount));
        
        /* Note: attempt to keep backward compatability here: existing users of this library will have code that expects a single out param
                 called 'returnParam'. For multiple out params, the first output will continue to be called 'returnParam' and subsequent outputs
                 will be called 'returnParamX'.
        */
        uint32_t index = 0;
        for (std::vector<output_t*>::iterator iterator = baton->outputs->begin(), end = baton->outputs->end(); iterator != end; ++iterator, index++) {
          output_t* output = *iterator;
          std::stringstream ss;          
          ss << "returnParam";
          if(index > 0) ss << index;
          std::string returnParam(ss.str());
          switch(output->type) {
          case OutParam::OCCIINT:
            obj->Set(String::New(returnParam.c_str()), Integer::New(output->intVal));
            break;
          case OutParam::OCCISTRING:
            obj->Set(String::New(returnParam.c_str()), String::New(output->strVal.c_str()));
            break;
          case OutParam::OCCIDOUBLE:
            obj->Set(String::New(returnParam.c_str()), Number::New(output->doubleVal));
            break;
          case OutParam::OCCIFLOAT:
            obj->Set(String::New(returnParam.c_str()), Number::New(output->floatVal));
            break;
          case OutParam::OCCICURSOR:
            obj->Set(String::New(returnParam.c_str()), CreateV8ArrayFromRows(output->columns, output->rows));
            break;
          case OutParam::OCCICLOB:
            {
              output->clobVal.open(oracle::occi::OCCI_LOB_READONLY);
              int lobLength = output->clobVal.length();
              oracle::occi::Stream* instream = output->clobVal.getStream(1,0);
              char *buffer = new char[lobLength];
              memset(buffer, 0, lobLength);
              instream->readBuffer(buffer, lobLength);
              output->clobVal.closeStream(instream);
              output->clobVal.close();
              obj->Set(String::New(returnParam.c_str()), String::New(buffer, lobLength));
              delete buffer;
              break;
            }
          case OutParam::OCCIBLOB:
            { 
              output->blobVal.open(oracle::occi::OCCI_LOB_READONLY);
              int lobLength = output->blobVal.length();
              oracle::occi::Stream* instream = output->blobVal.getStream(1,0);              
              char *buffer = new char[lobLength];
              memset(buffer, 0, lobLength);
              instream->readBuffer(buffer, lobLength);
              output->blobVal.closeStream(instream);
              output->blobVal.close();

              // convert to V8 buffer
              node::Buffer *nodeBuff = node::Buffer::New(buffer, lobLength, RandomBytesFree, NULL);
              v8::Local<v8::Object> globalObj = v8::Context::GetCurrent()->Global();
              v8::Local<v8::Function> bufferConstructor = v8::Local<v8::Function>::Cast(globalObj->Get(v8::String::New("Buffer")));
              v8::Handle<v8::Value> constructorArgs[3] = { nodeBuff->handle_, v8::Integer::New(lobLength), v8::Integer::New(0) };
              v8::Local<v8::Object> v8Buffer = bufferConstructor->NewInstance(3, constructorArgs);
              obj->Set(String::New(returnParam.c_str()), v8Buffer);
              delete buffer;            
              break;
            }
          case OutParam::OCCIDATE:
            obj->Set(String::New(returnParam.c_str()), OracleDateToV8Date(&output->dateVal));
            break;
          case OutParam::OCCITIMESTAMP:
            obj->Set(String::New(returnParam.c_str()), OracleTimestampToV8Date(&output->timestampVal));
            break;
          case OutParam::OCCINUMBER:
            obj->Set(String::New(returnParam.c_str()), Number::New(output->numberVal));
            break;
          default:
            throw NodeOracleException("Unknown OutParam type: " + output->type);
          }          
        }
        argv[1] = obj;
      }
    }
    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
  } catch(NodeOracleException &ex) {
    Handle<Value> argv[2];
    argv[0] = Exception::Error(String::New(ex.getMessage().c_str()));
    argv[1] = Undefined();
    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
  } catch(const std::exception &ex) {
	    Handle<Value> argv[2];
	    argv[0] = Exception::Error(String::New(ex.what()));
	    argv[1] = Undefined();
	    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
  }

  delete baton;
}
コード例 #25
0
ファイル: ds_emitter.hpp プロジェクト: ezhangle/node-mapnik
static void describe_datasource(Local<Object> description, mapnik::datasource_ptr ds)
{
    NanScope();
    try
    {
        // type
        if (ds->type() == mapnik::datasource::Raster)
        {
            description->Set(NanNew("type"), NanNew<String>("raster"));
        }
        else
        {
            description->Set(NanNew("type"), NanNew<String>("vector"));
        }

        mapnik::layer_descriptor ld = ds->get_descriptor();

        // encoding
        description->Set(NanNew("encoding"), NanNew<String>(ld.get_encoding().c_str()));

        // field names and types
        Local<Object> fields = NanNew<Object>();
        std::vector<mapnik::attribute_descriptor> const& desc = ld.get_descriptors();
        std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin();
        std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end();
        while (itr != end)
        {
            unsigned field_type = itr->get_type();
            std::string type("");
            if (field_type == mapnik::Integer) type = "Number";
            else if (field_type == mapnik::Float) type = "Number";
            else if (field_type == mapnik::Double) type = "Number";
            else if (field_type == mapnik::String) type = "String";
            else if (field_type == mapnik::Boolean) type = "Boolean";
            else if (field_type == mapnik::Geometry) type = "Geometry";
            else if (field_type == mapnik::Object) type = "Object";
            else type = "Unknown";
            fields->Set(NanNew(itr->get_name().c_str()), NanNew(type.c_str()));
            fields->Set(NanNew(itr->get_name().c_str()), NanNew(type.c_str()));
            ++itr;
        }
        description->Set(NanNew("fields"), fields);

        Local<String> js_type = NanNew<String>("unknown");
        if (ds->type() == mapnik::datasource::Raster)
        {
            js_type = NanNew<String>("raster");
        }
        else
        {
            boost::optional<mapnik::datasource::geometry_t> geom_type = ds->get_geometry_type();
            if (geom_type)
            {
                mapnik::datasource::geometry_t g_type = *geom_type;
                switch (g_type)
                {
                case mapnik::datasource::Point:
                {
                    js_type = NanNew<String>("point");
                    break;
                }
                case mapnik::datasource::LineString:
                {
                    js_type = NanNew<String>("linestring");
                    break;
                }
                case mapnik::datasource::Polygon:
                {
                    js_type = NanNew<String>("polygon");
                    break;
                }
                case mapnik::datasource::Collection:
                {
                    js_type = NanNew<String>("collection");
                    break;
                }
                default:
                {
                    break;
                }
                }
            }
        }
        description->Set(NanNew("geometry_type"), js_type);
    }
    catch (std::exception const& ex)
    {
        NanThrowError(ex.what());
    }
    catch (...)
    {
        NanThrowError("unknown exception happened when calling describe_datasource, please file bug");
    }
}
コード例 #26
0
ファイル: main.cpp プロジェクト: carriercomm/sphereclone
int main(int argc, char* argv[]) {
	SDL_Init(SDL_INIT_EVERYTHING);

	V8::Initialize();
	isolate = Isolate::GetCurrent();
	HandleScope handle_scope(isolate);
	
	Persistent<Context> context = Context::New();
    Context::Scope context_scope(context);

	Local<Object> global = context->Global();
	
	Local<Object> sphere = Object::New();
	
	global->Set(String::New("sphere"), sphere);
	
	API::fs::Init(sphere);
	API::engine::Init(sphere);
	API::graphics::Init(sphere);
	API::events::Init(sphere);
	
	Local<Object> engine = sphere->Get(String::New("engine"))->ToObject();
	
	engine->Set(String::New("argc"), Integer::New(argc));
	Local<Array> js_argv = Array::New(argc);
	
	for (int i = 0; i < argc; i++) {
		js_argv->Set(Number::New(i), String::New(argv[i]));
	}

	engine->Set(String::New("argv"), js_argv);
	
	const char* gameScript = Files::readTextFile("system/sphere.js");
	
	if (gameScript == NULL) {
		debug("Error loading bootstrap script.\n");
		exit(1);
	}
	
	TryCatch trycatch;
	Local<Script> compiled = Script::Compile(String::New(gameScript), String::New("system/sphere.js"));
	
	if (compiled.IsEmpty()) {
		Handle<Value> exception = trycatch.Exception();
		String::Utf8Value exception_str(exception);
		printf("Exception: %s\n", *exception_str);
		exit(1);
	}
	
	Handle<Value> value = compiled->Run();
	
	if (value.IsEmpty()) {
		Handle<Object> exception = trycatch.Exception()->ToObject();
		Handle<String> str;
		if (exception->Has(String::New("stack"))) {
			str = exception->Get(String::New("stack"))->ToString();
		}
		else {
			str = exception->ToString();
		}
		String::Utf8Value exception_str(str);
		printf("Exception: %s\n", *exception_str);
		exit(1);
	}
	
	return 0;
}
コード例 #27
0
void Proxy::proxyConstructor(const v8::FunctionCallbackInfo<v8::Value>& args)
{
    LOGD(TAG, "proxy constructor callback!");
    Isolate* isolate = args.GetIsolate();
    EscapableHandleScope scope(isolate);

    JNIEnv *env = JNIScope::getEnv();
    Local<Object> jsProxy = args.This();

    // First things first, we need to wrap the object in case future calls need to unwrap proxy!
    Proxy* proxy = new Proxy(NULL);
    proxy->wrap(isolate, jsProxy);

    // every instance gets a special "_properties" object for us to use internally for get/setProperty
    jsProxy->DefineOwnProperty(isolate->GetCurrentContext(), propertiesSymbol.Get(isolate), Object::New(isolate), static_cast<PropertyAttribute>(DontEnum));

    // Now we hook up a java Object from the JVM...
    jobject javaProxy = ProxyFactory::unwrapJavaProxy(args); // do we already have one that got passed in?
    bool deleteRef = false;
    if (!javaProxy) {
        // No passed in java object, so let's create an instance
        // Look up java class from prototype...
        Local<Object> prototype = jsProxy->GetPrototype()->ToObject(isolate);
        Local<Function> constructor = prototype->Get(constructorSymbol.Get(isolate)).As<Function>();
        Local<External> wrap = constructor->Get(javaClassSymbol.Get(isolate)).As<External>();
        jclass javaClass = static_cast<jclass>(wrap->Value());

        // Now we create an instance of the class and hook it up
        JNIUtil::logClassName("Creating java proxy for class %s", javaClass);
        javaProxy = ProxyFactory::createJavaProxy(javaClass, jsProxy, args);
        deleteRef = true;
    }
    proxy->attach(javaProxy);

    int length = args.Length();

    if (length > 0 && args[0]->IsObject()) {
        bool extend = true;
        Local<Object> createProperties = args[0].As<Object>();
        Local<String> constructorName = createProperties->GetConstructorName();
        if (strcmp(*titanium::Utf8Value(constructorName), "Arguments") == 0) {
            extend = false;
            int32_t argsLength = createProperties->Get(STRING_NEW(isolate, "length"))->Int32Value();
            if (argsLength > 1) {
                Local<Value> properties = createProperties->Get(1);
                if (properties->IsObject()) {
                    extend = true;
                    createProperties = properties.As<Object>();
                }
            }
        }

        if (extend) {
            Local<Array> names = createProperties->GetOwnPropertyNames();
            int length = names->Length();
            Local<Object> properties = jsProxy->Get(propertiesSymbol.Get(isolate))->ToObject(isolate);

            for (int i = 0; i < length; ++i) {
                Local<Value> name = names->Get(i);
                Local<Value> value = createProperties->Get(name);
                bool isProperty = true;
                if (name->IsString()) {
                    Local<String> nameString = name.As<String>();
                    if (!jsProxy->HasRealNamedCallbackProperty(nameString)
                            && !jsProxy->HasRealNamedProperty(nameString)) {
                        jsProxy->Set(name, value);
                        isProperty = false;
                    }
                }
                if (isProperty) {
                    properties->Set(name, value);
                }
            }
        }
    }


    if (!args.Data().IsEmpty() && args.Data()->IsFunction()) {
        Local<Function> proxyFn = args.Data().As<Function>();
        Local<Value> *fnArgs = new Local<Value>[length];
        for (int i = 0; i < length; ++i) {
            fnArgs[i] = args[i];
        }
        proxyFn->Call(isolate->GetCurrentContext(), jsProxy, length, fnArgs);
    }

    if (deleteRef) {
        JNIEnv *env = JNIScope::getEnv();
        if (env) {
            env->DeleteLocalRef(javaProxy);
        }
    }

    args.GetReturnValue().Set(scope.Escape(jsProxy));
}
コード例 #28
0
    static void InitMapnik (Handle<Object> target)
    {
        // module level functions
        NODE_SET_METHOD(target, "register_datasources", node_mapnik::register_datasources);
        NODE_SET_METHOD(target, "datasources", node_mapnik::available_input_plugins);
        NODE_SET_METHOD(target, "register_fonts", node_mapnik::register_fonts);
        NODE_SET_METHOD(target, "fonts", node_mapnik::available_font_faces);
        NODE_SET_METHOD(target, "fontFiles", node_mapnik::available_font_files);
        NODE_SET_METHOD(target, "clearCache", clearCache);
        NODE_SET_METHOD(target, "gc", gc);

        // Classes
        Map::Initialize(target);
        Color::Initialize(target);
        Geometry::Initialize(target);
        Feature::Initialize(target);
        Image::Initialize(target);
        ImageView::Initialize(target);
        Palette::Initialize(target);
        Projection::Initialize(target);
        ProjTransform::Initialize(target);
        Layer::Initialize(target);
        Grid::Initialize(target);
        GridView::Initialize(target);
        Datasource::Initialize(target);
        Featureset::Initialize(target);
        // Not production safe, so disabling indefinitely
        //JSDatasource::Initialize(target);
        MemoryDatasource::Initialize(target);
        Expression::Initialize(target);

        // versions of deps
        Local<Object> versions = Object::New();
        versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
        versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
        versions->Set(String::NewSymbol("boost"), String::New(format_version(BOOST_VERSION).c_str()));
        versions->Set(String::NewSymbol("boost_number"), Integer::New(BOOST_VERSION));
        versions->Set(String::NewSymbol("mapnik"), String::New(format_version(MAPNIK_VERSION).c_str()));
        versions->Set(String::NewSymbol("mapnik_number"), Integer::New(MAPNIK_VERSION));
#if defined(HAVE_CAIRO)
        versions->Set(String::NewSymbol("cairo"), String::New(CAIRO_VERSION_STRING));
#endif
        target->Set(String::NewSymbol("versions"), versions);

        // built in support
        Local<Object> supports = Object::New();
        supports->Set(String::NewSymbol("grid"), True());

#if defined(HAVE_CAIRO)
        supports->Set(String::NewSymbol("cairo"), True());
#else
        supports->Set(String::NewSymbol("cairo"), False());
#endif

#if defined(HAVE_JPEG)
        supports->Set(String::NewSymbol("jpeg"), True());
#else
        supports->Set(String::NewSymbol("jpeg"), False());
#endif
        target->Set(String::NewSymbol("supports"), supports);

#if MAPNIK_VERSION >= 200100
        Local<Object> composite_ops = Object::New();
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "clear", mapnik::clear)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src", mapnik::src)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst", mapnik::dst)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_over", mapnik::src_over)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_over", mapnik::dst_over)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_in", mapnik::src_in)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_in", mapnik::dst_in)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_out", mapnik::src_out)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_out", mapnik::dst_out)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "src_atop", mapnik::src_atop)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "dst_atop", mapnik::dst_atop)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "xor", mapnik::_xor)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "plus", mapnik::plus)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "minus", mapnik::minus)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "multiply", mapnik::multiply)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "screen", mapnik::screen)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "overlay", mapnik::overlay)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "darken", mapnik::darken)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "lighten", mapnik::lighten)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color_dodge", mapnik::color_dodge)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "color_burn", mapnik::color_burn)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "hard_light", mapnik::hard_light)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "soft_light", mapnik::soft_light)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "difference", mapnik::difference)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "exclusion", mapnik::exclusion)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "contrast", mapnik::contrast)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "invert", mapnik::invert)
        NODE_MAPNIK_DEFINE_CONSTANT(composite_ops, "invert_rgb", mapnik::invert_rgb)

        target->Set(String::NewSymbol("compositeOp"), composite_ops);
#endif
    }
コード例 #29
0
Local<Function> MetadataNode::SetMembersFromRuntimeMetadata(Isolate *isolate, Local<FunctionTemplate>& ctorFuncTemplate, Local<ObjectTemplate>& prototypeTemplate, vector<MethodCallbackData*>& instanceMethodsCallbackData, const vector<MethodCallbackData*>& baseInstanceMethodsCallbackData, MetadataTreeNode *treeNode)
{
	SET_PROFILER_FRAME();

	assert(treeNode->metadata != nullptr);

	string line;
	const string& metadata = *treeNode->metadata;
	stringstream s(metadata);

	string kind;
	string name;
	string signature;
	int paramCount;

	getline(s, line); // type line
	getline(s, line); // base class line

	string lastMethodName;
	MethodCallbackData *callbackData = nullptr;

	while (getline(s, line))
	{
		stringstream tmp(line);
		tmp >> kind >> name >> signature >> paramCount;

		char chKind = kind[0];

		// method or field
		assert((chKind == 'M') || (chKind == 'F'));

		MetadataEntry entry;
		entry.name = name;
		entry.sig = signature;
		MetadataReader::FillReturnType(entry);
		entry.paramCount = paramCount;
		entry.isStatic = false;

		if (chKind == 'M')
		{
			if (entry.name != lastMethodName)
			{
				callbackData = new MethodCallbackData(this);

				instanceMethodsCallbackData.push_back(callbackData);
				auto itBegin = baseInstanceMethodsCallbackData.begin();
				auto itEnd = baseInstanceMethodsCallbackData.end();
				auto itFound = find_if(itBegin, itEnd, [&entry] (MethodCallbackData *x)
				{	return x->candidates.front().name == entry.name;});
				if (itFound != itEnd)
				{
					callbackData->parent = *itFound;
				}

				auto funcData = External::New(isolate, callbackData);
				auto funcTemplate = FunctionTemplate::New(isolate, MethodCallback, funcData);
				auto funcName = ConvertToV8String(entry.name);
				prototypeTemplate->Set(funcName, funcTemplate->GetFunction());
				lastMethodName = entry.name;
			}
			callbackData->candidates.push_back(entry);
		}
		else if (chKind == 'F')
		{
			auto fieldName = ConvertToV8String(entry.name);
			auto fieldData = External::New(isolate, new FieldCallbackData(entry));
			auto access = entry.isFinal ? AccessControl::ALL_CAN_READ : AccessControl::DEFAULT;
			prototypeTemplate->SetAccessor(fieldName, FieldAccessorGetterCallback, FieldAccessorSetterCallback, fieldData, access, PropertyAttribute::DontDelete);
		}
	}

	auto ctorFunction = ctorFuncTemplate->GetFunction();

	return ctorFunction;
}
コード例 #30
0
ファイル: addon.cpp プロジェクト: nevermnd/anitomy-js
void Init(Local<Object> exports) {
  exports->Set(Nan::New("parseSync").ToLocalChecked(), Nan::New<FunctionTemplate>(ParseSync)->GetFunction());
  exports->Set(Nan::New("parseAsync").ToLocalChecked(), Nan::New<FunctionTemplate>(ParseAsync)->GetFunction());
}