Пример #1
0
getdns_dict* GNUtil::convertToDict(Local<Object> obj) {
    if (obj->IsRegExp() || obj->IsDate() ||
        obj->IsFunction() || obj->IsUndefined() ||
        obj->IsNull() || obj->IsArray()) {
        return NULL;
    }
    Local<Array> names = obj->GetOwnPropertyNames();
    getdns_dict* result = getdns_dict_create();
    for(unsigned int i = 0; i < names->Length(); i++) {
        Local<Value> nameVal = names->Get(i);
        Nan::Utf8String name(nameVal);
        Local<Value> val = obj->Get(nameVal);
        GetdnsType type = getGetdnsType(val);
        switch (type) {
            case IntType:
                getdns_dict_set_int(result, *name, val->ToUint32()->Value());
                break;
            case BoolType:
                if (val->IsTrue()) {
                    getdns_dict_set_int(result, *name, GETDNS_EXTENSION_TRUE);
                } else {
                    getdns_dict_set_int(result, *name, GETDNS_EXTENSION_FALSE);
                }
                break;
            case StringType:
                {
                    struct getdns_bindata strdata;
                    String::Utf8Value utf8Str(val->ToString());
                    int len = utf8Str.length();
                    strdata.data = (uint8_t*) *utf8Str;
                    strdata.size = len;
                    getdns_dict_set_bindata(result, *name, &strdata);
                }
                break;
            case BinDataType:
                {
                    struct getdns_bindata bdata;
                    bdata.data = (uint8_t*) node::Buffer::Data(val);
                    bdata.size = node::Buffer::Length(val);
                    getdns_dict_set_bindata(result, *name, &bdata);
                }
                break;
            case ListType:
                {
                    Local<Array> subArray = Local<Array>::Cast(val);
                    struct getdns_list* sublist = GNUtil::convertToList(subArray);
                    getdns_dict_set_list(result, *name, sublist);
                    getdns_list_destroy(sublist);
                }
                break;
            case DictType:
                {
                    Local<Object> subObj = val->ToObject();
                    struct getdns_dict* subdict = GNUtil::convertToDict(subObj);
                    if (subdict) {
                        getdns_dict_set_dict(result, *name, subdict);
                        getdns_dict_destroy(subdict);
                    }
                }
                break;
            default:
                break;
        }
    }
    return result;
}
Пример #2
0
/*
 * Wrap the quote() method to marshal and unmarshal arguments
 *
 * Entirely inefficient.
 *
 * Will throw an exception if the Quote fails.
 * Currently doing NO INPUT VALIDATION
 *
 * Arguments: srkpwd, aikfile, pcrs[], nonce
 *
 */
static Handle<Value> getQuote(const Arguments& args) {
	//unmarshal the arguments
	Local<String> srkpwd = args[0]->ToString();
	Local<String> aik = args[1]->ToString();
	Local<Object> pcrsObj = args[2]->ToObject();
	Local<Object> nonceObj = args[3]->ToObject();

	int fieldCount = 0;
	while (pcrsObj->Has(fieldCount))
		fieldCount++;
	long pcrs[fieldCount];
	int i = 0;
	for (i = 0; i < fieldCount; i++) {
		pcrs[i] = pcrsObj->Get(i)->Int32Value();
	}

	int j = 0;

	BYTE nonce[20];
	while (nonceObj->Has(j) && j < 20) {
		nonce[j] = nonceObj->Get(j)->Int32Value();
		j++;
	}

	char* srkpwdAscii = stringToChar(srkpwd);
	char* aikAscii = stringToChar(aik);

	TSS_VALIDATION valid;
	TPM_QUOTE_INFO quoteInfo;

	//perform the quote
	TSS_RESULT quoteRes = quote(srkpwdAscii, aikAscii, pcrs, fieldCount, nonce,
			&valid, &quoteInfo);
	if (quoteRes != 0) {
		return ThrowException(
				Exception::Error(String::New("Error producing TPM Quote")));
	}

	// turn all these stupid TSS structs into JSON structures!
	Local<Object> validData = Object::New();

	validData->Set(String::New("rgbData"),
			bytesToArray(valid.rgbData, valid.ulDataLength));
	validData->Set(String::New("rgbExternalData"),
			bytesToArray(valid.rgbExternalData, valid.ulExternalDataLength));
	validData->Set(String::New("rgbValidationData"),
			bytesToArray(valid.rgbValidationData, valid.ulValidationDataLength));
	validData->Set(String::New("versionInfo"),
			version2ToObject(valid.versionInfo));

	Local<Object> quoteData = Object::New();

	quoteData->Set(String::New("compositeHash"),
			bytesToArray(quoteInfo.compositeHash.digest, 20));
	quoteData->Set(String::New("externalData"),
			bytesToArray(quoteInfo.externalData.nonce, 20));
	quoteData->Set(String::New("fixed"), bytesToArray(quoteInfo.fixed, 4));
	quoteData->Set(String::New("versionInfo"),
			versionToObject(quoteInfo.version));

	Local<Object> both = Object::New();
	both->Set(String::New("validationData"), validData);
	both->Set(String::New("quoteInfo"), quoteData);

	free(aikAscii);
	free(srkpwdAscii);

	return both;
}
Пример #3
0
Handle<Object> HoneydNodeJs::WrapProfile(NodeProfile *pfile)
{
    HandleScope scope;  
    // Setup the template for the type if it hasn't been already
    if( m_profileTemplate.IsEmpty() )
    {
        Handle<FunctionTemplate> nodeTemplate = FunctionTemplate::New();
        nodeTemplate->InstanceTemplate()->SetInternalFieldCount(1);
        m_profileTemplate = Persistent<FunctionTemplate>::New(nodeTemplate);

        // Javascript methods
        Local<Template> proto = m_profileTemplate->PrototypeTemplate();
        proto->Set("GetName",           FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetName>));
        proto->Set("GetPortNames",		FunctionTemplate::New(InvokeMethod<std::vector<std::string>, NodeProfile, &Nova::NodeProfile::GetPortNames>));
        proto->Set("GetTcpAction",      FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetTcpAction>));
        proto->Set("GetUdpAction",      FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetUdpAction>));
        proto->Set("GetIcmpAction",     FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetIcmpAction>));
        proto->Set("GetPersonality",    FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetPersonality>));
        proto->Set("GetEthernet",       FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetEthernet>));
        proto->Set("GetUptimeMin",      FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetUptimeMin>));
        proto->Set("GetUptimeMax",      FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetUptimeMax>));
        proto->Set("GetDropRate",       FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetDropRate>));
        proto->Set("GetGenerated",       FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::GetGenerated>));
        proto->Set("GetDistribution",       FunctionTemplate::New(InvokeMethod<double, NodeProfile, &Nova::NodeProfile::GetDistribution>));
        proto->Set("GetParentProfile",  FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetParentProfile>));
        proto->Set("GetVendors",        FunctionTemplate::New(InvokeMethod<std::vector<std::string>, NodeProfile, &Nova::NodeProfile::GetVendors>));
        proto->Set("GetVendorDistributions",       FunctionTemplate::New(InvokeMethod<std::vector<double>, NodeProfile, &Nova::NodeProfile::GetVendorDistributions>));
        
        
        proto->Set("isTcpActionInherited",  FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isTcpActionInherited>));
        proto->Set("isUdpActionInherited",  FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isUdpActionInherited>));
        proto->Set("isIcmpActionInherited", FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isIcmpActionInherited>));
        proto->Set("isPersonalityInherited",FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isPersonalityInherited>));
        proto->Set("isEthernetInherited",   FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isEthernetInherited>));
        proto->Set("isUptimeInherited",     FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isUptimeInherited>));
        proto->Set("isDropRateInherited",   FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isDropRateInherited>));
    }

    // Get the constructor from the template
    Handle<Function> ctor = m_profileTemplate->GetFunction();
    // Instantiate the object with the constructor
    Handle<Object> result = ctor->NewInstance();
    // Wrap the native object in an handle and set it in the internal field to get at later.
    Handle<External> profilePtr = External::New(pfile);
    result->SetInternalField(0,profilePtr);

    return scope.Close(result);
}
Handle<Value> Datasource::New(const Arguments& args)
{
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Datasource* d =  static_cast<Datasource*>(ptr);
        d->Wrap(args.This());
        return args.This();
    }
    if (!args.Length() == 1){
        return ThrowException(Exception::TypeError(
          String::New("accepts only one argument, an object of key:value datasource options")));
    }

    if (!args[0]->IsObject())
        return ThrowException(Exception::TypeError(
          String::New("must provide an object, eg {type: 'shape', file : 'world.shp'}")));

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

    // TODO - maybe validate in js?

    bool bind=true;
    if (options->Has(String::New("bind")))
    {
        Local<Value> bind_opt = options->Get(String::New("bind"));
        if (!bind_opt->IsBoolean())
          return ThrowException(Exception::TypeError(
            String::New("'bind' must be a Boolean")));

        bind = bind_opt->BooleanValue();
    }

    mapnik::parameters params;
    Local<Array> names = options->GetPropertyNames();
    uint32_t i = 0;
    uint32_t a_length = names->Length();
    while (i < a_length) {
        Local<Value> name = names->Get(i)->ToString();
        Local<Value> value = options->Get(name);
        params[TOSTR(name)] = TOSTR(value);
        i++;
    }

    mapnik::datasource_ptr ds;
    try
    {
        ds = mapnik::datasource_cache::create(params, bind);
    }
    catch (const mapnik::config_error & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const mapnik::datasource_exception & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const std::runtime_error & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const std::exception & ex)
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (...)
    {
        return ThrowException(Exception::Error(
          String::New("unknown exception happened, please file bug")));
    }
    if (ds)
    {
        Datasource* d = new Datasource();
        d->Wrap(args.This());
        d->datasource_ = ds;
        return args.This();
    }

    return Undefined();
}
Пример #5
0
Handle<Value> newIndexBound(const Arguments &args) {
    HandleScope scope;

    const Local<Object> spec = args[0]->ToObject();
    Local<Value> v;
    Local<Object> o;

    NdbIndexScanOperation::IndexBound * bound =
        new NdbIndexScanOperation::IndexBound;
    Local<Object> jsBound = IndexBoundEnvelope.newWrapper();
    wrapPointerInObject(bound, IndexBoundEnvelope, jsBound);

    bound->low_key = 0;
    v = spec->Get(BOUND_LOW_KEY);
    if(v->IsNull()) {
        bound->low_key = 0;
    } else {
        o = v->ToObject();
        bound->low_key = node::Buffer::Data(o);
    }

    bound->low_key_count = 0;
    v = spec->Get(BOUND_LOW_KEY_COUNT);
    if(! v->IsNull()) {
        bound->low_key_count = v->Uint32Value();
    }

    bound->low_inclusive = false;
    v = spec->Get(BOUND_LOW_INCLUSIVE);
    if(! v->IsNull()) {
        bound->low_inclusive = v->BooleanValue();
    }

    bound->high_key = 0;
    v = spec->Get(BOUND_HIGH_KEY);
    if(v->IsNull()) {
        bound->high_key = 0;
    } else {
        o = v->ToObject();
        bound->high_key = node::Buffer::Data(o);
    }

    bound->high_key_count = 0;
    v = spec->Get(BOUND_HIGH_KEY_COUNT);
    if(! v->IsNull()) {
        bound->high_key_count = v->Uint32Value();
    }

    bound->high_inclusive = false;
    v = spec->Get(BOUND_HIGH_INCLUSIVE);
    if(! v->IsNull()) {
        bound->high_inclusive = v->BooleanValue();
    }

    bound->range_no = 0;
    v = spec->Get(BOUND_RANGE_NO);
    if(! v->IsNull()) {
        bound->range_no = v->Uint32Value();
    }

    debug_print_bound(bound);

    return scope.Close(jsBound);
}
Пример #6
0
Handle<Value> Grid::New(const Arguments& args)
{
    HandleScope scope;
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Grid* g =  static_cast<Grid*>(ptr);
        g->Wrap(args.This());
        return args.This();
    }

    if (args.Length() >= 2)
    {
        if (!args[0]->IsNumber() || !args[1]->IsNumber())
            return ThrowException(Exception::TypeError(
                                      String::New("Grid 'width' and 'height' must be a integers")));

        // defaults
        std::string key("__id__");
        unsigned int resolution = 1;

        if (args.Length() >= 3) {

            if (!args[2]->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("optional third arg must be an options object")));
            Local<Object> options = args[2]->ToObject();

            if (options->Has(String::New("key"))) {
                Local<Value> bind_opt = options->Get(String::New("key"));
                if (!bind_opt->IsString())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'key' must be an string")));

                key = TOSTR(bind_opt);
            }
            // TODO - remove, deprecated
            if (options->Has(String::New("resolution"))) {
                Local<Value> bind_opt = options->Get(String::New("resolution"));
                if (!bind_opt->IsNumber())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'resolution' must be an string")));

                resolution = bind_opt->IntegerValue();
            }
        }

        Grid* g = new Grid(args[0]->IntegerValue(),args[1]->IntegerValue(),key,resolution);
        g->Wrap(args.This());
        return args.This();
    }
    else
    {
        return ThrowException(Exception::Error(
                                  String::New("please provide Grid width and height")));
    }
    return Undefined();
}
Пример #7
0
int Conv::ToV8Sequence(JNIEnv *jniEnv, jarray jVal, int expectedType, Handle<Array> *val) {
  unsigned int componentType = getComponentType(expectedType);
  int length = jniEnv->GetArrayLength(jVal);
  Local<Array> lVal = Local<Array>(Array::New(length));
  int result = OK;
  if(isJavaObject(componentType)) {
    jobjectArray jOVal = (jobjectArray)jVal;
    for(int i = 0; i < length; i++) {
      Local<Value> elt;
      jobject jElt = jniEnv->GetObjectArrayElement(jOVal, i);
      result = ToV8Value(jniEnv, jElt, componentType, &elt);
      jniEnv->DeleteLocalRef(jElt);
      if(result != OK) break;
      lVal->Set(i, elt);
    }
    if(result == OK) {
      *val = lVal;
    }
    if(jniEnv->ExceptionCheck()) {
      jniEnv->ExceptionClear();
      result = ErrorVM;
    }
    return result;
  }
  /* FIXME: use optimised buffers */
  switch(componentType) {
    case TYPE_BYTE: {
      jbyteArray jBVal = (jbyteArray)jVal;
      jbyte *elts = jniEnv->GetByteArrayElements(jBVal, 0);
      for(int i = 0; i < length; i++) {
        lVal->Set(i, Number::New(elts[i]));
      }
      jniEnv->ReleaseByteArrayElements(jBVal, elts, 0);
    }
      break;
    case TYPE_INT: {
      jintArray jIVal = (jintArray)jVal;
      jint *elts = jniEnv->GetIntArrayElements(jIVal, 0);
      for(int i = 0; i < length; i++) {
        lVal->Set(i, Number::New(elts[i]));
      }
      jniEnv->ReleaseIntArrayElements(jIVal, elts, 0);
    }
      break;
    case TYPE_LONG: {
      jlongArray jJVal = (jlongArray)jVal;
      jlong *elts = jniEnv->GetLongArrayElements(jJVal, 0);
      for(int i = 0; i < length; i++) {
        lVal->Set(i, Number::New(elts[i]));
      }
      jniEnv->ReleaseLongArrayElements(jJVal, elts, 0);
    }
      break;
    case TYPE_DOUBLE: {
      jdoubleArray jDVal = (jdoubleArray)jVal;
      jdouble *elts = jniEnv->GetDoubleArrayElements(jDVal, 0);
      for(int i = 0; i < length; i++) {
        lVal->Set(i, Number::New(elts[i]));
      }
      jniEnv->ReleaseDoubleArrayElements(jDVal, elts, 0);
    }
      break;
    default:
      result = ErrorType;
  }
  if(result == OK) {
    *val = lVal;
  }
  if(jniEnv->ExceptionCheck()) {
    jniEnv->ExceptionClear();
    result = ErrorVM;
  }
  return result;
}
Пример #8
0
//	SELECT SYNC
void selectSync(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);
	
	char query[1000];
	unsigned int i,limit;
	int j,temp;
	SQLRETURN retcode;	
	SQLSMALLINT colCount = 0;
	SQLLEN indicator;
	SQLINTEGER *intData[30];
	SQLCHAR *charData[30];
	SQLDOUBLE *doubleData[30];

	
	
	// extract argument 1 (Query)
	v8::String::Utf8Value param1(args[0]->ToString());
	std::string queryRaw = std::string(*param1);
	for(i=0;i<queryRaw.length();i++) query[i] = queryRaw[i]; query[i] = '\0';
	
	//extracting SQL limit
	temp = (int)args[1]->NumberValue();
	if(temp < 0){
		limit = 4294967294;
	}
	else{
		limit = temp;
	}
	
	// define callback
	Local<Function> cb = Local<Function>::Cast(args[2]);
	
	// Allocate a statement handle
	retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
	if(!SQL_SUCCEEDED(retcode)){
		printf("ERROR AT ALLOCATING STATEMENT HANDLE\n");
		extract_error(hstmt, SQL_HANDLE_STMT);
	}

	// select statement
	retcode = SQLPrepare(hstmt, (SQLCHAR *)query, SQL_NTS);
	if(!SQL_SUCCEEDED(retcode)){
		printf("ERROR AT SQLPREPARE\n");
		extract_error(hstmt, SQL_HANDLE_STMT);
	}

	Column* columns = GetColumns(&colCount);

	for(j=0;j<colCount;j++) {
		if(columns[j].type == SQL_C_LONG) {
			intData[j] = (SQLINTEGER *) malloc (columns[j].size+1);
			retcode = SQLBindCol(hstmt, columns[j].index, columns[j].type, intData[j], columns[j].size, &indicator);
		}
		else if(columns[j].type == SQL_C_DOUBLE) {
			doubleData[j] = (SQLDOUBLE *) malloc (columns[j].size+1);
			retcode = SQLBindCol(hstmt, columns[j].index, columns[j].type, doubleData[j], columns[j].size, &indicator);
		}
		else if(columns[j].type == SQL_C_CHAR) {
			charData[j] = (SQLCHAR *) malloc (columns[j].size+1);
			retcode = SQLBindCol(hstmt, columns[j].index, columns[j].type, charData[j], columns[j].size, &indicator);
		}
		
		if(!SQL_SUCCEEDED(retcode)){
			printf("ERROR AT BINDING COLUMNS\n");
			extract_error(hstmt, SQL_HANDLE_STMT);
			break;
		}
	}
	// Execute the statement handle
	retcode = SQLExecute (hstmt);
	if(!SQL_SUCCEEDED(retcode)){
		printf("ERROR AT SQLEXECUTE\n");
		extract_error(hstmt, SQL_HANDLE_STMT);
	}
	
	// Array of Records
	Local<Array> result = Array::New(isolate);
	Local<Object> obj;

	// Fetch and print each row of data until SQL_NO_DATA returned.
	for(i=0;i<limit; i++) {
		retcode = SQLFetch(hstmt);
		
		if (retcode == SQL_NO_DATA) {
			break;
		}
		if(!SQL_SUCCEEDED(retcode)){
			printf("ERROR AT SQLFETCH\n");
			extract_error(hstmt, SQL_HANDLE_STMT);
			break;
		}
		
		// Retrieve individual Records and store in the object
		obj = Object::New(isolate);
		
		for(j=0;j<colCount;j++) {
			if (columns[j].type == SQL_C_LONG) {
				obj->Set(String::NewFromUtf8(isolate, (char *) columns[j].name), Number::New(isolate, (long) *intData[j]));
			} 
			else if(columns[j].type == SQL_C_DOUBLE) {
				obj->Set(String::NewFromUtf8(isolate, (char *) columns[j].name), Number::New(isolate, (double) *doubleData[j]));
			}
			else if(columns[j].type == SQL_C_CHAR) {
				obj->Set(String::NewFromUtf8(isolate, (char *) columns[j].name), String::NewFromUtf8(isolate, (char *) charData[j]));
			}
		}
		result->Set(i,obj);
	}
	
	Local<Value> argv[2] = { Number::New(isolate, retcode), result };
	cb->Call(isolate->GetCurrentContext()->Global(), 2, argv);
	
	SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
}
Пример #9
0
    // notification.protocol=
    static void SetProtocol(Local<String> property, Local<Value> value, const AccessorInfo& info) {
      RCSwitchNode* rcswitchNode_instance = node::ObjectWrap::Unwrap<RCSwitchNode>(info.Holder());

      if(value->IsInt32())
        rcswitchNode_instance->rcswitch.setProtocol(value->Int32Value());
    }
void ObjectManager::MarkReachableObjects(Isolate *isolate, const Local<Object>& obj)
{
	stack< Local<Value> > s;

	s.push(obj);

	auto propName = String::NewFromUtf8(isolate, "t::gcNum");

	assert(!m_markedForGC.empty());
	auto& topGCInfo = m_markedForGC.top();
	int numberOfGC = topGCInfo.numberOfGC;

	auto curGCNumValue = Integer::New(isolate, numberOfGC);

	while (!s.empty())
	{
		auto top = s.top();
		s.pop();

		if (top.IsEmpty() || !top->IsObject())
		{
			continue;
		}

		auto o = top.As<Object>();

		uint8_t *addr = NativeScriptExtension::GetAddress(o);
		auto itFound = m_visited.find(addr);
		if (itFound != m_visited.end())
		{
			continue;
		}
		m_visited.insert(addr);

		if (o->IsFunction())
		{
			auto func = o.As<Function>();

			int closureObjectLength;
			auto closureObjects = NativeScriptExtension::GetClosureObjects(isolate, func, &closureObjectLength);
			for (int i=0; i<closureObjectLength; i++)
			{
				auto& curV = *(closureObjects + i);
				if (!curV.IsEmpty() && curV->IsObject())
				{
					s.push(curV);
				}
			}
			NativeScriptExtension::ReleaseClosureObjects(closureObjects);
		}

		auto jsInfo = GetJSInstanceInfo(o);
		if (jsInfo != nullptr)
		{
			o->SetHiddenValue(propName, curGCNumValue);
		}

		auto proto = o->GetPrototype();
		if (!proto.IsEmpty() && !proto->IsNull() && !proto->IsUndefined() && proto->IsObject())
		{
			s.push(proto);
		}

		auto context = isolate->GetCurrentContext();
		bool success = false;
		auto propNames = NativeScriptExtension::GetPropertyKeys(isolate, context, o, success);
		assert(success);
		int len = propNames->Length();
		for (int i = 0; i < len; i++)
		{
			auto propName = propNames->Get(i);
			if (propName->IsString())
			{
				auto name = propName.As<String>();

				bool isPropDescriptor = o->HasRealNamedCallbackProperty(name);
				if (isPropDescriptor)
				{
					Local<Value> getter;
					Local<Value> setter;
					NativeScriptExtension::GetAssessorPair(isolate, o, name, getter, setter);

					if (!getter.IsEmpty() && getter->IsFunction())
					{
						int getterClosureObjectLength = 0;
						auto getterClosureObjects = NativeScriptExtension::GetClosureObjects(isolate, getter.As<Function>(), &getterClosureObjectLength);
						for (int i=0; i<getterClosureObjectLength; i++)
						{
							auto& curV = *(getterClosureObjects + i);
							if (!curV.IsEmpty() && curV->IsObject())
							{
								s.push(curV);
							}
						}
						NativeScriptExtension::ReleaseClosureObjects(getterClosureObjects);
					}

					if (!setter.IsEmpty() && setter->IsFunction())
					{
						int setterClosureObjectLength = 0;
						auto setterClosureObjects = NativeScriptExtension::GetClosureObjects(isolate, setter.As<Function>(), &setterClosureObjectLength);
						for (int i=0; i<setterClosureObjectLength; i++)
						{
							auto& curV = *(setterClosureObjects + i);
							if (!curV.IsEmpty() && curV->IsObject())
							{
								s.push(curV);
							}
						}
						NativeScriptExtension::ReleaseClosureObjects(setterClosureObjects);
					}
				}
				else
				{
					auto prop = o->Get(propName);

					if (!prop.IsEmpty() && prop->IsObject())
					{
						s.push(prop);
					}
				}
			}
		} // for

	} // while
}
Пример #11
0
/**
 * @details This is set by `MapservAsync` to run after `MapservWork` has
 * finished, being passed the response generated by the latter and running in
 * the same thread as the former. It formats the mapserv response into
 * javascript datatypes and returns them via the original callback.
 *
 * @param req The asynchronous libuv request.
 */
void Map::MapservAfter(uv_work_t *req) {
  HandleScope scope;

  MapBaton *baton = static_cast<MapBaton*>(req->data);
  Map *self = baton->self;
  gdBuffer *buffer = baton->buffer;

  Handle<Value> argv[2];

  if (baton->error) {
    argv[0] = baton->error->toV8Error();
    delete baton->error;        // we've finished with it
  } else {
    argv[0] = Undefined();
  }

  // convert the http_response to a javascript object
  Local<Object> result = Object::New();

  // Add the content-type to the headers object.  This object mirrors the
  // HTTP headers structure and creates an API that allows for the addition
  // of other headers in the future.
  Local<Object> headers = Object::New();
  if (baton->content_type) {
    Local<Array> values = Array::New(1);

    values->Set(0, String::New(baton->content_type));
    headers->Set(String::New("Content-Type"), values);
  }
  result->Set(headers_symbol, headers);

  // set the response data as a Node Buffer object. This is zero-copied from
  // mapserver and free'd when the buffer is garbage collected.
  if (buffer && buffer->data) {
    result->Set(data_symbol,
                Buffer::New((char *)buffer->data, buffer->size, FreeBuffer, NULL)->handle_);

    // add the content-length header
    Local<Array> values = Array::New(1);
    values->Set(0, Uint32::New(buffer->size));
    headers->Set(String::New("Content-Length"), values);
  }

  argv[1] = result;

  // pass the results to the user specified callback function
  TryCatch try_catch;
  baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
  if (try_catch.HasCaught()) {
    FatalException(try_catch);
  }

  // clean up
  if (buffer) {
    delete baton->buffer;
    baton->buffer = NULL;
  }

  if (baton->content_type) {
    msFree(baton->content_type);
  }

  baton->env.clear();
  baton->callback.Dispose();
  self->Unref(); // decrement the map reference so it can be garbage collected
  delete baton;
  return;
}
Handle<Value> Pngquant::Compress(const Arguments& args) {
    HandleScope scope;
    struct rwpng_data * out_buffer;
    struct rwpng_data * in_buffer;

    if (args.Length() != 3) {
        return ThrowException(Exception::TypeError(
                String::New("Invalid argument, Need three arguments!")
            )
        );
    }

    if (!Buffer::HasInstance(args[0])) {
        return ThrowException(Exception::TypeError(
                String::New("First argument must be a buffer.")
            )
        );
    }

    if (!args[2]->IsFunction()) {
        return ThrowException(Exception::TypeError(
                String::New("Third argument must be a callback function.")
            )
        );
    }

    png_bytep in_stream = (png_bytep) Buffer::Data(args[0]->ToObject());
    unsigned in_length = Buffer::Length(args[0]->ToObject());
    Local<String> opt = args[1]->ToString();
    Local<Function> callback = Local<Function>::Cast(args[2]);

    Buffer *buffer;
    char str_buffer[BUFFER_SIZE];
    memset(str_buffer, '\0', BUFFER_SIZE);

    opt->WriteUtf8(str_buffer);

    char *argv[32] = {""};

    char token[BUFFER_SIZE];
    memset(token, '\0', BUFFER_SIZE);

    int i = 0, argc = 0, k = 0, len = 0;
    while(str_buffer[i] != '\0') {
        if (argc >= 30) {
            break;
        }
        if (str_buffer[i] == ' ') {
            argc++;
            k = 0;
            len = strlen(token);
            argv[argc] = (char*) malloc(len + 1);
            memset(argv[argc], '\0', len + 1);
            memcpy(argv[argc], token, len + 1);
            //reset token
            memset(token, '\0', BUFFER_SIZE);
        } else {
            token[k++] = str_buffer[i];
        }
        i++;
    }
    argv[0] = "pngquant";
    if ((len = strlen(token)) > 0) {
        argc++;
        argv[argc] = (char*) malloc(len + 1);
        memset(argv[argc], '\0', len + 1);
        memcpy(argv[argc], token, len + 1);
        argc = argc + 1; //0 1 2
    }

    in_buffer = (struct rwpng_data *)malloc(sizeof(struct rwpng_data));
    if (in_buffer == NULL) {
        return ThrowException(Exception::TypeError(
                String::New("malloc fail!")
            )
        );
    }
    out_buffer = (struct rwpng_data *)malloc(sizeof(struct rwpng_data));
    if (out_buffer == NULL) {
        return ThrowException(Exception::TypeError(
                String::New("malloc fail!")
            )
        );
    }

    memset(out_buffer, '\0', sizeof(struct rwpng_data));

    in_buffer->png_data = in_stream;
    in_buffer->length = in_length;
    in_buffer->bytes_read = 0;

    int ret = pngquant(in_buffer, out_buffer, argc, argv);
    if (ret != 0) {
        out_buffer->png_data = in_buffer->png_data;
        out_buffer->length = in_buffer->length;
        fprintf(stderr, "File: %s\n", argv[argc-1]);
    }

    buffer = Buffer::New((char *)out_buffer->png_data, out_buffer->length);
    free(in_buffer);
    free(out_buffer);
    
    return scope.Close(
        buffer->handle_
    );
}
Пример #13
0
void afterListImpl(Baton *baton)
{

//ESPECIFICO *********
	Local<Object> responseInfo = Object::New();
	responseInfo->Set(String::NewSymbol("errorStatus"), Integer::New(baton->errorStatus));

	TorrentsStat *torrentsStat = baton->torrentsStat;
	Handle<Array> arrayToSend = Array::New(torrentsStat->totalTorrents);

	for ( int i=0; i < torrentsStat->totalTorrents; i++)
	{
		Local<Object> torrentInfo = Object::New();
		torrentInfo->Set(String::NewSymbol("id"), Integer::New(torrentsStat->torrentStatList[i].id));

		if ( torrentsStat->torrentStatList[i].error )
			torrentInfo->Set(String::NewSymbol("errorMark"), String::New("*"));
		else
			torrentInfo->Set(String::NewSymbol("errorMark"), String::New(" "));

        if ( torrentsStat->torrentStatList[i].sizeWhenDone )
        {
        	float done =  (torrentsStat->torrentStatList[i].sizeWhenDone - torrentsStat->torrentStatList[i].leftUntilDone) / torrentsStat->torrentStatList[i].sizeWhenDone;
        	torrentInfo->Set(String::NewSymbol("done"), String::New(tNode::Utils::folatToPercent(done).c_str()));
        }
        else
        	torrentInfo->Set(String::NewSymbol("done"), String::New("n/a"));

        torrentInfo->Set(String::NewSymbol("have"), Integer::New(torrentsStat->torrentStatList[i].sizeWhenDone - torrentsStat->torrentStatList[i].leftUntilDone));

        if ( torrentsStat->torrentStatList[i].leftUntilDone || torrentsStat->torrentStatList[i].eta != -1)
        	torrentInfo->Set(String::NewSymbol("eta"), String::New(tNode::Utils::intToString(torrentsStat->torrentStatList[i].eta).c_str()));
        else
        	torrentInfo->Set(String::NewSymbol("eta"), String::New("Done"));

        torrentInfo->Set(String::NewSymbol("up"), Number::New(torrentsStat->torrentStatList[i].rateUpload));
        torrentInfo->Set(String::NewSymbol("down"), Number::New(torrentsStat->torrentStatList[i].rateDownload));
        torrentInfo->Set(String::NewSymbol("ratio"), Number::New(torrentsStat->torrentStatList[i].uploadRatio));
        torrentInfo->Set(String::NewSymbol("status"), String::New(transSession->getTorrentStatusString(torrentsStat->torrentStatList[i]).c_str()));
        torrentInfo->Set(String::NewSymbol("name"), String::New(torrentsStat->torrentStatList[i].name));

		arrayToSend->Set(i,torrentInfo);
	}

	delete torrentsStat->torrentStatList;
	delete [] torrentsStat;

	responseInfo->Set(String::NewSymbol("torrents"), arrayToSend);

	const unsigned argc = 1;
	Local<Value> argv[argc];
	argv[0] = responseInfo;
//ESPECIFICO *********

	TryCatch try_catch;
	baton->callback->Call(Context::GetCurrent()->Global(), argc, argv);

	baton->callback.Dispose();
	delete baton;
}
Пример #14
0
static Handle<Value> mp3ToTorrent(const Arguments& args)
{
	HandleScope scope;

	if (args.Length() < 3) {
	    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
	    return scope.Close(Undefined());
	}

	pthread_mutex_lock(&suscribe_mutex);
	if ( !isSuscribed )
	{
		loop = uv_default_loop();
		uv_async_init(loop, &status_change_notifier, after);
		isSuscribed = false;
	}
	pthread_mutex_unlock(&suscribe_mutex);

	Baton *baton = new Baton();
	baton->errorStatus = NO_ERROR;

//ESPECIFICO *********
	baton->errorStatus = NO_ERROR;
	String::Utf8Value nodeOrgFilePath(args[0]->ToDetailString());
	baton->orgFilePath = string(*nodeOrgFilePath);
	baton->uframeDirectory = string("");
	baton->torrentDirectory = string("");
	baton->uframeFilePath = string("");
	baton->torrentFilePath = string("");
	baton->uframeHash = string("");
	baton->pieceSize = 0;

	baton->afterCallBack = &afterMp3ToTorrentImpl;

	//ARRAY

	if ( !args[1]->IsObject() ){
	    ThrowException(Exception::TypeError(String::New("Second argument must be an object")));
	    return scope.Close(Undefined());
	}

	Handle<Object> object = Handle<Object>::Cast(args[1]);

	Handle<Value> objUframeDirectory = object->Get(String::New("uframeDirectory"));
	if ( !objUframeDirectory->IsUndefined() )
	{
		String::Utf8Value nodeUframeDirectory(objUframeDirectory->ToDetailString());
		baton->uframeDirectory = string(*nodeUframeDirectory);
	}

	Handle<Value> objTorrentDirectory = object->Get(String::New("torrentDirectory"));
	if ( !objTorrentDirectory->IsUndefined() )
	{
		String::Utf8Value nodeTorrentDirectory(objTorrentDirectory->ToDetailString());
		baton->torrentDirectory = string(*nodeTorrentDirectory);
	}

	Handle<Value> objPieceSize = object->Get(String::New("pieceSize"));
	if ( !objTorrentDirectory->IsUndefined() )
	{
		Local<Integer> nodePieceSize = objPieceSize->ToInteger();
		baton->pieceSize = nodePieceSize->Value();
	}

	//CALLBACK
	baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2]));
//ESPECIFICO *********

	pthread_create(&status_change_thread, NULL, mp3ToTorrentImpl, (void *)baton);

	return scope.Close(True());
}
Пример #15
0
Handle<Value> Grid::encodeSync(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = ObjectWrap::Unwrap<Grid>(args.This());
    
    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;
    
    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
          return ThrowException(Exception::TypeError(
            String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }
    
    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
          return ThrowException(Exception::TypeError(
            String::New("optional second arg must be an options object")));

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

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
              return ThrowException(Exception::TypeError(
                String::New("'resolution' must be an Integer")));
    
            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
              return ThrowException(Exception::TypeError(
                String::New("'features' must be an Boolean")));
    
            add_features = bind_opt->BooleanValue();
        }
    }
    
    try {
    
        Local<Array> grid_array = Array::New();
        std::vector<mapnik::grid::lookup_type> key_order;
        node_mapnik::grid2utf<mapnik::grid>(*g->get(),grid_array,key_order,resolution);
    
        // convert key order to proper javascript array
        Local<Array> keys_a = Array::New(key_order.size());
        std::vector<std::string>::iterator it;
        unsigned int i;
        for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i)
        {
            keys_a->Set(i, String::New((*it).c_str()));
        }
    
        // gather feature data
        Local<Object> feature_data = Object::New();
        if (add_features) {
            node_mapnik::write_features<mapnik::grid>(*g->get(),
                           feature_data,
                           key_order
                           );
        }
        
        // Create the return hash.
        Local<Object> json = Object::New();
        json->Set(String::NewSymbol("grid"), grid_array);
        json->Set(String::NewSymbol("keys"), keys_a);
        json->Set(String::NewSymbol("data"), feature_data);
        return json;
        
    }
    catch (std::exception & ex)
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
}
Пример #16
0
/* static */
void V8Runtime::bootstrap(Local<Context> context)
{
	Isolate* isolate = context->GetIsolate();
	EventEmitter::initTemplate(context);

	Local<Object> global = Object::New(isolate);
	krollGlobalObject.Reset(isolate, global);
	Local<Array> mc = Array::New(isolate);
	moduleContexts.Reset(isolate, mc);

	KrollBindings::initFunctions(global, context);

	SetMethod(isolate, global, "log", krollLog);
	// Move this into the EventEmitter::initTemplate call?
	Local<FunctionTemplate> eect = Local<FunctionTemplate>::New(isolate, EventEmitter::constructorTemplate);
	global->Set(NEW_SYMBOL(isolate, "EventEmitter"), eect->GetFunction());

	global->Set(NEW_SYMBOL(isolate, "runtime"), STRING_NEW(isolate, "v8"));
	global->Set(NEW_SYMBOL(isolate, "DBG"), v8::Boolean::New(isolate, V8Runtime::DBG));
	global->Set(NEW_SYMBOL(isolate, "moduleContexts"), mc);

	LOG_TIMER(TAG, "Executing kroll.js");

	TryCatch tryCatch(isolate);
	Local<Value> result = V8Util::executeString(isolate, KrollBindings::getMainSource(isolate), STRING_NEW(isolate, "ti:/kroll.js"));

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
	}
	if (!result->IsFunction()) {
		LOGF(TAG, "kroll.js result is not a function");
		V8Util::reportException(isolate, tryCatch, true);
	}

	Local<Function> mainFunction = result.As<Function>();
	Local<Value> args[] = { global };
	mainFunction->Call(context, context->Global(), 1, args);

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
		LOGE(TAG, "Caught exception while bootstrapping Kroll");
	}
}
Пример #17
0
// @TODO: convert this to EIO. It's currently doing all the work in the main
// thread, and just provides an async interface.
Handle<Value> Grid::encode(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

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

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

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

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
              return ThrowException(Exception::TypeError(
                String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
              return ThrowException(Exception::TypeError(
                String::New("'features' must be an Boolean")));

            add_features = bind_opt->BooleanValue();
        }
    }

    // ensure callback is a function
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                  String::New("last argument must be a callback function")));
    Local<Function> callback = Local<Function>::Cast(args[args.Length()-1]);

    try {

        Local<Array> grid_array = Array::New();
        std::vector<mapnik::grid::lookup_type> key_order;
        node_mapnik::grid2utf<mapnik::grid>(*g->get(),grid_array,key_order,resolution);

        // convert key order to proper javascript array
        Local<Array> keys_a = Array::New(key_order.size());
        std::vector<std::string>::iterator it;
        unsigned int i;
        for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i)
        {
            keys_a->Set(i, String::New((*it).c_str()));
        }

        // gather feature data
        Local<Object> feature_data = Object::New();
        if (add_features) {
            node_mapnik::write_features<mapnik::grid>(*g->get(),
                           feature_data,
                           key_order
                           );
        }

        // Create the return hash.
        Local<Object> json = Object::New();
        json->Set(String::NewSymbol("grid"), grid_array);
        json->Set(String::NewSymbol("keys"), keys_a);
        json->Set(String::NewSymbol("data"), feature_data);

        TryCatch try_catch;
        Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(json) };
        callback->Call(Context::GetCurrent()->Global(), 2, argv);
        if (try_catch.HasCaught()) {
            FatalException(try_catch);
        }
    }
    catch (std::exception & ex)
    {
        Local<Value> argv[1] = { Exception::Error(String::New(ex.what())) };
        callback->Call(Context::GetCurrent()->Global(), 1, argv);
    }

    return scope.Close(Undefined());
}
Пример #18
0
Handle<Value> Feature::addAttributes(const Arguments& args)
{
    HandleScope scope;

    Feature* fp = ObjectWrap::Unwrap<Feature>(args.This());

    if (args.Length() > 0 ) {
        Local<Value> value = args[0];
        if (value->IsNull() || value->IsUndefined()) {
            return ThrowException(Exception::TypeError(String::New("object expected")));
        } else {
            Local<Object> attr = value->ToObject();
            try
            {
                Local<Array> names = attr->GetPropertyNames();
                uint32_t i = 0;
                uint32_t a_length = names->Length();
                boost::scoped_ptr<mapnik::transcoder> tr(new mapnik::transcoder("utf8"));
                while (i < a_length) {
                    Local<Value> name = names->Get(i)->ToString();
                    Local<Value> value = attr->Get(name);
                    if (value->IsString()) {
                        UnicodeString ustr = tr->transcode(TOSTR(value));
                        boost::put(*fp->get(),TOSTR(name),ustr);
                    } else if (value->IsNumber()) {
                        double num = value->NumberValue();
                        // todo - round
                        if (num == value->IntegerValue()) {
                            int integer = value->IntegerValue();
                            boost::put(*fp->get(),TOSTR(name),integer);
                        } else {
                            double dub_val = value->NumberValue();
                            boost::put(*fp->get(),TOSTR(name),dub_val);
                        }
                    } else {
                        std::clog << "unhandled type for property: " << TOSTR(name) << "\n";
                    }
                    i++;
                }
            }
            catch (const std::exception & ex )
            {
                return ThrowException(Exception::Error(
                  String::New(ex.what())));
            }
            catch (...) {
                return ThrowException(Exception::Error(
                  String::New("Unknown exception happended - please report bug")));
            }
        }
    }

    return Undefined();
}
Пример #19
0
int Conv::ToJavaSequence(JNIEnv *jniEnv, Handle<Value> val, int componentType, jarray *jVal) {
  Local<Object> oVal;
  Local<Value> vLength;
  if(val.IsEmpty() || val->IsNull() || val->IsUndefined()) {
    *jVal = 0;
    return OK;
  }
  if(!val->IsObject())
    return ErrorType;
  
  oVal = val->ToObject();
  vLength = oVal->Get(sLength);
  if(vLength.IsEmpty() || !vLength->IsNumber())
    return ErrorType;
  
  jarray ob;
  jint len = vLength->Int32Value();
  if(isJavaObject(componentType)) {
    jclass componentClass;
    if(isInterfaceOrDict(componentType)) {
      Interface *interface = env->getInterface(getClassId(componentType));
      componentClass = interface->getDeclaredClass();
    } else {
      switch(componentType) {
        default:
          return ErrorType;
        case TYPE_STRING:
          componentClass = jni.java.lang.String.class_;
          break;
        case TYPE_DATE:
          componentClass = jni.java.util.Date.class_;
          break;
        case TYPE_OBJECT:
          componentClass = jni.anode.js.JSObject.class_;
          break;
      }
    }
    ob = jniEnv->NewObjectArray(len, componentClass, 0);
    if(ob) {
      int res = OK;
      for(int i = 0; i < len; i++) {
        jobject item;
        res = ToJavaObject(jniEnv, oVal->Get(i), componentType, &item);
        if(res != OK) break;
        jniEnv->SetObjectArrayElement((jobjectArray)ob, i, item);
        jniEnv->DeleteLocalRef(item);
      }
    }
  } else {
    switch(componentType) {
      default:
        return ErrorType;
      case TYPE_BYTE:
        ob = jniEnv->NewByteArray(len);
        if(ob) {
          /* FIXME: see if this case can be optimised */
          jbyte *buf = jniEnv->GetByteArrayElements((jbyteArray)ob, 0);
          for(int i = 0; i < len; i++)
            buf[i] = (jbyte)oVal->Get(i)->Uint32Value();
          
          jniEnv->ReleaseByteArrayElements((jbyteArray)ob, buf, 0);
          break;
        }
      case TYPE_INT:
        ob = jniEnv->NewIntArray(len);
        if(ob) {
          jint *buf = jniEnv->GetIntArrayElements((jintArray)ob, 0);
          for(int i = 0; i < len; i++)
            buf[i] = oVal->Get(i)->Int32Value();
          
          jniEnv->ReleaseIntArrayElements((jintArray)ob, buf, 0);
          break;
        }
      case TYPE_LONG:
        ob = jniEnv->NewLongArray(len);
        if(ob) {
          jlong *buf = jniEnv->GetLongArrayElements((jlongArray)ob, 0);
          for(int i = 0; i < len; i++)
            buf[i] = oVal->Get(i)->IntegerValue();
          
          jniEnv->ReleaseLongArrayElements((jlongArray)ob, buf, 0);
          break;
        }
      case TYPE_DOUBLE:
        ob = jniEnv->NewDoubleArray(len);
        if(ob) {
          jdouble *buf = jniEnv->GetDoubleArrayElements((jdoubleArray)ob, 0);
          if(!buf) return ErrorMem;
          for(int i = 0; i < len; i++)
            buf[i] = oVal->Get(i)->NumberValue();
          
          jniEnv->ReleaseDoubleArrayElements((jdoubleArray)ob, buf, 0);
          break;
        }
    }
  }
  if(ob) {
    *jVal = ob;
    return OK;
  }
  if(jniEnv->ExceptionCheck())
    jniEnv->ExceptionClear();
  return ErrorVM;
}
Пример #20
0
void NovaConfigBinding::Init(Handle<Object> target) {
  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
  tpl->SetClassName(String::NewSymbol("NovaConfigBinding"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);
  // Prototype
  tpl->PrototypeTemplate()->Set(String::NewSymbol("ListInterfaces"),FunctionTemplate::New(InvokeWrappedMethod<std::vector<std::string>, NovaConfigBinding, Config, &Config::ListInterfaces>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetGroup"),FunctionTemplate::New(InvokeWrappedMethod<std::string, NovaConfigBinding, Config, &Config::GetGroup>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("ListLoopbacks"),FunctionTemplate::New(InvokeWrappedMethod<std::vector<std::string>, NovaConfigBinding, Config, &Config::ListLoopbacks>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetInterfaces"),FunctionTemplate::New(InvokeWrappedMethod<std::vector<std::string>, NovaConfigBinding, Config, &Config::GetInterfaces>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetDoppelInterface"),FunctionTemplate::New(InvokeWrappedMethod<std::string, NovaConfigBinding, Config, &Config::GetDoppelInterface>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetUseAllInterfacesBinding"),FunctionTemplate::New(InvokeWrappedMethod<std::string, NovaConfigBinding, Config, &Config::GetUseAllInterfacesBinding>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("SetDoppelInterface"),FunctionTemplate::New(SetDoppelInterface)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("AddIface"),FunctionTemplate::New(AddIface)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("SetSMTPUseAuth"),FunctionTemplate::New(SetSMTPUseAuth)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("ClearInterfaces"),FunctionTemplate::New(ClearInterfaces)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("UseAllInterfaces"),FunctionTemplate::New(UseAllInterfaces)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetUseAnyLoopback"),FunctionTemplate::New(InvokeWrappedMethod<bool, NovaConfigBinding, Config, &Config::GetUseAnyLoopback>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("SetGroup"),FunctionTemplate::New(SetGroup)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("UseAnyLoopback"),FunctionTemplate::New(UseAnyLoopback)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("ReadSetting"),FunctionTemplate::New(ReadSetting)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("WriteSetting"),FunctionTemplate::New(WriteSetting)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("ReloadConfiguration"),FunctionTemplate::New(ReloadConfiguration)->GetFunction());
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetVersionString"),FunctionTemplate::New(InvokeWrappedMethod<string, NovaConfigBinding, Config, &Config::GetVersionString>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetPathConfigHoneydHS"),FunctionTemplate::New(InvokeWrappedMethod<string, NovaConfigBinding, Config, &Config::GetPathConfigHoneydHS>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetPathHome"),FunctionTemplate::New(InvokeWrappedMethod<string, NovaConfigBinding, Config, &Config::GetPathHome>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetPathShared"),FunctionTemplate::New(InvokeWrappedMethod<string, NovaConfigBinding, Config, &Config::GetPathShared>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetCurrentConfig"),FunctionTemplate::New(InvokeWrappedMethod<string, NovaConfigBinding, Config, &Config::GetCurrentConfig>));


  tpl->PrototypeTemplate()->Set(String::NewSymbol("SetSMTPUser"),FunctionTemplate::New(InvokeWrappedMethod<bool, NovaConfigBinding, Config, std::string, &Config::SetSMTPUser>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("SetCurrentConfig"),FunctionTemplate::New(InvokeWrappedMethod<bool, NovaConfigBinding, Config, std::string, &Config::SetCurrentConfig>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("SetSMTPPass"),FunctionTemplate::New(InvokeWrappedMethod<bool, NovaConfigBinding, Config, std::string, &Config::SetSMTPPass>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetSMTPUser"),FunctionTemplate::New(InvokeWrappedMethod<string, NovaConfigBinding, Config, &Config::GetSMTPUser>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetSMTPPass"),FunctionTemplate::New(InvokeWrappedMethod<string, NovaConfigBinding, Config, &Config::GetSMTPPass>));
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetSMTPUseAuth"),FunctionTemplate::New(InvokeWrappedMethod<bool, NovaConfigBinding, Config, &Config::GetSMTPUseAuth>));
	
  tpl->PrototypeTemplate()->Set(String::NewSymbol("GetIpAddresses"),FunctionTemplate::New(InvokeMethod<std::vector<std::string>, std::string, Config::GetIpAddresses>));

  Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
  target->Set(String::NewSymbol("NovaConfigBinding"), constructor);
}
Пример #21
0
void ModuleByteArray::registerTemplates(v8::Isolate* isolate, Local<ObjectTemplate> globalObject)
{
	HandleScope handle_scope(isolate);
	Local<ObjectTemplate> object = ObjectTemplate::New(isolate);

	// Create function template for our constructor it will call the constructByteArray function
	Local<FunctionTemplate> constructorTemplate = FunctionTemplate::New(isolate, constructByteArray);
	constructorTemplate->SetClassName(String::NewFromUtf8(isolate, "ByteArray"));

	// Define function added to each instance
	Local<ObjectTemplate> constructorInstanceTemplate = constructorTemplate->InstanceTemplate();
	constructorInstanceTemplate->SetInternalFieldCount(1);
	constructorInstanceTemplate->Set(String::NewFromUtf8(isolate, "hex"), FunctionTemplate::New(isolate, hex));
	constructorInstanceTemplate->Set(String::NewFromUtf8(isolate, "base64"), FunctionTemplate::New(isolate, base64));
	constructorInstanceTemplate->Set(String::NewFromUtf8(isolate, "hash"), FunctionTemplate::New(isolate, hash));
	constructorInstanceTemplate->Set(String::NewFromUtf8(isolate, "printable"), FunctionTemplate::New(isolate, printable));
	constructorInstanceTemplate->Set(String::NewFromUtf8(isolate, "toString"), FunctionTemplate::New(isolate, toString));

	// Store template
	ByteArrayTemplate.Reset(isolate, constructorInstanceTemplate);

	// Set the function in the global scope -- that is, set "ByteArray" to the constructor
	globalObject->Set(String::NewFromUtf8(isolate, "ByteArray"), constructorTemplate);
}
Пример #22
0
DBScanHelper::DBScanHelper(const Arguments &args) : 
  nbounds(0),
  isIndexScan(false)
{
  DEBUG_MARKER(UDEB_DEBUG);

  Local<Value> v;

  const Local<Object> spec = args[0]->ToObject();
  int opcode = args[1]->Int32Value();
  tx = unwrapPointer<NdbTransaction *>(args[2]->ToObject());

  lmode = NdbOperation::LM_CommittedRead;
  scan_options = & options;
  options.optionsPresent = 0ULL;

  v = spec->Get(SCAN_TABLE_RECORD);
  if(! v->IsNull()) {
    Local<Object> o = v->ToObject();
    row_record = unwrapPointer<const Record *>(o);
  }

  v = spec->Get(SCAN_INDEX_RECORD);
  if(! v->IsNull()) {
    Local<Object> o = v->ToObject();
    isIndexScan = true;
    key_record = unwrapPointer<const Record *>(o);
  }
  
  v = spec->Get(SCAN_LOCK_MODE);
  if(! v->IsNull()) {
    int intLockMode = v->Int32Value();
    lmode = static_cast<NdbOperation::LockMode>(intLockMode);
  }

  // SCAN_BOUNDS is an array of BoundHelpers  
  v = spec->Get(SCAN_BOUNDS);
  if(v->IsArray()) {
    Local<Object> o = v->ToObject();
    while(o->Has(nbounds)) {
      nbounds++; 
    }
    bounds = new NdbIndexScanOperation::IndexBound *[nbounds];
    for(int i = 0 ; i < nbounds ; i++) {
      Local<Object> b = o->Get(i)->ToObject();
      bounds[i] = unwrapPointer<NdbIndexScanOperation::IndexBound *>(b);
    }
  }

  v = spec->Get(SCAN_OPTION_FLAGS);
  if(! v->IsNull()) {
    options.scan_flags = v->Uint32Value();
    options.optionsPresent |= NdbScanOperation::ScanOptions::SO_SCANFLAGS;
  }
  
  v = spec->Get(SCAN_OPTION_BATCH_SIZE);
  if(! v->IsNull()) {
    options.batch = v->Uint32Value();
    options.optionsPresent |= NdbScanOperation::ScanOptions::SO_BATCH;
  }
  
  v = spec->Get(SCAN_OPTION_PARALLELISM);
  if(! v->IsNull()) {
    options.parallel = v->Uint32Value();
    options.optionsPresent |= NdbScanOperation::ScanOptions::SO_PARALLEL;
  }
  
  v = spec->Get(SCAN_FILTER_CODE);
  if(! v->IsNull()) {
    Local<Object> o = v->ToObject();
    options.interpretedCode = unwrapPointer<NdbInterpretedCode *>(o);
    options.optionsPresent |= NdbScanOperation::ScanOptions::SO_INTERPRETED;
  }

  /* Scanning delete requires key info */
  if(opcode == OP_SCAN_DELETE) {
    options.scan_flags |= NdbScanOperation::SF_KeyInfo;
    options.optionsPresent |= NdbScanOperation::ScanOptions::SO_SCANFLAGS;    
  }
  
  /* Done defining the object */
}
Пример #23
0
jsvalue JsEngine::ErrorFromV8(TryCatch& trycatch)
{
    jsvalue v;

    HandleScope scope;
    
    Local<Value> exception = trycatch.Exception();
	    
	v.type = JSVALUE_TYPE_UNKNOWN_ERROR;
	v.value.str = 0;
    v.length = 0;

	// If this is a managed exception we need to place its ID inside the jsvalue
    // and set the type JSVALUE_TYPE_MANAGED_ERROR to make sure the CLR side will
    // throw on it.

    if (exception->IsObject()) {
        Local<Object> obj = Local<Object>::Cast(exception);
        if (obj->InternalFieldCount() == 1) {
			Local<External> wrap = Local<External>::Cast(obj->GetInternalField(0));
			ManagedRef* ref = (ManagedRef*)wrap->Value();
	        v.type = JSVALUE_TYPE_MANAGED_ERROR;
            v.length = ref->Id();
			return v;
		}
	}

	jserror *error = new jserror();
	memset(error, 0, sizeof(jserror));
	
	Local<Message> message = trycatch.Message();

	if (!message.IsEmpty()) {
		error->line = message->GetLineNumber();
		error->column = message->GetStartColumn();
		error->resource = AnyFromV8(message->GetScriptResourceName());
		error->message = AnyFromV8(message->Get());
	}
	 if (exception->IsObject()) {
        Local<Object> obj2 = Local<Object>::Cast(exception);
		error->type = AnyFromV8(obj2->GetConstructorName());
	 }

	error->exception = AnyFromV8(exception);
	v.type = JSVALUE_TYPE_ERROR;
	v.value.ptr = error;
    
	return v;
}
Пример #24
0
Handle<Value> MemoryDatasource::add(const Arguments& args)
{

    HandleScope scope;

    if ((args.Length() != 1) || !args[0]->IsObject())
    {
        return ThrowException(Exception::Error(
           String::New("accepts one argument: an object including x and y (or wkt) and properties")));
    }

    MemoryDatasource* d = ObjectWrap::Unwrap<MemoryDatasource>(args.This());

    Local<Object> obj = args[0]->ToObject();

    if (obj->Has(String::New("wkt")) || (obj->Has(String::New("x")) && obj->Has(String::New("y"))))
    {
        if (obj->Has(String::New("wkt")))
            return ThrowException(Exception::Error(
               String::New("wkt not yet supported")));

        Local<Value> x = obj->Get(String::New("x"));
        Local<Value> y = obj->Get(String::New("y"));
        if (!x->IsUndefined() && x->IsNumber() && !y->IsUndefined() && y->IsNumber())
        {
            mapnik::geometry_type * pt = new mapnik::geometry_type(mapnik::Point);
            pt->move_to(x->NumberValue(),y->NumberValue());
            mapnik::feature_ptr feature(new mapnik::Feature(d->feature_id_));
            ++(d->feature_id_);
            feature->add_geometry(pt);
            if (obj->Has(String::New("properties")))
            {
                Local<Value> props = obj->Get(String::New("properties"));
                if (props->IsObject())
                {
                    Local<Object> p_obj = props->ToObject();
                    Local<Array> names = p_obj->GetPropertyNames();
                    uint32_t i = 0;
                    uint32_t a_length = names->Length();
                    while (i < a_length)
                    {
                        Local<Value> name = names->Get(i)->ToString();
                        // if name in q.property_names() ?
                        Local<Value> value = p_obj->Get(name);
                        if (value->IsString()) {
                            UnicodeString ustr = d->tr_->transcode(TOSTR(value));
                            boost::put(*feature,TOSTR(name),ustr);
                        } else if (value->IsNumber()) {
                            double num = value->NumberValue();
                            // todo - round
                            if (num == value->IntegerValue()) {
                                int integer = value->IntegerValue();
                                boost::put(*feature,TOSTR(name),integer);
                            } else {
                                double dub_val = value->NumberValue();
                                boost::put(*feature,TOSTR(name),dub_val);
                            }
                        } else {
                            std::clog << "unhandled type for property: " << TOSTR(name) << "\n";
                        }
                        i++;
                    }
                }
            }
            mapnik::memory_datasource *cache = dynamic_cast<mapnik::memory_datasource *>(d->datasource_.get());
            cache->push(feature);
        }
    }
    return scope.Close(Boolean::New(false));
}
Пример #25
0
void ODBCResult::UV_AfterFetchAll(uv_work_t* work_req, int status) {
  DEBUG_PRINTF("ODBCResult::UV_AfterFetchAll\n");
  Nan::HandleScope scope;

  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++;

    data->objError.Reset(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 = Nan::New(data->rows);
    if (data->fetchMode == FETCH_ARRAY) {
      rows->Set(
        Nan::New(data->count),
        ODBC::GetRecordArray(
          self->m_hSTMT,
          self->columns,
          &self->colCount,
          self->buffer,
          self->bufferLength)
      );
    }
    else {
      rows->Set(
        Nan::New(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> info[2];

    if (data->errorCount > 0) {
      info[0] = Nan::New(data->objError);
    }
    else {
      info[0] = Nan::Null();
    }

    info[1] = Nan::New(data->rows);

    Nan::TryCatch try_catch;

    data->cb->Call(2, info);
    delete data->cb;
    data->rows.Reset();
    data->objError.Reset();

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

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

    self->Unref();
  }
}
Пример #26
0
Handle<Value> Query::New(Arguments const& args)
{
    HandleScope scope;
    if (!args.IsConstructCall()) {
        return ThrowException(Exception::Error(String::New("Cannot call constructor as function, you need to use 'new' keyword")));
    }
    try {
        if (args.Length() != 1) {
            return ThrowException(Exception::TypeError(String::New("please provide an object of options for the first argument")));
        }
        if (!args[0]->IsObject()) {
            return ThrowException(Exception::TypeError(String::New("first argument must be an object")));
        }
        Local<Object> obj = args[0]->ToObject();
        if (obj->IsNull() || obj->IsUndefined()) {
            return ThrowException(Exception::TypeError(String::New("first arg must be an object")));
        }
        if (!obj->Has(String::New("coordinates"))) {
            return ThrowException(Exception::TypeError(String::New("must provide a coordinates property")));
        }
        Local<Value> coordinates = obj->Get(String::New("coordinates"));
        if (!coordinates->IsArray()) {
            return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
        }
        Local<Array> coordinates_array = Local<Array>::Cast(coordinates);
        if (coordinates_array->Length() < 2) {
            return ThrowException(Exception::TypeError(String::New("at least two coordinates must be provided")));
        }

        Query* q = new Query();
        q->this_->zoomLevel = 18; //no generalization
        q->this_->printInstructions = false; //turn by turn instructions
        q->this_->alternateRoute = true; //get an alternate route, too
        q->this_->geometry = true; //retrieve geometry of route
        q->this_->compression = true; //polyline encoding
        q->this_->checkSum = UINT_MAX; //see wiki
        q->this_->service = "viaroute"; //that's routing
        q->this_->outputFormat = "json";
        q->this_->jsonpParameter = ""; //set for jsonp wrapping
        q->this_->language = ""; //unused atm

        if (obj->Has(String::New("alternateRoute"))) {
            q->this_->alternateRoute = obj->Get(String::New("alternateRoute"))->BooleanValue();
        }

        if (obj->Has(String::New("checksum"))) {
            q->this_->checkSum = static_cast<unsigned>(obj->Get(String::New("checksum"))->Uint32Value());
        }

        if (obj->Has(String::New("zoomLevel"))) {
            q->this_->zoomLevel = static_cast<short>(obj->Get(String::New("zoomLevel"))->Int32Value());
        }

        if (obj->Has(String::New("printInstructions"))) {
            q->this_->printInstructions = obj->Get(String::New("printInstructions"))->BooleanValue();
        }

        if (obj->Has(String::New("jsonpParameter"))) {
            q->this_->jsonpParameter = *v8::String::Utf8Value(obj->Get(String::New("jsonpParameter")));
        }

        if (obj->Has(String::New("hints"))) {
            Local<Value> hints = obj->Get(String::New("hints"));
            if (!hints->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("hints must be an array of strings/null")));
            }
            Local<Array> hints_array = Local<Array>::Cast(hints);
            for (uint32_t i = 0; i < hints_array->Length(); ++i) {
                Local<Value> hint = hints_array->Get(i);
                if (hint->IsString()) {
                    q->this_->hints.push_back(*v8::String::Utf8Value(hint));
                } else if(hint->IsNull()){
                    q->this_->hints.push_back("");
                }else{
                    return ThrowException(Exception::TypeError(String::New("hint must be null or string")));
                }
            }
        }

        for (uint32_t i = 0; i < coordinates_array->Length(); ++i) {
            Local<Value> coordinate = coordinates_array->Get(i);
            if (!coordinate->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            Local<Array> coordinate_array = Local<Array>::Cast(coordinate);
            if (coordinate_array->Length() != 2) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            q->this_->coordinates.push_back(
                FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION,
                                     coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION));
        }

        q->Wrap(args.This());
        return args.This();
    } catch (std::exception const& ex) {
        return ThrowException(Exception::TypeError(String::New(ex.what())));
    }
    return Undefined();
}
void Transaction::Init() {
	Local<FunctionTemplate> tpl = FunctionTemplate::New(New);

	tpl->SetClassName(String::NewSymbol("Transaction"));
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	tpl->PrototypeTemplate()->Set(String::NewSymbol("get"), FunctionTemplate::New(Get)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("getRange"), FunctionTemplate::New(GetRange)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("getKey"), FunctionTemplate::New(GetKey)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("watch"), FunctionTemplate::New(Watch)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("set"), FunctionTemplate::New(Set)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("commit"), FunctionTemplate::New(Commit)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("clear"), FunctionTemplate::New(Clear)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("clearRange"), FunctionTemplate::New(ClearRange)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("addReadConflictRange"), FunctionTemplate::New(AddReadConflictRange)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("addWriteConflictRange"), FunctionTemplate::New(AddWriteConflictRange)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("onError"), FunctionTemplate::New(OnError)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("reset"), FunctionTemplate::New(Reset)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("getReadVersion"), FunctionTemplate::New(GetReadVersion)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("setReadVersion"), FunctionTemplate::New(SetReadVersion)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("getCommittedVersion"), FunctionTemplate::New(GetCommittedVersion)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("cancel"), FunctionTemplate::New(Cancel)->GetFunction());
	tpl->PrototypeTemplate()->Set(String::NewSymbol("getAddressesForKey"), FunctionTemplate::New(GetAddressesForKey)->GetFunction());
	
	constructor = Persistent<Function>::New(tpl->GetFunction());
}
Пример #28
0
Handle<Value> Grid::encode(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

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

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

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

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
                return ThrowException(Exception::TypeError(
                                          String::New("'features' must be an Boolean")));

            add_features = bind_opt->BooleanValue();
        }
    }

    // ensure callback is a function
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));
    Local<Function> callback = Local<Function>::Cast(args[args.Length()-1]);

    encode_grid_baton_t *closure = new encode_grid_baton_t();
    closure->request.data = closure;
    closure->g = g;
    closure->format = format;
    closure->error = false;
    closure->resolution = resolution;
    closure->add_features = add_features;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    // todo - reserve lines size?
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Encode, EIO_AfterEncode);
    g->Ref();
    return Undefined();
}
Пример #29
0
/* static */
void V8Runtime::bootstrap(Local<Context> context)
{
	Isolate* isolate = context->GetIsolate();
	EventEmitter::initTemplate(context);

	Local<Object> kroll = Object::New(isolate);
	krollGlobalObject.Reset(isolate, kroll);
	Local<Array> mc = Array::New(isolate);
	moduleContexts.Reset(isolate, mc);

	KrollBindings::initFunctions(kroll, context);

	SetMethod(isolate, kroll, "log", krollLog);
	// Move this into the EventEmitter::initTemplate call?
	Local<FunctionTemplate> eect = Local<FunctionTemplate>::New(isolate, EventEmitter::constructorTemplate);
	{
		v8::TryCatch tryCatch(isolate);
		Local<Function> eventEmitterConstructor;
		MaybeLocal<Function> maybeEventEmitterConstructor = eect->GetFunction(context);
		if (!maybeEventEmitterConstructor.ToLocal(&eventEmitterConstructor)) {
			titanium::V8Util::fatalException(isolate, tryCatch);
			return;
		}
		kroll->Set(NEW_SYMBOL(isolate, "EventEmitter"), eventEmitterConstructor);
	}

	kroll->Set(NEW_SYMBOL(isolate, "runtime"), STRING_NEW(isolate, "v8"));
	kroll->Set(NEW_SYMBOL(isolate, "DBG"), v8::Boolean::New(isolate, V8Runtime::DBG));
	kroll->Set(NEW_SYMBOL(isolate, "moduleContexts"), mc);

	LOG_TIMER(TAG, "Executing kroll.js");

	TryCatch tryCatch(isolate);
	Local<Value> result = V8Util::executeString(isolate, KrollBindings::getMainSource(isolate), STRING_NEW(isolate, "ti:/kroll.js"));

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
	}
	if (!result->IsFunction()) {
		LOGF(TAG, "kroll.js result is not a function");
		V8Util::reportException(isolate, tryCatch, true);
	}

	// Add a reference to the global object
	Local<Object> global = context->Global();

	// Expose the global object as a property on itself
	// (Allows you to set stuff on `global` from anywhere in JavaScript.)
	global->Set(NEW_SYMBOL(isolate, "global"), global);

	Local<Function> mainFunction = result.As<Function>();
	Local<Value> args[] = { kroll };
	mainFunction->Call(context, global, 1, args);

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
		LOGE(TAG, "Caught exception while bootstrapping Kroll");
	}
}
Пример #30
0
bool GNUtil::isDictionaryObject(Local<Value> obj) {
    return obj->IsObject() &&
           !(obj->IsRegExp() || obj->IsDate() ||
             obj->IsFunction() || obj->IsArray());
}